diff --git a/.editorconfig b/.editorconfig index 5ebf4a129c..d3bd86c3ba 100644 --- a/.editorconfig +++ b/.editorconfig @@ -1,9 +1,9 @@ root = true [*] +indent_size = 4 trim_trailing_whitespace = true insert_final_newline = true [{*.json,*.yml}] indent_style = space -indent_size = 2 diff --git a/README.md b/README.md index f6d2e5d585..b43e3592e4 100644 --- a/README.md +++ b/README.md @@ -133,6 +133,7 @@ For a good example package, see [base64-js](https://github.com/DefinitelyTyped/D * First, follow advice from the [handbook](http://www.typescriptlang.org/docs/handbook/declaration-files/do-s-and-don-ts.html). * Formatting: Either use all tabs, or always use 4 spaces. +* `function sum(nums: number[]): number`: Use `ReadonlyArray` if a function does not write to its parameters. * `interface Foo { new(): Foo; }`: This defines a type of objects that are new-able. You probably want `declare class Foo { constructor(); }`. * `const Class: { new(): IClass; }`: diff --git a/notNeededPackages.json b/notNeededPackages.json index 8cf6a8ce83..4a3280ccb0 100644 --- a/notNeededPackages.json +++ b/notNeededPackages.json @@ -18,6 +18,12 @@ "sourceRepoURL": "https://github.com/doxout/anydb-sql", "asOfVersion": "0.6.46" }, + { + "libraryName": "apn", + "typingsPackageName": "apn", + "sourceRepoURL": "https://github.com/node-apn/node-apn", + "asOfVersion": "2.1.2" + }, { "libraryName": "Argon2", "typingsPackageName": "argon2", diff --git a/types/alexa-sdk/alexa-sdk-tests.ts b/types/alexa-sdk/alexa-sdk-tests.ts index 1454309b93..c384bf194d 100644 --- a/types/alexa-sdk/alexa-sdk-tests.ts +++ b/types/alexa-sdk/alexa-sdk-tests.ts @@ -2,6 +2,7 @@ import * as Alexa from "alexa-sdk"; const handler = (event: Alexa.RequestBody, context: Alexa.Context, callback: () => void) => { let alexa = Alexa.handler(event, context); + alexa.resources = {}; alexa.registerHandlers(handlers); alexa.execute(); }; diff --git a/types/alexa-sdk/index.d.ts b/types/alexa-sdk/index.d.ts index 24baccf484..d5892f6ec7 100644 --- a/types/alexa-sdk/index.d.ts +++ b/types/alexa-sdk/index.d.ts @@ -3,6 +3,7 @@ // Definitions by: Pete Beegle // Huw // pascalwhoop +// Ben // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped // TypeScript Version: 2.2 @@ -20,6 +21,7 @@ export interface AlexaObject extends Handler { state: any; appId: any; response: any; + resources: any; dynamoDBTableName: any; saveBeforeResponse: boolean; registerHandlers: (...handlers: Array>) => any; diff --git a/types/amqplib/amqplib-tests.ts b/types/amqplib/amqplib-tests.ts index 8bfcf3c9b4..ef448d5b36 100644 --- a/types/amqplib/amqplib-tests.ts +++ b/types/amqplib/amqplib-tests.ts @@ -16,13 +16,19 @@ amqp.connect('amqp://localhost') .then(connection => { return connection.createChannel() .tap(channel => channel.checkQueue('myQueue')) - .then(channel => channel.consume('myQueue', newMsg => console.log('New Message: ' + newMsg.content.toString()))) + .then(channel => { + return channel.consume('myQueue', newMsg => { + if (newMsg != null) { + // test promise api properties + if (newMsg.properties.contentType === 'application/json') { + console.log('New Message: ' + newMsg.content.toString()); + } + } + }); + }) .finally(() => connection.close()); }); -// test promise api properties -let amqpMessage: amqp.Message; -amqpMessage.properties.contentType = 'application/json'; let amqpAssertExchangeOptions: amqp.Options.AssertExchange; let anqpAssertExchangeReplies: amqp.Replies.AssertExchange; @@ -49,7 +55,14 @@ amqpcb.connect('amqp://localhost', (err, connection) => { if (!err) { channel.assertQueue('myQueue', {}, (err, ok) => { if (!err) { - channel.consume('myQueue', newMsg => console.log('New Message: ' + newMsg.content.toString())); + channel.consume('myQueue', newMsg => { + if (newMsg != null) { + // test callback api properties + if (newMsg.properties.contentType === 'application/json') { + console.log('New Message: ' + newMsg.content.toString()); + } + } + }); } }); } @@ -57,8 +70,5 @@ amqpcb.connect('amqp://localhost', (err, connection) => { } }); -// test callback api properties -let amqpcbMessage: amqpcb.Message; -amqpcbMessage.properties.contentType = 'application/json'; let amqpcbAssertExchangeOptions: amqpcb.Options.AssertExchange; let anqpcbAssertExchangeReplies: amqpcb.Replies.AssertExchange; diff --git a/types/amqplib/callback_api.d.ts b/types/amqplib/callback_api.d.ts index d36a849873..60ff8cf622 100644 --- a/types/amqplib/callback_api.d.ts +++ b/types/amqplib/callback_api.d.ts @@ -31,7 +31,7 @@ export interface Channel extends events.EventEmitter { publish(exchange: string, routingKey: string, content: Buffer, options?: Options.Publish): boolean; sendToQueue(queue: string, content: Buffer, options?: Options.Publish): boolean; - consume(queue: string, onMessage: (msg: Message) => any, options?: Options.Consume, callback?: (err: any, ok: Replies.Consume) => void): void; + consume(queue: string, onMessage: (msg: Message | null) => any, options?: Options.Consume, callback?: (err: any, ok: Replies.Consume) => void): void; cancel(consumerTag: string, callback?: (err: any, ok: Replies.Empty) => void): void; get(queue: string, options?: Options.Get, callback?: (err: any, ok: Message | false) => void): void; diff --git a/types/amqplib/index.d.ts b/types/amqplib/index.d.ts index 45b5e6e3ca..91060d23b0 100644 --- a/types/amqplib/index.d.ts +++ b/types/amqplib/index.d.ts @@ -40,7 +40,7 @@ export interface Channel extends events.EventEmitter { publish(exchange: string, routingKey: string, content: Buffer, options?: Options.Publish): boolean; sendToQueue(queue: string, content: Buffer, options?: Options.Publish): boolean; - consume(queue: string, onMessage: (msg: Message) => any, options?: Options.Consume): Promise; + consume(queue: string, onMessage: (msg: Message | null) => any, options?: Options.Consume): Promise; cancel(consumerTag: string): Promise; get(queue: string, options?: Options.Get): Promise; diff --git a/types/amqplib/tsconfig.json b/types/amqplib/tsconfig.json index 1f880d1396..16ed704846 100644 --- a/types/amqplib/tsconfig.json +++ b/types/amqplib/tsconfig.json @@ -6,7 +6,7 @@ ], "noImplicitAny": true, "noImplicitThis": true, - "strictNullChecks": false, + "strictNullChecks": true, "baseUrl": "../", "typeRoots": [ "../" @@ -20,4 +20,4 @@ "callback_api.d.ts", "amqplib-tests.ts" ] -} \ No newline at end of file +} diff --git a/types/angular-clipboard/angular-clipboard-tests.ts b/types/angular-clipboard/angular-clipboard-tests.ts index 00c5074ec5..6df5af0c5e 100644 --- a/types/angular-clipboard/angular-clipboard-tests.ts +++ b/types/angular-clipboard/angular-clipboard-tests.ts @@ -1,5 +1,5 @@ import * as angular from "angular"; -import {ClipboardService} from "angular-clipboard"; +import { ClipboardService } from "angular-clipboard"; interface TestScope extends ng.IScope { [index: string]: any; diff --git a/types/angular-strap/index.d.ts b/types/angular-strap/index.d.ts index 2b31f00148..f7749a049b 100644 --- a/types/angular-strap/index.d.ts +++ b/types/angular-strap/index.d.ts @@ -45,9 +45,14 @@ declare namespace mgcrea.ngStrap { template?: string; templateUrl?: string; contentTemplate?: string; + prefixClass?: string; prefixEvent?: string; id?: string; scope?: ng.IScope; + onBeforeHide?: (modal: IModal) => void; + onHide?: (modal: IModal) => void; + onBeforeShow?: (modal: IModal) => void; + onShow?: (modal: IModal) => void; } interface IModalScope extends ng.IScope { diff --git a/types/angular/angular-component-router.d.ts b/types/angular/angular-component-router.d.ts index da3afc7a71..b8c939f7c8 100644 --- a/types/angular/angular-component-router.d.ts +++ b/types/angular/angular-component-router.d.ts @@ -15,7 +15,7 @@ declare namespace angular { * ### Example * * ``` - * import {Component} from 'angular2/core'; + * import { Component } from 'angular2/core'; * import {bootstrap} from 'angular2/platform/browser'; * import {Router, ROUTER_DIRECTIVES, ROUTER_PROVIDERS, RouteConfig} from 'angular2/router'; * diff --git a/types/angular/index.d.ts b/types/angular/index.d.ts index fcfcf183e2..ba8e81f834 100644 --- a/types/angular/index.d.ts +++ b/types/angular/index.d.ts @@ -1035,6 +1035,12 @@ declare namespace angular { * Creates a Deferred object which represents a task which will finish in the future. */ defer(): IDeferred; + /** + * Returns a promise that resolves or rejects as soon as one of those promises resolves or rejects, with the value or reason from that promise. + * + * @param promises A list or hash of promises. + */ + race(promises: Array> | {[key: string]: IPromise}): IPromise; /** * Creates a promise that is resolved as rejected with the specified reason. This api should be used to forward rejection in a chain of promises. If you are dealing with the last promise in a promise chain, you don't need to worry about it. * diff --git a/types/apn/apn-tests.ts b/types/apn/apn-tests.ts deleted file mode 100644 index ea4bb34ae3..0000000000 --- a/types/apn/apn-tests.ts +++ /dev/null @@ -1,145 +0,0 @@ -import apn = require("apn"); - -//Hand made TypeScript tests -//========================== - -//Create with a hex string -var device1 = new apn.Device("ca11ab1e"); -//Create with a Buffer -var device2 = new apn.Device(new Buffer("ca55e77e")); - -//Create the notification -var notification = new apn.Notification(); -notification.alert = { - title: "The Title", - body: "This is the body", -}; -notification.badge = 5; -//Fluid api -notification.setAlertTitle("The Title") - .setAlertText("This is the body") - .setLaunchImage("LaunchImage"); - -//Establish the connection -var connection = new apn.Connection({ - cert: "path/to/cert.pem", - key: "path/to/cert.pem" -}); -//Testing some specialized event listeners -connection.on("error", (error) => { - console.log("push error", error.name, error.message); -}); -connection.on("transmissionError", (errorCode, notification, device) => { - console.log("push failed", errorCode, "notification", notification.alert, "device id: ", device.toString()); -}); - -//Send it using hex string -connection.pushNotification(notification, "ba5eba11"); -//Send it using Buffer -connection.pushNotification(notification, new Buffer("5ca1ab1e")); -//Send it using Device -connection.pushNotification(notification, device1); - -//Connecting to feedback service -var feedbackService = new apn.Feedback({ - cert: "path/to/cert.pem", - key: "path/to/cert.pem", - interval: 0 -}); -feedbackService.on("error", (error:Error) => { - console.log("push feedback error", error.name, error.message); -}); -function processFeedbackData(device:apn.Device, time:number) { -} -feedbackService.on("feedback", (feedbackData) => { - feedbackData.forEach((data) => { - processFeedbackData(data.device, data.time); - }) -}); -feedbackService.start(); - - -//Original examples from apn package -//================================== - -//sending-to-multiple-devices.js -//------------------------------ - -var tokens = ["", ""]; - -if(tokens[0] === "") { - console.log("Please set token to a valid device token for the push notification service"); - process.exit(); -} - -// Create a connection to the service using mostly default parameters. - -var service = new apn.connection({ production: false }); - -service.on("connected", function() { - console.log("Connected"); -}); - -service.on("transmitted", function(notification, device) { - console.log("Notification transmitted to:" + device.token.toString("hex")); -}); - -service.on("transmissionError", function(errCode, notification, device) { - console.error("Notification caused error: " + errCode + " for device ", device, notification); - if (errCode === 8) { - console.log("A error code of 8 indicates that the device token is invalid. This could be for a number of reasons - are you using the correct environment? i.e. Production vs. Sandbox"); - } -}); - -service.on("timeout", function () { - console.log("Connection Timeout"); -}); - -service.on("disconnected", function() { - console.log("Disconnected from APNS"); -}); - -service.on("socketError", console.error); - - -// If you plan on sending identical paylods to many devices you can do something like this. -function pushNotificationToMany() { - console.log("Sending the same notification each of the devices with one call to pushNotification."); - var note = new apn.notification(); - note.setAlertText("Hello, from node-apn!"); - note.badge = 1; - - service.pushNotification(note, tokens); -} - -pushNotificationToMany(); - - -// If you have a list of devices for which you want to send a customised notification you can create one and send it to and individual device. -function pushSomeNotifications() { - console.log("Sending a tailored notification to %d devices", tokens.length); - tokens.forEach(function(token, i) { - var note = new apn.notification(); - note.setAlertText("Hello, from node-apn! You are number: " + i); - note.badge = i; - - service.pushNotification(note, token); - }); -} - -pushSomeNotifications(); - -//feedback.js -//----------- - -function handleFeedback(feedbackData:apn.FeedbackData[]) { - feedbackData.forEach(function(feedbackItem) { - console.log("Device: " + feedbackItem.device.toString() + " has been unreachable, since: " + feedbackItem.time); - }); -} - -// Setup a connection to the feedback service using a custom interval (10 seconds) -var feedback = new apn.feedback({ production: false, interval: 10 }); - -feedback.on("feedback", handleFeedback); -feedback.on("feedbackError", console.error); diff --git a/types/apn/index.d.ts b/types/apn/index.d.ts deleted file mode 100644 index 96ce6e9720..0000000000 --- a/types/apn/index.d.ts +++ /dev/null @@ -1,364 +0,0 @@ -// Type definitions for node-apn -// Project: https://github.com/argon/node-apn -// Definitions by: Zenorbi -// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped - -/// - -import events = require("events"); -import net = require("net"); -export interface ConnectionOptions { - /** - * The filename of the connection certificate to load from disk, or a Buffer/String containing the certificate data. (Defaults to: `cert.pem`) - */ - cert?: string | Buffer; - /** - * The filename of the connection key to load from disk, or a Buffer/String containing the key data. (Defaults to: `key.pem`) - */ - key?: string | Buffer; - /** - * An array of trusted certificates. Each element should contain either a filename to load, or a Buffer/String (in PEM format) to be used directly. If this is omitted several well known "root" CAs will be used. - You may need to use this as some environments don't include the CA used by Apple (entrust_2048). - */ - ca?: (string | Buffer)[]; - /** - * File path for private key, certificate and CA certs in PFX or PKCS12 format, or a Buffer containing the PFX data. If supplied will always be used instead of certificate and key above. - */ - pfx?: string | Buffer; - /** - * The passphrase for the connection key, if required - */ - passphrase?: string; - /** - * Specifies which environment to connect to: Production (if true) or Sandbox - The hostname will be set automatically. (Defaults to NODE_ENV == "production", i.e. false unless the NODE_ENV environment variable is set accordingly) - */ - production?: boolean; - /** - * Enable when you are using a VoIP certificate to enable paylods up to 4096 bytes. - */ - voip?: boolean; - /** - * Gateway port (Defaults to: `2195`) - */ - port?: number; - /** - * Reject Unauthorized property to be passed through to tls.connect() (Defaults to `true`) - */ - rejectUnauthorized?: boolean; - /** - * Number of notifications to cache for error purposes (See "Handling Errors" below, (Defaults to: `1000`) - */ - cacheLength?: number; - /** - * Whether the cache should grow in response to messages being lost after errors. (Will still emit a 'cacheTooSmall' event) (Defaults to: `true`) - */ - autoAdjustCache?: boolean; - /** - * The maximum number of connections to create for sending messages. (Defaults to: `1`) - */ - maxConnections?: number; - /** - * The duration of time the module should wait, in milliseconds, when trying to establish a connection to Apple before failing. 0 = Disabled. {Defaults to: `10000`} - */ - connectTimeout?: number; - /** - * The duration the socket should stay alive with no activity in milliseconds. 0 = Disabled. (Defaults to: `3600000` - 1h) - */ - connectionTimeout?: number; - /** - * The maximum number of connection failures that will be tolerated before `apn` will "terminate". (Defaults to: 10) - */ - connectionRetryLimit?: number; - /** - * Whether to buffer notifications and resend them after failure. (Defaults to: `true`) - */ - buffersNotifications?: number; - /** - * Whether to aggresively empty the notification buffer while connected - if set to true node-apn may enter a tight loop under heavy load while delivering notifications. (Defaults to: `false`) - */ - fastMode?: boolean; -} -export declare class Connection extends events.EventEmitter { - constructor(options: ConnectionOptions); - /** - * This is the business end of the module. Create a `Notification` object and pass it in, along with a single recipient or an array of them and node-apn will take care of the rest, delivering the notification to each recipient. - * - * A "recipient" is either a `Device` object, a `String`, or a `Buffer` containing the device token. `Device` objects are used internally and will be created if necessary. Where applicable, all events will return a `Device` regardless of the type passed to this method. - */ - pushNotification(notification: Notification, recipient: Device | string | Buffer | (Device | string | Buffer)[]): void; - /** - * Used to manually adjust the "cacheLength" property in the options. This is ideal if you choose to use the `cacheTooSmall` event to tweak your environment. It is safe for increasing and reducing cache size. - */ - setCacheLength(newLength: number): void; - /** - * Indicate to node-apn that when the queue of pending notifications is fully drained that it should close all open connections. This will mean that if there are no other pending resources (open sockets, running timers, etc.) the application will terminate. If notifications are pushed after the connection has completely shutdown a new connection will be established and, if applicable, `shutdown` will need to be called again. - */ - shutdown(): void; - /** - * Emitted when an error occurs during initialisation of the module, usually due to a problem with the keys and certificates. - */ - on(event: "error", listener: (error: Error) => void): this; - /** - * Emitted when the connection socket experiences an error. This may be useful for debugging but no action should be necessary. - */ - on(event: "socketError", listener: (error: Error) => void): this; - /** - * Emitted when a notification has been sent to Apple - not a guarantee that it has been accepted by Apple, an error relating to it may occur later on. A notification may also be "transmitted" several times if a preceding notification caused an error requiring retransmission. - */ - on(event: "transmitted", listener: (notification: Notification, decive: Device) => void): this; - /** - * Emitted when all pending notifications have been transmitted to Apple and the pending queue is empty. This may be called more than once if a notification error occurs and notifications must be re-sent. - */ - on(event: "completed", listener: () => void): this; - /** - * Emitted when Apple returns a notification as invalid but the notification has already been expunged from the cache - usually due to high throughput and indicates that notifications will be getting lost. The parameter is an estimate of how many notifications have been lost. You should experiment with increasing the cache size or enabling ```autoAdjustCache``` if you see this frequently. - * - * **Note**: With ```autoAdjustCache``` enabled this event will still be emitted when an adjustment is triggered. - */ - on(event: "cacheTooSmall", listener: (sizeDifference: number) => void): this; - /** - * Emitted when a connection to Apple is successfully established. The parameter indicates the number of open connections. No action is required as the connection is managed internally. - */ - on(event: "connected", listener: (openSockets: net.Socket[]) => void): this; - /** - * Emitted when the connection to Apple has been closed, this could be for numerous reasons, for example an error has occurred or the connection has timed out. The parameter is the same as for `connected` and again, no action is required. - */ - on(event: "disconnected", listener: (openSockets: net.Socket[]) => void): this; - /** - * Emitted when the connectionTimeout option has been specified and no activity has occurred on a socket for a specified duration. The socket will be closed immediately after this event and a `disconnected` event will also be emitted. - */ - on(event: "timeout", listener: () => void): this; - /** - * Emitted when a message has been received from Apple stating that a notification was invalid or if an internal error occurred before that notification could be pushed to Apple. If the notification is still in the cache it will be passed as the second argument, otherwise null. Where possible the associated `Device` object will be passed as a third parameter, however in cases where the token supplied to the module cannot be parsed into a `Buffer` the supplied value will be returned. - - * Error codes smaller than 512 correspond to those returned by Apple as per their [docs][errors]. Other errors are applicable to `node-apn` itself. Definitions can be found in `lib/errors.js`. - */ - on(event: "transmissionError", listener: (errorCode: number, notification: Notification, device: Device | Buffer) => void): this; - on(event: string, listener: Function): this; -} -export interface NotificationAlertOptions { - title?: string; - subtitle?: string; - body: string; - "title-loc-key"?: string; - "title-loc-args"?: string[]; - "action-loc-key"?: string; - "loc-key"?: string; - "loc-args"?: string[]; - "launch-image"?: string; -} -export declare class Notification { - /** - * The maximum number of retries which should be performed when sending a notification if an error occurs. A value of 0 will only allow one attempt at sending (0 retries). Set to -1 to disable (default). - */ - public retryLimit: number; - /** - * The UNIX timestamp representing when the notification should expire. This does not contribute to the 2048 byte payload size limit. An expiry of 0 indicates that the notification expires immediately. - */ - public expiry: number; - /** - * From Apple's Documentation, Provide one of the following values: - * - * - 10 - The push message is sent immediately. (Default) - * > The push notification must trigger an alert, sound, or badge on the device. It is an error use this priority for a push that contains only the content-available key. - * - 5 - The push message is sent at a time that conserves power on the device receiving it. - */ - public priority: number; - /** - * The encoding to use when transmitting the notification to APNS, defaults to `utf8`. `utf16le` is also possible but as each character is represented by a minimum of 2 bytes, will at least halve the possible payload size. If in doubt leave as default. - */ - public encoding: string; - /** - * This object represents the root JSON object that you can add custom information for your application to. The properties below will only be added to the payload (under `aps`) when the notification is prepared for sending. - */ - public payload: any; - /** - * The value to specify for `payload.aps.badge` - */ - public badge: number; - /** - * The value to specify for `payload.aps.sound` - */ - public sound: string; - /** - * The value to specify for `payload.aps.alert` can be either a `String` or an `Object` as outlined by the payload documentation. - */ - public alert: string | NotificationAlertOptions; - /** - * Setting this to true will specify "content-available" in the payload when it is compiled. - */ - public newsstandAvailable: boolean; - /** - * Setting this to true will specify "content-available" in the payload when it is compiled. - */ - public contentAvailable: boolean; - /** - * The value to specify for the `mdm` field where applicable. - */ - public mdm: string | Object; - /** - * The value to specify for `payload.aps['url-args']`. This used for Safari Push NOtifications and should be an array of values in accordance with the Web Payload Documentation. - */ - public urlArgs: string[]; - /** - * When this parameter is set and `notification#trim()` is called it will attempt to truncate the string at the nearest space. - */ - public truncateAtWordEnd: boolean; - /** - * You can optionally pass in an object representing the payload, or configure properties on the returned object. - */ - constructor(payload?: any); - /** - * Set the `aps.alert` text body. This will use the most space-efficient means. - */ - setAlertText(alertText: string): Notification; - /** - * Set the `title` property of the `aps.alert` object - used with Safari Push Notifications - */ - setAlertTitle(alertTitle: string): Notification; - /** - * Set the `action` property of the `aps.alert` object - used with Safari Push Notifications - */ - setAlertAction(alertAction: string): Notification; - /** - * Set the `action-loc-key` property of the `aps.alert` object. - */ - setActionLocKey(key: string): Notification; - /** - * Set the `loc-key` property of the `aps.alert` object. - */ - setLocKey(key: string): Notification; - /** - * Set the `loc-args` property of the `aps.alert` object. - */ - setLocArgs(args: string[]): Notification; - /** - * Set the `launch-image` property of the `aps.alert` object. - */ - setLaunchImage(image: string): Notification; - /** - * Set the `mdm` property on the payload. - */ - setMDM(mdm: string | Object): Notification; - /** - * Set the `content-available` property of the `aps` object. - */ - setNewsstandAvailable(available: boolean): Notification; - /** - * Set the `content-available` property of the `aps` object. - */ - setContentAvailable(available: boolean): Notification; - /** - * Set the `url-args` property of the `aps` object. - */ - setUrlArgs(urlArgs: string[]): Notification; - /** - * Attempt to automatically trim the notification alert text body to meet the payload size limit of 2048 bytes. - */ - trim(): number; -} -export declare class Device { - public token: Buffer; - /** - * `deviceToken` can be a `Buffer` or a `String` containing a "hex" representation of the token. Throws an error if the deviceToken supplied is invalid. - */ - constructor(deviceToken: string | Buffer); -} - -export interface FeedbackOptions { - /** - * The filename of the connection certificate to load from disk, or a Buffer/String containing the certificate data. (Defaults to: `cert.pem`) - */ - cert?: string | Buffer; - /** - * The filename of the connection key to load from disk, or a Buffer/String containing the key data. (Defaults to: `key.pem`) - */ - key?: string | Buffer; - /** - * An array of trusted certificates. Each element should contain either a filename to load, or a Buffer/String (in PEM format) to be used directly. If this is omitted several well known "root" CAs will be used. - You may need to use this as some environments don't include the CA used by Apple (entrust_2048). - */ - ca?: (string | Buffer)[]; - /** - * File path for private key, certificate and CA certs in PFX or PKCS12 format, or a Buffer containing the PFX data. If supplied will be used instead of certificate and key above. - */ - pfx?: string | Buffer; - /** - * The passphrase for the connection key, if required - */ - passphrase?: string; - /** - * Specifies which environment to connect to: Production (if true) or Sandbox - The hostname will be set automatically. (Defaults to NODE_ENV == "production", i.e. false unless the NODE_ENV environment variable is set accordingly) - */ - production?: boolean; - /** - * Feedback server port (Defaults to: `2196`) - */ - port?: number; - /** - * Sets the behaviour for triggering the `feedback` event. When `true` the event will be triggered once per connection with an array of timestamp and device token tuples. Otherwise a `feedback` event will be emitted once per token received. (Defaults to: true) - */ - batchFeedback?: boolean; - /** - * The maximum number of tokens to pass when emitting the event - a value of 0 will cause all tokens to be passed after connection is reset. After this number of tokens are received the `feedback` event will be emitted. (Only applies when `batchFeedback` is enabled) - */ - batchSize?: number; - /** - * How often to automatically poll the feedback service. Set to `0` to disable. (Defaults to: `3600`) - */ - interval?: number; -} -export interface FeedbackData { - time: number; - device: Device; -} -/** - * Connection to the Apple Push Notification Feedback Service and if `interval` isn't disabled automatically begins polling the service. Many of the options are the same as `apn.Connection()` - */ -export declare class Feedback { - constructor(options: FeedbackOptions); - /** - * Trigger a query of the feedback service. If `interval` is non-zero then this method will be called automatically. - */ - start(): void; - /** - * You can cancel the interval by calling `feedback.cancel()`. If you do not wish to have the service automatically queried then set `interval` to 0 and use `feedback.start()` to manually invoke it one time. - */ - cancel(): void; - /** - * Emitted when an error occurs initialising the module. Usually caused by failing to load the certificates. - */ - on(event: "error", listener: (error: Error) => void): Feedback; - /** - * Emitted when an error occurs receiving or processing the feedback and in the case of a socket error occurring. These errors are usually informational and node-apn will automatically recover. - */ - on(event: "feedbackError", listener: (error: Error) => void): Feedback; - /** - * Emitted when data has been received from the feedback service, typically once per connection. `feedbackData` is an array of objects, each containing the `time` returned by the server (epoch time) and the `device` a `Buffer` containing the device token. - */ - on(event: "feedback", listener: (feedbackData: FeedbackData[]) => void): Feedback; - on(event: string, listener: Function): Feedback; -} - -export declare enum Errors { - "noErrorsEncountered" = 0, - "processingError" = 1, - "missingDeviceToken" = 2, - "missingTopic" = 3, - "missingPayload" = 4, - "invalidTokenSize" = 5, - "invalidTopicSize" = 6, - "invalidPayloadSize" = 7, - "invalidToken" = 8, - "apnsShutdown" = 10, - "none" = 255, - "retryLimitExceeded" = 512, - "moduleInitialisationFailed" = 513, - "connectionRetryLimitExceeded" = 514, // When a connection is unable to be established. Usually because of a network / SSL error this will be emitted - "connectionTerminated" = 515 -} - -//Lowercase aliases -export { Connection as connection }; -export { Device as device }; -export { Errors as error }; -export { Feedback as feedback }; -export { Notification as notification }; diff --git a/types/argparse/argparse-tests.ts b/types/argparse/argparse-tests.ts index cec1ece95b..f5b9e76f81 100644 --- a/types/argparse/argparse-tests.ts +++ b/types/argparse/argparse-tests.ts @@ -1,7 +1,7 @@ // near copy of each of the tests from https://github.com/nodeca/argparse/tree/master/examples -import {ArgumentParser, RawDescriptionHelpFormatter} from 'argparse'; +import { ArgumentParser, RawDescriptionHelpFormatter } from 'argparse'; var args: any; var simpleExample = new ArgumentParser({ diff --git a/types/arrify/index.d.ts b/types/arrify/index.d.ts index fb552e161e..896ee23224 100644 --- a/types/arrify/index.d.ts +++ b/types/arrify/index.d.ts @@ -1,4 +1,4 @@ -// Type definitions for arrify 1.0.1 +// Type definitions for arrify 1.0 // Project: https://github.com/sindresorhus/arrify // Definitions by: AnJun Wang // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped diff --git a/types/arrify/tsconfig.json b/types/arrify/tsconfig.json index b2579c233e..e0ac439953 100644 --- a/types/arrify/tsconfig.json +++ b/types/arrify/tsconfig.json @@ -19,4 +19,4 @@ "index.d.ts", "arrify-tests.ts" ] -} \ No newline at end of file +} diff --git a/types/arrify/tslint.json b/types/arrify/tslint.json new file mode 100644 index 0000000000..3db14f85ea --- /dev/null +++ b/types/arrify/tslint.json @@ -0,0 +1 @@ +{ "extends": "dtslint/dt.json" } diff --git a/types/askmethat-rating/askmethat-rating-tests.ts b/types/askmethat-rating/askmethat-rating-tests.ts index 2f17ad0b62..af0ab3cb88 100644 --- a/types/askmethat-rating/askmethat-rating-tests.ts +++ b/types/askmethat-rating/askmethat-rating-tests.ts @@ -13,3 +13,6 @@ let options = { let div = document.createElement("div"); let amcRating = new AskmethatRating(div, 2 , options); + +options.readonly = true; +amcRating.defaultOptions = options; diff --git a/types/askmethat-rating/index.d.ts b/types/askmethat-rating/index.d.ts index ff31f81747..43a59957bd 100644 --- a/types/askmethat-rating/index.d.ts +++ b/types/askmethat-rating/index.d.ts @@ -75,7 +75,12 @@ export class AskmethatRating { * * @return options based on @type AskmethatRatingOptions */ - readonly defaultOptions: any; + /** + * @function set the default option for the rating + * + * @return options based on @type AskmethatRatingOptions + */ + defaultOptions: AskmethatRatingOptions; /** * constructor with div element, default rating value & default options * @@ -122,6 +127,12 @@ export class AskmethatRating { * Update readonly status if needed for the rating */ private mutationEvent(); + /** + * This is fired by mutation observer when an attribute changed in the hidden input + * Is protected to have some unit tests + * @param {MutationRecord[]} mutations list of mutations record + */ + protected mutationDisableEvent(mutations: MutationRecord[]): void; /** * @function static method to retrieve with identifier the value * @param {string} identifier: string container identifier diff --git a/types/assert-plus/index.d.ts b/types/assert-plus/index.d.ts index d79172bc49..6c1f369729 100644 --- a/types/assert-plus/index.d.ts +++ b/types/assert-plus/index.d.ts @@ -5,7 +5,7 @@ /// -import {Stream} from 'stream'; +import { Stream } from 'stream'; export function array(arr: any[], message ?: string): void; diff --git a/types/async.nexttick/async.nexttick-tests.ts b/types/async.nexttick/async.nexttick-tests.ts index 90f6ae7f15..876a8e0f88 100644 --- a/types/async.nexttick/async.nexttick-tests.ts +++ b/types/async.nexttick/async.nexttick-tests.ts @@ -1,4 +1,4 @@ -import {nextTick} from 'async.nexttick'; +import { nextTick } from 'async.nexttick'; function calledOnNextTick(a: string): number { return parseInt(a, 10); diff --git a/types/auto-sni/index.d.ts b/types/auto-sni/index.d.ts index bc252831ca..19272446a6 100644 --- a/types/auto-sni/index.d.ts +++ b/types/auto-sni/index.d.ts @@ -5,7 +5,7 @@ /// -import {Server} from "https"; +import { Server } from "https"; declare namespace createServer { interface Options { diff --git a/types/aws-lambda/aws-lambda-tests.ts b/types/aws-lambda/aws-lambda-tests.ts index 10b4fa1073..4e404fcd55 100644 --- a/types/aws-lambda/aws-lambda-tests.ts +++ b/types/aws-lambda/aws-lambda-tests.ts @@ -130,6 +130,7 @@ num = proxyResult.statusCode; proxyResult.headers["example"] = str; proxyResult.headers["example"] = b; proxyResult.headers["example"] = num; +b = proxyResult.isBase64Encoded; str = proxyResult.body; /* API Gateway CustomAuthorizer AuthResponse */ diff --git a/types/aws-lambda/index.d.ts b/types/aws-lambda/index.d.ts index 1da094ac46..0c8f0fc26d 100644 --- a/types/aws-lambda/index.d.ts +++ b/types/aws-lambda/index.d.ts @@ -288,6 +288,7 @@ interface ProxyResult { [header: string]: boolean | number | string; }, body: string; + isBase64Encoded?: boolean; } /** diff --git a/types/babel-core/babel-core-tests.ts b/types/babel-core/babel-core-tests.ts index 4c62d3c2f5..45fc649549 100644 --- a/types/babel-core/babel-core-tests.ts +++ b/types/babel-core/babel-core-tests.ts @@ -1,7 +1,5 @@ - import * as babel from "babel-core"; - // Example from https://github.com/babel/babel/tree/master/packages/babel-core const code = `class Example {}`; const result = babel.transform(code, { /* options */ }); @@ -9,7 +7,6 @@ result.code; // Generated code result.map; // Sourcemap result.ast; // AST - // Examples from http://babeljs.io/docs/usage/api/ let options: babel.TransformOptions = { plugins: [ @@ -23,7 +20,7 @@ let options: babel.TransformOptions = { sourceMaps: true }; -babel.transformFile("filename.js", options, function (err, result) { +babel.transformFile("filename.js", options, (err, result) => { result.code; result.map; result.ast; diff --git a/types/babel-core/index.d.ts b/types/babel-core/index.d.ts index a3cd7019ab..d3b3053a84 100644 --- a/types/babel-core/index.d.ts +++ b/types/babel-core/index.d.ts @@ -1,20 +1,17 @@ -// Type definitions for babel-core v6.7 +// Type definitions for babel-core 6.25 // Project: https://github.com/babel/babel/tree/master/packages/babel-core // Definitions by: Troy Gerwien +// Marvin Hagemeister // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped - -/// -/// -/// +// TypeScript Version: 2.3 import * as t from 'babel-types'; export {t as types}; -type Node = t.Node; +export type Node = t.Node; export import template = require('babel-template'); -export var version: string; -import traverse, {Visitor} from "babel-traverse"; -export {traverse, Visitor}; - +export const version: string; +import traverse, { Visitor } from "babel-traverse"; +export { traverse, Visitor }; /** Transforms the passed in `code`. Returning an object with the generated code, source map, and AST. */ export function transform(code: string, opts?: TransformOptions): BabelFileResult; @@ -28,7 +25,6 @@ export function transformFileSync(filename: string, opts?: TransformOptions): Ba export function transformFromAst(ast: Node, code?: string, opts?: TransformOptions): BabelFileResult; export interface TransformOptions { - /** Filename to use when reading from stdin - this will be used in source-maps, errors etc. Default: "unknown". */ filename?: string; @@ -36,7 +32,7 @@ export interface TransformOptions { filenameRelative?: string; /** A source map object that the output source map will be based on. */ - inputSourceMap?: Object; + inputSourceMap?: object; /** * This is an object of keys that represent different environments. For example, you may have: @@ -44,7 +40,7 @@ export interface TransformOptions { * which will use those options when the enviroment variable `BABEL_ENV` is set to `"production"`. * If `BABEL_ENV` isn't set then `NODE_ENV` will be used, if it's not set then it defaults to `"development"`. */ - env?: Object; + env?: object; /** Retain line numbers - will result in really ugly code. Default: `false` */ retainLines?: boolean; @@ -83,7 +79,7 @@ export interface TransformOptions { * An optional callback that controls whether a comment should be output or not. Called as * `shouldPrintComment(commentContents)`. **NOTE**: This overrides the `comments` option when used. */ - shouldPrintComment?: (comment: string) => boolean; + shouldPrintComment?(comment: string): boolean; /** * Do not include superfluous whitespace characters and line terminators. When set to `"auto"`, `compact` is set to @@ -120,7 +116,7 @@ export interface TransformOptions { * Specify a custom callback to generate a module id with. Called as `getModuleId(moduleName)`. * If falsy value is returned then the generated module id is used. */ - getModuleId?: (moduleName: string) => string; + getModuleId?(moduleName: string): string; /** Optional prefix for the AMD module formatter that will be prepend to the filename on module definitions. */ moduleRoot?: string; @@ -138,7 +134,6 @@ export interface TransformOptions { export interface BabelFileResult { ast?: Node; code?: string; - map?: Object; + map?: object; } export as namespace babel; - diff --git a/types/babel-core/tslint.json b/types/babel-core/tslint.json new file mode 100644 index 0000000000..3db14f85ea --- /dev/null +++ b/types/babel-core/tslint.json @@ -0,0 +1 @@ +{ "extends": "dtslint/dt.json" } diff --git a/types/babel-generator/babel-generator-tests.ts b/types/babel-generator/babel-generator-tests.ts index 92c65b7f54..1aeec38831 100644 --- a/types/babel-generator/babel-generator-tests.ts +++ b/types/babel-generator/babel-generator-tests.ts @@ -1,5 +1,5 @@ // Example from https://github.com/babel/babel/tree/master/packages/babel-generator -import {parse} from 'babylon'; +import { parse } from 'babylon'; import generate from 'babel-generator'; const code = 'class Example {}'; diff --git a/types/babel-plugin-syntax-jsx/babel-plugin-syntax-jsx-tests.ts b/types/babel-plugin-syntax-jsx/babel-plugin-syntax-jsx-tests.ts new file mode 100644 index 0000000000..4dcb7b4882 --- /dev/null +++ b/types/babel-plugin-syntax-jsx/babel-plugin-syntax-jsx-tests.ts @@ -0,0 +1,10 @@ +import jsx from "babel-plugin-syntax-jsx"; + +// Example taken from the babel plugin handbook: +// https://github.com/thejameskyle/babel-handbook/blob/master/translations/en/plugin-handbook.md#-enabling-syntax-in-plugins +export default function myBabelPlugin() { + return { + visitor: {}, + inherits: jsx, + }; +} diff --git a/types/babel-plugin-syntax-jsx/index.d.ts b/types/babel-plugin-syntax-jsx/index.d.ts new file mode 100644 index 0000000000..c7b0ede972 --- /dev/null +++ b/types/babel-plugin-syntax-jsx/index.d.ts @@ -0,0 +1,13 @@ +// Type definitions for babel-plugin-syntax-jsx 6.18 +// Project: https://github.com/babel/babel/tree/master/packages/babel-plugin-syntax-jsx +// Definitions by: Marvin Hagemeister +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +// NB: This export doesn't match the handbook example, where `jsx` is the default export. +// But it does match the runtime behaviour (at least at the time of this writing). For some reason, +// babel-plugin-syntax-jsx/lib/index.js has this line at the bottom: module.exports = exports["default"]; +declare function jsx(): { + manipulateOptions(opts: any, parserOpts: { plugins: string[] }): void; +}; + +export default jsx; diff --git a/types/apn/tsconfig.json b/types/babel-plugin-syntax-jsx/tsconfig.json similarity index 90% rename from types/apn/tsconfig.json rename to types/babel-plugin-syntax-jsx/tsconfig.json index a6d716d8fe..bb19fbf329 100644 --- a/types/apn/tsconfig.json +++ b/types/babel-plugin-syntax-jsx/tsconfig.json @@ -17,6 +17,6 @@ }, "files": [ "index.d.ts", - "apn-tests.ts" + "babel-plugin-syntax-jsx-tests.ts" ] -} \ No newline at end of file +} diff --git a/types/babel-plugin-syntax-jsx/tslint.json b/types/babel-plugin-syntax-jsx/tslint.json new file mode 100644 index 0000000000..3db14f85ea --- /dev/null +++ b/types/babel-plugin-syntax-jsx/tslint.json @@ -0,0 +1 @@ +{ "extends": "dtslint/dt.json" } diff --git a/types/babel-template/babel-template-tests.ts b/types/babel-template/babel-template-tests.ts index 31e3bd44d9..684a291be7 100644 --- a/types/babel-template/babel-template-tests.ts +++ b/types/babel-template/babel-template-tests.ts @@ -1,5 +1,3 @@ -/// - // Example from https://github.com/babel/babel/tree/master/packages/babel-template import template = require('babel-template'); import generate from 'babel-generator'; diff --git a/types/babel-template/index.d.ts b/types/babel-template/index.d.ts index 7d73adc466..467b0193e7 100644 --- a/types/babel-template/index.d.ts +++ b/types/babel-template/index.d.ts @@ -1,13 +1,11 @@ -// Type definitions for babel-template v6.7 +// Type definitions for babel-template 6.25 // Project: https://github.com/babel/babel/tree/master/packages/babel-template // Definitions by: Troy Gerwien +// Marvin Hagemeister // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.3 -/// -/// - - -import {BabylonOptions} from 'babylon'; +import { BabylonOptions } from 'babylon'; import * as t from 'babel-types'; type Node = t.Node; @@ -18,4 +16,3 @@ export = template; declare function template(code: string, opts?: BabylonOptions): UseTemplate; type UseTemplate = (nodes?: {[placeholder: string]: Node}) => Node; - diff --git a/types/babel-template/tslint.json b/types/babel-template/tslint.json new file mode 100644 index 0000000000..3db14f85ea --- /dev/null +++ b/types/babel-template/tslint.json @@ -0,0 +1 @@ +{ "extends": "dtslint/dt.json" } diff --git a/types/babel-traverse/babel-traverse-tests.ts b/types/babel-traverse/babel-traverse-tests.ts index 5952faefd1..571620fd09 100644 --- a/types/babel-traverse/babel-traverse-tests.ts +++ b/types/babel-traverse/babel-traverse-tests.ts @@ -1,11 +1,7 @@ -/// - - import * as babylon from "babylon"; -import traverse, {Visitor} from 'babel-traverse'; +import traverse, { Visitor } from 'babel-traverse'; import * as t from 'babel-types'; - // Examples from: https://github.com/thejameskyle/babel-handbook/blob/master/translations/en/plugin-handbook.md const MyVisitor: Visitor = { Identifier: { @@ -24,7 +20,6 @@ const MyVisitor2: Visitor = { } }; - // Example from https://github.com/thejameskyle/babel-handbook/blob/master/translations/en/plugin-handbook.md#babel-traverse const code = `function square(n) { return n * n; @@ -41,11 +36,9 @@ traverse(ast, { } }); - // Examples from https://github.com/thejameskyle/babel-handbook/blob/master/translations/en/plugin-handbook.md#writing-your-first-babel-plugin const v1: Visitor = { - BinaryExpression(path) { if (t.isIdentifier(path.node.left)) { // ... diff --git a/types/babel-traverse/index.d.ts b/types/babel-traverse/index.d.ts index 8d34144d0a..bf92ae899f 100644 --- a/types/babel-traverse/index.d.ts +++ b/types/babel-traverse/index.d.ts @@ -1,13 +1,12 @@ -// Type definitions for babel-traverse v6.7 +// Type definitions for babel-traverse 6.25 // Project: https://github.com/babel/babel/tree/master/packages/babel-traverse // Definitions by: Troy Gerwien +// Marvin Hagemeister // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped - -/// - +// TypeScript Version: 2.3 import * as t from 'babel-types'; -type Node = t.Node; +export type Node = t.Node; export default function traverse(parent: Node | Node[], opts?: TraverseOptions, scope?: Scope, state?: any, parentPath?: NodePath): void; @@ -54,7 +53,7 @@ export class Scope { /** Possibly generate a memoised identifier if it is not static and has consequences. */ maybeGenerateMemoised(node: Node, dontPush?: boolean): t.Identifier; - checkBlockScopedCollisions(local: Node, kind: string, name: string, id: Object): void; + checkBlockScopedCollisions(local: Node, kind: string, name: string, id: object): void; rename(oldName: string, newName?: string, block?: Node): void; @@ -95,7 +94,7 @@ export class Scope { getBlockParent(): Scope; /** Walks the scope tree and gathers **all** bindings. */ - getAllBindings(...kinds: string[]): Object; + getAllBindings(...kinds: string[]): object; bindingIdentifierEquals(name: string, node: Node): boolean; @@ -129,9 +128,9 @@ export class Binding { kind: 'var' | 'let' | 'const' | 'module'; referenced: boolean; references: number; - referencePaths: NodePath[]; + referencePaths: Array>; constant: boolean; - constantViolations: NodePath[]; + constantViolations: Array>; } export interface Visitor extends VisitNodeObject { @@ -317,21 +316,21 @@ export interface VisitNodeObject { exit?(path: NodePath, state: any): void; } -export class NodePath { +export class NodePath { constructor(hub: Hub, parent: Node); parent: Node; hub: Hub; contexts: TraversalContext[]; - data: Object; + data: object; shouldSkip: boolean; shouldStop: boolean; removed: boolean; state: any; - opts: Object; - skipKeys: Object; + opts: object; + skipKeys: object; parentPath: NodePath; context: TraversalContext; - container: Object | Object[]; + container: object | object[]; listKey: string; inList: boolean; parentKey: string; @@ -339,7 +338,7 @@ export class NodePath { node: T; scope: Scope; type: string; - typeAnnotation: Object; + typeAnnotation: object; getScope(scope: Scope): Scope; @@ -355,7 +354,8 @@ export class NodePath { getPathLocation(): string; - debug(buildMessage: Function): void; + // Example: https://github.com/babel/babel/blob/63204ae51e020d84a5b246312f5eeb4d981ab952/packages/babel-traverse/src/path/modification.js#L83 + debug(buildMessage: () => string): void; // ------------------------- ancestry ------------------------- /** @@ -379,17 +379,20 @@ export class NodePath { * Earliest is defined as being "before" all the other nodes in terms of list container * position and visiting key. */ - getEarliestCommonAncestorFrom(paths: NodePath[]): NodePath; + getEarliestCommonAncestorFrom(paths: Array>): Array>; /** Get the earliest path in the tree where the provided `paths` intersect. */ - getDeepestCommonAncestorFrom(paths: NodePath[], filter?: Function): NodePath; + getDeepestCommonAncestorFrom( + paths: Array>, + filter?: (deepest: Node, i: number, ancestries: Array>) => NodePath + ): NodePath; /** * Build an array of node paths containing the entire ancestry of the current node path. * * NOTE: The current node path is included in this. */ - getAncestry(): NodePath[]; + getAncestry(): Array>; inType(...candidateTypes: string[]): boolean; @@ -570,11 +573,9 @@ export class NodePath { hoist(scope: Scope): void; // ------------------------- family ------------------------- - getStatementParent(): NodePath; - getOpposite(): NodePath; - getCompletionRecords(): NodePath[]; + getCompletionRecords(): Array>; getSibling(key: string): NodePath; @@ -594,362 +595,362 @@ export class NodePath { addComments(type: string, comments: any[]): void; // ------------------------- isXXX ------------------------- - isArrayExpression(opts?: Object): boolean; - isAssignmentExpression(opts?: Object): boolean; - isBinaryExpression(opts?: Object): boolean; - isDirective(opts?: Object): boolean; - isDirectiveLiteral(opts?: Object): boolean; - isBlockStatement(opts?: Object): boolean; - isBreakStatement(opts?: Object): boolean; - isCallExpression(opts?: Object): boolean; - isCatchClause(opts?: Object): boolean; - isConditionalExpression(opts?: Object): boolean; - isContinueStatement(opts?: Object): boolean; - isDebuggerStatement(opts?: Object): boolean; - isDoWhileStatement(opts?: Object): boolean; - isEmptyStatement(opts?: Object): boolean; - isExpressionStatement(opts?: Object): boolean; - isFile(opts?: Object): boolean; - isForInStatement(opts?: Object): boolean; - isForStatement(opts?: Object): boolean; - isFunctionDeclaration(opts?: Object): boolean; - isFunctionExpression(opts?: Object): boolean; - isIdentifier(opts?: Object): boolean; - isIfStatement(opts?: Object): boolean; - isLabeledStatement(opts?: Object): boolean; - isStringLiteral(opts?: Object): boolean; - isNumericLiteral(opts?: Object): boolean; - isNullLiteral(opts?: Object): boolean; - isBooleanLiteral(opts?: Object): boolean; - isRegExpLiteral(opts?: Object): boolean; - isLogicalExpression(opts?: Object): boolean; - isMemberExpression(opts?: Object): boolean; - isNewExpression(opts?: Object): boolean; - isProgram(opts?: Object): boolean; - isObjectExpression(opts?: Object): boolean; - isObjectMethod(opts?: Object): boolean; - isObjectProperty(opts?: Object): boolean; - isRestElement(opts?: Object): boolean; - isReturnStatement(opts?: Object): boolean; - isSequenceExpression(opts?: Object): boolean; - isSwitchCase(opts?: Object): boolean; - isSwitchStatement(opts?: Object): boolean; - isThisExpression(opts?: Object): boolean; - isThrowStatement(opts?: Object): boolean; - isTryStatement(opts?: Object): boolean; - isUnaryExpression(opts?: Object): boolean; - isUpdateExpression(opts?: Object): boolean; - isVariableDeclaration(opts?: Object): boolean; - isVariableDeclarator(opts?: Object): boolean; - isWhileStatement(opts?: Object): boolean; - isWithStatement(opts?: Object): boolean; - isAssignmentPattern(opts?: Object): boolean; - isArrayPattern(opts?: Object): boolean; - isArrowFunctionExpression(opts?: Object): boolean; - isClassBody(opts?: Object): boolean; - isClassDeclaration(opts?: Object): boolean; - isClassExpression(opts?: Object): boolean; - isExportAllDeclaration(opts?: Object): boolean; - isExportDefaultDeclaration(opts?: Object): boolean; - isExportNamedDeclaration(opts?: Object): boolean; - isExportSpecifier(opts?: Object): boolean; - isForOfStatement(opts?: Object): boolean; - isImportDeclaration(opts?: Object): boolean; - isImportDefaultSpecifier(opts?: Object): boolean; - isImportNamespaceSpecifier(opts?: Object): boolean; - isImportSpecifier(opts?: Object): boolean; - isMetaProperty(opts?: Object): boolean; - isClassMethod(opts?: Object): boolean; - isObjectPattern(opts?: Object): boolean; - isSpreadElement(opts?: Object): boolean; - isSuper(opts?: Object): boolean; - isTaggedTemplateExpression(opts?: Object): boolean; - isTemplateElement(opts?: Object): boolean; - isTemplateLiteral(opts?: Object): boolean; - isYieldExpression(opts?: Object): boolean; - isAnyTypeAnnotation(opts?: Object): boolean; - isArrayTypeAnnotation(opts?: Object): boolean; - isBooleanTypeAnnotation(opts?: Object): boolean; - isBooleanLiteralTypeAnnotation(opts?: Object): boolean; - isNullLiteralTypeAnnotation(opts?: Object): boolean; - isClassImplements(opts?: Object): boolean; - isClassProperty(opts?: Object): boolean; - isDeclareClass(opts?: Object): boolean; - isDeclareFunction(opts?: Object): boolean; - isDeclareInterface(opts?: Object): boolean; - isDeclareModule(opts?: Object): boolean; - isDeclareTypeAlias(opts?: Object): boolean; - isDeclareVariable(opts?: Object): boolean; - isExistentialTypeParam(opts?: Object): boolean; - isFunctionTypeAnnotation(opts?: Object): boolean; - isFunctionTypeParam(opts?: Object): boolean; - isGenericTypeAnnotation(opts?: Object): boolean; - isInterfaceExtends(opts?: Object): boolean; - isInterfaceDeclaration(opts?: Object): boolean; - isIntersectionTypeAnnotation(opts?: Object): boolean; - isMixedTypeAnnotation(opts?: Object): boolean; - isNullableTypeAnnotation(opts?: Object): boolean; - isNumericLiteralTypeAnnotation(opts?: Object): boolean; - isNumberTypeAnnotation(opts?: Object): boolean; - isStringLiteralTypeAnnotation(opts?: Object): boolean; - isStringTypeAnnotation(opts?: Object): boolean; - isThisTypeAnnotation(opts?: Object): boolean; - isTupleTypeAnnotation(opts?: Object): boolean; - isTypeofTypeAnnotation(opts?: Object): boolean; - isTypeAlias(opts?: Object): boolean; - isTypeAnnotation(opts?: Object): boolean; - isTypeCastExpression(opts?: Object): boolean; - isTypeParameterDeclaration(opts?: Object): boolean; - isTypeParameterInstantiation(opts?: Object): boolean; - isObjectTypeAnnotation(opts?: Object): boolean; - isObjectTypeCallProperty(opts?: Object): boolean; - isObjectTypeIndexer(opts?: Object): boolean; - isObjectTypeProperty(opts?: Object): boolean; - isQualifiedTypeIdentifier(opts?: Object): boolean; - isUnionTypeAnnotation(opts?: Object): boolean; - isVoidTypeAnnotation(opts?: Object): boolean; - isJSXAttribute(opts?: Object): boolean; - isJSXClosingElement(opts?: Object): boolean; - isJSXElement(opts?: Object): boolean; - isJSXEmptyExpression(opts?: Object): boolean; - isJSXExpressionContainer(opts?: Object): boolean; - isJSXIdentifier(opts?: Object): boolean; - isJSXMemberExpression(opts?: Object): boolean; - isJSXNamespacedName(opts?: Object): boolean; - isJSXOpeningElement(opts?: Object): boolean; - isJSXSpreadAttribute(opts?: Object): boolean; - isJSXText(opts?: Object): boolean; - isNoop(opts?: Object): boolean; - isParenthesizedExpression(opts?: Object): boolean; - isAwaitExpression(opts?: Object): boolean; - isBindExpression(opts?: Object): boolean; - isDecorator(opts?: Object): boolean; - isDoExpression(opts?: Object): boolean; - isExportDefaultSpecifier(opts?: Object): boolean; - isExportNamespaceSpecifier(opts?: Object): boolean; - isRestProperty(opts?: Object): boolean; - isSpreadProperty(opts?: Object): boolean; - isExpression(opts?: Object): boolean; - isBinary(opts?: Object): boolean; - isScopable(opts?: Object): boolean; - isBlockParent(opts?: Object): boolean; - isBlock(opts?: Object): boolean; - isStatement(opts?: Object): boolean; - isTerminatorless(opts?: Object): boolean; - isCompletionStatement(opts?: Object): boolean; - isConditional(opts?: Object): boolean; - isLoop(opts?: Object): boolean; - isWhile(opts?: Object): boolean; - isExpressionWrapper(opts?: Object): boolean; - isFor(opts?: Object): boolean; - isForXStatement(opts?: Object): boolean; - isFunction(opts?: Object): boolean; - isFunctionParent(opts?: Object): boolean; - isPureish(opts?: Object): boolean; - isDeclaration(opts?: Object): boolean; - isLVal(opts?: Object): boolean; - isLiteral(opts?: Object): boolean; - isImmutable(opts?: Object): boolean; - isUserWhitespacable(opts?: Object): boolean; - isMethod(opts?: Object): boolean; - isObjectMember(opts?: Object): boolean; - isProperty(opts?: Object): boolean; - isUnaryLike(opts?: Object): boolean; - isPattern(opts?: Object): boolean; - isClass(opts?: Object): boolean; - isModuleDeclaration(opts?: Object): boolean; - isExportDeclaration(opts?: Object): boolean; - isModuleSpecifier(opts?: Object): boolean; - isFlow(opts?: Object): boolean; - isFlowBaseAnnotation(opts?: Object): boolean; - isFlowDeclaration(opts?: Object): boolean; - isJSX(opts?: Object): boolean; - isNumberLiteral(opts?: Object): boolean; - isRegexLiteral(opts?: Object): boolean; - isReferencedIdentifier(opts?: Object): boolean; - isReferencedMemberExpression(opts?: Object): boolean; - isBindingIdentifier(opts?: Object): boolean; - isScope(opts?: Object): boolean; - isReferenced(opts?: Object): boolean; - isBlockScoped(opts?: Object): boolean; - isVar(opts?: Object): boolean; - isUser(opts?: Object): boolean; - isGenerated(opts?: Object): boolean; - isPure(opts?: Object): boolean; + isArrayExpression(opts?: object): boolean; + isAssignmentExpression(opts?: object): boolean; + isBinaryExpression(opts?: object): boolean; + isDirective(opts?: object): boolean; + isDirectiveLiteral(opts?: object): boolean; + isBlockStatement(opts?: object): boolean; + isBreakStatement(opts?: object): boolean; + isCallExpression(opts?: object): boolean; + isCatchClause(opts?: object): boolean; + isConditionalExpression(opts?: object): boolean; + isContinueStatement(opts?: object): boolean; + isDebuggerStatement(opts?: object): boolean; + isDoWhileStatement(opts?: object): boolean; + isEmptyStatement(opts?: object): boolean; + isExpressionStatement(opts?: object): boolean; + isFile(opts?: object): boolean; + isForInStatement(opts?: object): boolean; + isForStatement(opts?: object): boolean; + isFunctionDeclaration(opts?: object): boolean; + isFunctionExpression(opts?: object): boolean; + isIdentifier(opts?: object): boolean; + isIfStatement(opts?: object): boolean; + isLabeledStatement(opts?: object): boolean; + isStringLiteral(opts?: object): boolean; + isNumericLiteral(opts?: object): boolean; + isNullLiteral(opts?: object): boolean; + isBooleanLiteral(opts?: object): boolean; + isRegExpLiteral(opts?: object): boolean; + isLogicalExpression(opts?: object): boolean; + isMemberExpression(opts?: object): boolean; + isNewExpression(opts?: object): boolean; + isProgram(opts?: object): boolean; + isObjectExpression(opts?: object): boolean; + isObjectMethod(opts?: object): boolean; + isObjectProperty(opts?: object): boolean; + isRestElement(opts?: object): boolean; + isReturnStatement(opts?: object): boolean; + isSequenceExpression(opts?: object): boolean; + isSwitchCase(opts?: object): boolean; + isSwitchStatement(opts?: object): boolean; + isThisExpression(opts?: object): boolean; + isThrowStatement(opts?: object): boolean; + isTryStatement(opts?: object): boolean; + isUnaryExpression(opts?: object): boolean; + isUpdateExpression(opts?: object): boolean; + isVariableDeclaration(opts?: object): boolean; + isVariableDeclarator(opts?: object): boolean; + isWhileStatement(opts?: object): boolean; + isWithStatement(opts?: object): boolean; + isAssignmentPattern(opts?: object): boolean; + isArrayPattern(opts?: object): boolean; + isArrowFunctionExpression(opts?: object): boolean; + isClassBody(opts?: object): boolean; + isClassDeclaration(opts?: object): boolean; + isClassExpression(opts?: object): boolean; + isExportAllDeclaration(opts?: object): boolean; + isExportDefaultDeclaration(opts?: object): boolean; + isExportNamedDeclaration(opts?: object): boolean; + isExportSpecifier(opts?: object): boolean; + isForOfStatement(opts?: object): boolean; + isImportDeclaration(opts?: object): boolean; + isImportDefaultSpecifier(opts?: object): boolean; + isImportNamespaceSpecifier(opts?: object): boolean; + isImportSpecifier(opts?: object): boolean; + isMetaProperty(opts?: object): boolean; + isClassMethod(opts?: object): boolean; + isObjectPattern(opts?: object): boolean; + isSpreadElement(opts?: object): boolean; + isSuper(opts?: object): boolean; + isTaggedTemplateExpression(opts?: object): boolean; + isTemplateElement(opts?: object): boolean; + isTemplateLiteral(opts?: object): boolean; + isYieldExpression(opts?: object): boolean; + isAnyTypeAnnotation(opts?: object): boolean; + isArrayTypeAnnotation(opts?: object): boolean; + isBooleanTypeAnnotation(opts?: object): boolean; + isBooleanLiteralTypeAnnotation(opts?: object): boolean; + isNullLiteralTypeAnnotation(opts?: object): boolean; + isClassImplements(opts?: object): boolean; + isClassProperty(opts?: object): boolean; + isDeclareClass(opts?: object): boolean; + isDeclareFunction(opts?: object): boolean; + isDeclareInterface(opts?: object): boolean; + isDeclareModule(opts?: object): boolean; + isDeclareTypeAlias(opts?: object): boolean; + isDeclareVariable(opts?: object): boolean; + isExistentialTypeParam(opts?: object): boolean; + isFunctionTypeAnnotation(opts?: object): boolean; + isFunctionTypeParam(opts?: object): boolean; + isGenericTypeAnnotation(opts?: object): boolean; + isInterfaceExtends(opts?: object): boolean; + isInterfaceDeclaration(opts?: object): boolean; + isIntersectionTypeAnnotation(opts?: object): boolean; + isMixedTypeAnnotation(opts?: object): boolean; + isNullableTypeAnnotation(opts?: object): boolean; + isNumericLiteralTypeAnnotation(opts?: object): boolean; + isNumberTypeAnnotation(opts?: object): boolean; + isStringLiteralTypeAnnotation(opts?: object): boolean; + isStringTypeAnnotation(opts?: object): boolean; + isThisTypeAnnotation(opts?: object): boolean; + isTupleTypeAnnotation(opts?: object): boolean; + isTypeofTypeAnnotation(opts?: object): boolean; + isTypeAlias(opts?: object): boolean; + isTypeAnnotation(opts?: object): boolean; + isTypeCastExpression(opts?: object): boolean; + isTypeParameterDeclaration(opts?: object): boolean; + isTypeParameterInstantiation(opts?: object): boolean; + isObjectTypeAnnotation(opts?: object): boolean; + isObjectTypeCallProperty(opts?: object): boolean; + isObjectTypeIndexer(opts?: object): boolean; + isObjectTypeProperty(opts?: object): boolean; + isQualifiedTypeIdentifier(opts?: object): boolean; + isUnionTypeAnnotation(opts?: object): boolean; + isVoidTypeAnnotation(opts?: object): boolean; + isJSXAttribute(opts?: object): boolean; + isJSXClosingElement(opts?: object): boolean; + isJSXElement(opts?: object): boolean; + isJSXEmptyExpression(opts?: object): boolean; + isJSXExpressionContainer(opts?: object): boolean; + isJSXIdentifier(opts?: object): boolean; + isJSXMemberExpression(opts?: object): boolean; + isJSXNamespacedName(opts?: object): boolean; + isJSXOpeningElement(opts?: object): boolean; + isJSXSpreadAttribute(opts?: object): boolean; + isJSXText(opts?: object): boolean; + isNoop(opts?: object): boolean; + isParenthesizedExpression(opts?: object): boolean; + isAwaitExpression(opts?: object): boolean; + isBindExpression(opts?: object): boolean; + isDecorator(opts?: object): boolean; + isDoExpression(opts?: object): boolean; + isExportDefaultSpecifier(opts?: object): boolean; + isExportNamespaceSpecifier(opts?: object): boolean; + isRestProperty(opts?: object): boolean; + isSpreadProperty(opts?: object): boolean; + isExpression(opts?: object): boolean; + isBinary(opts?: object): boolean; + isScopable(opts?: object): boolean; + isBlockParent(opts?: object): boolean; + isBlock(opts?: object): boolean; + isStatement(opts?: object): boolean; + isTerminatorless(opts?: object): boolean; + isCompletionStatement(opts?: object): boolean; + isConditional(opts?: object): boolean; + isLoop(opts?: object): boolean; + isWhile(opts?: object): boolean; + isExpressionWrapper(opts?: object): boolean; + isFor(opts?: object): boolean; + isForXStatement(opts?: object): boolean; + isFunction(opts?: object): boolean; + isFunctionParent(opts?: object): boolean; + isPureish(opts?: object): boolean; + isDeclaration(opts?: object): boolean; + isLVal(opts?: object): boolean; + isLiteral(opts?: object): boolean; + isImmutable(opts?: object): boolean; + isUserWhitespacable(opts?: object): boolean; + isMethod(opts?: object): boolean; + isObjectMember(opts?: object): boolean; + isProperty(opts?: object): boolean; + isUnaryLike(opts?: object): boolean; + isPattern(opts?: object): boolean; + isClass(opts?: object): boolean; + isModuleDeclaration(opts?: object): boolean; + isExportDeclaration(opts?: object): boolean; + isModuleSpecifier(opts?: object): boolean; + isFlow(opts?: object): boolean; + isFlowBaseAnnotation(opts?: object): boolean; + isFlowDeclaration(opts?: object): boolean; + isJSX(opts?: object): boolean; + isNumberLiteral(opts?: object): boolean; + isRegexLiteral(opts?: object): boolean; + isReferencedIdentifier(opts?: object): boolean; + isReferencedMemberExpression(opts?: object): boolean; + isBindingIdentifier(opts?: object): boolean; + isScope(opts?: object): boolean; + isReferenced(opts?: object): boolean; + isBlockScoped(opts?: object): boolean; + isVar(opts?: object): boolean; + isUser(opts?: object): boolean; + isGenerated(opts?: object): boolean; + isPure(opts?: object): boolean; // ------------------------- assertXXX ------------------------- - assertArrayExpression(opts?: Object): void; - assertAssignmentExpression(opts?: Object): void; - assertBinaryExpression(opts?: Object): void; - assertDirective(opts?: Object): void; - assertDirectiveLiteral(opts?: Object): void; - assertBlockStatement(opts?: Object): void; - assertBreakStatement(opts?: Object): void; - assertCallExpression(opts?: Object): void; - assertCatchClause(opts?: Object): void; - assertConditionalExpression(opts?: Object): void; - assertContinueStatement(opts?: Object): void; - assertDebuggerStatement(opts?: Object): void; - assertDoWhileStatement(opts?: Object): void; - assertEmptyStatement(opts?: Object): void; - assertExpressionStatement(opts?: Object): void; - assertFile(opts?: Object): void; - assertForInStatement(opts?: Object): void; - assertForStatement(opts?: Object): void; - assertFunctionDeclaration(opts?: Object): void; - assertFunctionExpression(opts?: Object): void; - assertIdentifier(opts?: Object): void; - assertIfStatement(opts?: Object): void; - assertLabeledStatement(opts?: Object): void; - assertStringLiteral(opts?: Object): void; - assertNumericLiteral(opts?: Object): void; - assertNullLiteral(opts?: Object): void; - assertBooleanLiteral(opts?: Object): void; - assertRegExpLiteral(opts?: Object): void; - assertLogicalExpression(opts?: Object): void; - assertMemberExpression(opts?: Object): void; - assertNewExpression(opts?: Object): void; - assertProgram(opts?: Object): void; - assertObjectExpression(opts?: Object): void; - assertObjectMethod(opts?: Object): void; - assertObjectProperty(opts?: Object): void; - assertRestElement(opts?: Object): void; - assertReturnStatement(opts?: Object): void; - assertSequenceExpression(opts?: Object): void; - assertSwitchCase(opts?: Object): void; - assertSwitchStatement(opts?: Object): void; - assertThisExpression(opts?: Object): void; - assertThrowStatement(opts?: Object): void; - assertTryStatement(opts?: Object): void; - assertUnaryExpression(opts?: Object): void; - assertUpdateExpression(opts?: Object): void; - assertVariableDeclaration(opts?: Object): void; - assertVariableDeclarator(opts?: Object): void; - assertWhileStatement(opts?: Object): void; - assertWithStatement(opts?: Object): void; - assertAssignmentPattern(opts?: Object): void; - assertArrayPattern(opts?: Object): void; - assertArrowFunctionExpression(opts?: Object): void; - assertClassBody(opts?: Object): void; - assertClassDeclaration(opts?: Object): void; - assertClassExpression(opts?: Object): void; - assertExportAllDeclaration(opts?: Object): void; - assertExportDefaultDeclaration(opts?: Object): void; - assertExportNamedDeclaration(opts?: Object): void; - assertExportSpecifier(opts?: Object): void; - assertForOfStatement(opts?: Object): void; - assertImportDeclaration(opts?: Object): void; - assertImportDefaultSpecifier(opts?: Object): void; - assertImportNamespaceSpecifier(opts?: Object): void; - assertImportSpecifier(opts?: Object): void; - assertMetaProperty(opts?: Object): void; - assertClassMethod(opts?: Object): void; - assertObjectPattern(opts?: Object): void; - assertSpreadElement(opts?: Object): void; - assertSuper(opts?: Object): void; - assertTaggedTemplateExpression(opts?: Object): void; - assertTemplateElement(opts?: Object): void; - assertTemplateLiteral(opts?: Object): void; - assertYieldExpression(opts?: Object): void; - assertAnyTypeAnnotation(opts?: Object): void; - assertArrayTypeAnnotation(opts?: Object): void; - assertBooleanTypeAnnotation(opts?: Object): void; - assertBooleanLiteralTypeAnnotation(opts?: Object): void; - assertNullLiteralTypeAnnotation(opts?: Object): void; - assertClassImplements(opts?: Object): void; - assertClassProperty(opts?: Object): void; - assertDeclareClass(opts?: Object): void; - assertDeclareFunction(opts?: Object): void; - assertDeclareInterface(opts?: Object): void; - assertDeclareModule(opts?: Object): void; - assertDeclareTypeAlias(opts?: Object): void; - assertDeclareVariable(opts?: Object): void; - assertExistentialTypeParam(opts?: Object): void; - assertFunctionTypeAnnotation(opts?: Object): void; - assertFunctionTypeParam(opts?: Object): void; - assertGenericTypeAnnotation(opts?: Object): void; - assertInterfaceExtends(opts?: Object): void; - assertInterfaceDeclaration(opts?: Object): void; - assertIntersectionTypeAnnotation(opts?: Object): void; - assertMixedTypeAnnotation(opts?: Object): void; - assertNullableTypeAnnotation(opts?: Object): void; - assertNumericLiteralTypeAnnotation(opts?: Object): void; - assertNumberTypeAnnotation(opts?: Object): void; - assertStringLiteralTypeAnnotation(opts?: Object): void; - assertStringTypeAnnotation(opts?: Object): void; - assertThisTypeAnnotation(opts?: Object): void; - assertTupleTypeAnnotation(opts?: Object): void; - assertTypeofTypeAnnotation(opts?: Object): void; - assertTypeAlias(opts?: Object): void; - assertTypeAnnotation(opts?: Object): void; - assertTypeCastExpression(opts?: Object): void; - assertTypeParameterDeclaration(opts?: Object): void; - assertTypeParameterInstantiation(opts?: Object): void; - assertObjectTypeAnnotation(opts?: Object): void; - assertObjectTypeCallProperty(opts?: Object): void; - assertObjectTypeIndexer(opts?: Object): void; - assertObjectTypeProperty(opts?: Object): void; - assertQualifiedTypeIdentifier(opts?: Object): void; - assertUnionTypeAnnotation(opts?: Object): void; - assertVoidTypeAnnotation(opts?: Object): void; - assertJSXAttribute(opts?: Object): void; - assertJSXClosingElement(opts?: Object): void; - assertJSXElement(opts?: Object): void; - assertJSXEmptyExpression(opts?: Object): void; - assertJSXExpressionContainer(opts?: Object): void; - assertJSXIdentifier(opts?: Object): void; - assertJSXMemberExpression(opts?: Object): void; - assertJSXNamespacedName(opts?: Object): void; - assertJSXOpeningElement(opts?: Object): void; - assertJSXSpreadAttribute(opts?: Object): void; - assertJSXText(opts?: Object): void; - assertNoop(opts?: Object): void; - assertParenthesizedExpression(opts?: Object): void; - assertAwaitExpression(opts?: Object): void; - assertBindExpression(opts?: Object): void; - assertDecorator(opts?: Object): void; - assertDoExpression(opts?: Object): void; - assertExportDefaultSpecifier(opts?: Object): void; - assertExportNamespaceSpecifier(opts?: Object): void; - assertRestProperty(opts?: Object): void; - assertSpreadProperty(opts?: Object): void; - assertExpression(opts?: Object): void; - assertBinary(opts?: Object): void; - assertScopable(opts?: Object): void; - assertBlockParent(opts?: Object): void; - assertBlock(opts?: Object): void; - assertStatement(opts?: Object): void; - assertTerminatorless(opts?: Object): void; - assertCompletionStatement(opts?: Object): void; - assertConditional(opts?: Object): void; - assertLoop(opts?: Object): void; - assertWhile(opts?: Object): void; - assertExpressionWrapper(opts?: Object): void; - assertFor(opts?: Object): void; - assertForXStatement(opts?: Object): void; - assertFunction(opts?: Object): void; - assertFunctionParent(opts?: Object): void; - assertPureish(opts?: Object): void; - assertDeclaration(opts?: Object): void; - assertLVal(opts?: Object): void; - assertLiteral(opts?: Object): void; - assertImmutable(opts?: Object): void; - assertUserWhitespacable(opts?: Object): void; - assertMethod(opts?: Object): void; - assertObjectMember(opts?: Object): void; - assertProperty(opts?: Object): void; - assertUnaryLike(opts?: Object): void; - assertPattern(opts?: Object): void; - assertClass(opts?: Object): void; - assertModuleDeclaration(opts?: Object): void; - assertExportDeclaration(opts?: Object): void; - assertModuleSpecifier(opts?: Object): void; - assertFlow(opts?: Object): void; - assertFlowBaseAnnotation(opts?: Object): void; - assertFlowDeclaration(opts?: Object): void; - assertJSX(opts?: Object): void; - assertNumberLiteral(opts?: Object): void; - assertRegexLiteral(opts?: Object): void; + assertArrayExpression(opts?: object): void; + assertAssignmentExpression(opts?: object): void; + assertBinaryExpression(opts?: object): void; + assertDirective(opts?: object): void; + assertDirectiveLiteral(opts?: object): void; + assertBlockStatement(opts?: object): void; + assertBreakStatement(opts?: object): void; + assertCallExpression(opts?: object): void; + assertCatchClause(opts?: object): void; + assertConditionalExpression(opts?: object): void; + assertContinueStatement(opts?: object): void; + assertDebuggerStatement(opts?: object): void; + assertDoWhileStatement(opts?: object): void; + assertEmptyStatement(opts?: object): void; + assertExpressionStatement(opts?: object): void; + assertFile(opts?: object): void; + assertForInStatement(opts?: object): void; + assertForStatement(opts?: object): void; + assertFunctionDeclaration(opts?: object): void; + assertFunctionExpression(opts?: object): void; + assertIdentifier(opts?: object): void; + assertIfStatement(opts?: object): void; + assertLabeledStatement(opts?: object): void; + assertStringLiteral(opts?: object): void; + assertNumericLiteral(opts?: object): void; + assertNullLiteral(opts?: object): void; + assertBooleanLiteral(opts?: object): void; + assertRegExpLiteral(opts?: object): void; + assertLogicalExpression(opts?: object): void; + assertMemberExpression(opts?: object): void; + assertNewExpression(opts?: object): void; + assertProgram(opts?: object): void; + assertObjectExpression(opts?: object): void; + assertObjectMethod(opts?: object): void; + assertObjectProperty(opts?: object): void; + assertRestElement(opts?: object): void; + assertReturnStatement(opts?: object): void; + assertSequenceExpression(opts?: object): void; + assertSwitchCase(opts?: object): void; + assertSwitchStatement(opts?: object): void; + assertThisExpression(opts?: object): void; + assertThrowStatement(opts?: object): void; + assertTryStatement(opts?: object): void; + assertUnaryExpression(opts?: object): void; + assertUpdateExpression(opts?: object): void; + assertVariableDeclaration(opts?: object): void; + assertVariableDeclarator(opts?: object): void; + assertWhileStatement(opts?: object): void; + assertWithStatement(opts?: object): void; + assertAssignmentPattern(opts?: object): void; + assertArrayPattern(opts?: object): void; + assertArrowFunctionExpression(opts?: object): void; + assertClassBody(opts?: object): void; + assertClassDeclaration(opts?: object): void; + assertClassExpression(opts?: object): void; + assertExportAllDeclaration(opts?: object): void; + assertExportDefaultDeclaration(opts?: object): void; + assertExportNamedDeclaration(opts?: object): void; + assertExportSpecifier(opts?: object): void; + assertForOfStatement(opts?: object): void; + assertImportDeclaration(opts?: object): void; + assertImportDefaultSpecifier(opts?: object): void; + assertImportNamespaceSpecifier(opts?: object): void; + assertImportSpecifier(opts?: object): void; + assertMetaProperty(opts?: object): void; + assertClassMethod(opts?: object): void; + assertObjectPattern(opts?: object): void; + assertSpreadElement(opts?: object): void; + assertSuper(opts?: object): void; + assertTaggedTemplateExpression(opts?: object): void; + assertTemplateElement(opts?: object): void; + assertTemplateLiteral(opts?: object): void; + assertYieldExpression(opts?: object): void; + assertAnyTypeAnnotation(opts?: object): void; + assertArrayTypeAnnotation(opts?: object): void; + assertBooleanTypeAnnotation(opts?: object): void; + assertBooleanLiteralTypeAnnotation(opts?: object): void; + assertNullLiteralTypeAnnotation(opts?: object): void; + assertClassImplements(opts?: object): void; + assertClassProperty(opts?: object): void; + assertDeclareClass(opts?: object): void; + assertDeclareFunction(opts?: object): void; + assertDeclareInterface(opts?: object): void; + assertDeclareModule(opts?: object): void; + assertDeclareTypeAlias(opts?: object): void; + assertDeclareVariable(opts?: object): void; + assertExistentialTypeParam(opts?: object): void; + assertFunctionTypeAnnotation(opts?: object): void; + assertFunctionTypeParam(opts?: object): void; + assertGenericTypeAnnotation(opts?: object): void; + assertInterfaceExtends(opts?: object): void; + assertInterfaceDeclaration(opts?: object): void; + assertIntersectionTypeAnnotation(opts?: object): void; + assertMixedTypeAnnotation(opts?: object): void; + assertNullableTypeAnnotation(opts?: object): void; + assertNumericLiteralTypeAnnotation(opts?: object): void; + assertNumberTypeAnnotation(opts?: object): void; + assertStringLiteralTypeAnnotation(opts?: object): void; + assertStringTypeAnnotation(opts?: object): void; + assertThisTypeAnnotation(opts?: object): void; + assertTupleTypeAnnotation(opts?: object): void; + assertTypeofTypeAnnotation(opts?: object): void; + assertTypeAlias(opts?: object): void; + assertTypeAnnotation(opts?: object): void; + assertTypeCastExpression(opts?: object): void; + assertTypeParameterDeclaration(opts?: object): void; + assertTypeParameterInstantiation(opts?: object): void; + assertObjectTypeAnnotation(opts?: object): void; + assertObjectTypeCallProperty(opts?: object): void; + assertObjectTypeIndexer(opts?: object): void; + assertObjectTypeProperty(opts?: object): void; + assertQualifiedTypeIdentifier(opts?: object): void; + assertUnionTypeAnnotation(opts?: object): void; + assertVoidTypeAnnotation(opts?: object): void; + assertJSXAttribute(opts?: object): void; + assertJSXClosingElement(opts?: object): void; + assertJSXElement(opts?: object): void; + assertJSXEmptyExpression(opts?: object): void; + assertJSXExpressionContainer(opts?: object): void; + assertJSXIdentifier(opts?: object): void; + assertJSXMemberExpression(opts?: object): void; + assertJSXNamespacedName(opts?: object): void; + assertJSXOpeningElement(opts?: object): void; + assertJSXSpreadAttribute(opts?: object): void; + assertJSXText(opts?: object): void; + assertNoop(opts?: object): void; + assertParenthesizedExpression(opts?: object): void; + assertAwaitExpression(opts?: object): void; + assertBindExpression(opts?: object): void; + assertDecorator(opts?: object): void; + assertDoExpression(opts?: object): void; + assertExportDefaultSpecifier(opts?: object): void; + assertExportNamespaceSpecifier(opts?: object): void; + assertRestProperty(opts?: object): void; + assertSpreadProperty(opts?: object): void; + assertExpression(opts?: object): void; + assertBinary(opts?: object): void; + assertScopable(opts?: object): void; + assertBlockParent(opts?: object): void; + assertBlock(opts?: object): void; + assertStatement(opts?: object): void; + assertTerminatorless(opts?: object): void; + assertCompletionStatement(opts?: object): void; + assertConditional(opts?: object): void; + assertLoop(opts?: object): void; + assertWhile(opts?: object): void; + assertExpressionWrapper(opts?: object): void; + assertFor(opts?: object): void; + assertForXStatement(opts?: object): void; + assertFunction(opts?: object): void; + assertFunctionParent(opts?: object): void; + assertPureish(opts?: object): void; + assertDeclaration(opts?: object): void; + assertLVal(opts?: object): void; + assertLiteral(opts?: object): void; + assertImmutable(opts?: object): void; + assertUserWhitespacable(opts?: object): void; + assertMethod(opts?: object): void; + assertObjectMember(opts?: object): void; + assertProperty(opts?: object): void; + assertUnaryLike(opts?: object): void; + assertPattern(opts?: object): void; + assertClass(opts?: object): void; + assertModuleDeclaration(opts?: object): void; + assertExportDeclaration(opts?: object): void; + assertModuleSpecifier(opts?: object): void; + assertFlow(opts?: object): void; + assertFlowBaseAnnotation(opts?: object): void; + assertFlowDeclaration(opts?: object): void; + assertJSX(opts?: object): void; + assertNumberLiteral(opts?: object): void; + assertRegexLiteral(opts?: object): void; } export class Hub { @@ -958,7 +959,7 @@ export class Hub { options: any; } -interface TraversalContext { +export interface TraversalContext { parentPath: NodePath; scope: Scope; state: any; diff --git a/types/babel-traverse/tslint.json b/types/babel-traverse/tslint.json new file mode 100644 index 0000000000..3db14f85ea --- /dev/null +++ b/types/babel-traverse/tslint.json @@ -0,0 +1 @@ +{ "extends": "dtslint/dt.json" } diff --git a/types/babel-types/babel-types-tests.ts b/types/babel-types/babel-types-tests.ts index 394603ab31..0ef79f39f4 100644 --- a/types/babel-types/babel-types-tests.ts +++ b/types/babel-types/babel-types-tests.ts @@ -1,7 +1,3 @@ - -/// - - // Examples from https://github.com/thejameskyle/babel-handbook/blob/master/translations/en/plugin-handbook.md#babel-types import traverse from "babel-traverse"; import * as t from "babel-types"; @@ -25,13 +21,13 @@ if (t.isBinaryExpression(ast)) { ast.right; ast.operator; } + t.assertBinaryExpression(ast); t.assertBinaryExpression(ast, { operator: "*" }); -var exp: t.Expression = t.nullLiteral(); +const exp: t.Expression = t.nullLiteral(); // React examples: - // https://github.com/babel/babel/blob/4e50b2d9d9c376cee7a2cbf56553fe5b982ea53c/packages/babel-plugin-transform-react-inline-elements/src/index.js#L61 traverse(ast, { JSXElement(path, file) { diff --git a/types/babel-types/index.d.ts b/types/babel-types/index.d.ts index c3f77b559f..1879c81e85 100644 --- a/types/babel-types/index.d.ts +++ b/types/babel-types/index.d.ts @@ -1,9 +1,10 @@ -// Type definitions for babel-types v6.25 +// Type definitions for babel-types 6.25 // Project: https://github.com/babel/babel/tree/master/packages/babel-types // Definitions by: Troy Gerwien // Sam Baxter // Marvin Hagemeister // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.3 export interface Comment { value: string; @@ -34,9 +35,9 @@ export interface SourceLocation { export interface Node { type: string; - leadingComments?: Array; - innerComments?: Array; - trailingComments?: Array; + leadingComments?: Comment[]; + innerComments?: Comment[]; + trailingComments?: Comment[]; start: number; end: number; loc: SourceLocation; @@ -150,7 +151,7 @@ export interface ForStatement extends Node { export interface FunctionDeclaration extends Node { type: "FunctionDeclaration"; id: Identifier; - params: Array; + params: LVal[]; body: BlockStatement; generator: boolean; async: boolean; @@ -161,7 +162,7 @@ export interface FunctionDeclaration extends Node { export interface FunctionExpression extends Node { type: "FunctionExpression"; id: Identifier; - params: Array; + params: LVal[]; body: BlockStatement; generator: boolean; async: boolean; @@ -254,7 +255,7 @@ export interface ObjectMethod extends Node { value: Expression; decorators?: Decorator[]; id: Identifier; - params: Array; + params: LVal[]; body: BlockStatement; generator: boolean; async: boolean; @@ -361,14 +362,14 @@ export interface AssignmentPattern extends Node { export interface ArrayPattern extends Node { type: "ArrayPattern"; - elements: Array; + elements: Expression[]; typeAnnotation?: TypeAnnotation; } export interface ArrowFunctionExpression extends Node { type: "ArrowFunctionExpression"; id: Identifier; - params: Array; + params: LVal[]; body: BlockStatement | Expression; generator: boolean; async: boolean; @@ -474,7 +475,7 @@ export interface ClassMethod extends Node { static: boolean; decorators?: Decorator[]; id: Identifier; - params: Array; + params: LVal[]; body: BlockStatement; generator: boolean; async: boolean; @@ -872,12 +873,33 @@ export interface SpreadProperty extends Node { argument: Expression; } -export type Expression = ArrayExpression | AssignmentExpression | BinaryExpression | CallExpression | ConditionalExpression | FunctionExpression | Identifier | StringLiteral | NumericLiteral | BooleanLiteral | NullLiteral | RegExpLiteral | LogicalExpression | MemberExpression | NewExpression | ObjectExpression | SequenceExpression | ThisExpression | UnaryExpression | UpdateExpression | ArrowFunctionExpression | ClassExpression | MetaProperty | Super | TaggedTemplateExpression | TemplateLiteral | YieldExpression | TypeCastExpression | JSXElement | JSXEmptyExpression | JSXIdentifier | JSXMemberExpression | ParenthesizedExpression | AwaitExpression | BindExpression | DoExpression; +export type Expression = ArrayExpression | AssignmentExpression | BinaryExpression | CallExpression + | ConditionalExpression | FunctionExpression | Identifier | StringLiteral | NumericLiteral | BooleanLiteral + | NullLiteral | RegExpLiteral | LogicalExpression | MemberExpression | NewExpression | ObjectExpression + | SequenceExpression | ThisExpression | UnaryExpression | UpdateExpression | ArrowFunctionExpression + | ClassExpression | MetaProperty | Super | TaggedTemplateExpression | TemplateLiteral | YieldExpression + | TypeCastExpression | JSXElement | JSXEmptyExpression | JSXIdentifier | JSXMemberExpression + | ParenthesizedExpression | AwaitExpression | BindExpression | DoExpression; + export type Binary = BinaryExpression | LogicalExpression; -export type Scopable = BlockStatement | CatchClause | DoWhileStatement | ForInStatement | ForStatement | FunctionDeclaration | FunctionExpression | Program | ObjectMethod | SwitchStatement | WhileStatement | ArrowFunctionExpression | ClassDeclaration | ClassExpression | ForOfStatement | ClassMethod; -export type BlockParent = BlockStatement | DoWhileStatement | ForInStatement | ForStatement | FunctionDeclaration | FunctionExpression | Program | ObjectMethod | SwitchStatement | WhileStatement | ArrowFunctionExpression | ForOfStatement | ClassMethod; + +export type Scopable = BlockStatement | CatchClause | DoWhileStatement | ForInStatement | ForStatement + | FunctionDeclaration | FunctionExpression | Program | ObjectMethod | SwitchStatement | WhileStatement + | ArrowFunctionExpression | ClassDeclaration | ClassExpression | ForOfStatement | ClassMethod; + +export type BlockParent = BlockStatement | DoWhileStatement | ForInStatement | ForStatement | FunctionDeclaration + | FunctionExpression | Program | ObjectMethod | SwitchStatement | WhileStatement | ArrowFunctionExpression + | ForOfStatement | ClassMethod; + export type Block = BlockStatement | Program; -export type Statement = BlockStatement | BreakStatement | ContinueStatement | DebuggerStatement | DoWhileStatement | EmptyStatement | ExpressionStatement | ForInStatement | ForStatement | FunctionDeclaration | IfStatement | LabeledStatement | ReturnStatement | SwitchStatement | ThrowStatement | TryStatement | VariableDeclaration | WhileStatement | WithStatement | ClassDeclaration | ExportAllDeclaration | ExportDefaultDeclaration | ExportNamedDeclaration | ForOfStatement | ImportDeclaration | DeclareClass | DeclareFunction | DeclareInterface | DeclareModule | DeclareTypeAlias | DeclareVariable | InterfaceDeclaration | TypeAlias; + +export type Statement = BlockStatement | BreakStatement | ContinueStatement | DebuggerStatement | DoWhileStatement + | EmptyStatement | ExpressionStatement | ForInStatement | ForStatement | FunctionDeclaration | IfStatement + | LabeledStatement | ReturnStatement | SwitchStatement | ThrowStatement | TryStatement | VariableDeclaration + | WhileStatement | WithStatement | ClassDeclaration | ExportAllDeclaration | ExportDefaultDeclaration + | ExportNamedDeclaration | ForOfStatement | ImportDeclaration | DeclareClass | DeclareFunction | DeclareInterface + | DeclareModule | DeclareTypeAlias | DeclareVariable | InterfaceDeclaration | TypeAlias; + export type Terminatorless = BreakStatement | ContinueStatement | ReturnStatement | ThrowStatement | YieldExpression | AwaitExpression; export type CompletionStatement = BreakStatement | ContinueStatement | ReturnStatement | ThrowStatement; export type Conditional = ConditionalExpression | IfStatement; @@ -889,7 +911,11 @@ export type ForXStatement = ForInStatement | ForOfStatement; export type Function = FunctionDeclaration | FunctionExpression | ObjectMethod | ArrowFunctionExpression | ClassMethod; export type FunctionParent = FunctionDeclaration | FunctionExpression | Program | ObjectMethod | ArrowFunctionExpression | ClassMethod; export type Pureish = FunctionDeclaration | FunctionExpression | StringLiteral | NumericLiteral | BooleanLiteral | NullLiteral | ArrowFunctionExpression | ClassDeclaration | ClassExpression; -export type Declaration = FunctionDeclaration | VariableDeclaration | ClassDeclaration | ExportAllDeclaration | ExportDefaultDeclaration | ExportNamedDeclaration | ImportDeclaration | DeclareClass | DeclareFunction | DeclareInterface | DeclareModule | DeclareTypeAlias | DeclareVariable | InterfaceDeclaration | TypeAlias; + +export type Declaration = FunctionDeclaration | VariableDeclaration | ClassDeclaration | ExportAllDeclaration + | ExportDefaultDeclaration | ExportNamedDeclaration | ImportDeclaration | DeclareClass | DeclareFunction + | DeclareInterface | DeclareModule | DeclareTypeAlias | DeclareVariable | InterfaceDeclaration | TypeAlias; + export type LVal = Identifier | MemberExpression | RestElement | AssignmentPattern | ArrayPattern | ObjectPattern; export type Literal = StringLiteral | NumericLiteral | BooleanLiteral | NullLiteral | RegExpLiteral | TemplateLiteral; export type Immutable = StringLiteral | NumericLiteral | BooleanLiteral | NullLiteral | JSXAttribute | JSXClosingElement | JSXElement | JSXExpressionContainer | JSXOpeningElement; @@ -903,15 +929,36 @@ export type Class = ClassDeclaration | ClassExpression; export type ModuleDeclaration = ExportAllDeclaration | ExportDefaultDeclaration | ExportNamedDeclaration | ImportDeclaration; export type ExportDeclaration = ExportAllDeclaration | ExportDefaultDeclaration | ExportNamedDeclaration; export type ModuleSpecifier = ExportSpecifier | ImportDefaultSpecifier | ImportNamespaceSpecifier | ImportSpecifier | ExportDefaultSpecifier | ExportNamespaceSpecifier; -export type Flow = AnyTypeAnnotation | ArrayTypeAnnotation | BooleanTypeAnnotation | BooleanLiteralTypeAnnotation | ClassImplements | ClassProperty | DeclareClass | DeclareFunction | DeclareInterface | DeclareModule | DeclareTypeAlias | DeclareVariable | ExistentialTypeParam | FunctionTypeAnnotation | FunctionTypeParam | GenericTypeAnnotation | InterfaceExtends | InterfaceDeclaration | IntersectionTypeAnnotation | MixedTypeAnnotation | NullableTypeAnnotation | NumericLiteralTypeAnnotation | NumberTypeAnnotation | StringLiteralTypeAnnotation | StringTypeAnnotation | ThisTypeAnnotation | TupleTypeAnnotation | TypeofTypeAnnotation | TypeAlias | TypeAnnotation | TypeCastExpression | TypeParameterDeclaration | TypeParameterInstantiation | ObjectTypeAnnotation | ObjectTypeCallProperty | ObjectTypeIndexer | ObjectTypeProperty | QualifiedTypeIdentifier | UnionTypeAnnotation | VoidTypeAnnotation; -export type FlowTypeAnnotation = AnyTypeAnnotation | ArrayTypeAnnotation | BooleanTypeAnnotation | BooleanLiteralTypeAnnotation | FunctionTypeAnnotation | GenericTypeAnnotation | IntersectionTypeAnnotation | MixedTypeAnnotation | NullableTypeAnnotation | NumericLiteralTypeAnnotation | NumberTypeAnnotation | StringLiteralTypeAnnotation | StringTypeAnnotation | ThisTypeAnnotation | TupleTypeAnnotation | TypeofTypeAnnotation | TypeAnnotation | ObjectTypeAnnotation | UnionTypeAnnotation | VoidTypeAnnotation; + +export type Flow = AnyTypeAnnotation | ArrayTypeAnnotation | BooleanTypeAnnotation | BooleanLiteralTypeAnnotation + | ClassImplements | ClassProperty | DeclareClass | DeclareFunction | DeclareInterface | DeclareModule + | DeclareTypeAlias | DeclareVariable | ExistentialTypeParam | FunctionTypeAnnotation | FunctionTypeParam + | GenericTypeAnnotation | InterfaceExtends | InterfaceDeclaration | IntersectionTypeAnnotation + | MixedTypeAnnotation | NullableTypeAnnotation | NumericLiteralTypeAnnotation | NumberTypeAnnotation + | StringLiteralTypeAnnotation | StringTypeAnnotation | ThisTypeAnnotation | TupleTypeAnnotation + | TypeofTypeAnnotation | TypeAlias | TypeAnnotation | TypeCastExpression | TypeParameterDeclaration + | TypeParameterInstantiation | ObjectTypeAnnotation | ObjectTypeCallProperty | ObjectTypeIndexer + | ObjectTypeProperty | QualifiedTypeIdentifier | UnionTypeAnnotation | VoidTypeAnnotation; + +export type FlowTypeAnnotation = AnyTypeAnnotation | ArrayTypeAnnotation | BooleanTypeAnnotation + | BooleanLiteralTypeAnnotation | FunctionTypeAnnotation | GenericTypeAnnotation | IntersectionTypeAnnotation + | MixedTypeAnnotation | NullableTypeAnnotation | NumericLiteralTypeAnnotation | NumberTypeAnnotation + | StringLiteralTypeAnnotation | StringTypeAnnotation | ThisTypeAnnotation | TupleTypeAnnotation + | TypeofTypeAnnotation | TypeAnnotation | ObjectTypeAnnotation | UnionTypeAnnotation | VoidTypeAnnotation; + export type FlowBaseAnnotation = AnyTypeAnnotation | BooleanTypeAnnotation | MixedTypeAnnotation | NumberTypeAnnotation | StringTypeAnnotation | ThisTypeAnnotation | VoidTypeAnnotation; export type FlowDeclaration = DeclareClass | DeclareFunction | DeclareInterface | DeclareModule | DeclareTypeAlias | DeclareVariable | InterfaceDeclaration | TypeAlias; -export type JSX = JSXAttribute | JSXClosingElement | JSXElement | JSXEmptyExpression | JSXExpressionContainer | JSXIdentifier | JSXMemberExpression | JSXNamespacedName | JSXOpeningElement | JSXSpreadAttribute | JSXText; + +export type JSX = JSXAttribute | JSXClosingElement | JSXElement | JSXEmptyExpression | JSXExpressionContainer + | JSXIdentifier | JSXMemberExpression | JSXNamespacedName | JSXOpeningElement | JSXSpreadAttribute | JSXText; export function arrayExpression(elements?: Array): ArrayExpression; export function assignmentExpression(operator?: string, left?: LVal, right?: Expression): AssignmentExpression; -export function binaryExpression(operator?: "+" | "-" | "/" | "%" | "*" | "**" | "&" | "|" | ">>" | ">>>" | "<<" | "^" | "==" | "===" | "!=" | "!==" | "in" | "instanceof" | ">" | "<" | ">=" | "<=", left?: Expression, right?: Expression): BinaryExpression; +export function binaryExpression( + operator?: "+" | "-" | "/" | "%" | "*" | "**" | "&" | "|" | ">>" | ">>>" | "<<" | "^" | "==" | "===" | "!=" | "!==" | "in" | "instanceof" | ">" | "<" | ">=" | "<=", + left?: Expression, + right?: Expression +): BinaryExpression; export function directive(value?: DirectiveLiteral): Directive; export function directiveLiteral(value?: string): DirectiveLiteral; export function blockStatement(body?: Statement[], directives?: Directive[]): BlockStatement; @@ -927,8 +974,8 @@ export function expressionStatement(expression?: Expression): ExpressionStatemen export function file(program?: Program, comments?: Comment[], tokens?: any[]): File; export function forInStatement(left?: VariableDeclaration | LVal, right?: Expression, body?: Statement): ForInStatement; export function forStatement(init?: VariableDeclaration | Expression, test?: Expression, update?: Expression, body?: Statement): ForStatement; -export function functionDeclaration(id?: Identifier, params?: Array, body?: BlockStatement, generator?: boolean, async?: boolean): FunctionDeclaration; -export function functionExpression(id?: Identifier, params?: Array, body?: BlockStatement, generator?: boolean, async?: boolean): FunctionExpression; +export function functionDeclaration(id?: Identifier, params?: LVal[], body?: BlockStatement, generator?: boolean, async?: boolean): FunctionDeclaration; +export function functionExpression(id?: Identifier, params?: LVal[], body?: BlockStatement, generator?: boolean, async?: boolean): FunctionExpression; export function identifier(name?: string): Identifier; export function ifStatement(test?: Expression, consequent?: Statement, alternate?: Statement): IfStatement; export function labeledStatement(label?: Identifier, body?: Statement): LabeledStatement; @@ -942,7 +989,7 @@ export function memberExpression(object?: Expression | Super, property?: Express export function newExpression(callee?: Expression | Super, _arguments?: Array): NewExpression; export function program(body?: Array, directives?: Directive[]): Program; export function objectExpression(properties?: Array): ObjectExpression; -export function objectMethod(kind?: "get" | "set" | "method", key?: Expression, params?: Array, body?: BlockStatement, computed?: boolean): ObjectMethod; +export function objectMethod(kind?: "get" | "set" | "method", key?: Expression, params?: LVal[], body?: BlockStatement, computed?: boolean): ObjectMethod; export function objectProperty(key?: Expression, value?: Expression, computed?: boolean, shorthand?: boolean, decorators?: Decorator[]): ObjectProperty; export function restElement(argument?: LVal, typeAnnotation?: TypeAnnotation): RestElement; export function returnStatement(argument?: Expression): ReturnStatement; @@ -959,8 +1006,8 @@ export function variableDeclarator(id?: LVal, init?: Expression): VariableDeclar export function whileStatement(test?: Expression, body?: BlockStatement | Statement): WhileStatement; export function withStatement(object?: Expression, body?: BlockStatement | Statement): WithStatement; export function assignmentPattern(left?: Identifier, right?: Expression): AssignmentPattern; -export function arrayPattern(elements?: Array, typeAnnotation?: TypeAnnotation): ArrayPattern; -export function arrowFunctionExpression(params?: Array, body?: BlockStatement | Expression, async?: boolean): ArrowFunctionExpression; +export function arrayPattern(elements?: Expression[], typeAnnotation?: TypeAnnotation): ArrayPattern; +export function arrowFunctionExpression(params?: LVal[], body?: BlockStatement | Expression, async?: boolean): ArrowFunctionExpression; export function classBody(body?: Array): ClassBody; export function classDeclaration(id?: Identifier, superClass?: Expression, body?: ClassBody, decorators?: Decorator[]): ClassDeclaration; export function classExpression(id?: Identifier, superClass?: Expression, body?: ClassBody, decorators?: Decorator[]): ClassExpression; @@ -974,11 +1021,11 @@ export function importDefaultSpecifier(local?: Identifier): ImportDefaultSpecifi export function importNamespaceSpecifier(local?: Identifier): ImportNamespaceSpecifier; export function importSpecifier(local?: Identifier, imported?: Identifier): ImportSpecifier; export function metaProperty(meta?: string, property?: string): MetaProperty; -export function classMethod(kind?: "constructor" | "method" | "get" | "set", key?: Expression, params?: Array, body?: BlockStatement, computed?: boolean, _static?: boolean): ClassMethod; +export function classMethod(kind?: "constructor" | "method" | "get" | "set", key?: Expression, params?: LVal[], body?: BlockStatement, computed?: boolean, _static?: boolean): ClassMethod; export function objectPattern(properties?: Array, typeAnnotation?: TypeAnnotation): ObjectPattern; export function spreadElement(argument?: Expression): SpreadElement; export function taggedTemplateExpression(tag?: Expression, quasi?: TemplateLiteral): TaggedTemplateExpression; -export function templateElement(value?: {cooked?: string; raw?: string;}, tail?: boolean): TemplateElement; +export function templateElement(value?: { cooked?: string; raw?: string; }, tail?: boolean): TemplateElement; export function templateLiteral(quasis?: TemplateElement[], expressions?: Expression[]): TemplateLiteral; export function yieldExpression(argument?: Expression, delegate?: boolean): YieldExpression; export function anyTypeAnnotation(): AnyTypeAnnotation; @@ -1044,367 +1091,367 @@ export function exportNamespaceSpecifier(exported?: Identifier): ExportNamespace export function restProperty(argument?: LVal): RestProperty; export function spreadProperty(argument?: Expression): SpreadProperty; -export function isArrayExpression(node: Object, opts?: Object): node is ArrayExpression; -export function isAssignmentExpression(node: Object, opts?: Object): node is AssignmentExpression; -export function isBinaryExpression(node: Object, opts?: Object): node is BinaryExpression; -export function isDirective(node: Object, opts?: Object): node is Directive; -export function isDirectiveLiteral(node: Object, opts?: Object): node is DirectiveLiteral; -export function isBlockStatement(node: Object, opts?: Object): node is BlockStatement; -export function isBreakStatement(node: Object, opts?: Object): node is BreakStatement; -export function isCallExpression(node: Object, opts?: Object): node is CallExpression; -export function isCatchClause(node: Object, opts?: Object): node is CatchClause; -export function isConditionalExpression(node: Object, opts?: Object): node is ConditionalExpression; -export function isContinueStatement(node: Object, opts?: Object): node is ContinueStatement; -export function isDebuggerStatement(node: Object, opts?: Object): node is DebuggerStatement; -export function isDoWhileStatement(node: Object, opts?: Object): node is DoWhileStatement; -export function isEmptyStatement(node: Object, opts?: Object): node is EmptyStatement; -export function isExpressionStatement(node: Object, opts?: Object): node is ExpressionStatement; -export function isFile(node: Object, opts?: Object): node is File; -export function isForInStatement(node: Object, opts?: Object): node is ForInStatement; -export function isForStatement(node: Object, opts?: Object): node is ForStatement; -export function isFunctionDeclaration(node: Object, opts?: Object): node is FunctionDeclaration; -export function isFunctionExpression(node: Object, opts?: Object): node is FunctionExpression; -export function isIdentifier(node: Object, opts?: Object): node is Identifier; -export function isIfStatement(node: Object, opts?: Object): node is IfStatement; -export function isLabeledStatement(node: Object, opts?: Object): node is LabeledStatement; -export function isStringLiteral(node: Object, opts?: Object): node is StringLiteral; -export function isNumericLiteral(node: Object, opts?: Object): node is NumericLiteral; -export function isNullLiteral(node: Object, opts?: Object): node is NullLiteral; -export function isBooleanLiteral(node: Object, opts?: Object): node is BooleanLiteral; -export function isRegExpLiteral(node: Object, opts?: Object): node is RegExpLiteral; -export function isLogicalExpression(node: Object, opts?: Object): node is LogicalExpression; -export function isMemberExpression(node: Object, opts?: Object): node is MemberExpression; -export function isNewExpression(node: Object, opts?: Object): node is NewExpression; -export function isProgram(node: Object, opts?: Object): node is Program; -export function isObjectExpression(node: Object, opts?: Object): node is ObjectExpression; -export function isObjectMethod(node: Object, opts?: Object): node is ObjectMethod; -export function isObjectProperty(node: Object, opts?: Object): node is ObjectProperty; -export function isRestElement(node: Object, opts?: Object): node is RestElement; -export function isReturnStatement(node: Object, opts?: Object): node is ReturnStatement; -export function isSequenceExpression(node: Object, opts?: Object): node is SequenceExpression; -export function isSwitchCase(node: Object, opts?: Object): node is SwitchCase; -export function isSwitchStatement(node: Object, opts?: Object): node is SwitchStatement; -export function isThisExpression(node: Object, opts?: Object): node is ThisExpression; -export function isThrowStatement(node: Object, opts?: Object): node is ThrowStatement; -export function isTryStatement(node: Object, opts?: Object): node is TryStatement; -export function isUnaryExpression(node: Object, opts?: Object): node is UnaryExpression; -export function isUpdateExpression(node: Object, opts?: Object): node is UpdateExpression; -export function isVariableDeclaration(node: Object, opts?: Object): node is VariableDeclaration; -export function isVariableDeclarator(node: Object, opts?: Object): node is VariableDeclarator; -export function isWhileStatement(node: Object, opts?: Object): node is WhileStatement; -export function isWithStatement(node: Object, opts?: Object): node is WithStatement; -export function isAssignmentPattern(node: Object, opts?: Object): node is AssignmentPattern; -export function isArrayPattern(node: Object, opts?: Object): node is ArrayPattern; -export function isArrowFunctionExpression(node: Object, opts?: Object): node is ArrowFunctionExpression; -export function isClassBody(node: Object, opts?: Object): node is ClassBody; -export function isClassDeclaration(node: Object, opts?: Object): node is ClassDeclaration; -export function isClassExpression(node: Object, opts?: Object): node is ClassExpression; -export function isExportAllDeclaration(node: Object, opts?: Object): node is ExportAllDeclaration; -export function isExportDefaultDeclaration(node: Object, opts?: Object): node is ExportDefaultDeclaration; -export function isExportNamedDeclaration(node: Object, opts?: Object): node is ExportNamedDeclaration; -export function isExportSpecifier(node: Object, opts?: Object): node is ExportSpecifier; -export function isForOfStatement(node: Object, opts?: Object): node is ForOfStatement; -export function isImportDeclaration(node: Object, opts?: Object): node is ImportDeclaration; -export function isImportDefaultSpecifier(node: Object, opts?: Object): node is ImportDefaultSpecifier; -export function isImportNamespaceSpecifier(node: Object, opts?: Object): node is ImportNamespaceSpecifier; -export function isImportSpecifier(node: Object, opts?: Object): node is ImportSpecifier; -export function isMetaProperty(node: Object, opts?: Object): node is MetaProperty; -export function isClassMethod(node: Object, opts?: Object): node is ClassMethod; -export function isObjectPattern(node: Object, opts?: Object): node is ObjectPattern; -export function isSpreadElement(node: Object, opts?: Object): node is SpreadElement; -export function isSuper(node: Object, opts?: Object): node is Super; -export function isTaggedTemplateExpression(node: Object, opts?: Object): node is TaggedTemplateExpression; -export function isTemplateElement(node: Object, opts?: Object): node is TemplateElement; -export function isTemplateLiteral(node: Object, opts?: Object): node is TemplateLiteral; -export function isYieldExpression(node: Object, opts?: Object): node is YieldExpression; -export function isAnyTypeAnnotation(node: Object, opts?: Object): node is AnyTypeAnnotation; -export function isArrayTypeAnnotation(node: Object, opts?: Object): node is ArrayTypeAnnotation; -export function isBooleanTypeAnnotation(node: Object, opts?: Object): node is BooleanTypeAnnotation; -export function isBooleanLiteralTypeAnnotation(node: Object, opts?: Object): node is BooleanLiteralTypeAnnotation; -export function isNullLiteralTypeAnnotation(node: Object, opts?: Object): node is NullLiteralTypeAnnotation; -export function isClassImplements(node: Object, opts?: Object): node is ClassImplements; -export function isClassProperty(node: Object, opts?: Object): node is ClassProperty; -export function isDeclareClass(node: Object, opts?: Object): node is DeclareClass; -export function isDeclareFunction(node: Object, opts?: Object): node is DeclareFunction; -export function isDeclareInterface(node: Object, opts?: Object): node is DeclareInterface; -export function isDeclareModule(node: Object, opts?: Object): node is DeclareModule; -export function isDeclareTypeAlias(node: Object, opts?: Object): node is DeclareTypeAlias; -export function isDeclareVariable(node: Object, opts?: Object): node is DeclareVariable; -export function isExistentialTypeParam(node: Object, opts?: Object): node is ExistentialTypeParam; -export function isFunctionTypeAnnotation(node: Object, opts?: Object): node is FunctionTypeAnnotation; -export function isFunctionTypeParam(node: Object, opts?: Object): node is FunctionTypeParam; -export function isGenericTypeAnnotation(node: Object, opts?: Object): node is GenericTypeAnnotation; -export function isInterfaceExtends(node: Object, opts?: Object): node is InterfaceExtends; -export function isInterfaceDeclaration(node: Object, opts?: Object): node is InterfaceDeclaration; -export function isIntersectionTypeAnnotation(node: Object, opts?: Object): node is IntersectionTypeAnnotation; -export function isMixedTypeAnnotation(node: Object, opts?: Object): node is MixedTypeAnnotation; -export function isNullableTypeAnnotation(node: Object, opts?: Object): node is NullableTypeAnnotation; -export function isNumericLiteralTypeAnnotation(node: Object, opts?: Object): node is NumericLiteralTypeAnnotation; -export function isNumberTypeAnnotation(node: Object, opts?: Object): node is NumberTypeAnnotation; -export function isStringLiteralTypeAnnotation(node: Object, opts?: Object): node is StringLiteralTypeAnnotation; -export function isStringTypeAnnotation(node: Object, opts?: Object): node is StringTypeAnnotation; -export function isThisTypeAnnotation(node: Object, opts?: Object): node is ThisTypeAnnotation; -export function isTupleTypeAnnotation(node: Object, opts?: Object): node is TupleTypeAnnotation; -export function isTypeofTypeAnnotation(node: Object, opts?: Object): node is TypeofTypeAnnotation; -export function isTypeAlias(node: Object, opts?: Object): node is TypeAlias; -export function isTypeAnnotation(node: Object, opts?: Object): node is TypeAnnotation; -export function isTypeCastExpression(node: Object, opts?: Object): node is TypeCastExpression; -export function isTypeParameterDeclaration(node: Object, opts?: Object): node is TypeParameterDeclaration; -export function isTypeParameterInstantiation(node: Object, opts?: Object): node is TypeParameterInstantiation; -export function isObjectTypeAnnotation(node: Object, opts?: Object): node is ObjectTypeAnnotation; -export function isObjectTypeCallProperty(node: Object, opts?: Object): node is ObjectTypeCallProperty; -export function isObjectTypeIndexer(node: Object, opts?: Object): node is ObjectTypeIndexer; -export function isObjectTypeProperty(node: Object, opts?: Object): node is ObjectTypeProperty; -export function isQualifiedTypeIdentifier(node: Object, opts?: Object): node is QualifiedTypeIdentifier; -export function isUnionTypeAnnotation(node: Object, opts?: Object): node is UnionTypeAnnotation; -export function isVoidTypeAnnotation(node: Object, opts?: Object): node is VoidTypeAnnotation; -export function isJSXAttribute(node: Object, opts?: Object): node is JSXAttribute; -export function isJSXClosingElement(node: Object, opts?: Object): node is JSXClosingElement; -export function isJSXElement(node: Object, opts?: Object): node is JSXElement; -export function isJSXEmptyExpression(node: Object, opts?: Object): node is JSXEmptyExpression; -export function isJSXExpressionContainer(node: Object, opts?: Object): node is JSXExpressionContainer; -export function isJSXIdentifier(node: Object, opts?: Object): node is JSXIdentifier; -export function isJSXMemberExpression(node: Object, opts?: Object): node is JSXMemberExpression; -export function isJSXNamespacedName(node: Object, opts?: Object): node is JSXNamespacedName; -export function isJSXOpeningElement(node: Object, opts?: Object): node is JSXOpeningElement; -export function isJSXSpreadAttribute(node: Object, opts?: Object): node is JSXSpreadAttribute; -export function isJSXText(node: Object, opts?: Object): node is JSXText; -export function isNoop(node: Object, opts?: Object): node is Noop; -export function isParenthesizedExpression(node: Object, opts?: Object): node is ParenthesizedExpression; -export function isAwaitExpression(node: Object, opts?: Object): node is AwaitExpression; -export function isBindExpression(node: Object, opts?: Object): node is BindExpression; -export function isDecorator(node: Object, opts?: Object): node is Decorator; -export function isDoExpression(node: Object, opts?: Object): node is DoExpression; -export function isExportDefaultSpecifier(node: Object, opts?: Object): node is ExportDefaultSpecifier; -export function isExportNamespaceSpecifier(node: Object, opts?: Object): node is ExportNamespaceSpecifier; -export function isRestProperty(node: Object, opts?: Object): node is RestProperty; -export function isSpreadProperty(node: Object, opts?: Object): node is SpreadProperty; -export function isExpression(node: Object, opts?: Object): node is Expression; -export function isBinary(node: Object, opts?: Object): node is Binary; -export function isScopable(node: Object, opts?: Object): node is Scopable; -export function isBlockParent(node: Object, opts?: Object): node is BlockParent; -export function isBlock(node: Object, opts?: Object): node is Block; -export function isStatement(node: Object, opts?: Object): node is Statement; -export function isTerminatorless(node: Object, opts?: Object): node is Terminatorless; -export function isCompletionStatement(node: Object, opts?: Object): node is CompletionStatement; -export function isConditional(node: Object, opts?: Object): node is Conditional; -export function isLoop(node: Object, opts?: Object): node is Loop; -export function isWhile(node: Object, opts?: Object): node is While; -export function isExpressionWrapper(node: Object, opts?: Object): node is ExpressionWrapper; -export function isFor(node: Object, opts?: Object): node is For; -export function isForXStatement(node: Object, opts?: Object): node is ForXStatement; -export function isFunction(node: Object, opts?: Object): node is Function; -export function isFunctionParent(node: Object, opts?: Object): node is FunctionParent; -export function isPureish(node: Object, opts?: Object): node is Pureish; -export function isDeclaration(node: Object, opts?: Object): node is Declaration; -export function isLVal(node: Object, opts?: Object): node is LVal; -export function isLiteral(node: Object, opts?: Object): node is Literal; -export function isImmutable(node: Object, opts?: Object): node is Immutable; -export function isUserWhitespacable(node: Object, opts?: Object): node is UserWhitespacable; -export function isMethod(node: Object, opts?: Object): node is Method; -export function isObjectMember(node: Object, opts?: Object): node is ObjectMember; -export function isProperty(node: Object, opts?: Object): node is Property; -export function isUnaryLike(node: Object, opts?: Object): node is UnaryLike; -export function isPattern(node: Object, opts?: Object): node is Pattern; -export function isClass(node: Object, opts?: Object): node is Class; -export function isModuleDeclaration(node: Object, opts?: Object): node is ModuleDeclaration; -export function isExportDeclaration(node: Object, opts?: Object): node is ExportDeclaration; -export function isModuleSpecifier(node: Object, opts?: Object): node is ModuleSpecifier; -export function isFlow(node: Object, opts?: Object): node is Flow; -export function isFlowBaseAnnotation(node: Object, opts?: Object): node is FlowBaseAnnotation; -export function isFlowDeclaration(node: Object, opts?: Object): node is FlowDeclaration; -export function isJSX(node: Object, opts?: Object): node is JSX; -export function isNumberLiteral(node: Object, opts?: Object): node is NumericLiteral; -export function isRegexLiteral(node: Object, opts?: Object): node is RegExpLiteral; +export function isArrayExpression(node: object, opts?: object): node is ArrayExpression; +export function isAssignmentExpression(node: object, opts?: object): node is AssignmentExpression; +export function isBinaryExpression(node: object, opts?: object): node is BinaryExpression; +export function isDirective(node: object, opts?: object): node is Directive; +export function isDirectiveLiteral(node: object, opts?: object): node is DirectiveLiteral; +export function isBlockStatement(node: object, opts?: object): node is BlockStatement; +export function isBreakStatement(node: object, opts?: object): node is BreakStatement; +export function isCallExpression(node: object, opts?: object): node is CallExpression; +export function isCatchClause(node: object, opts?: object): node is CatchClause; +export function isConditionalExpression(node: object, opts?: object): node is ConditionalExpression; +export function isContinueStatement(node: object, opts?: object): node is ContinueStatement; +export function isDebuggerStatement(node: object, opts?: object): node is DebuggerStatement; +export function isDoWhileStatement(node: object, opts?: object): node is DoWhileStatement; +export function isEmptyStatement(node: object, opts?: object): node is EmptyStatement; +export function isExpressionStatement(node: object, opts?: object): node is ExpressionStatement; +export function isFile(node: object, opts?: object): node is File; +export function isForInStatement(node: object, opts?: object): node is ForInStatement; +export function isForStatement(node: object, opts?: object): node is ForStatement; +export function isFunctionDeclaration(node: object, opts?: object): node is FunctionDeclaration; +export function isFunctionExpression(node: object, opts?: object): node is FunctionExpression; +export function isIdentifier(node: object, opts?: object): node is Identifier; +export function isIfStatement(node: object, opts?: object): node is IfStatement; +export function isLabeledStatement(node: object, opts?: object): node is LabeledStatement; +export function isStringLiteral(node: object, opts?: object): node is StringLiteral; +export function isNumericLiteral(node: object, opts?: object): node is NumericLiteral; +export function isNullLiteral(node: object, opts?: object): node is NullLiteral; +export function isBooleanLiteral(node: object, opts?: object): node is BooleanLiteral; +export function isRegExpLiteral(node: object, opts?: object): node is RegExpLiteral; +export function isLogicalExpression(node: object, opts?: object): node is LogicalExpression; +export function isMemberExpression(node: object, opts?: object): node is MemberExpression; +export function isNewExpression(node: object, opts?: object): node is NewExpression; +export function isProgram(node: object, opts?: object): node is Program; +export function isObjectExpression(node: object, opts?: object): node is ObjectExpression; +export function isObjectMethod(node: object, opts?: object): node is ObjectMethod; +export function isObjectProperty(node: object, opts?: object): node is ObjectProperty; +export function isRestElement(node: object, opts?: object): node is RestElement; +export function isReturnStatement(node: object, opts?: object): node is ReturnStatement; +export function isSequenceExpression(node: object, opts?: object): node is SequenceExpression; +export function isSwitchCase(node: object, opts?: object): node is SwitchCase; +export function isSwitchStatement(node: object, opts?: object): node is SwitchStatement; +export function isThisExpression(node: object, opts?: object): node is ThisExpression; +export function isThrowStatement(node: object, opts?: object): node is ThrowStatement; +export function isTryStatement(node: object, opts?: object): node is TryStatement; +export function isUnaryExpression(node: object, opts?: object): node is UnaryExpression; +export function isUpdateExpression(node: object, opts?: object): node is UpdateExpression; +export function isVariableDeclaration(node: object, opts?: object): node is VariableDeclaration; +export function isVariableDeclarator(node: object, opts?: object): node is VariableDeclarator; +export function isWhileStatement(node: object, opts?: object): node is WhileStatement; +export function isWithStatement(node: object, opts?: object): node is WithStatement; +export function isAssignmentPattern(node: object, opts?: object): node is AssignmentPattern; +export function isArrayPattern(node: object, opts?: object): node is ArrayPattern; +export function isArrowFunctionExpression(node: object, opts?: object): node is ArrowFunctionExpression; +export function isClassBody(node: object, opts?: object): node is ClassBody; +export function isClassDeclaration(node: object, opts?: object): node is ClassDeclaration; +export function isClassExpression(node: object, opts?: object): node is ClassExpression; +export function isExportAllDeclaration(node: object, opts?: object): node is ExportAllDeclaration; +export function isExportDefaultDeclaration(node: object, opts?: object): node is ExportDefaultDeclaration; +export function isExportNamedDeclaration(node: object, opts?: object): node is ExportNamedDeclaration; +export function isExportSpecifier(node: object, opts?: object): node is ExportSpecifier; +export function isForOfStatement(node: object, opts?: object): node is ForOfStatement; +export function isImportDeclaration(node: object, opts?: object): node is ImportDeclaration; +export function isImportDefaultSpecifier(node: object, opts?: object): node is ImportDefaultSpecifier; +export function isImportNamespaceSpecifier(node: object, opts?: object): node is ImportNamespaceSpecifier; +export function isImportSpecifier(node: object, opts?: object): node is ImportSpecifier; +export function isMetaProperty(node: object, opts?: object): node is MetaProperty; +export function isClassMethod(node: object, opts?: object): node is ClassMethod; +export function isObjectPattern(node: object, opts?: object): node is ObjectPattern; +export function isSpreadElement(node: object, opts?: object): node is SpreadElement; +export function isSuper(node: object, opts?: object): node is Super; +export function isTaggedTemplateExpression(node: object, opts?: object): node is TaggedTemplateExpression; +export function isTemplateElement(node: object, opts?: object): node is TemplateElement; +export function isTemplateLiteral(node: object, opts?: object): node is TemplateLiteral; +export function isYieldExpression(node: object, opts?: object): node is YieldExpression; +export function isAnyTypeAnnotation(node: object, opts?: object): node is AnyTypeAnnotation; +export function isArrayTypeAnnotation(node: object, opts?: object): node is ArrayTypeAnnotation; +export function isBooleanTypeAnnotation(node: object, opts?: object): node is BooleanTypeAnnotation; +export function isBooleanLiteralTypeAnnotation(node: object, opts?: object): node is BooleanLiteralTypeAnnotation; +export function isNullLiteralTypeAnnotation(node: object, opts?: object): node is NullLiteralTypeAnnotation; +export function isClassImplements(node: object, opts?: object): node is ClassImplements; +export function isClassProperty(node: object, opts?: object): node is ClassProperty; +export function isDeclareClass(node: object, opts?: object): node is DeclareClass; +export function isDeclareFunction(node: object, opts?: object): node is DeclareFunction; +export function isDeclareInterface(node: object, opts?: object): node is DeclareInterface; +export function isDeclareModule(node: object, opts?: object): node is DeclareModule; +export function isDeclareTypeAlias(node: object, opts?: object): node is DeclareTypeAlias; +export function isDeclareVariable(node: object, opts?: object): node is DeclareVariable; +export function isExistentialTypeParam(node: object, opts?: object): node is ExistentialTypeParam; +export function isFunctionTypeAnnotation(node: object, opts?: object): node is FunctionTypeAnnotation; +export function isFunctionTypeParam(node: object, opts?: object): node is FunctionTypeParam; +export function isGenericTypeAnnotation(node: object, opts?: object): node is GenericTypeAnnotation; +export function isInterfaceExtends(node: object, opts?: object): node is InterfaceExtends; +export function isInterfaceDeclaration(node: object, opts?: object): node is InterfaceDeclaration; +export function isIntersectionTypeAnnotation(node: object, opts?: object): node is IntersectionTypeAnnotation; +export function isMixedTypeAnnotation(node: object, opts?: object): node is MixedTypeAnnotation; +export function isNullableTypeAnnotation(node: object, opts?: object): node is NullableTypeAnnotation; +export function isNumericLiteralTypeAnnotation(node: object, opts?: object): node is NumericLiteralTypeAnnotation; +export function isNumberTypeAnnotation(node: object, opts?: object): node is NumberTypeAnnotation; +export function isStringLiteralTypeAnnotation(node: object, opts?: object): node is StringLiteralTypeAnnotation; +export function isStringTypeAnnotation(node: object, opts?: object): node is StringTypeAnnotation; +export function isThisTypeAnnotation(node: object, opts?: object): node is ThisTypeAnnotation; +export function isTupleTypeAnnotation(node: object, opts?: object): node is TupleTypeAnnotation; +export function isTypeofTypeAnnotation(node: object, opts?: object): node is TypeofTypeAnnotation; +export function isTypeAlias(node: object, opts?: object): node is TypeAlias; +export function isTypeAnnotation(node: object, opts?: object): node is TypeAnnotation; +export function isTypeCastExpression(node: object, opts?: object): node is TypeCastExpression; +export function isTypeParameterDeclaration(node: object, opts?: object): node is TypeParameterDeclaration; +export function isTypeParameterInstantiation(node: object, opts?: object): node is TypeParameterInstantiation; +export function isObjectTypeAnnotation(node: object, opts?: object): node is ObjectTypeAnnotation; +export function isObjectTypeCallProperty(node: object, opts?: object): node is ObjectTypeCallProperty; +export function isObjectTypeIndexer(node: object, opts?: object): node is ObjectTypeIndexer; +export function isObjectTypeProperty(node: object, opts?: object): node is ObjectTypeProperty; +export function isQualifiedTypeIdentifier(node: object, opts?: object): node is QualifiedTypeIdentifier; +export function isUnionTypeAnnotation(node: object, opts?: object): node is UnionTypeAnnotation; +export function isVoidTypeAnnotation(node: object, opts?: object): node is VoidTypeAnnotation; +export function isJSXAttribute(node: object, opts?: object): node is JSXAttribute; +export function isJSXClosingElement(node: object, opts?: object): node is JSXClosingElement; +export function isJSXElement(node: object, opts?: object): node is JSXElement; +export function isJSXEmptyExpression(node: object, opts?: object): node is JSXEmptyExpression; +export function isJSXExpressionContainer(node: object, opts?: object): node is JSXExpressionContainer; +export function isJSXIdentifier(node: object, opts?: object): node is JSXIdentifier; +export function isJSXMemberExpression(node: object, opts?: object): node is JSXMemberExpression; +export function isJSXNamespacedName(node: object, opts?: object): node is JSXNamespacedName; +export function isJSXOpeningElement(node: object, opts?: object): node is JSXOpeningElement; +export function isJSXSpreadAttribute(node: object, opts?: object): node is JSXSpreadAttribute; +export function isJSXText(node: object, opts?: object): node is JSXText; +export function isNoop(node: object, opts?: object): node is Noop; +export function isParenthesizedExpression(node: object, opts?: object): node is ParenthesizedExpression; +export function isAwaitExpression(node: object, opts?: object): node is AwaitExpression; +export function isBindExpression(node: object, opts?: object): node is BindExpression; +export function isDecorator(node: object, opts?: object): node is Decorator; +export function isDoExpression(node: object, opts?: object): node is DoExpression; +export function isExportDefaultSpecifier(node: object, opts?: object): node is ExportDefaultSpecifier; +export function isExportNamespaceSpecifier(node: object, opts?: object): node is ExportNamespaceSpecifier; +export function isRestProperty(node: object, opts?: object): node is RestProperty; +export function isSpreadProperty(node: object, opts?: object): node is SpreadProperty; +export function isExpression(node: object, opts?: object): node is Expression; +export function isBinary(node: object, opts?: object): node is Binary; +export function isScopable(node: object, opts?: object): node is Scopable; +export function isBlockParent(node: object, opts?: object): node is BlockParent; +export function isBlock(node: object, opts?: object): node is Block; +export function isStatement(node: object, opts?: object): node is Statement; +export function isTerminatorless(node: object, opts?: object): node is Terminatorless; +export function isCompletionStatement(node: object, opts?: object): node is CompletionStatement; +export function isConditional(node: object, opts?: object): node is Conditional; +export function isLoop(node: object, opts?: object): node is Loop; +export function isWhile(node: object, opts?: object): node is While; +export function isExpressionWrapper(node: object, opts?: object): node is ExpressionWrapper; +export function isFor(node: object, opts?: object): node is For; +export function isForXStatement(node: object, opts?: object): node is ForXStatement; +// tslint:disable-next-line ban-types +export function isFunction(node: object, opts?: object): node is Function; +export function isFunctionParent(node: object, opts?: object): node is FunctionParent; +export function isPureish(node: object, opts?: object): node is Pureish; +export function isDeclaration(node: object, opts?: object): node is Declaration; +export function isLVal(node: object, opts?: object): node is LVal; +export function isLiteral(node: object, opts?: object): node is Literal; +export function isImmutable(node: object, opts?: object): node is Immutable; +export function isUserWhitespacable(node: object, opts?: object): node is UserWhitespacable; +export function isMethod(node: object, opts?: object): node is Method; +export function isObjectMember(node: object, opts?: object): node is ObjectMember; +export function isProperty(node: object, opts?: object): node is Property; +export function isUnaryLike(node: object, opts?: object): node is UnaryLike; +export function isPattern(node: object, opts?: object): node is Pattern; +export function isClass(node: object, opts?: object): node is Class; +export function isModuleDeclaration(node: object, opts?: object): node is ModuleDeclaration; +export function isExportDeclaration(node: object, opts?: object): node is ExportDeclaration; +export function isModuleSpecifier(node: object, opts?: object): node is ModuleSpecifier; +export function isFlow(node: object, opts?: object): node is Flow; +export function isFlowBaseAnnotation(node: object, opts?: object): node is FlowBaseAnnotation; +export function isFlowDeclaration(node: object, opts?: object): node is FlowDeclaration; +export function isJSX(node: object, opts?: object): node is JSX; +export function isNumberLiteral(node: object, opts?: object): node is NumericLiteral; +export function isRegexLiteral(node: object, opts?: object): node is RegExpLiteral; -export function isReferencedIdentifier(node: Object, opts?: Object): boolean; -export function isReferencedMemberExpression(node: Object, opts?: Object): boolean; -export function isBindingIdentifier(node: Object, opts?: Object): boolean; -export function isScope(node: Object, opts?: Object): boolean; -export function isReferenced(node: Object, opts?: Object): boolean; -export function isBlockScoped(node: Object, opts?: Object): boolean; -export function isVar(node: Object, opts?: Object): boolean; -export function isUser(node: Object, opts?: Object): boolean; -export function isGenerated(node: Object, opts?: Object): boolean; -export function isPure(node: Object, opts?: Object): boolean; +export function isReferencedIdentifier(node: object, opts?: object): boolean; +export function isReferencedMemberExpression(node: object, opts?: object): boolean; +export function isBindingIdentifier(node: object, opts?: object): boolean; +export function isScope(node: object, opts?: object): boolean; +export function isReferenced(node: object, opts?: object): boolean; +export function isBlockScoped(node: object, opts?: object): boolean; +export function isVar(node: object, opts?: object): boolean; +export function isUser(node: object, opts?: object): boolean; +export function isGenerated(node: object, opts?: object): boolean; +export function isPure(node: object, opts?: object): boolean; // React specific -interface ReactHelpers { +export interface ReactHelpers { isCompatTag(tagName?: string): boolean; - buildChildren(node: Object): Object[]; + buildChildren(node: object): Node[]; } export const react: ReactHelpers; -export function assertArrayExpression(node: Object, opts?: Object): void; -export function assertAssignmentExpression(node: Object, opts?: Object): void; -export function assertBinaryExpression(node: Object, opts?: Object): void; -export function assertDirective(node: Object, opts?: Object): void; -export function assertDirectiveLiteral(node: Object, opts?: Object): void; -export function assertBlockStatement(node: Object, opts?: Object): void; -export function assertBreakStatement(node: Object, opts?: Object): void; -export function assertCallExpression(node: Object, opts?: Object): void; -export function assertCatchClause(node: Object, opts?: Object): void; -export function assertConditionalExpression(node: Object, opts?: Object): void; -export function assertContinueStatement(node: Object, opts?: Object): void; -export function assertDebuggerStatement(node: Object, opts?: Object): void; -export function assertDoWhileStatement(node: Object, opts?: Object): void; -export function assertEmptyStatement(node: Object, opts?: Object): void; -export function assertExpressionStatement(node: Object, opts?: Object): void; -export function assertFile(node: Object, opts?: Object): void; -export function assertForInStatement(node: Object, opts?: Object): void; -export function assertForStatement(node: Object, opts?: Object): void; -export function assertFunctionDeclaration(node: Object, opts?: Object): void; -export function assertFunctionExpression(node: Object, opts?: Object): void; -export function assertIdentifier(node: Object, opts?: Object): void; -export function assertIfStatement(node: Object, opts?: Object): void; -export function assertLabeledStatement(node: Object, opts?: Object): void; -export function assertStringLiteral(node: Object, opts?: Object): void; -export function assertNumericLiteral(node: Object, opts?: Object): void; -export function assertNullLiteral(node: Object, opts?: Object): void; -export function assertBooleanLiteral(node: Object, opts?: Object): void; -export function assertRegExpLiteral(node: Object, opts?: Object): void; -export function assertLogicalExpression(node: Object, opts?: Object): void; -export function assertMemberExpression(node: Object, opts?: Object): void; -export function assertNewExpression(node: Object, opts?: Object): void; -export function assertProgram(node: Object, opts?: Object): void; -export function assertObjectExpression(node: Object, opts?: Object): void; -export function assertObjectMethod(node: Object, opts?: Object): void; -export function assertObjectProperty(node: Object, opts?: Object): void; -export function assertRestElement(node: Object, opts?: Object): void; -export function assertReturnStatement(node: Object, opts?: Object): void; -export function assertSequenceExpression(node: Object, opts?: Object): void; -export function assertSwitchCase(node: Object, opts?: Object): void; -export function assertSwitchStatement(node: Object, opts?: Object): void; -export function assertThisExpression(node: Object, opts?: Object): void; -export function assertThrowStatement(node: Object, opts?: Object): void; -export function assertTryStatement(node: Object, opts?: Object): void; -export function assertUnaryExpression(node: Object, opts?: Object): void; -export function assertUpdateExpression(node: Object, opts?: Object): void; -export function assertVariableDeclaration(node: Object, opts?: Object): void; -export function assertVariableDeclarator(node: Object, opts?: Object): void; -export function assertWhileStatement(node: Object, opts?: Object): void; -export function assertWithStatement(node: Object, opts?: Object): void; -export function assertAssignmentPattern(node: Object, opts?: Object): void; -export function assertArrayPattern(node: Object, opts?: Object): void; -export function assertArrowFunctionExpression(node: Object, opts?: Object): void; -export function assertClassBody(node: Object, opts?: Object): void; -export function assertClassDeclaration(node: Object, opts?: Object): void; -export function assertClassExpression(node: Object, opts?: Object): void; -export function assertExportAllDeclaration(node: Object, opts?: Object): void; -export function assertExportDefaultDeclaration(node: Object, opts?: Object): void; -export function assertExportNamedDeclaration(node: Object, opts?: Object): void; -export function assertExportSpecifier(node: Object, opts?: Object): void; -export function assertForOfStatement(node: Object, opts?: Object): void; -export function assertImportDeclaration(node: Object, opts?: Object): void; -export function assertImportDefaultSpecifier(node: Object, opts?: Object): void; -export function assertImportNamespaceSpecifier(node: Object, opts?: Object): void; -export function assertImportSpecifier(node: Object, opts?: Object): void; -export function assertMetaProperty(node: Object, opts?: Object): void; -export function assertClassMethod(node: Object, opts?: Object): void; -export function assertObjectPattern(node: Object, opts?: Object): void; -export function assertSpreadElement(node: Object, opts?: Object): void; -export function assertSuper(node: Object, opts?: Object): void; -export function assertTaggedTemplateExpression(node: Object, opts?: Object): void; -export function assertTemplateElement(node: Object, opts?: Object): void; -export function assertTemplateLiteral(node: Object, opts?: Object): void; -export function assertYieldExpression(node: Object, opts?: Object): void; -export function assertAnyTypeAnnotation(node: Object, opts?: Object): void; -export function assertArrayTypeAnnotation(node: Object, opts?: Object): void; -export function assertBooleanTypeAnnotation(node: Object, opts?: Object): void; -export function assertBooleanLiteralTypeAnnotation(node: Object, opts?: Object): void; -export function assertNullLiteralTypeAnnotation(node: Object, opts?: Object): void; -export function assertClassImplements(node: Object, opts?: Object): void; -export function assertClassProperty(node: Object, opts?: Object): void; -export function assertDeclareClass(node: Object, opts?: Object): void; -export function assertDeclareFunction(node: Object, opts?: Object): void; -export function assertDeclareInterface(node: Object, opts?: Object): void; -export function assertDeclareModule(node: Object, opts?: Object): void; -export function assertDeclareTypeAlias(node: Object, opts?: Object): void; -export function assertDeclareVariable(node: Object, opts?: Object): void; -export function assertExistentialTypeParam(node: Object, opts?: Object): void; -export function assertFunctionTypeAnnotation(node: Object, opts?: Object): void; -export function assertFunctionTypeParam(node: Object, opts?: Object): void; -export function assertGenericTypeAnnotation(node: Object, opts?: Object): void; -export function assertInterfaceExtends(node: Object, opts?: Object): void; -export function assertInterfaceDeclaration(node: Object, opts?: Object): void; -export function assertIntersectionTypeAnnotation(node: Object, opts?: Object): void; -export function assertMixedTypeAnnotation(node: Object, opts?: Object): void; -export function assertNullableTypeAnnotation(node: Object, opts?: Object): void; -export function assertNumericLiteralTypeAnnotation(node: Object, opts?: Object): void; -export function assertNumberTypeAnnotation(node: Object, opts?: Object): void; -export function assertStringLiteralTypeAnnotation(node: Object, opts?: Object): void; -export function assertStringTypeAnnotation(node: Object, opts?: Object): void; -export function assertThisTypeAnnotation(node: Object, opts?: Object): void; -export function assertTupleTypeAnnotation(node: Object, opts?: Object): void; -export function assertTypeofTypeAnnotation(node: Object, opts?: Object): void; -export function assertTypeAlias(node: Object, opts?: Object): void; -export function assertTypeAnnotation(node: Object, opts?: Object): void; -export function assertTypeCastExpression(node: Object, opts?: Object): void; -export function assertTypeParameterDeclaration(node: Object, opts?: Object): void; -export function assertTypeParameterInstantiation(node: Object, opts?: Object): void; -export function assertObjectTypeAnnotation(node: Object, opts?: Object): void; -export function assertObjectTypeCallProperty(node: Object, opts?: Object): void; -export function assertObjectTypeIndexer(node: Object, opts?: Object): void; -export function assertObjectTypeProperty(node: Object, opts?: Object): void; -export function assertQualifiedTypeIdentifier(node: Object, opts?: Object): void; -export function assertUnionTypeAnnotation(node: Object, opts?: Object): void; -export function assertVoidTypeAnnotation(node: Object, opts?: Object): void; -export function assertJSXAttribute(node: Object, opts?: Object): void; -export function assertJSXClosingElement(node: Object, opts?: Object): void; -export function assertJSXElement(node: Object, opts?: Object): void; -export function assertJSXEmptyExpression(node: Object, opts?: Object): void; -export function assertJSXExpressionContainer(node: Object, opts?: Object): void; -export function assertJSXIdentifier(node: Object, opts?: Object): void; -export function assertJSXMemberExpression(node: Object, opts?: Object): void; -export function assertJSXNamespacedName(node: Object, opts?: Object): void; -export function assertJSXOpeningElement(node: Object, opts?: Object): void; -export function assertJSXSpreadAttribute(node: Object, opts?: Object): void; -export function assertJSXText(node: Object, opts?: Object): void; -export function assertNoop(node: Object, opts?: Object): void; -export function assertParenthesizedExpression(node: Object, opts?: Object): void; -export function assertAwaitExpression(node: Object, opts?: Object): void; -export function assertBindExpression(node: Object, opts?: Object): void; -export function assertDecorator(node: Object, opts?: Object): void; -export function assertDoExpression(node: Object, opts?: Object): void; -export function assertExportDefaultSpecifier(node: Object, opts?: Object): void; -export function assertExportNamespaceSpecifier(node: Object, opts?: Object): void; -export function assertRestProperty(node: Object, opts?: Object): void; -export function assertSpreadProperty(node: Object, opts?: Object): void; -export function assertExpression(node: Object, opts?: Object): void; -export function assertBinary(node: Object, opts?: Object): void; -export function assertScopable(node: Object, opts?: Object): void; -export function assertBlockParent(node: Object, opts?: Object): void; -export function assertBlock(node: Object, opts?: Object): void; -export function assertStatement(node: Object, opts?: Object): void; -export function assertTerminatorless(node: Object, opts?: Object): void; -export function assertCompletionStatement(node: Object, opts?: Object): void; -export function assertConditional(node: Object, opts?: Object): void; -export function assertLoop(node: Object, opts?: Object): void; -export function assertWhile(node: Object, opts?: Object): void; -export function assertExpressionWrapper(node: Object, opts?: Object): void; -export function assertFor(node: Object, opts?: Object): void; -export function assertForXStatement(node: Object, opts?: Object): void; -export function assertFunction(node: Object, opts?: Object): void; -export function assertFunctionParent(node: Object, opts?: Object): void; -export function assertPureish(node: Object, opts?: Object): void; -export function assertDeclaration(node: Object, opts?: Object): void; -export function assertLVal(node: Object, opts?: Object): void; -export function assertLiteral(node: Object, opts?: Object): void; -export function assertImmutable(node: Object, opts?: Object): void; -export function assertUserWhitespacable(node: Object, opts?: Object): void; -export function assertMethod(node: Object, opts?: Object): void; -export function assertObjectMember(node: Object, opts?: Object): void; -export function assertProperty(node: Object, opts?: Object): void; -export function assertUnaryLike(node: Object, opts?: Object): void; -export function assertPattern(node: Object, opts?: Object): void; -export function assertClass(node: Object, opts?: Object): void; -export function assertModuleDeclaration(node: Object, opts?: Object): void; -export function assertExportDeclaration(node: Object, opts?: Object): void; -export function assertModuleSpecifier(node: Object, opts?: Object): void; -export function assertFlow(node: Object, opts?: Object): void; -export function assertFlowBaseAnnotation(node: Object, opts?: Object): void; -export function assertFlowDeclaration(node: Object, opts?: Object): void; -export function assertJSX(node: Object, opts?: Object): void; -export function assertNumberLiteral(node: Object, opts?: Object): void; -export function assertRegexLiteral(node: Object, opts?: Object): void; - +export function assertArrayExpression(node: object, opts?: object): void; +export function assertAssignmentExpression(node: object, opts?: object): void; +export function assertBinaryExpression(node: object, opts?: object): void; +export function assertDirective(node: object, opts?: object): void; +export function assertDirectiveLiteral(node: object, opts?: object): void; +export function assertBlockStatement(node: object, opts?: object): void; +export function assertBreakStatement(node: object, opts?: object): void; +export function assertCallExpression(node: object, opts?: object): void; +export function assertCatchClause(node: object, opts?: object): void; +export function assertConditionalExpression(node: object, opts?: object): void; +export function assertContinueStatement(node: object, opts?: object): void; +export function assertDebuggerStatement(node: object, opts?: object): void; +export function assertDoWhileStatement(node: object, opts?: object): void; +export function assertEmptyStatement(node: object, opts?: object): void; +export function assertExpressionStatement(node: object, opts?: object): void; +export function assertFile(node: object, opts?: object): void; +export function assertForInStatement(node: object, opts?: object): void; +export function assertForStatement(node: object, opts?: object): void; +export function assertFunctionDeclaration(node: object, opts?: object): void; +export function assertFunctionExpression(node: object, opts?: object): void; +export function assertIdentifier(node: object, opts?: object): void; +export function assertIfStatement(node: object, opts?: object): void; +export function assertLabeledStatement(node: object, opts?: object): void; +export function assertStringLiteral(node: object, opts?: object): void; +export function assertNumericLiteral(node: object, opts?: object): void; +export function assertNullLiteral(node: object, opts?: object): void; +export function assertBooleanLiteral(node: object, opts?: object): void; +export function assertRegExpLiteral(node: object, opts?: object): void; +export function assertLogicalExpression(node: object, opts?: object): void; +export function assertMemberExpression(node: object, opts?: object): void; +export function assertNewExpression(node: object, opts?: object): void; +export function assertProgram(node: object, opts?: object): void; +export function assertObjectExpression(node: object, opts?: object): void; +export function assertObjectMethod(node: object, opts?: object): void; +export function assertObjectProperty(node: object, opts?: object): void; +export function assertRestElement(node: object, opts?: object): void; +export function assertReturnStatement(node: object, opts?: object): void; +export function assertSequenceExpression(node: object, opts?: object): void; +export function assertSwitchCase(node: object, opts?: object): void; +export function assertSwitchStatement(node: object, opts?: object): void; +export function assertThisExpression(node: object, opts?: object): void; +export function assertThrowStatement(node: object, opts?: object): void; +export function assertTryStatement(node: object, opts?: object): void; +export function assertUnaryExpression(node: object, opts?: object): void; +export function assertUpdateExpression(node: object, opts?: object): void; +export function assertVariableDeclaration(node: object, opts?: object): void; +export function assertVariableDeclarator(node: object, opts?: object): void; +export function assertWhileStatement(node: object, opts?: object): void; +export function assertWithStatement(node: object, opts?: object): void; +export function assertAssignmentPattern(node: object, opts?: object): void; +export function assertArrayPattern(node: object, opts?: object): void; +export function assertArrowFunctionExpression(node: object, opts?: object): void; +export function assertClassBody(node: object, opts?: object): void; +export function assertClassDeclaration(node: object, opts?: object): void; +export function assertClassExpression(node: object, opts?: object): void; +export function assertExportAllDeclaration(node: object, opts?: object): void; +export function assertExportDefaultDeclaration(node: object, opts?: object): void; +export function assertExportNamedDeclaration(node: object, opts?: object): void; +export function assertExportSpecifier(node: object, opts?: object): void; +export function assertForOfStatement(node: object, opts?: object): void; +export function assertImportDeclaration(node: object, opts?: object): void; +export function assertImportDefaultSpecifier(node: object, opts?: object): void; +export function assertImportNamespaceSpecifier(node: object, opts?: object): void; +export function assertImportSpecifier(node: object, opts?: object): void; +export function assertMetaProperty(node: object, opts?: object): void; +export function assertClassMethod(node: object, opts?: object): void; +export function assertObjectPattern(node: object, opts?: object): void; +export function assertSpreadElement(node: object, opts?: object): void; +export function assertSuper(node: object, opts?: object): void; +export function assertTaggedTemplateExpression(node: object, opts?: object): void; +export function assertTemplateElement(node: object, opts?: object): void; +export function assertTemplateLiteral(node: object, opts?: object): void; +export function assertYieldExpression(node: object, opts?: object): void; +export function assertAnyTypeAnnotation(node: object, opts?: object): void; +export function assertArrayTypeAnnotation(node: object, opts?: object): void; +export function assertBooleanTypeAnnotation(node: object, opts?: object): void; +export function assertBooleanLiteralTypeAnnotation(node: object, opts?: object): void; +export function assertNullLiteralTypeAnnotation(node: object, opts?: object): void; +export function assertClassImplements(node: object, opts?: object): void; +export function assertClassProperty(node: object, opts?: object): void; +export function assertDeclareClass(node: object, opts?: object): void; +export function assertDeclareFunction(node: object, opts?: object): void; +export function assertDeclareInterface(node: object, opts?: object): void; +export function assertDeclareModule(node: object, opts?: object): void; +export function assertDeclareTypeAlias(node: object, opts?: object): void; +export function assertDeclareVariable(node: object, opts?: object): void; +export function assertExistentialTypeParam(node: object, opts?: object): void; +export function assertFunctionTypeAnnotation(node: object, opts?: object): void; +export function assertFunctionTypeParam(node: object, opts?: object): void; +export function assertGenericTypeAnnotation(node: object, opts?: object): void; +export function assertInterfaceExtends(node: object, opts?: object): void; +export function assertInterfaceDeclaration(node: object, opts?: object): void; +export function assertIntersectionTypeAnnotation(node: object, opts?: object): void; +export function assertMixedTypeAnnotation(node: object, opts?: object): void; +export function assertNullableTypeAnnotation(node: object, opts?: object): void; +export function assertNumericLiteralTypeAnnotation(node: object, opts?: object): void; +export function assertNumberTypeAnnotation(node: object, opts?: object): void; +export function assertStringLiteralTypeAnnotation(node: object, opts?: object): void; +export function assertStringTypeAnnotation(node: object, opts?: object): void; +export function assertThisTypeAnnotation(node: object, opts?: object): void; +export function assertTupleTypeAnnotation(node: object, opts?: object): void; +export function assertTypeofTypeAnnotation(node: object, opts?: object): void; +export function assertTypeAlias(node: object, opts?: object): void; +export function assertTypeAnnotation(node: object, opts?: object): void; +export function assertTypeCastExpression(node: object, opts?: object): void; +export function assertTypeParameterDeclaration(node: object, opts?: object): void; +export function assertTypeParameterInstantiation(node: object, opts?: object): void; +export function assertObjectTypeAnnotation(node: object, opts?: object): void; +export function assertObjectTypeCallProperty(node: object, opts?: object): void; +export function assertObjectTypeIndexer(node: object, opts?: object): void; +export function assertObjectTypeProperty(node: object, opts?: object): void; +export function assertQualifiedTypeIdentifier(node: object, opts?: object): void; +export function assertUnionTypeAnnotation(node: object, opts?: object): void; +export function assertVoidTypeAnnotation(node: object, opts?: object): void; +export function assertJSXAttribute(node: object, opts?: object): void; +export function assertJSXClosingElement(node: object, opts?: object): void; +export function assertJSXElement(node: object, opts?: object): void; +export function assertJSXEmptyExpression(node: object, opts?: object): void; +export function assertJSXExpressionContainer(node: object, opts?: object): void; +export function assertJSXIdentifier(node: object, opts?: object): void; +export function assertJSXMemberExpression(node: object, opts?: object): void; +export function assertJSXNamespacedName(node: object, opts?: object): void; +export function assertJSXOpeningElement(node: object, opts?: object): void; +export function assertJSXSpreadAttribute(node: object, opts?: object): void; +export function assertJSXText(node: object, opts?: object): void; +export function assertNoop(node: object, opts?: object): void; +export function assertParenthesizedExpression(node: object, opts?: object): void; +export function assertAwaitExpression(node: object, opts?: object): void; +export function assertBindExpression(node: object, opts?: object): void; +export function assertDecorator(node: object, opts?: object): void; +export function assertDoExpression(node: object, opts?: object): void; +export function assertExportDefaultSpecifier(node: object, opts?: object): void; +export function assertExportNamespaceSpecifier(node: object, opts?: object): void; +export function assertRestProperty(node: object, opts?: object): void; +export function assertSpreadProperty(node: object, opts?: object): void; +export function assertExpression(node: object, opts?: object): void; +export function assertBinary(node: object, opts?: object): void; +export function assertScopable(node: object, opts?: object): void; +export function assertBlockParent(node: object, opts?: object): void; +export function assertBlock(node: object, opts?: object): void; +export function assertStatement(node: object, opts?: object): void; +export function assertTerminatorless(node: object, opts?: object): void; +export function assertCompletionStatement(node: object, opts?: object): void; +export function assertConditional(node: object, opts?: object): void; +export function assertLoop(node: object, opts?: object): void; +export function assertWhile(node: object, opts?: object): void; +export function assertExpressionWrapper(node: object, opts?: object): void; +export function assertFor(node: object, opts?: object): void; +export function assertForXStatement(node: object, opts?: object): void; +export function assertFunction(node: object, opts?: object): void; +export function assertFunctionParent(node: object, opts?: object): void; +export function assertPureish(node: object, opts?: object): void; +export function assertDeclaration(node: object, opts?: object): void; +export function assertLVal(node: object, opts?: object): void; +export function assertLiteral(node: object, opts?: object): void; +export function assertImmutable(node: object, opts?: object): void; +export function assertUserWhitespacable(node: object, opts?: object): void; +export function assertMethod(node: object, opts?: object): void; +export function assertObjectMember(node: object, opts?: object): void; +export function assertProperty(node: object, opts?: object): void; +export function assertUnaryLike(node: object, opts?: object): void; +export function assertPattern(node: object, opts?: object): void; +export function assertClass(node: object, opts?: object): void; +export function assertModuleDeclaration(node: object, opts?: object): void; +export function assertExportDeclaration(node: object, opts?: object): void; +export function assertModuleSpecifier(node: object, opts?: object): void; +export function assertFlow(node: object, opts?: object): void; +export function assertFlowBaseAnnotation(node: object, opts?: object): void; +export function assertFlowDeclaration(node: object, opts?: object): void; +export function assertJSX(node: object, opts?: object): void; +export function assertNumberLiteral(node: object, opts?: object): void; +export function assertRegexLiteral(node: object, opts?: object): void; diff --git a/types/babel-types/tslint.json b/types/babel-types/tslint.json new file mode 100644 index 0000000000..3db14f85ea --- /dev/null +++ b/types/babel-types/tslint.json @@ -0,0 +1 @@ +{ "extends": "dtslint/dt.json" } diff --git a/types/babelify/index.d.ts b/types/babelify/index.d.ts index c69eef42b2..f394d2ba44 100644 --- a/types/babelify/index.d.ts +++ b/types/babelify/index.d.ts @@ -1,7 +1,9 @@ // Type definitions for babelify v7.3.0 // Project: https://github.com/babel/babelify // Definitions by: TeamworkGuy2 +// Marvin Hagemeister // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.3 /// diff --git a/types/babylon/babylon-tests.ts b/types/babylon/babylon-tests.ts index 769d635e89..d844b9a8f7 100644 --- a/types/babylon/babylon-tests.ts +++ b/types/babylon/babylon-tests.ts @@ -12,7 +12,6 @@ assert(node.start === 0); assert(node.end === 38); assert(node.loc.start > node.loc.end); - babylon.parse(code, { sourceType: "module", // default: "script" plugins: ["jsx"] // default: [] diff --git a/types/babylon/index.d.ts b/types/babylon/index.d.ts index eb35a5d799..eb22f30c13 100644 --- a/types/babylon/index.d.ts +++ b/types/babylon/index.d.ts @@ -1,9 +1,9 @@ -// Type definitions for babylon v6.16.1 +// Type definitions for babylon 6.16 // Project: https://github.com/babel/babylon // Definitions by: Troy Gerwien +// Marvin Hagemeister // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped - -/// +// TypeScript Version: 2.3 import { File, Expression } from 'babel-types'; diff --git a/types/babylon/tslint.json b/types/babylon/tslint.json new file mode 100644 index 0000000000..3db14f85ea --- /dev/null +++ b/types/babylon/tslint.json @@ -0,0 +1 @@ +{ "extends": "dtslint/dt.json" } diff --git a/types/basic-auth/basic-auth-tests.ts b/types/basic-auth/basic-auth-tests.ts index e416afe352..9c03137b37 100644 --- a/types/basic-auth/basic-auth-tests.ts +++ b/types/basic-auth/basic-auth-tests.ts @@ -1,4 +1,4 @@ -import {IncomingMessage} from 'http'; +import { IncomingMessage } from 'http'; import auth = require('basic-auth'); const loginData = auth(undefined! as IncomingMessage); diff --git a/types/bintrees/bintrees-tests.ts b/types/bintrees/bintrees-tests.ts index 707d8e0adf..fb4a22a3d8 100644 --- a/types/bintrees/bintrees-tests.ts +++ b/types/bintrees/bintrees-tests.ts @@ -1,14 +1,50 @@ +/// +/// +import assert = require('assert'); import { BinTree, RBTree } from 'bintrees'; -let treeA = new RBTree((a:number, b:number) => a - b); +describe('bintrees', () => { + it('builds a simple tree', () => { + let treeA = new RBTree((a: number, b: number) => a - b); -treeA.insert(5); -treeA.insert(3); -treeA.remove(3); + treeA.insert(5); + treeA.insert(3); + treeA.remove(3); -let treeB = new BinTree((a:string, b:string) => a.length - b.length); + assert.equal(treeA.size, 1); + }); + + it('builds a tree of strings', () => { + let treeB = new BinTree((a:string, b:string) => a.length - b.length); + + treeB.insert('hi'); + treeB.insert('there'); + treeB.insert('how'); + treeB.insert('are'); // ignored + treeB.remove('how'); + + assert.equal(treeB.size, 2); + assert.equal(treeB.min(), 'hi'); + }); + + it('maintains a tree of objects', () => { + + interface C { + id: number + } + + let treeC = new BinTree((a: C, b: C) => a.id - b.id); + + treeC.insert({ id: 100 }); + treeC.insert({ id: 110 }); + treeC.insert({ id: 105 }); + + let ids: number[] = []; + treeC.each((val: C) => { + ids.push(val.id); + }); + + assert.deepEqual(ids, [100, 105, 110]); + }); +}); -treeB.insert('hi'); -treeB.insert('there'); -treeB.insert('how'); -treeB.insert('are'); diff --git a/types/bintrees/index.d.ts b/types/bintrees/index.d.ts index 7a7b2c233e..743997dc03 100644 --- a/types/bintrees/index.d.ts +++ b/types/bintrees/index.d.ts @@ -5,8 +5,8 @@ declare module 'bintrees' { - type Callback = (item: T) => void; - type Comparator = (a: T, b: T) => number; + type Callback = (item: T) => void; + type Comparator = (a: T, b: T) => number; class Iterator { constructor(tree: TreeBase); @@ -37,14 +37,14 @@ declare module 'bintrees' { iterator(): Iterator; - each(cb: Callback): void; + each(cb: Callback): void; - reach(cb: Callback): void; + reach(cb: Callback): void; } export class RBTree extends TreeBase { - constructor(comparator: Comparator); + constructor(comparator: Comparator); insert(item: T): boolean; @@ -52,7 +52,7 @@ declare module 'bintrees' { } export class BinTree extends TreeBase { - constructor(comparator: Comparator); + constructor(comparator: Comparator); insert(item: T): boolean; diff --git a/types/bleno/tslint.json b/types/bleno/tslint.json index 377cc837d4..3db14f85ea 100644 --- a/types/bleno/tslint.json +++ b/types/bleno/tslint.json @@ -1 +1 @@ -{ "extends": "../tslint.json" } +{ "extends": "dtslint/dt.json" } diff --git a/types/blessed/index.d.ts b/types/blessed/index.d.ts index b08f77b3b1..abbc31d295 100644 --- a/types/blessed/index.d.ts +++ b/types/blessed/index.d.ts @@ -5,7 +5,7 @@ /// -import {EventEmitter} from 'events'; +import { EventEmitter } from 'events'; import * as stream from "stream"; import * as child_process from "child_process"; diff --git a/types/bookshelf/index.d.ts b/types/bookshelf/index.d.ts index 55be61ba9e..914107816f 100644 --- a/types/bookshelf/index.d.ts +++ b/types/bookshelf/index.d.ts @@ -96,7 +96,7 @@ declare namespace Bookshelf { static where(key: string, operatorOrValue: string | number | boolean, valueIfOperator?: string | number | boolean): T; belongsTo>(target: { new (...args: any[]): R }, foreignKey?: string, foreignKeyTarget?: string): R; - belongsToMany>(target: { new (...args: any[]): R }, table?: string, foreignKey?: string, otherKey?: string): Collection; + belongsToMany>(target: { new (...args: any[]): R }, table?: string, foreignKey?: string, otherKey?: string, foreignKeyTarget?: string, otherKeyTarget?: string): Collection; count(column?: string, options?: SyncOptions): BlueBird; destroy(options?: DestroyOptions): BlueBird; fetch(options?: FetchOptions): BlueBird; diff --git a/types/boom/boom-tests.ts b/types/boom/boom-tests.ts index 38dc39058f..1819be25cb 100644 --- a/types/boom/boom-tests.ts +++ b/types/boom/boom-tests.ts @@ -136,7 +136,8 @@ const gatewayTimeoutError = Boom.gatewayTimeout('message', {some: 'data'}); gatewayTimeoutError.data.some; const gatewayTimeoutError2: Boom.BoomError = Boom.gatewayTimeout('message'); -// wrap and create +// boomify, wrap, and create +const boomifiedError = Boom.boomify(new Error('test'), { statusCode: 400, message: 'some message' }) const wrappedError = Boom.wrap(new Error('test'), 400, 'some message'); diff --git a/types/boom/index.d.ts b/types/boom/index.d.ts index b8f41a85be..97a0f7ef59 100644 --- a/types/boom/index.d.ts +++ b/types/boom/index.d.ts @@ -1,6 +1,8 @@ // Type definitions for boom 4.3 // Project: http://github.com/hapijs/boom -// Definitions by: Igor Rogatty , AJP +// Definitions by: Igor Rogatty +// AJP +// Jinesh Shah // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped // TypeScript Version: 2.3 @@ -53,6 +55,14 @@ declare namespace Boom { // Excluded this to aid typing of the other values. See tests for example casting to a custom interface to manipulate the payload // [anyContent: string]: any; } + + /** + * Decorates an error with the boom properties + * @param error the error object to wrap. If error is already a boom object, it defaults to overriding the object with the new status code and message. + * @param options optional additional options + * @see {@link https://github.com/hapijs/boom#boomifyerror-options} + */ + export function boomify(error: Error, options?: { statusCode?: number, message?: string, override?: boolean }): BoomError; /** * Decorates an error with the boom properties diff --git a/types/bootstrap-table/index.d.ts b/types/bootstrap-table/index.d.ts index e70ada9e38..166289f14f 100644 --- a/types/bootstrap-table/index.d.ts +++ b/types/bootstrap-table/index.d.ts @@ -7,7 +7,8 @@ /// interface JQuery { - bootstrapTable(options?: any): JQuery; + bootstrapTable(options?: any): JQuery; + bootstrapTable(method: string, parameter?: any): JQuery; } declare var bootstrapTable: JQueryStatic; diff --git a/types/bwip-js/index.d.ts b/types/bwip-js/index.d.ts index 9c37fa6e44..04732ef703 100644 --- a/types/bwip-js/index.d.ts +++ b/types/bwip-js/index.d.ts @@ -5,7 +5,7 @@ /// -import {IncomingMessage as Request, ServerResponse as Response} from 'http'; +import { IncomingMessage as Request, ServerResponse as Response } from 'http'; declare namespace BwipJs { export function loadFont(fontName:string, sizeMulti: number, fontFile: string): void; diff --git a/types/catbox/catbox-tests.ts b/types/catbox/catbox-tests.ts new file mode 100644 index 0000000000..565573adad --- /dev/null +++ b/types/catbox/catbox-tests.ts @@ -0,0 +1,27 @@ +import Catbox = require("catbox"); + +const Memory: Catbox.EnginePrototypeOrObject = { + start(callback: Catbox.CallBackNoResult) {}, + stop() {}, + get() {}, + set() {}, + drop() {}, + isReady(): boolean { return true; }, + validateSegmentName(segment: string): null { return null; }, +}; + +const client = new Catbox.Client(Memory, { partition: 'cache' }); + +const cache = new Catbox.Policy({ + expiresIn: 5000, +}, client, 'cache'); + +cache.set('foo', 'bar', 5000, () => {}); + +cache.get('foo', () => {}); + +cache.drop('foo', () => {}); + +cache.isReady(); + +cache.stats(); diff --git a/types/catbox/index.d.ts b/types/catbox/index.d.ts index 5dad5af29a..e34059d618 100644 --- a/types/catbox/index.d.ts +++ b/types/catbox/index.d.ts @@ -6,12 +6,8 @@ import * as Boom from 'boom'; -export interface CallBackNoResult { - (err?: Boom.BoomError): void; -} -export interface CallBackWithResult { - (err: Boom.BoomError | null | undefined, result: T): void; -} +export type CallBackNoResult = (err?: Boom.BoomError) => void; +export type CallBackWithResult = (err: Boom.BoomError | null | undefined, result: T) => void; /** * Client @@ -20,14 +16,44 @@ export interface CallBackWithResult { * * function - a prototype function with the signature function(options). catbox will call new func(options). * * object - a pre instantiated client implementation object. Does not support passing options. * options - the strategy configuration object. Each strategy defines its own configuration options with the following common options: - * * partition - the partition name used to isolate the cached results across multiple clients. The partition name is used as the MongoDB database name, the Riak bucket, or as a key prefix in Redis and Memcached. To share the cache across multiple clients, use the same partition name. + * * partition - the partition name used to isolate the cached results across multiple clients. The partition name is used as the MongoDB database name, + * the Riak bucket, or as a key prefix in Redis and Memcached. To share the cache across multiple clients, use the same partition name. * @see {@link https://github.com/hapijs/catbox#client} */ -export interface Client extends ClientApi { - new(engine: EnginePrototypeOrObject, options: ClientOptions): Client; +export class Client implements ClientApi { + constructor(engine: EnginePrototypeOrObject, options: ClientOptions); + + /** start(callback) - creates a connection to the cache server. Must be called before any other method is available. The callback signature is function(err). */ + start(callback: CallBackNoResult): void; + /** stop() - terminates the connection to the cache server. */ + stop(): void; + /** + * get(key, callback) - retrieve an item from the cache engine if found where: + * * key - a cache key object (see [ICacheKey]). + * * callback - a function with the signature function(err, cached). If the item is not found, both err and cached are null. If found, the cached object is returned + */ + get(key: CacheKey, callback: CallBackWithResult): CacheItem; + /** + * set(key, value, ttl, callback) - store an item in the cache for a specified length of time, where: + * * key - a cache key object (see [ICacheKey]). + * * value - the string or object value to be stored. + * * ttl - a time-to-live value in milliseconds after which the item is automatically removed from the cache (or is marked invalid). + * * callback - a function with the signature function(err). + */ + set(key: CacheKey, value: CacheItem, ttl: number, callback: CallBackNoResult): void; + /** + * drop(key, callback) - remove an item from cache where: + * * key - a cache key object (see [ICacheKey]). + * * callback - a function with the signature function(err). + */ + drop(key: CacheKey, callback: CallBackNoResult): void; + /** isReady() - returns true if cache engine determines itself as ready, false if it is not ready. */ + isReady(): boolean; + /** validateSegmentName(segment) - returns null if the segment name is valid (see below), otherwise should return an instance of Error with an appropriate message. */ + validateSegmentName(segment: string): null | Boom.BoomError; } -type EnginePrototypeOrObject = EnginePrototype | ClientApi; +export type EnginePrototypeOrObject = EnginePrototype | ClientApi; /** * A prototype CatBox engine function @@ -50,7 +76,7 @@ export interface ClientApi { * get(key, callback) - retrieve an item from the cache engine if found where: * * key - a cache key object (see [ICacheKey]). * * callback - a function with the signature function(err, cached). If the item is not found, both err and cached are null. If found, the cached object is returned - */ + */ get(key: CacheKey, callback: CallBackWithResult): CacheItem; /** * set(key, value, ttl, callback) - store an item in the cache for a specified length of time, where: @@ -92,21 +118,52 @@ export interface CachedObject { ttl: number; } -type CacheItem = any; +export type CacheItem = any; export interface ClientOptions { partition: string; } /** - * The Policy object provides a convenient cache interface by setting a global policy which is automatically applied to every storage action. The object is constructed using new Policy(options, [cache, segment]) where: + * The Policy object provides a convenient cache interface by setting a global policy which is automatically applied to every storage action. + * The object is constructed using new Policy(options, [cache, segment]) where: * * options - an object with the IPolicyOptions structure * * cache - a Client instance (which has already been started). * * segment - required when cache is provided. The segment name used to isolate cached items within the cache partition. * @see {@link https://github.com/hapijs/catbox#policy} */ -export interface Policy extends PolicyAPI { - new(options: PolicyOptions, cache: Client, segment: string): Policy; +export class Policy implements PolicyAPI { + constructor(options: PolicyOptions, cache: Client, segment: string); + /** + * get(id, callback) - retrieve an item from the cache. If the item is not found and the generateFunc method was provided, + * a new value is generated, stored in the cache, and returned. Multiple concurrent requests are queued and processed once. The method arguments are: + * * id - the unique item identifier (within the policy segment). Can be a string or an object with the required 'id' key. + * * callback - the return function. + */ + get(id: string | {id: string}, callback: PolicyGetCallback): CacheItem; + /** + * set(id, value, ttl, callback) - store an item in the cache where: + * * id - the unique item identifier (within the policy segment). + * * value - the string or object value to be stored. + * * ttl - a time-to-live override value in milliseconds after which the item is automatically removed from the cache (or is marked invalid). + * This should be set to 0 in order to use the caching rules configured when creating the Policy object. + * * callback - a function with the signature function(err). + */ + set(id: string | {id: string}, value: CacheItem, ttl: number | null, callback: CallBackNoResult): void; + /** + * drop(id, callback) - remove the item from cache where: + * * id - the unique item identifier (within the policy segment). + * * callback - a function with the signature function(err). + */ + drop(id: string | {id: string}, callback: CallBackNoResult): void; + /** ttl(created) - given a created timestamp in milliseconds, returns the time-to-live left based on the configured rules. */ + ttl(created: number): number; + /** rules(options) - changes the policy rules after construction (note that items already stored will not be affected) */ + rules(options: PolicyOptions): void; + /** isReady() - returns true if cache engine determines itself as ready, false if it is not ready or if there is no cache engine set. */ + isReady(): boolean; + /** stats - an object with cache statistics */ + stats(): CacheStatisticsObject; } /** @@ -116,7 +173,8 @@ export interface Policy extends PolicyAPI { */ export interface PolicyAPI { /** - * get(id, callback) - retrieve an item from the cache. If the item is not found and the generateFunc method was provided, a new value is generated, stored in the cache, and returned. Multiple concurrent requests are queued and processed once. The method arguments are: + * get(id, callback) - retrieve an item from the cache. If the item is not found and the generateFunc method was provided, + * a new value is generated, stored in the cache, and returned. Multiple concurrent requests are queued and processed once. The method arguments are: * * id - the unique item identifier (within the policy segment). Can be a string or an object with the required 'id' key. * * callback - the return function. */ @@ -125,7 +183,8 @@ export interface PolicyAPI { * set(id, value, ttl, callback) - store an item in the cache where: * * id - the unique item identifier (within the policy segment). * * value - the string or object value to be stored. - * * ttl - a time-to-live override value in milliseconds after which the item is automatically removed from the cache (or is marked invalid). This should be set to 0 in order to use the caching rules configured when creating the Policy object. + * * ttl - a time-to-live override value in milliseconds after which the item is automatically removed from the cache (or is marked invalid). + * This should be set to 0 in order to use the caching rules configured when creating the Policy object. * * callback - a function with the signature function(err). */ set(id: string | {id: string}, value: CacheItem, ttl: number | null, callback: CallBackNoResult): void; @@ -152,9 +211,7 @@ export interface PolicyAPI { * @param cached - null if a valid item was not found in the cache, or IPolicyGetCallbackCachedOptions * @param report - an object with logging information about the generation operation */ -export interface PolicyGetCallback{ - (err: null | Boom.BoomError, value: CacheItem, cached: PolicyGetCallbackCachedOptions, report: PolicyGetCallbackReportLog): void; -} +export type PolicyGetCallback = (err: null | Boom.BoomError, value: CacheItem, cached: PolicyGetCallbackCachedOptions, report: PolicyGetCallbackReportLog) => void; export interface PolicyGetCallbackCachedOptions { /** item - the cached value. */ @@ -178,14 +235,19 @@ export interface PolicyOptions { /** generateFunc - a function used to generate a new cache item if one is not found in the cache when calling get(). The method's signature is function(id, next) where: */ generateFunc?: GenerateFunc; /** - * staleIn - number of milliseconds to mark an item stored in cache as stale and attempt to regenerate it when generateFunc is provided. Must be less than expiresIn. Alternatively function that returns staleIn value in milliseconds. The function signature is function(stored, ttl) where: + * staleIn - number of milliseconds to mark an item stored in cache as stale and attempt to regenerate it when generateFunc is provided. + * Must be less than expiresIn. Alternatively function that returns staleIn value in milliseconds. The function signature is function(stored, ttl) where: * * stored - the timestamp when the item was stored in the cache (in milliseconds). * * ttl - the remaining time-to-live (not the original value used when storing the object). - */ + */ staleIn?: number | ((stored: number, ttl: number) => number); /** staleTimeout - number of milliseconds to wait before returning a stale value while generateFunc is generating a fresh value. */ staleTimeout?: number; - /** generateTimeout - number of milliseconds to wait before returning a timeout error when the generateFunc function takes too long to return a value. When the value is eventually returned, it is stored in the cache for future requests. Required if generateFunc is present. Set to false to disable timeouts which may cause all get() requests to get stuck forever. */ + /** + * generateTimeout - number of milliseconds to wait before returning a timeout error when the generateFunc function takes too long to return a value. + * When the value is eventually returned, it is stored in the cache for future requests. Required if generateFunc is present. + * Set to false to disable timeouts which may cause all get() requests to get stuck forever. + */ generateTimeout?: number | false; /** dropOnError - if true, an error or timeout in the generateFunc causes the stale value to be evicted from the cache. Defaults to true. */ dropOnError?: boolean; @@ -193,7 +255,10 @@ export interface PolicyOptions { generateOnReadError?: boolean; /** generateIgnoreWriteError - if false, an upstream cache write error will be passed back with the generated value when calling the get() method. Defaults to true. */ generateIgnoreWriteError?: boolean; - /** pendingGenerateTimeout - number of milliseconds while generateFunc call is in progress for a given id, before a subsequent generateFunc call is allowed. Defaults to 0, no blocking of concurrent generateFunc calls beyond staleTimeout. */ + /** + * pendingGenerateTimeout - number of milliseconds while generateFunc call is in progress for a given id, before a subsequent generateFunc call is allowed. + * Defaults to 0, no blocking of concurrent generateFunc calls beyond staleTimeout. + */ pendingGenerateTimeout?: number; } @@ -208,9 +273,7 @@ export interface PolicyOptions { * * ttl - the cache ttl value in milliseconds. Set to 0 to skip storing in the cache. Defaults to the cache global policy. * @see {@link https://github.com/hapijs/catbox#policy} */ -export interface GenerateFunc { - (id: string, next: ((err: null | Boom.BoomError, value: CacheItem, ttl?: number) => void)): void; -} +export type GenerateFunc = (id: string, next: ((err: null | Boom.BoomError, value: CacheItem, ttl?: number) => void)) => void; /** * An object with logging information about the generation operation containing the following keys (as relevant): @@ -242,6 +305,6 @@ export interface CacheStatisticsObject { stales: number; /** generates - number of calls to the generate function. */ generates: number; - /** errors - cache operations errors. TODO check this*/ + /** errors - cache operations errors. TODO check this */ errors: number; } diff --git a/types/catbox/tsconfig.json b/types/catbox/tsconfig.json index 3bc13b0278..b04177a675 100644 --- a/types/catbox/tsconfig.json +++ b/types/catbox/tsconfig.json @@ -16,6 +16,7 @@ "forceConsistentCasingInFileNames": true }, "files": [ - "index.d.ts" + "index.d.ts", + "catbox-tests.ts" ] -} \ No newline at end of file +} diff --git a/types/catbox/tslint.json b/types/catbox/tslint.json new file mode 100644 index 0000000000..3db14f85ea --- /dev/null +++ b/types/catbox/tslint.json @@ -0,0 +1 @@ +{ "extends": "dtslint/dt.json" } diff --git a/types/chai/index.d.ts b/types/chai/index.d.ts index 20f3c2b7df..01fc42631a 100644 --- a/types/chai/index.d.ts +++ b/types/chai/index.d.ts @@ -6,6 +6,7 @@ // Olivier Chevet , // Matt Wistrand , // Josh Goldberg +// Shaun Luttin // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped // @@ -487,6 +488,24 @@ declare namespace Chai { */ isNotNaN(value: T, message?: string): void; + /** + * Asserts that the target is neither null nor undefined. + * + * @type T Type of value. + * @param value Actual value. + * @param message Message to display on error. + */ + exists(value: T, message?: string): void; + + /** + * Asserts that the target is either null or undefined. + * + * @type T Type of value. + * @param value Actual value. + * @param message Message to display on error. + */ + notExists(value: T, message?: string): void; + /** * Asserts that value is undefined. * @@ -1318,6 +1337,17 @@ declare namespace Chai { * @param message Message to display on error. */ notFrozen(object: T, message?: string): void; + + /** + * Asserts that the target contains values. For arrays and strings, it checks + * the length property. For Map and Set instances, it checks the size property. + * For non-function objects, it gets the count of own enumerable string keys. + * + * @type T Type of object. + * @param object Object to test. + * @param message Message to display on error. + */ + isNotEmpty(object: T, message?: string): void; } export interface Config { diff --git a/types/chance/chance-tests.ts b/types/chance/chance-tests.ts index a426142d7f..dfb942f5c5 100644 --- a/types/chance/chance-tests.ts +++ b/types/chance/chance-tests.ts @@ -37,3 +37,4 @@ var timeString: string = chance.time(); var chanceConstructedWithSeed100 = new Chance(100); var chanceCalledWithSeed100 = Chance() +var chanceConstructedWithStringSeed = new Chance("test") diff --git a/types/chance/index.d.ts b/types/chance/index.d.ts index fc5347e859..7149e1032c 100644 --- a/types/chance/index.d.ts +++ b/types/chance/index.d.ts @@ -4,20 +4,21 @@ // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped declare namespace Chance { + type Seed = number | string; interface Seeded { - seed: number; + seed: Seed; } type SeededChance = Chance & Seeded; interface ChanceStatic { (): Chance - (seed: number): SeededChance + (seed: Seed): SeededChance (generator: () => any): Chance new(): Chance; - new(seed: number): SeededChance; + new(seed: Seed): SeededChance; new(generator: () => any): Chance; } @@ -156,7 +157,7 @@ declare namespace Chance { // "Hidden" cc_types(): CreditCardType[]; - mersenne_twister(seed?: number): any; // API return type not defined in docs + mersenne_twister(seed?: Seed): any; // API return type not defined in docs months(): Month[]; name_prefixes(): Name[]; provinces(): Name[]; diff --git a/types/chart.js/index.d.ts b/types/chart.js/index.d.ts index f1a39c84c4..a465806797 100644 --- a/types/chart.js/index.d.ts +++ b/types/chart.js/index.d.ts @@ -159,6 +159,8 @@ declare namespace Chart { elements?: ChartElementsOptions; scales?: ChartScales; cutoutPercentage?: number; + circumference?: number; + rotation?: number; } interface ChartFontOptions { diff --git a/types/chokidar/index.d.ts b/types/chokidar/index.d.ts index 09e957aa05..b60a4a5655 100644 --- a/types/chokidar/index.d.ts +++ b/types/chokidar/index.d.ts @@ -6,7 +6,7 @@ /// import * as fs from 'fs'; -import {EventEmitter} from 'events'; +import { EventEmitter } from 'events'; /** * The object's keys are all the directories (using absolute paths unless the `cwd` option was diff --git a/types/clear-require/clear-require-tests.ts b/types/clear-require/clear-require-tests.ts new file mode 100644 index 0000000000..53aea4d832 --- /dev/null +++ b/types/clear-require/clear-require-tests.ts @@ -0,0 +1,8 @@ +import * as clear from 'clear-require'; + +clear('my-module'); // clear specific module from require cache + +clear.all(); // clear all of the require cache + +clear.match(new RegExp('^.*$')); // clear all modules which match the RegExp +clear.match(/^.*$/); // similar to above but using /regex/ notation diff --git a/types/clear-require/index.d.ts b/types/clear-require/index.d.ts new file mode 100644 index 0000000000..4b9118a008 --- /dev/null +++ b/types/clear-require/index.d.ts @@ -0,0 +1,14 @@ +// Type definitions for clear-require 2.0 +// Project: https://github.com/sindresorhus/clear-module +// Definitions by: dan-j +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +interface ClearRequire { + (moduleId: string): boolean; + all(): void; + match(regex: RegExp): void; +} + +declare const clear: ClearRequire; + +export = clear; diff --git a/types/node-portscanner/tsconfig.json b/types/clear-require/tsconfig.json similarity index 92% rename from types/node-portscanner/tsconfig.json rename to types/clear-require/tsconfig.json index f9ce1f0f99..9c28741f0b 100644 --- a/types/node-portscanner/tsconfig.json +++ b/types/clear-require/tsconfig.json @@ -17,6 +17,6 @@ }, "files": [ "index.d.ts", - "node-portscanner-tests.ts" + "clear-require-tests.ts" ] } diff --git a/types/clear-require/tslint.json b/types/clear-require/tslint.json new file mode 100644 index 0000000000..3db14f85ea --- /dev/null +++ b/types/clear-require/tslint.json @@ -0,0 +1 @@ +{ "extends": "dtslint/dt.json" } diff --git a/types/closure-compiler/closure-compiler-tests.ts b/types/closure-compiler/closure-compiler-tests.ts index 3dd827a0f8..44693fca43 100644 --- a/types/closure-compiler/closure-compiler-tests.ts +++ b/types/closure-compiler/closure-compiler-tests.ts @@ -1,4 +1,4 @@ -import {compile} from 'closure-compiler'; +import { compile } from 'closure-compiler'; compile('some.source()', {'check-only': null}, (err: Error, stdout: string, stderr: string): void => { diff --git a/types/codemirror/codemirror-runmode.d.ts b/types/codemirror/codemirror-runmode.d.ts index 2252eb9649..e08be74ee0 100644 --- a/types/codemirror/codemirror-runmode.d.ts +++ b/types/codemirror/codemirror-runmode.d.ts @@ -20,5 +20,5 @@ declare module "codemirror" { * tokens will be converted to span elements as in an editor, * and inserted into the node (through innerHTML). */ - function runMode(text: string, modespec: any, callback: (HTMLElement | ((text: string, style: string) => void)), options? : { tabSize?: number; state?: any; }): void; + function runMode(text: string, modespec: any, callback: (HTMLElement | ((text: string, style: string | null) => void)), options? : { tabSize?: number; state?: any; }): void; } diff --git a/types/codemirror/index.d.ts b/types/codemirror/index.d.ts index b42ebabae3..65696db739 100644 --- a/types/codemirror/index.d.ts +++ b/types/codemirror/index.d.ts @@ -163,7 +163,7 @@ declare namespace CodeMirror { /** Sets the gutter marker for the given gutter (identified by its CSS class, see the gutters option) to the given value. Value can be either null, to clear the marker, or a DOM element, to set it. The DOM element will be shown in the specified gutter next to the specified line. */ - setGutterMarker(line: any, gutterID: string, value: HTMLElement): CodeMirror.LineHandle; + setGutterMarker(line: any, gutterID: string, value: HTMLElement | null): CodeMirror.LineHandle; /** Remove all gutter markers in the gutter with the given ID. */ clearGutter(gutterID: string): void; @@ -228,7 +228,7 @@ declare namespace CodeMirror { setSize(width: any, height: any): void; /** Scroll the editor to a given(pixel) position.Both arguments may be left as null or undefined to have no effect. */ - scrollTo(x: number, y: number): void; + scrollTo(x?: number | null, y?: number | null): void; /** Get an { left , top , width , height , clientWidth , clientHeight } object that represents the current scroll position, the size of the scrollable area, and the size of the visible area(minus scrollbars). */ @@ -236,7 +236,7 @@ declare namespace CodeMirror { /** Scrolls the given element into view. pos is a { line , ch } position, referring to a given character, null, to refer to the cursor. The margin parameter is optional. When given, it indicates the amount of pixels around the given area that should be made visible as well. */ - scrollIntoView(pos: CodeMirror.Position, margin?: number): void; + scrollIntoView(pos: CodeMirror.Position | null, margin?: number): void; /** Scrolls the given element into view. pos is a { left , top , right , bottom } object, in editor-local coordinates. The margin parameter is optional. When given, it indicates the amount of pixels around the given area that should be made visible as well. */ @@ -297,7 +297,7 @@ declare namespace CodeMirror { /** The token's string. */ string: string; /** The token type the mode assigned to the token, such as "keyword" or "comment" (may also be null). */ - type: string; + type: string | null; /** The mode's state at the end of this token. */ state: any; }; @@ -464,7 +464,7 @@ declare namespace CodeMirror { getLineHandle(num: number): CodeMirror.LineHandle; /** Given a line handle, returns the current position of that line (or null when it is no longer in the document). */ - getLineNumber(handle: CodeMirror.LineHandle): number; + getLineNumber(handle: CodeMirror.LineHandle): number | null; /** Iterate over the whole document, and call f for each line, passing the line handle. This is a faster way to visit a range of line handlers than calling getLineHandle for each of them. @@ -522,7 +522,7 @@ declare namespace CodeMirror { /** Retrieve the editor associated with a document. May return null. */ - getEditor(): CodeMirror.Editor; + getEditor(): CodeMirror.Editor | null; /** Create an identical copy of the given doc. When copyHistory is true , the history will also be copied.Can not be called directly on an editor. */ @@ -935,12 +935,12 @@ declare namespace CodeMirror { /** * Returns the next character in the stream without advancing it. Will return an null at the end of the line. */ - peek(): string; + peek(): string | null; /** * Returns the next character in the stream and advances it. Also returns null when no more characters are available. */ - next(): string; + next(): string | null; /** * match can be a character, a regular expression, or a function that takes a character and returns a boolean. @@ -1016,7 +1016,7 @@ declare namespace CodeMirror { * This function should read one token from the stream it is given as an argument, optionally update its state, * and return a style string, or null for tokens that do not have to be styled. Multiple styles can be returned, separated by spaces. */ - token(stream: StringStream, state: T): string; + token(stream: StringStream, state: T): string | null; /** * A function that produces a state object to be used at the start of a document. diff --git a/types/color-convert/color-convert-tests.ts b/types/color-convert/color-convert-tests.ts new file mode 100644 index 0000000000..735c169a2f --- /dev/null +++ b/types/color-convert/color-convert-tests.ts @@ -0,0 +1,6 @@ +import * as color from 'color-convert'; +import * as conv from 'color-convert/conversions'; + +let hsv: [number, number, number] = color.rgb.hsv([1, 2, 3]); +let hsv_raw: [number, number, number] = color.rgb.hsv.raw([1, 2, 3]); +let aaa: [number, number, number] = color.rgb.hsv([1, 2, 3]); diff --git a/types/color-convert/conversions.d.ts b/types/color-convert/conversions.d.ts new file mode 100644 index 0000000000..aa461d40b0 --- /dev/null +++ b/types/color-convert/conversions.d.ts @@ -0,0 +1,136 @@ +import * as cssKeywords from 'color-name'; + +export type RGB = [number, number, number]; +export type HSL = [number, number, number]; +export type HSV = [number, number, number]; +export type HWB = [number, number, number]; +export type CMYK = [number, number, number, number]; +export type XYZ = [number, number, number]; +export type LAB = [number, number, number]; +export type LCH = [number, number, number]; +export type HEX = string; +export type KEYWORD = keyof typeof cssKeywords; +export type ANSI16 = number; +export type ANSI256 = number; +export type HCG = [number, number, number]; +export type APPLE = [number, number, number]; +export type GRAY = [number]; + +export namespace rgb { + const channels: 3; + const labels: 'rgb'; + function hsl(rgb: RGB): HSL; + function hsv(rgb: RGB): HSV; + function hwb(rgb: RGB): HWB; + function cmyk(rgb: RGB): CMYK; + function keyword(rgb: RGB): KEYWORD; + function xyz(rgb: RGB): XYZ; + function lab(rgb: RGB): LAB; + function ansi16(rgb: RGB): ANSI16; + function ansi256(rgb: RGB): ANSI256; + function hex(rgb: RGB): HEX; + function hcg(rgb: RGB): HCG; + function apple(rgb: RGB): APPLE; + function gray(rgb: RGB): GRAY; +} + +export namespace hsl { + const channels: 3; + const labels: 'hsl'; + function rgb(hsl: HSL): RGB; + function hsv(hsl: HSL): HSV; + function hcg(hsl: HSL): HCG; +} + +export namespace hsv { + const channels: 3; + const labels: 'hsv'; + function rgb(hsv: HSV): RGB; + function hsl(hsv: HSV): HSL; + function ansi16(hsv: HSV): ANSI16; + function hcg(hsv: HSV): HCG; +} + +export namespace hwb { + const channels: 3; + const labels: 'hwb'; + function rgb(hwb: HWB): RGB; + function hcg(hwb: HWB): HCG; +} + +export namespace cmyk { + const channels: 4; + const labels: 'cmyk'; + function rgb(cmyk: CMYK): RGB; +} + +export namespace xyz { + const channels: 3; + const labels: 'xyz'; + function rgb(xyz: XYZ): RGB; + function lab(xyz: XYZ): LAB; +} + +export namespace lab { + const channels: 3; + const labels: 'lab'; + function xyz(lab: LAB): XYZ; + function lch(lab: LAB): LCH; +} + +export namespace lch { + const channels: 3; + const labels: 'lch'; + function lab(lch: LCH): LAB; +} + +export namespace hex { + const channels: 1; + const labels: ['hex']; + function rgb(hex: HEX): RGB; +} + +export namespace keyword { + const channels: 1; + const labels: ['keyword']; + function rgb(keyword: KEYWORD): RGB; +} + +export namespace ansi16 { + const channels: 1; + const labels: ['ansi16']; + function rgb(ansi16: ANSI16): RGB; +} + +export namespace ansi256 { + const channels: 1; + const labels: ['ansi256']; + function rgb(ansi256: ANSI256): RGB; +} + +export namespace hcg { + const channels: 3; + const labels: ['h', 'c', 'g']; + function rgb(hcg: HCG): RGB; + function hsv(hcg: HCG): HSV; + function hsl(hcg: HCG): HSL; + function hwb(hcg: HCG): HWB; +} + +export namespace apple { + const channels: 3; + const labels: ['r16', 'g16', 'b16']; + function rgb(apple: APPLE): RGB; +} + +export namespace gray { + const channels: 1; + const labels: ['gray']; + function rgb(gray: GRAY): RGB; + function hsl(gray: GRAY): HSL; + function hsv(gray: GRAY): HSV; + function hwb(gray: GRAY): HWB; + function cmyk(gray: GRAY): CMYK; + function lab(gray: GRAY): LAB; + function hex(gray: GRAY): HEX; +} diff --git a/types/color-convert/index.d.ts b/types/color-convert/index.d.ts new file mode 100644 index 0000000000..be2a0dafa6 --- /dev/null +++ b/types/color-convert/index.d.ts @@ -0,0 +1,98 @@ +// Type definitions for color-convert 1.9 +// Project: https://github.com/qix-/color-convert#readme +// Definitions by: Junyoung Clare Jang +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.3 + +import conversions = require('./conversions'); +import route = require('./route'); + +export const rgb: typeof conversions.rgb & route.rgb & { + [F in keyof route.rgb]: { + raw: route.rgb[F] + } +}; + +export const hsl: typeof conversions.hsl & route.hsl & { + [F in keyof route.hsl]: { + raw: route.hsl[F] + } +}; + +export const hsv: typeof conversions.hsv & route.hsv & { + [F in keyof route.hsv]: { + raw: route.hsv[F] + } +}; + +export const hwb: typeof conversions.hwb & route.hwb & { + [F in keyof route.hwb]: { + raw: route.hwb[F] + } +}; + +export const cmyk: typeof conversions.cmyk & route.cmyk & { + [F in keyof route.cmyk]: { + raw: route.cmyk[F] + } +}; + +export const xyz: typeof conversions.xyz & route.xyz & { + [F in keyof route.xyz]: { + raw: route.xyz[F] + } +}; + +export const lab: typeof conversions.lab & route.lab & { + [F in keyof route.lab]: { + raw: route.lab[F] + } +}; + +export const lch: typeof conversions.lch & route.lch & { + [F in keyof route.lch]: { + raw: route.lch[F] + } +}; + +export const hex: typeof conversions.hex & route.hex & { + [F in keyof route.hex]: { + raw: route.hex[F] + } +}; + +export const keyword: typeof conversions.keyword & route.keyword & { + [F in keyof route.keyword]: { + raw: route.keyword[F] + } +}; + +export const ansi16: typeof conversions.ansi16 & route.ansi16 & { + [F in keyof route.ansi16]: { + raw: route.ansi16[F] + } +}; + +export const ansi256: typeof conversions.ansi256 & route.ansi256 & { + [F in keyof route.ansi256]: { + raw: route.ansi256[F] + } +}; + +export const hcg: typeof conversions.hcg & route.hcg & { + [F in keyof route.hcg]: { + raw: route.hcg[F] + } +}; + +export const apple: typeof conversions.apple & route.apple & { + [F in keyof route.apple]: { + raw: route.apple[F] + } +}; + +export const gray: typeof conversions.gray & route.gray & { + [F in keyof route.gray]: { + raw: route.gray[F] + } +}; diff --git a/types/color-convert/route.d.ts b/types/color-convert/route.d.ts new file mode 100644 index 0000000000..f9ea4f7cf8 --- /dev/null +++ b/types/color-convert/route.d.ts @@ -0,0 +1,262 @@ +import conversions = require('./conversions'); + +declare namespace route { + interface rgb { + hsl(from: conversions.RGB): conversions.HSL; + hsv(from: conversions.RGB): conversions.HSV; + hwb(from: conversions.RGB): conversions.HWB; + cmyk(from: conversions.RGB): conversions.CMYK; + xyz(from: conversions.RGB): conversions.XYZ; + lab(from: conversions.RGB): conversions.LAB; + lch(from: conversions.RGB): conversions.LCH; + hex(from: conversions.RGB): conversions.HEX; + keyword(from: conversions.RGB): conversions.KEYWORD; + ansi16(from: conversions.RGB): conversions.ANSI16; + ansi256(from: conversions.RGB): conversions.ANSI256; + hcg(from: conversions.RGB): conversions.HCG; + apple(from: conversions.RGB): conversions.APPLE; + gray(from: conversions.RGB): conversions.GRAY; + } + interface hsl { + rgb(from: conversions.HSL): conversions.RGB; + hsv(from: conversions.HSL): conversions.HSV; + hwb(from: conversions.HSL): conversions.HWB; + cmyk(from: conversions.HSL): conversions.CMYK; + xyz(from: conversions.HSL): conversions.XYZ; + lab(from: conversions.HSL): conversions.LAB; + lch(from: conversions.HSL): conversions.LCH; + hex(from: conversions.HSL): conversions.HEX; + keyword(from: conversions.HSL): conversions.KEYWORD; + ansi16(from: conversions.HSL): conversions.ANSI16; + ansi256(from: conversions.HSL): conversions.ANSI256; + hcg(from: conversions.HSL): conversions.HCG; + apple(from: conversions.HSL): conversions.APPLE; + gray(from: conversions.HSL): conversions.GRAY; + } + interface hsv { + rgb(from: conversions.HSV): conversions.RGB; + hsl(from: conversions.HSV): conversions.HSL; + hwb(from: conversions.HSV): conversions.HWB; + cmyk(from: conversions.HSV): conversions.CMYK; + xyz(from: conversions.HSV): conversions.XYZ; + lab(from: conversions.HSV): conversions.LAB; + lch(from: conversions.HSV): conversions.LCH; + hex(from: conversions.HSV): conversions.HEX; + keyword(from: conversions.HSV): conversions.KEYWORD; + ansi16(from: conversions.HSV): conversions.ANSI16; + ansi256(from: conversions.HSV): conversions.ANSI256; + hcg(from: conversions.HSV): conversions.HCG; + apple(from: conversions.HSV): conversions.APPLE; + gray(from: conversions.HSV): conversions.GRAY; + } + interface hwb { + rgb(from: conversions.HWB): conversions.RGB; + hsl(from: conversions.HWB): conversions.HSL; + hsv(from: conversions.HWB): conversions.HSV; + cmyk(from: conversions.HWB): conversions.CMYK; + xyz(from: conversions.HWB): conversions.XYZ; + lab(from: conversions.HWB): conversions.LAB; + lch(from: conversions.HWB): conversions.LCH; + hex(from: conversions.HWB): conversions.HEX; + keyword(from: conversions.HWB): conversions.KEYWORD; + ansi16(from: conversions.HWB): conversions.ANSI16; + ansi256(from: conversions.HWB): conversions.ANSI256; + hcg(from: conversions.HWB): conversions.HCG; + apple(from: conversions.HWB): conversions.APPLE; + gray(from: conversions.HWB): conversions.GRAY; + } + interface cmyk { + rgb(from: conversions.CMYK): conversions.RGB; + hsl(from: conversions.CMYK): conversions.HSL; + hsv(from: conversions.CMYK): conversions.HSV; + hwb(from: conversions.CMYK): conversions.HWB; + xyz(from: conversions.CMYK): conversions.XYZ; + lab(from: conversions.CMYK): conversions.LAB; + lch(from: conversions.CMYK): conversions.LCH; + hex(from: conversions.CMYK): conversions.HEX; + keyword(from: conversions.CMYK): conversions.KEYWORD; + ansi16(from: conversions.CMYK): conversions.ANSI16; + ansi256(from: conversions.CMYK): conversions.ANSI256; + hcg(from: conversions.CMYK): conversions.HCG; + apple(from: conversions.CMYK): conversions.APPLE; + gray(from: conversions.CMYK): conversions.GRAY; + } + interface xyz { + rgb(from: conversions.XYZ): conversions.RGB; + hsl(from: conversions.XYZ): conversions.HSL; + hsv(from: conversions.XYZ): conversions.HSV; + hwb(from: conversions.XYZ): conversions.HWB; + cmyk(from: conversions.XYZ): conversions.CMYK; + lab(from: conversions.XYZ): conversions.LAB; + lch(from: conversions.XYZ): conversions.LCH; + hex(from: conversions.XYZ): conversions.HEX; + keyword(from: conversions.XYZ): conversions.KEYWORD; + ansi16(from: conversions.XYZ): conversions.ANSI16; + ansi256(from: conversions.XYZ): conversions.ANSI256; + hcg(from: conversions.XYZ): conversions.HCG; + apple(from: conversions.XYZ): conversions.APPLE; + gray(from: conversions.XYZ): conversions.GRAY; + } + interface lab { + rgb(from: conversions.LAB): conversions.RGB; + hsl(from: conversions.LAB): conversions.HSL; + hsv(from: conversions.LAB): conversions.HSV; + hwb(from: conversions.LAB): conversions.HWB; + cmyk(from: conversions.LAB): conversions.CMYK; + xyz(from: conversions.LAB): conversions.XYZ; + lch(from: conversions.LAB): conversions.LCH; + hex(from: conversions.LAB): conversions.HEX; + keyword(from: conversions.LAB): conversions.KEYWORD; + ansi16(from: conversions.LAB): conversions.ANSI16; + ansi256(from: conversions.LAB): conversions.ANSI256; + hcg(from: conversions.LAB): conversions.HCG; + apple(from: conversions.LAB): conversions.APPLE; + gray(from: conversions.LAB): conversions.GRAY; + } + interface lch { + rgb(from: conversions.LCH): conversions.RGB; + hsl(from: conversions.LCH): conversions.HSL; + hsv(from: conversions.LCH): conversions.HSV; + hwb(from: conversions.LCH): conversions.HWB; + cmyk(from: conversions.LCH): conversions.CMYK; + xyz(from: conversions.LCH): conversions.XYZ; + lab(from: conversions.LCH): conversions.LAB; + hex(from: conversions.LCH): conversions.HEX; + keyword(from: conversions.LCH): conversions.KEYWORD; + ansi16(from: conversions.LCH): conversions.ANSI16; + ansi256(from: conversions.LCH): conversions.ANSI256; + hcg(from: conversions.LCH): conversions.HCG; + apple(from: conversions.LCH): conversions.APPLE; + gray(from: conversions.LCH): conversions.GRAY; + } + interface hex { + rgb(from: conversions.HEX): conversions.RGB; + hsl(from: conversions.HEX): conversions.HSL; + hsv(from: conversions.HEX): conversions.HSV; + hwb(from: conversions.HEX): conversions.HWB; + cmyk(from: conversions.HEX): conversions.CMYK; + xyz(from: conversions.HEX): conversions.XYZ; + lab(from: conversions.HEX): conversions.LAB; + lch(from: conversions.HEX): conversions.LCH; + keyword(from: conversions.HEX): conversions.KEYWORD; + ansi16(from: conversions.HEX): conversions.ANSI16; + ansi256(from: conversions.HEX): conversions.ANSI256; + hcg(from: conversions.HEX): conversions.HCG; + apple(from: conversions.HEX): conversions.APPLE; + gray(from: conversions.HEX): conversions.GRAY; + } + interface keyword { + rgb(from: conversions.KEYWORD): conversions.RGB; + hsl(from: conversions.KEYWORD): conversions.HSL; + hsv(from: conversions.KEYWORD): conversions.HSV; + hwb(from: conversions.KEYWORD): conversions.HWB; + cmyk(from: conversions.KEYWORD): conversions.CMYK; + xyz(from: conversions.KEYWORD): conversions.XYZ; + lab(from: conversions.KEYWORD): conversions.LAB; + lch(from: conversions.KEYWORD): conversions.LCH; + hex(from: conversions.KEYWORD): conversions.HEX; + ansi16(from: conversions.KEYWORD): conversions.ANSI16; + ansi256(from: conversions.KEYWORD): conversions.ANSI256; + hcg(from: conversions.KEYWORD): conversions.HCG; + apple(from: conversions.KEYWORD): conversions.APPLE; + gray(from: conversions.KEYWORD): conversions.GRAY; + } + interface ansi16 { + rgb(from: conversions.ANSI16): conversions.RGB; + hsl(from: conversions.ANSI16): conversions.HSL; + hsv(from: conversions.ANSI16): conversions.HSV; + hwb(from: conversions.ANSI16): conversions.HWB; + cmyk(from: conversions.ANSI16): conversions.CMYK; + xyz(from: conversions.ANSI16): conversions.XYZ; + lab(from: conversions.ANSI16): conversions.LAB; + lch(from: conversions.ANSI16): conversions.LCH; + hex(from: conversions.ANSI16): conversions.HEX; + keyword(from: conversions.ANSI16): conversions.KEYWORD; + ansi256(from: conversions.ANSI16): conversions.ANSI256; + hcg(from: conversions.ANSI16): conversions.HCG; + apple(from: conversions.ANSI16): conversions.APPLE; + gray(from: conversions.ANSI16): conversions.GRAY; + } + interface ansi256 { + rgb(from: conversions.ANSI256): conversions.RGB; + hsl(from: conversions.ANSI256): conversions.HSL; + hsv(from: conversions.ANSI256): conversions.HSV; + hwb(from: conversions.ANSI256): conversions.HWB; + cmyk(from: conversions.ANSI256): conversions.CMYK; + xyz(from: conversions.ANSI256): conversions.XYZ; + lab(from: conversions.ANSI256): conversions.LAB; + lch(from: conversions.ANSI256): conversions.LCH; + hex(from: conversions.ANSI256): conversions.HEX; + keyword(from: conversions.ANSI256): conversions.KEYWORD; + ansi16(from: conversions.ANSI256): conversions.ANSI16; + hcg(from: conversions.ANSI256): conversions.HCG; + apple(from: conversions.ANSI256): conversions.APPLE; + gray(from: conversions.ANSI256): conversions.GRAY; + } + interface hcg { + rgb(from: conversions.HCG): conversions.RGB; + hsl(from: conversions.HCG): conversions.HSL; + hsv(from: conversions.HCG): conversions.HSV; + hwb(from: conversions.HCG): conversions.HWB; + cmyk(from: conversions.HCG): conversions.CMYK; + xyz(from: conversions.HCG): conversions.XYZ; + lab(from: conversions.HCG): conversions.LAB; + lch(from: conversions.HCG): conversions.LCH; + hex(from: conversions.HCG): conversions.HEX; + keyword(from: conversions.HCG): conversions.KEYWORD; + ansi16(from: conversions.HCG): conversions.ANSI16; + ansi256(from: conversions.HCG): conversions.ANSI256; + apple(from: conversions.HCG): conversions.APPLE; + gray(from: conversions.HCG): conversions.GRAY; + } + interface apple { + rgb(from: conversions.APPLE): conversions.RGB; + hsl(from: conversions.APPLE): conversions.HSL; + hsv(from: conversions.APPLE): conversions.HSV; + hwb(from: conversions.APPLE): conversions.HWB; + cmyk(from: conversions.APPLE): conversions.CMYK; + xyz(from: conversions.APPLE): conversions.XYZ; + lab(from: conversions.APPLE): conversions.LAB; + lch(from: conversions.APPLE): conversions.LCH; + hex(from: conversions.APPLE): conversions.HEX; + keyword(from: conversions.APPLE): conversions.KEYWORD; + ansi16(from: conversions.APPLE): conversions.ANSI16; + ansi256(from: conversions.APPLE): conversions.ANSI256; + hcg(from: conversions.APPLE): conversions.HCG; + gray(from: conversions.APPLE): conversions.GRAY; + } + interface gray { + rgb(from: conversions.GRAY): conversions.RGB; + hsl(from: conversions.GRAY): conversions.HSL; + hsv(from: conversions.GRAY): conversions.HSV; + hwb(from: conversions.GRAY): conversions.HWB; + cmyk(from: conversions.GRAY): conversions.CMYK; + xyz(from: conversions.GRAY): conversions.XYZ; + lab(from: conversions.GRAY): conversions.LAB; + lch(from: conversions.GRAY): conversions.LCH; + hex(from: conversions.GRAY): conversions.HEX; + keyword(from: conversions.GRAY): conversions.KEYWORD; + ansi16(from: conversions.GRAY): conversions.ANSI16; + ansi256(from: conversions.GRAY): conversions.ANSI256; + hcg(from: conversions.GRAY): conversions.HCG; + apple(from: conversions.GRAY): conversions.APPLE; + } +} + +declare function route(fromModel: 'rgb'): route.rgb; +declare function route(fromModel: 'hsl'): route.hsl; +declare function route(fromModel: 'hsv'): route.hsv; +declare function route(fromModel: 'hwb'): route.hwb; +declare function route(fromModel: 'cmyk'): route.cmyk; +declare function route(fromModel: 'xyz'): route.xyz; +declare function route(fromModel: 'lab'): route.lab; +declare function route(fromModel: 'lch'): route.lch; +declare function route(fromModel: 'hex'): route.hex; +declare function route(fromModel: 'keyword'): route.keyword; +declare function route(fromModel: 'ansi16'): route.ansi16; +declare function route(fromModel: 'ansi256'): route.ansi256; +declare function route(fromModel: 'hcg'): route.hcg; +declare function route(fromModel: 'apple'): route.apple; +declare function route(fromModel: 'gray'): route.gray; + +export = route; diff --git a/types/color-convert/tsconfig.json b/types/color-convert/tsconfig.json new file mode 100644 index 0000000000..70b4bd0fd9 --- /dev/null +++ b/types/color-convert/tsconfig.json @@ -0,0 +1,24 @@ +{ + "compilerOptions": { + "module": "commonjs", + "lib": [ + "es6" + ], + "noImplicitAny": true, + "noImplicitThis": true, + "strictNullChecks": true, + "baseUrl": "../", + "typeRoots": [ + "../" + ], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true + }, + "files": [ + "index.d.ts", + "conversions.d.ts", + "route.d.ts", + "color-convert-tests.ts" + ] +} diff --git a/types/color-convert/tslint.json b/types/color-convert/tslint.json new file mode 100644 index 0000000000..3db14f85ea --- /dev/null +++ b/types/color-convert/tslint.json @@ -0,0 +1 @@ +{ "extends": "dtslint/dt.json" } diff --git a/types/color-name/color-name-tests.ts b/types/color-name/color-name-tests.ts new file mode 100644 index 0000000000..5d8998c97a --- /dev/null +++ b/types/color-name/color-name-tests.ts @@ -0,0 +1,5 @@ +import * as colorname from 'color-name'; + +let color: [number, number, number] = colorname.aliceblue; +color = colorname.darkkhaki; +color = colorname.gainsboro; diff --git a/types/color-name/index.d.ts b/types/color-name/index.d.ts new file mode 100644 index 0000000000..65b4ecc8fb --- /dev/null +++ b/types/color-name/index.d.ts @@ -0,0 +1,161 @@ +// Type definitions for color-name 1.1 +// Project: https://www.npmjs.com/package/color-name +// Definitions by: Junyoung Clare Jang +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +/** + * Tuple of Red, Green, and Blue + * @example + * // Red = 55, Green = 70, Blue = 0 + * const rgb: RGB = [55, 70, 0]; + */ +export type RGB = [number, number, number]; + +export const aliceblue: RGB; +export const antiquewhite: RGB; +export const aqua: RGB; +export const aquamarine: RGB; +export const azure: RGB; +export const beige: RGB; +export const bisque: RGB; +export const black: RGB; +export const blanchedalmond: RGB; +export const blue: RGB; +export const blueviolet: RGB; +export const brown: RGB; +export const burlywood: RGB; +export const cadetblue: RGB; +export const chartreuse: RGB; +export const chocolate: RGB; +export const coral: RGB; +export const cornflowerblue: RGB; +export const cornsilk: RGB; +export const crimson: RGB; +export const cyan: RGB; +export const darkblue: RGB; +export const darkcyan: RGB; +export const darkgoldenrod: RGB; +export const darkgray: RGB; +export const darkgreen: RGB; +export const darkgrey: RGB; +export const darkkhaki: RGB; +export const darkmagenta: RGB; +export const darkolivegreen: RGB; +export const darkorange: RGB; +export const darkorchid: RGB; +export const darkred: RGB; +export const darksalmon: RGB; +export const darkseagreen: RGB; +export const darkslateblue: RGB; +export const darkslategray: RGB; +export const darkslategrey: RGB; +export const darkturquoise: RGB; +export const darkviolet: RGB; +export const deeppink: RGB; +export const deepskyblue: RGB; +export const dimgray: RGB; +export const dimgrey: RGB; +export const dodgerblue: RGB; +export const firebrick: RGB; +export const floralwhite: RGB; +export const forestgreen: RGB; +export const fuchsia: RGB; +export const gainsboro: RGB; +export const ghostwhite: RGB; +export const gold: RGB; +export const goldenrod: RGB; +export const gray: RGB; +export const green: RGB; +export const greenyellow: RGB; +export const grey: RGB; +export const honeydew: RGB; +export const hotpink: RGB; +export const indianred: RGB; +export const indigo: RGB; +export const ivory: RGB; +export const khaki: RGB; +export const lavender: RGB; +export const lavenderblush: RGB; +export const lawngreen: RGB; +export const lemonchiffon: RGB; +export const lightblue: RGB; +export const lightcoral: RGB; +export const lightcyan: RGB; +export const lightgoldenrodyellow: RGB; +export const lightgray: RGB; +export const lightgreen: RGB; +export const lightgrey: RGB; +export const lightpink: RGB; +export const lightsalmon: RGB; +export const lightseagreen: RGB; +export const lightskyblue: RGB; +export const lightslategray: RGB; +export const lightslategrey: RGB; +export const lightsteelblue: RGB; +export const lightyellow: RGB; +export const lime: RGB; +export const limegreen: RGB; +export const linen: RGB; +export const magenta: RGB; +export const maroon: RGB; +export const mediumaquamarine: RGB; +export const mediumblue: RGB; +export const mediumorchid: RGB; +export const mediumpurple: RGB; +export const mediumseagreen: RGB; +export const mediumslateblue: RGB; +export const mediumspringgreen: RGB; +export const mediumturquoise: RGB; +export const mediumvioletred: RGB; +export const midnightblue: RGB; +export const mintcream: RGB; +export const mistyrose: RGB; +export const moccasin: RGB; +export const navajowhite: RGB; +export const navy: RGB; +export const oldlace: RGB; +export const olive: RGB; +export const olivedrab: RGB; +export const orange: RGB; +export const orangered: RGB; +export const orchid: RGB; +export const palegoldenrod: RGB; +export const palegreen: RGB; +export const paleturquoise: RGB; +export const palevioletred: RGB; +export const papayawhip: RGB; +export const peachpuff: RGB; +export const peru: RGB; +export const pink: RGB; +export const plum: RGB; +export const powderblue: RGB; +export const purple: RGB; +export const rebeccapurple: RGB; +export const red: RGB; +export const rosybrown: RGB; +export const royalblue: RGB; +export const saddlebrown: RGB; +export const salmon: RGB; +export const sandybrown: RGB; +export const seagreen: RGB; +export const seashell: RGB; +export const sienna: RGB; +export const silver: RGB; +export const skyblue: RGB; +export const slateblue: RGB; +export const slategray: RGB; +export const slategrey: RGB; +export const snow: RGB; +export const springgreen: RGB; +export const steelblue: RGB; +export const tan: RGB; +export const teal: RGB; +export const thistle: RGB; +export const tomato: RGB; +export const turquoise: RGB; +export const violet: RGB; +export const wheat: RGB; +export const white: RGB; +export const whitesmoke: RGB; +export const yellow: RGB; +export const yellowgreen: RGB; diff --git a/types/color-name/tsconfig.json b/types/color-name/tsconfig.json new file mode 100644 index 0000000000..30cfb50814 --- /dev/null +++ b/types/color-name/tsconfig.json @@ -0,0 +1,20 @@ +{ + "compilerOptions": { + "baseUrl": "../", + "forceConsistentCasingInFileNames": true, + "lib": [ + "es6" + ], + "module": "commonjs", + "noEmit": true, + "noImplicitAny": true, + "noImplicitThis": true, + "strictNullChecks": true, + "types": [], + "typeRoots": ["../"] + }, + "files": [ + "index.d.ts", + "color-name-tests.ts" + ] +} diff --git a/types/color-name/tslint.json b/types/color-name/tslint.json new file mode 100644 index 0000000000..3db14f85ea --- /dev/null +++ b/types/color-name/tslint.json @@ -0,0 +1 @@ +{ "extends": "dtslint/dt.json" } diff --git a/types/color-string/color-string-tests.ts b/types/color-string/color-string-tests.ts new file mode 100644 index 0000000000..3f084fbc25 --- /dev/null +++ b/types/color-string/color-string-tests.ts @@ -0,0 +1,38 @@ +import * as colorString from 'color-string'; + +let colorDescriptor: colorString.ColorDescriptor | null; +colorDescriptor = colorString.get('#FFF'); +colorDescriptor = colorString.get('#FFFA'); +colorDescriptor = colorString.get('#FFFFFFAA'); +colorDescriptor = colorString.get('hsl(360, 100%, 50%)'); +colorDescriptor = colorString.get('hwb(60, 3%, 60%)'); + +let color: colorString.Color | null; +color = colorString.get.rgb('#FFF'); +color = colorString.get.rgb('blue'); +color = colorString.get.rgb('rgba(200, 60, 60, 0.3)'); +color = colorString.get.rgb('rgb(200, 200, 200)'); + +color = colorString.get.hsl('hsl(360, 100%, 50%)'); +color = colorString.get.hsl('hsla(360, 60%, 50%, 0.4)'); +color = colorString.get.hwb('hwb(60, 3%, 60%)'); + +color = colorString.get.hwb('hwb(60, 3%, 60%, 0.6)'); + +color = colorString.get.rgb('invalid color string'); + +let stringifiedColor: string; +stringifiedColor = colorString.to.hex([255, 255, 255]); +stringifiedColor = colorString.to.hex([0, 0, 255, 0.4]); +stringifiedColor = colorString.to.hex([0, 0, 255], 0.4); +stringifiedColor = colorString.to.rgb([255, 255, 255]); +stringifiedColor = colorString.to.rgb([0, 0, 255, 0.4]); +stringifiedColor = colorString.to.rgb([0, 0, 255], 0.4); +stringifiedColor = colorString.to.rgb.percent([0, 0, 255]); +stringifiedColor = colorString.to.keyword([255, 255, 0]); +stringifiedColor = colorString.to.hsl([360, 100, 100]); +stringifiedColor = colorString.to.hwb([50, 3, 15]); + +stringifiedColor = colorString.to.rgb(0, [0, 255], 0.4); +stringifiedColor = colorString.to.rgb([0, 0], [255], 0.4); +stringifiedColor = colorString.to.rgb([0], 0, [255, 0.4]); diff --git a/types/color-string/index.d.ts b/types/color-string/index.d.ts new file mode 100644 index 0000000000..4eda883297 --- /dev/null +++ b/types/color-string/index.d.ts @@ -0,0 +1,31 @@ +// Type definitions for color-string 1.5 +// Project: https://github.com/qix-/color-string#readme +// Definitions by: BendingBender +// Dan Marshall +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +export type Color = [number, number, number, number]; + +export interface ColorDescriptor { + model: 'rgb' | 'hsl' | 'hwb'; + value: Color; +} + +export function get(colorString: string): ColorDescriptor | null; + +export namespace get { + function hsl(colorString: string): Color | null; + function hwb(colorString: string): Color | null; + function rgb(colorString: string): Color | null; +} + +export namespace to { + function hex(...args: Array): string; + function rgb(...args: Array): string; + namespace rgb { + function percent(...args: Array): string; + } + function keyword(...args: Array): string; + function hsl(...args: Array): string; + function hwb(...args: Array): string; +} diff --git a/types/color-string/tsconfig.json b/types/color-string/tsconfig.json new file mode 100644 index 0000000000..bf5a829c6e --- /dev/null +++ b/types/color-string/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", + "color-string-tests.ts" + ] +} diff --git a/types/color-string/tslint.json b/types/color-string/tslint.json new file mode 100644 index 0000000000..3db14f85ea --- /dev/null +++ b/types/color-string/tslint.json @@ -0,0 +1 @@ +{ "extends": "dtslint/dt.json" } diff --git a/types/color/color-tests.ts b/types/color/color-tests.ts index 2d05e86f05..4e475a0ce0 100644 --- a/types/color/color-tests.ts +++ b/types/color/color-tests.ts @@ -1,41 +1,43 @@ -import * as Color from "color" +import Color = require('color'); -var color: Color.Color = Color("white") -var colorOther: Color.Color = Color("black") -var colorRGB: Color.Color = Color({ r : 0, g : 0, b : 0 }, "rgb") -var colorInt: Color.Color = Color(0x000000) +const color: Color = new Color("white"); +const colorOther: Color = new Color("black"); +const colorRGB: Color = new Color({ r: 0, g: 0, b: 0 }, "rgb"); +const colorInt: Color = new Color(0x000000); +const colorWithoutNew: Color = Color(0x000000); +const colorByStaticMethod: Color = Color.rgb({ r: 0, g: 0, b: 0 }); -var hex: string = color.hex() -var percent: string = color.percentString() -var keyword: string | void = color.keyword() -var alpha: number = color.alpha() -var red: number = color.red() -var green: number = color.green() -var blue: number = color.blue() -var hue: number = color.hue() -var saturationl: number = color.saturationl() -var lightness: number = color.lightness() -var saturationv: number = color.saturationv() -var value: number = color.value() -var cyan: number = color.cyan() -var magenta: number = color.magenta() -var yellow: number = color.yellow() -var black: number = color.black() -var luminosity: number = color.luminosity() -var contrast: number = color.contrast(colorOther) -var dark: boolean = color.dark() -var light: boolean = color.light() -var level: string = color.level(colorOther) +const hex: string = color.hex(); +const percent: string = color.percentString(); +const keyword: string = color.keyword(); +const alpha: number = color.alpha(); +const red: number = color.red(); +const green: number = color.green(); +const blue: number = color.blue(); +const hue: number = color.hue(); +const saturationl: number = color.saturationl(); +const lightness: number = color.lightness(); +const saturationv: number = color.saturationv(); +const value: number = color.value(); +const cyan: number = color.cyan(); +const magenta: number = color.magenta(); +const yellow: number = color.yellow(); +const black: number = color.black(); +const luminosity: number = color.luminosity(); +const contrast: number = color.contrast(colorOther); +const dark: boolean = color.dark(); +const light: boolean = color.light(); +const level: string = color.level(colorOther); -var x: number = color.x() -var y: number = color.y() -var z: number = color.z() -var l: number = color.l() -var a: number = color.a() -var b: number = color.b() -var rgbNumber: number = color.rgbNumber() +const x: number = color.x(); +const y: number = color.y(); +const z: number = color.z(); +const l: number = color.l(); +const a: number = color.a(); +const b: number = color.b(); +const rgbNumber: number = color.rgbNumber(); -var chain: Color.Color = color +const chain: Color = color .alpha(0) .red(0) .green(0) @@ -54,7 +56,7 @@ var chain: Color.Color = color .darken(0) .saturate(0) .desaturate(0) - .greyscale() + .grayscale() .whiten(0) .blacken(0) .opaquer(0) diff --git a/types/color/index.d.ts b/types/color/index.d.ts index a9fc18f29a..8290b78129 100644 --- a/types/color/index.d.ts +++ b/types/color/index.d.ts @@ -1,101 +1,135 @@ -// Type definitions for color 1.0 -// Project: https://www.npmjs.com/package/color -// Definitions by: Karol Janyst +// Type definitions for color 2.0 +// Project: https://github.com/qix-/color#readme +// Definitions by: Junyoung Clare Jang // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.3 -declare namespace Color { +import convert = require('color-convert'); - type ColorParam = string | { [param: string]: number } | number; +type ColorParam = Color | string | ArrayLike | number | { [key: string]: any }; - type ColorModel = "rgb" | "hsl" | "hsv" | "hwb" | "hcg" | "cmyk" | "xyz" | "lab" | "hex" | "gray" | "keyword"; +interface Color { + toString(): string; + toJSON(): Color; + string(places?: number): string; + percentString(places?: number): string; + array(): number[]; + object(): { alpha?: number } & { [key: string]: number }; + unitArray(): number[]; + unitObject(): { r: number, g: number, b: number, alpha?: number }; + round(places?: number): Color; + alpha(): number; + alpha(val: number): Color; + red(): number; + red(val: number): Color; + green(): number; + green(val: number): Color; + blue(): number; + blue(val: number): Color; + hue(): number; + hue(val: number): Color; + saturationl(): number; + saturationl(val: number): Color; + lightness(): number; + lightness(val: number): Color; + saturationv(): number; + saturationv(val: number): Color; + value(): number; + value(val: number): Color; + chroma(): number; + chroma(val: number): Color; + gray(): number; + gray(val: number): Color; + white(): number; + white(val: number): Color; + wblack(): number; + wblack(val: number): Color; + cyan(): number; + cyan(val: number): Color; + magenta(): number; + magenta(val: number): Color; + yellow(): number; + yellow(val: number): Color; + black(): number; + black(val: number): Color; + x(): number; + x(val: number): Color; + y(): number; + y(val: number): Color; + z(): number; + z(val: number): Color; + l(): number; + l(val: number): Color; + a(): number; + a(val: number): Color; + b(): number; + b(val: number): Color; + keyword(): string; + keyword(val: string): Color; + hex(): string; + hex(val: string): Color; + rgbNumber(): number; + luminosity(): number; + contrast(color2: Color): number; + level(color2: Color): 'AAA' | 'AA' | ''; + dark(): boolean; + light(): boolean; + negate(): Color; + lighten(ratio: number): Color; + darken(ratio: number): Color; + saturate(ratio: number): Color; + desaturate(ratio: number): Color; + whiten(ratio: number): Color; + blacken(ratio: number): Color; + grayscale(): Color; + fade(ratio: number): Color; + opaquer(ratio: number): Color; + rotate(degrees: number): Color; + mix(mixinColor: Color, weight?: number): Color; - interface Color { - (color: ColorParam | Color, model?: ColorModel) : Color; - toString(): string; - toJSON(): any; - string(places?: number): string; - percentString(placse?: number): string; - array(): number[]; - object(): any; - unitArray(): any[]; - unitObject(): any; - round(places?: number): Color; - alpha(alpha: number): Color; - alpha(): number; - red(red: number): Color; - red(): number; - green(green: number): Color; - green(): number; - blue(blue: number): Color; - blue(): number; - hue(hue: number): Color; - hue(): number; - saturationl(saturation: number): Color; - saturationl(): number; - lightness(lightness: number): Color; - lightness(): number; - saturationv(saturationv: number): Color; - saturationv(): number; - value(value: number): Color; - value(): number; - chroma(chroma: number): Color; - chroma(): number; - gray(value: number): Color; - gray(): number; - cyan(cyan: number): Color; - cyan(): number; - magenta(magenta: number): Color; - magenta(): number; - yellow(yellow: number): Color; - yellow(): number; - black(black: number): Color; - black(): number; - x(x: number): Color; - x(): number; - y(y: number): Color; - y(): number; - z(z: number): Color; - z(): number; - l(l: number): Color; - l(): number; - a(a: number): Color; - a(): number; - b(b: number): Color; - b(): number; - keyword(keyword: string): Color; - keyword(): string | undefined; - hex(color: string): Color; - hex(): string; - rgb(): Color; - hsl(): Color; - hsv(): Color; - hwb(): Color; - hcg(): Color; - cmyk(): Color; - xyz(): Color; - lab(): Color; - rgbNumber(): number; - luminosity(): number; - contrast(color: Color): number; - level(color: Color): string; - dark(): boolean; - light(): boolean; - negate(): Color; - lighten(value: number): Color; - darken(value: number): Color; - saturate(value: number): Color; - desaturate(value: number): Color; - whiten(value: number): Color; - blacken(value: number): Color; - greyscale(): Color; - fade(ratio: number): Color; - opaquer(value: number): Color; - rotate(value: number): Color; - mix(color: Color, value?: number): Color; - hsl(): Color; - } + rgb(...args: number[]): Color; + hsl(...args: number[]): Color; + hsv(...args: number[]): Color; + hwb(...args: number[]): Color; + cmyk(...args: number[]): Color; + xyz(...args: number[]): Color; + lab(...args: number[]): Color; + lch(...args: number[]): Color; + ansi16(...args: number[]): Color; + ansi256(...args: number[]): Color; + hcg(...args: number[]): Color; + apple(...args: number[]): Color; } -declare const Color: Color.Color; +interface ColorConstructor { + (obj?: ColorParam, model?: keyof (typeof convert)): Color; + new(obj?: ColorParam, model?: keyof (typeof convert)): Color; + rgb(...val: number[]): Color; + rgb(color: ColorParam): Color; + hsl(...val: number[]): Color; + hsl(color: ColorParam): Color; + hsv(...val: number[]): Color; + hsv(color: ColorParam): Color; + hwb(...val: number[]): Color; + hwb(color: ColorParam): Color; + cmyk(...val: number[]): Color; + cmyk(color: ColorParam): Color; + xyz(...val: number[]): Color; + xyz(color: ColorParam): Color; + lab(...val: number[]): Color; + lab(color: ColorParam): Color; + lch(...val: number[]): Color; + lch(color: ColorParam): Color; + ansi16(...val: number[]): Color; + ansi16(color: ColorParam): Color; + ansi256(...val: number[]): Color; + ansi256(color: ColorParam): Color; + hcg(...val: number[]): Color; + hcg(color: ColorParam): Color; + apple(...val: number[]): Color; + apple(color: ColorParam): Color; +} + +declare const Color: ColorConstructor; + export = Color; -export as namespace Color; diff --git a/types/color/tsconfig.json b/types/color/tsconfig.json index 3034984bd5..77175286b3 100644 --- a/types/color/tsconfig.json +++ b/types/color/tsconfig.json @@ -19,4 +19,4 @@ "index.d.ts", "color-tests.ts" ] -} \ No newline at end of file +} diff --git a/types/color/tslint.json b/types/color/tslint.json new file mode 100644 index 0000000000..3db14f85ea --- /dev/null +++ b/types/color/tslint.json @@ -0,0 +1 @@ +{ "extends": "dtslint/dt.json" } diff --git a/types/color/v1/color-tests.ts b/types/color/v1/color-tests.ts new file mode 100644 index 0000000000..2d05e86f05 --- /dev/null +++ b/types/color/v1/color-tests.ts @@ -0,0 +1,63 @@ +import * as Color from "color" + +var color: Color.Color = Color("white") +var colorOther: Color.Color = Color("black") +var colorRGB: Color.Color = Color({ r : 0, g : 0, b : 0 }, "rgb") +var colorInt: Color.Color = Color(0x000000) + +var hex: string = color.hex() +var percent: string = color.percentString() +var keyword: string | void = color.keyword() +var alpha: number = color.alpha() +var red: number = color.red() +var green: number = color.green() +var blue: number = color.blue() +var hue: number = color.hue() +var saturationl: number = color.saturationl() +var lightness: number = color.lightness() +var saturationv: number = color.saturationv() +var value: number = color.value() +var cyan: number = color.cyan() +var magenta: number = color.magenta() +var yellow: number = color.yellow() +var black: number = color.black() +var luminosity: number = color.luminosity() +var contrast: number = color.contrast(colorOther) +var dark: boolean = color.dark() +var light: boolean = color.light() +var level: string = color.level(colorOther) + +var x: number = color.x() +var y: number = color.y() +var z: number = color.z() +var l: number = color.l() +var a: number = color.a() +var b: number = color.b() +var rgbNumber: number = color.rgbNumber() + +var chain: Color.Color = color + .alpha(0) + .red(0) + .green(0) + .blue(0) + .hue(0) + .saturationl(0) + .lightness(0) + .saturationv(0) + .value(0) + .cyan(0) + .magenta(0) + .yellow(0) + .black(0) + .negate() + .lighten(0) + .darken(0) + .saturate(0) + .desaturate(0) + .greyscale() + .whiten(0) + .blacken(0) + .opaquer(0) + .rotate(0) + .mix(colorOther, 0) + .hsl(); diff --git a/types/color/v1/index.d.ts b/types/color/v1/index.d.ts new file mode 100644 index 0000000000..a9fc18f29a --- /dev/null +++ b/types/color/v1/index.d.ts @@ -0,0 +1,101 @@ +// Type definitions for color 1.0 +// Project: https://www.npmjs.com/package/color +// Definitions by: Karol Janyst +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +declare namespace Color { + + type ColorParam = string | { [param: string]: number } | number; + + type ColorModel = "rgb" | "hsl" | "hsv" | "hwb" | "hcg" | "cmyk" | "xyz" | "lab" | "hex" | "gray" | "keyword"; + + interface Color { + (color: ColorParam | Color, model?: ColorModel) : Color; + toString(): string; + toJSON(): any; + string(places?: number): string; + percentString(placse?: number): string; + array(): number[]; + object(): any; + unitArray(): any[]; + unitObject(): any; + round(places?: number): Color; + alpha(alpha: number): Color; + alpha(): number; + red(red: number): Color; + red(): number; + green(green: number): Color; + green(): number; + blue(blue: number): Color; + blue(): number; + hue(hue: number): Color; + hue(): number; + saturationl(saturation: number): Color; + saturationl(): number; + lightness(lightness: number): Color; + lightness(): number; + saturationv(saturationv: number): Color; + saturationv(): number; + value(value: number): Color; + value(): number; + chroma(chroma: number): Color; + chroma(): number; + gray(value: number): Color; + gray(): number; + cyan(cyan: number): Color; + cyan(): number; + magenta(magenta: number): Color; + magenta(): number; + yellow(yellow: number): Color; + yellow(): number; + black(black: number): Color; + black(): number; + x(x: number): Color; + x(): number; + y(y: number): Color; + y(): number; + z(z: number): Color; + z(): number; + l(l: number): Color; + l(): number; + a(a: number): Color; + a(): number; + b(b: number): Color; + b(): number; + keyword(keyword: string): Color; + keyword(): string | undefined; + hex(color: string): Color; + hex(): string; + rgb(): Color; + hsl(): Color; + hsv(): Color; + hwb(): Color; + hcg(): Color; + cmyk(): Color; + xyz(): Color; + lab(): Color; + rgbNumber(): number; + luminosity(): number; + contrast(color: Color): number; + level(color: Color): string; + dark(): boolean; + light(): boolean; + negate(): Color; + lighten(value: number): Color; + darken(value: number): Color; + saturate(value: number): Color; + desaturate(value: number): Color; + whiten(value: number): Color; + blacken(value: number): Color; + greyscale(): Color; + fade(ratio: number): Color; + opaquer(value: number): Color; + rotate(value: number): Color; + mix(color: Color, value?: number): Color; + hsl(): Color; + } +} + +declare const Color: Color.Color; +export = Color; +export as namespace Color; diff --git a/types/color/v1/tsconfig.json b/types/color/v1/tsconfig.json new file mode 100644 index 0000000000..66541f0172 --- /dev/null +++ b/types/color/v1/tsconfig.json @@ -0,0 +1,27 @@ +{ + "compilerOptions": { + "module": "commonjs", + "lib": [ + "es6" + ], + "noImplicitAny": true, + "noImplicitThis": true, + "strictNullChecks": true, + "baseUrl": "../../", + "typeRoots": [ + "../../" + ], + "types": [], + "paths": { + "color": [ + "color/v1" + ] + }, + "noEmit": true, + "forceConsistentCasingInFileNames": true + }, + "files": [ + "index.d.ts", + "color-tests.ts" + ] +} diff --git a/types/connect-timeout/index.d.ts b/types/connect-timeout/index.d.ts index bfaa7c473d..0ec4963306 100644 --- a/types/connect-timeout/index.d.ts +++ b/types/connect-timeout/index.d.ts @@ -2,6 +2,7 @@ // Project: https://github.com/expressjs/timeout // Definitions by: Cyril Schumacher // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.2 /// diff --git a/types/consul/index.d.ts b/types/consul/index.d.ts index 4d577cd2a1..3d344ae983 100644 --- a/types/consul/index.d.ts +++ b/types/consul/index.d.ts @@ -7,7 +7,7 @@ -import {IncomingMessage as HttpIncomingMessage} from "http"; +import { IncomingMessage as HttpIncomingMessage } from "http"; declare namespace Consul { diff --git a/types/cookie-parser/cookie-parser-tests.ts b/types/cookie-parser/cookie-parser-tests.ts index 1f9aaa1a8b..3a9f885efd 100644 --- a/types/cookie-parser/cookie-parser-tests.ts +++ b/types/cookie-parser/cookie-parser-tests.ts @@ -1,6 +1,31 @@ - import express = require('express'); import cookieParser = require('cookie-parser'); -var app = express(); +const app = express(); app.use(cookieParser('optional secret string')); + +let obj: object; +let str: string; +let notTrue: false; +let undef: undefined; + +const res = cookieParser.JSONCookie('foo'); +if (typeof res === 'undefined') { + undef = res; +} else { + obj = res; +} + +const res2 = cookieParser.JSONCookies({foo: 'bar'}); +const jsonRes: { foo?: object } = res2; + +const res3 = cookieParser.signedCookie('', 'keyboard cat'); +cookieParser.signedCookie('', ['keyboard', 'cat']); +if (typeof res3 === 'string') { + str = res3; +} else { + notTrue = res3; +} + +const res4 = cookieParser.signedCookies({foo: 'bar'}, 'keyboard cat'); +const signedCookieRes: { foo?: string | false } = res4; diff --git a/types/cookie-parser/index.d.ts b/types/cookie-parser/index.d.ts index 96412d6ee9..b2520080b0 100644 --- a/types/cookie-parser/index.d.ts +++ b/types/cookie-parser/index.d.ts @@ -1,12 +1,26 @@ -// Type definitions for cookie-parser v1.3.4 +// Type definitions for cookie-parser 1.4 // Project: https://github.com/expressjs/cookie-parser // Definitions by: Santi Albo +// BendingBender // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.2 +import * as express from 'express'; +declare function cookieParser(secret?: string | string[], options?: cookieParser.CookieParseOptions): express.RequestHandler; +declare namespace cookieParser { + interface CookieParseOptions { + decode?(val: string): string; + } -import express = require('express'); -declare function e(secret?: string, options?: any): express.RequestHandler; -declare namespace e { } -export = e; + function JSONCookie(jsonCookie: string): object | undefined; + + function JSONCookies(jsonCookies: T): { [P in keyof T]: object | undefined }; + + function signedCookie(cookie: string, secret: string | string[]): string | false; + + function signedCookies(cookies: T, secret: string | string[]): { [P in keyof T]?: string | false}; +} + +export = cookieParser; diff --git a/types/cookie-parser/tslint.json b/types/cookie-parser/tslint.json new file mode 100644 index 0000000000..3db14f85ea --- /dev/null +++ b/types/cookie-parser/tslint.json @@ -0,0 +1 @@ +{ "extends": "dtslint/dt.json" } diff --git a/types/cookie/cookie-tests.ts b/types/cookie/cookie-tests.ts index dd5be0f850..08e4d43519 100644 --- a/types/cookie/cookie-tests.ts +++ b/types/cookie/cookie-tests.ts @@ -1,23 +1,21 @@ - - import cookie = require('cookie'); function test_serialize(): void { - var retVal: string; + let retVal: string; retVal = cookie.serialize('foo', 'bar'); retVal = cookie.serialize('foo', 'bar', { httpOnly: true }); } function test_parse(): void { - var retVal: { [key: string]: string }; + let retVal: { [key: string]: string }; retVal = cookie.parse('foo=bar; bar=baz;'); retVal = cookie.parse('foo=bar; bar=baz', { decode: x => x }); } function test_options(): void { - var serializeOptions: cookie.CookieSerializeOptions = { + const serializeOptions: cookie.CookieSerializeOptions = { encode: (x: string) => x, path: '/', expires: new Date(), @@ -27,7 +25,7 @@ function test_options(): void { httpOnly: false }; - var parseOptios: cookie.CookieParseOptions = { + const parseOptios: cookie.CookieParseOptions = { decode: (x: string) => x }; } diff --git a/types/cookie/index.d.ts b/types/cookie/index.d.ts index 507eaee01d..bb7fc2cb54 100644 --- a/types/cookie/index.d.ts +++ b/types/cookie/index.d.ts @@ -1,15 +1,16 @@ -// Type definitions for cookie v0.3.0 +// Type definitions for cookie 0.3 // Project: https://github.com/jshttp/cookie // Definitions by: Pine Mizune // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -interface CookieSerializeOptions { +export interface CookieSerializeOptions { /** * Specifies the value for the Domain Set-Cookie attribute. By default, no * domain is set, and most clients will consider the cookie to apply to only * the current domain. */ domain?: string; + /** * Specifies a function that will be used to encode a cookie's value. Since * value of a cookie has a limited character set (and must be a simple @@ -20,7 +21,8 @@ interface CookieSerializeOptions { * encode a JavaScript string into UTF-8 byte sequences and then URL-encode * any that fall outside of the cookie range. */ - encode?: (val: string) => string; + encode?(val: string): string; + /** * Specifies the `Date` object to be the value for the `Expires` * `Set-Cookie` attribute. By default, no expiration is set, and most @@ -83,7 +85,7 @@ interface CookieSerializeOptions { secure?: boolean; } -interface CookieParseOptions { +export interface CookieParseOptions { /** * Specifies a function that will be used to decode a cookie's value. Since * the value of a cookie has a limited character set (and must be a simple @@ -96,7 +98,7 @@ interface CookieParseOptions { * *Note* if an error is thrown from this function, the original, non-decoded * cookie value will be returned as the cookie's value. */ - decode?: (val: string) => string; + decode?(val: string): string; } /** diff --git a/types/cookie/tslint.json b/types/cookie/tslint.json new file mode 100644 index 0000000000..3db14f85ea --- /dev/null +++ b/types/cookie/tslint.json @@ -0,0 +1 @@ +{ "extends": "dtslint/dt.json" } diff --git a/types/csv-stringify/csv-stringify-tests.ts b/types/csv-stringify/csv-stringify-tests.ts index e73e9abde3..803575e554 100644 --- a/types/csv-stringify/csv-stringify-tests.ts +++ b/types/csv-stringify/csv-stringify-tests.ts @@ -12,6 +12,12 @@ stringify([["1", "2", "3"], ["4", "5", "6"]], { // nothing }); +stringify([{a: "1", b: "2", c: "3"}, {c: "4", b: "5", a: "6"}], { + delimiter: "," +}, (error: Error, output: string): void => { + // nothing +}); + stringify([["1", true, new Date()], ["4", false, new Date()]], { delimiter: ",", formatters: { diff --git a/types/csv-stringify/index.d.ts b/types/csv-stringify/index.d.ts index 78c049ad3a..2e8cb32edb 100644 --- a/types/csv-stringify/index.d.ts +++ b/types/csv-stringify/index.d.ts @@ -85,7 +85,7 @@ declare function stringify(opts?: stringify.StringifyOpts): stringify.Stringifie /** * Callback version: string in --> callback with string out */ -declare function stringify(input: any[][], opts: stringify.StringifyOpts, callback: (error: Error | undefined, output: string) => void): void; -declare function stringify(input: any[][], callback: (error: Error | undefined, output: string) => void): void; +declare function stringify(input: any[][] | Array<{}>, opts: stringify.StringifyOpts, callback: (error: Error | undefined, output: string) => void): void; +declare function stringify(input: any[][] | Array<{}>, callback: (error: Error | undefined, output: string) => void): void; export = stringify; diff --git a/types/cucumber/cucumber-tests.ts b/types/cucumber/cucumber-tests.ts index 53ca726230..e0ecc2bed9 100644 --- a/types/cucumber/cucumber-tests.ts +++ b/types/cucumber/cucumber-tests.ts @@ -62,7 +62,7 @@ function StepSample() { }); Then(/^I should see "(.*)" as the page title$/, {timeout: 60 * 1000}, function (title: string, callback: Callback) { - var pageTitle = this.browser.text('title'); + const pageTitle = this.browser.text('title'); if (title === pageTitle) { callback(); @@ -75,38 +75,41 @@ function StepSample() { // https://github.com/cucumber/cucumber-js/blob/a5fd8251918c278ab2e389226d165cedb44df14a/lib/cucumber/ast/data_table.js Given(/^a table step with Table raw$/, function (table: Table) { - var expected = [ + const expected = [ ['Cucumber', 'Cucumis sativus'], ['Burr Gherkin', 'Cucumis anguria'] ]; - - assert.deepEqual(table.raw(), expected); + const actual: string[][] = table.raw(); + assert.deepEqual(actual, expected); }); Given(/^a table step with Table rows$/, function (table: Table) { - var expected = [ + const expected = [ ['Apricot', '5'], ['Brocolli', '2'], ['Cucumber', '10'] ]; - assert.deepEqual(table.rows(), expected) + const actual: string[][] = table.rows(); + assert.deepEqual(actual, expected); }); Given(/^a table step with Table rowHash$/, function (table: Table) { - var expected = { + const expected = { 'Cucumber': 'Cucumis sativus', 'Burr Gherkin': 'Cucumis anguria' }; - assert.deepEqual(table.rowsHash(), expected) + const actual: { [firstCol:string]: string } = table.rowsHash(); + assert.deepEqual(actual, expected); }); Given(/^a table step$/, function (table: Table) { - var expected = [ + const expected = [ {'Vegetable': 'Apricot', 'Rating': '5'}, {'Vegetable': 'Brocolli', 'Rating': '2'}, {'Vegetable': 'Cucumber', 'Rating': '10'} ]; - assert.deepEqual(table.hashes(), expected) + const actual: { [colName:string]: string }[] = table.hashes(); + assert.deepEqual(actual, expected); }); defineParameterType({ diff --git a/types/cucumber/index.d.ts b/types/cucumber/index.d.ts index 60e3d27d5d..635a594ae5 100644 --- a/types/cucumber/index.d.ts +++ b/types/cucumber/index.d.ts @@ -13,10 +13,10 @@ declare namespace cucumber { } export interface TableDefinition { - raw: () => Array; - rows: () => Array; - rowsHash: () => {}; - hashes: () => {}; + raw: () => Array>; + rows: () => Array>; + rowsHash: () => { [firstCol:string]: string }; + hashes: () => Array<{ [colName:string]: string }>; } type StepDefinitionParam = string | number | CallbackStepDefinition | TableDefinition; diff --git a/types/cucumber/v1/cucumber-tests.ts b/types/cucumber/v1/cucumber-tests.ts index 596772274f..347bec135b 100644 --- a/types/cucumber/v1/cucumber-tests.ts +++ b/types/cucumber/v1/cucumber-tests.ts @@ -5,17 +5,17 @@ function StepSample() { type Callback = cucumber.CallbackStepDefinition; type Table = cucumber.TableDefinition; type HookScenario = cucumber.HookScenario; - var step = this; - var hook = this; + const step = this; + const hook = this; hook.Before(function (scenario: HookScenario, callback: Callback) { scenario.isFailed() && callback.pending(); }); - + hook.Before({ timeout: 1000 }, function(scenario: HookScenario, callback: Callback) { callback(); }); - + hook.After({ timeout: 1000 }, function(scenario: HookScenario, callback: Callback) { callback(); }); @@ -39,7 +39,7 @@ function StepSample() { }); step.Then(/^I should see "(.*)" as the page title$/, {timeout: 60 * 1000}, function (title: string, callback: Callback) { - var pageTitle = this.browser.text('title'); + const pageTitle = this.browser.text('title'); if (title === pageTitle) { callback(); @@ -52,38 +52,41 @@ function StepSample() { // https://github.com/cucumber/cucumber-js/blob/a5fd8251918c278ab2e389226d165cedb44df14a/lib/cucumber/ast/data_table.js step.Given(/^a table step with Table raw$/, function (table: Table) { - var expected = [ + const expected = [ ['Cucumber', 'Cucumis sativus'], ['Burr Gherkin', 'Cucumis anguria'] ]; - - assert.deepEqual(table.raw(), expected); + const actual: string[][] = table.raw(); + assert.deepEqual(actual, expected); }); step.Given(/^a table step with Table rows$/, function (table: Table) { - var expected = [ + const expected = [ ['Apricot', '5'], ['Brocolli', '2'], ['Cucumber', '10'] ]; - assert.deepEqual(table.rows(), expected) + const actual: string[][] = table.rows(); + assert.deepEqual(actual, expected); }); step.Given(/^a table step with Table rowHash$/, function (table: Table) { - var expected = { + const expected = { 'Cucumber': 'Cucumis sativus', 'Burr Gherkin': 'Cucumis anguria' }; - assert.deepEqual(table.rowsHash(), expected) + const actual: { [firstCol:string]: string } = table.rowsHash(); + assert.deepEqual(actual, expected); }); step.Given(/^a table step$/, function (table: Table) { - var expected = [ + const expected = [ {'Vegetable': 'Apricot', 'Rating': '5'}, {'Vegetable': 'Brocolli', 'Rating': '2'}, {'Vegetable': 'Cucumber', 'Rating': '10'} ]; - assert.deepEqual(table.hashes(), expected) + const actual: { [colName:string]: string }[] = table.hashes(); + assert.deepEqual(actual, expected); }); } diff --git a/types/cucumber/v1/index.d.ts b/types/cucumber/v1/index.d.ts index bdf30d740d..39a915f935 100644 --- a/types/cucumber/v1/index.d.ts +++ b/types/cucumber/v1/index.d.ts @@ -13,10 +13,10 @@ declare namespace cucumber { } export interface TableDefinition { - raw: () => Array; - rows: () => Array; - rowsHash: () => {}; - hashes: () => {}; + raw: () => Array>; + rows: () => Array>; + rowsHash: () => { [firstCol:string]: string }; + hashes: () => Array<{ [colName:string]: string }>; } type StepDefinitionParam = string | CallbackStepDefinition | TableDefinition; diff --git a/types/cwise-compiler/index.d.ts b/types/cwise-compiler/index.d.ts index e661934a6a..8703355ba3 100644 --- a/types/cwise-compiler/index.d.ts +++ b/types/cwise-compiler/index.d.ts @@ -2,6 +2,7 @@ // Project: https://github.com/scijs/cwise-compiler // Definitions by: taoqf // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.3 import { CompiledRoutine } from 'cwise-parser'; import * as ndarray from 'ndarray'; diff --git a/types/cwise/index.d.ts b/types/cwise/index.d.ts index d99d43ce59..95df45bb03 100644 --- a/types/cwise/index.d.ts +++ b/types/cwise/index.d.ts @@ -2,6 +2,7 @@ // Project: https://github.com/scijs/cwise#readme // Definitions by: taoqf // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.3 import { ArgType } from "cwise-compiler"; import * as ndarray from "ndarray"; diff --git a/types/d3-axis/index.d.ts b/types/d3-axis/index.d.ts index 9cee537067..1c7820c809 100644 --- a/types/d3-axis/index.d.ts +++ b/types/d3-axis/index.d.ts @@ -3,7 +3,7 @@ // Definitions by: Tom Wanzek , Alex Ford , Boris Yankov // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -// Last module patch version validated against: 1.0.4 +// Last module patch version validated against: 1.0.8 import { Selection, TransitionLike } from 'd3-selection'; @@ -82,6 +82,10 @@ export interface Axis { /** * Sets the arguments that will be passed to scale.ticks and scale.tickFormat when the axis is rendered, and returns the axis generator. * + * This method has no effect if the scale does not implement scale.ticks, as with band and point scales. + * + * This method is also a convenience function for axis.tickArguments. + * * @param count Number of ticks that should be rendered * @param specifier An optional format specifier to customize how the tick values are formatted. */ @@ -91,6 +95,8 @@ export interface Axis { * Sets the arguments that will be passed to scale.ticks and scale.tickFormat when the axis is rendered, and returns the axis generator. * Use with a TIME SCALE ONLY. * + * This method is also a convenience function for axis.tickArguments. + * * @param interval A time interval used to generate date-based ticks. This is typically a TimeInterval/CountableTimeInterval as defined * in d3-time. E.g. as obtained by passing in d3.timeMinute.every(15). * @param specifier An optional format specifier to customize how the tick values are formatted. @@ -99,17 +105,31 @@ export interface Axis { /** * Sets the arguments that will be passed to scale.ticks and scale.tickFormat when the axis is rendered, and returns the axis generator. + * + * The meaning of the arguments depends on the axis’ scale type: most commonly, the arguments are a suggested count for the number of ticks + * (or a time interval for time scales), and an optional format specifier to customize how the tick values are formatted. + * + * This method has no effect if the scale does not implement scale.ticks, as with band and point scales. + * + * To set the tick values explicitly, use axis.tickValues. To set the tick format explicitly, use axis.tickFormat. + * + * This method is also a convenience function for axis.tickArguments. */ ticks(arg0: any, ...args: any[]): this; /** - * Get an array containing the currently set arguments to be passed into scale.ticks and scale.tickFormat. + * Get an array containing the currently set arguments to be passed into scale.ticks and scale.tickFormat, which defaults to the empty array. */ tickArguments(): any[]; /** * Sets the arguments that will be passed to scale.ticks and scale.tickFormat when the axis is rendered, and returns the axis generator. * + * This method has no effect if the scale does not implement scale.ticks, as with band and point scales. + * To set the tick values explicitly, use axis.tickValues. To set the tick format explicitly, use axis.tickFormat. + * + * See also axis.ticks. + * * @param args An array containing a single element representing the count, i.e. number of ticks to be rendered. */ tickArguments(args: [number]): this; @@ -117,6 +137,11 @@ export interface Axis { /** * Sets the arguments that will be passed to scale.ticks and scale.tickFormat when the axis is rendered, and returns the axis generator. * + * This method has no effect if the scale does not implement scale.ticks, as with band and point scales. + * To set the tick values explicitly, use axis.tickValues. To set the tick format explicitly, use axis.tickFormat. + * + * See also axis.ticks. + * * @param args An array containing two elements. The first element represents the count, i.e. number of ticks to be rendered. The second * element is a string representing the format specifier to customize how the tick values are formatted. */ @@ -126,6 +151,8 @@ export interface Axis { * Sets the arguments that will be passed to scale.ticks and scale.tickFormat when the axis is rendered, and returns the axis generator. * Use with a TIME SCALE ONLY. * + * See also axis.ticks. + * * @param args An array containing a single element representing a time interval used to generate date-based ticks. * This is typically a TimeInterval/CountableTimeInterval as defined in d3-time. E.g. as obtained by passing in d3.timeMinute.every(15). */ @@ -135,6 +162,8 @@ export interface Axis { * Sets the arguments that will be passed to scale.ticks and scale.tickFormat when the axis is rendered, and returns the axis generator. * Use with a TIME SCALE ONLY. * + * See also axis.ticks. + * * @param args An array containing two elements. The first element represents a time interval used to generate date-based ticks. * This is typically a TimeInterval/CountableTimeInterval as defined in d3-time. E.g. as obtained by passing in d3.timeMinute.every(15). * The second element is a string representing the format specifier to customize how the tick values are formatted. @@ -144,6 +173,11 @@ export interface Axis { /** * Sets the arguments that will be passed to scale.ticks and scale.tickFormat when the axis is rendered, and returns the axis generator. * + * This method has no effect if the scale does not implement scale.ticks, as with band and point scales. + * To set the tick values explicitly, use axis.tickValues. To set the tick format explicitly, use axis.tickFormat. + * + * See also axis.ticks. + * * @param args An array with arguments suitable for the scale to be used for tick generation */ tickArguments(args: any[]): this; diff --git a/types/d3-hsv/d3-hsv-tests.ts b/types/d3-hsv/d3-hsv-tests.ts index 72e18145e6..0d3e564360 100644 --- a/types/d3-hsv/d3-hsv-tests.ts +++ b/types/d3-hsv/d3-hsv-tests.ts @@ -6,8 +6,8 @@ * are not intended as functional tests. */ -import {hsv, HSVColor} from 'd3-hsv'; -import {rgb, RGBColor} from 'd3-color'; +import { hsv, HSVColor } from 'd3-hsv'; +import { rgb, RGBColor } from 'd3-color'; let c: RGBColor; let cHSV: HSVColor; diff --git a/types/d3-hsv/index.d.ts b/types/d3-hsv/index.d.ts index c10fa6ee44..6a7a2c8560 100644 --- a/types/d3-hsv/index.d.ts +++ b/types/d3-hsv/index.d.ts @@ -5,7 +5,7 @@ // Last module patch version validated against: 0.0.3 -import {Color, RGBColor, ColorSpaceObject, ColorCommonInstance} from 'd3-color'; +import { Color, RGBColor, ColorSpaceObject, ColorCommonInstance } from 'd3-color'; export type ColorSpaceObjectWithHSV = ColorSpaceObject | HSVColor; diff --git a/types/d3-selection-multi/index.d.ts b/types/d3-selection-multi/index.d.ts index da3c64e5e3..4dd2a47c46 100644 --- a/types/d3-selection-multi/index.d.ts +++ b/types/d3-selection-multi/index.d.ts @@ -5,8 +5,8 @@ // Last module patch version validated against: 1.0.0 -import {Selection, BaseType, ArrayLike, ValueFn} from 'd3-selection'; -import {Transition} from 'd3-transition'; +import { Selection, BaseType, ArrayLike, ValueFn } from 'd3-selection'; +import { Transition } from 'd3-transition'; /** * An object mapping attribute (or style or property) names to value accessors diff --git a/types/d3-shape/d3-shape-tests.ts b/types/d3-shape/d3-shape-tests.ts index 6e0fa97d96..ee9a8fbb98 100644 --- a/types/d3-shape/d3-shape-tests.ts +++ b/types/d3-shape/d3-shape-tests.ts @@ -1319,10 +1319,10 @@ customSymbol = d3Shape.symbolTriangle; customSymbol = d3Shape.symbolWye; // ----------------------------------------------------------------------------------- -// Test pointRadius +// Test pointRadial // ----------------------------------------------------------------------------------- -let coordinatates: [number, number] = d3Shape.pointRadius(0, 12); +let coordinatates: [number, number] = d3Shape.pointRadial(0, 12); // ----------------------------------------------------------------------------------- // Test Stacks diff --git a/types/d3-shape/index.d.ts b/types/d3-shape/index.d.ts index 010c2108e9..27a92a79fe 100644 --- a/types/d3-shape/index.d.ts +++ b/types/d3-shape/index.d.ts @@ -2436,7 +2436,7 @@ export const symbolTriangle: SymbolType; export const symbolWye: SymbolType; // ----------------------------------------------------------------------------------- -// pointRadius +// pointRadial // ----------------------------------------------------------------------------------- /** @@ -2444,7 +2444,7 @@ export const symbolWye: SymbolType; * @param angle Angle in radians, with 0 at -y (12 o’clock) and positive angles proceeding clockwise. * @param radius Radius. */ -export function pointRadius(angle: number, radius: number): [number, number]; +export function pointRadial(angle: number, radius: number): [number, number]; // ----------------------------------------------------------------------------------- // STACKS diff --git a/types/d3-time/index.d.ts b/types/d3-time/index.d.ts index 5e2b66718f..3d88edbf27 100644 --- a/types/d3-time/index.d.ts +++ b/types/d3-time/index.d.ts @@ -3,7 +3,7 @@ // Definitions by: Tom Wanzek , Alex Ford , Boris Yankov // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -// Last module patch version validated against: 1.0.4 +// Last module patch version validated against: 1.0.7 // --------------------------------------------------------------- // Interfaces @@ -151,6 +151,8 @@ export interface CountableTimeInterval extends TimeInterval { * * This method can be used in conjunction with interval.range to ensure that two overlapping ranges are consistent. * + * The returned filtered interval does not support interval.count. See also interval.filter. + * * @param step Number of steps. */ every(step: number): TimeInterval | null; diff --git a/types/d3-tip/index.d.ts b/types/d3-tip/index.d.ts index e820e8120f..5a70a6cf4d 100644 --- a/types/d3-tip/index.d.ts +++ b/types/d3-tip/index.d.ts @@ -3,7 +3,7 @@ // Definitions by: Gert Braspenning // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -import {Primitive} from "d3"; +import { Primitive } from "d3"; declare module "d3" { type TooltipDirection = ("n" | "s" | "e" | "w" | "nw" | "ne" | "sw" | "se"); diff --git a/types/d3-zoom/d3-zoom-tests.ts b/types/d3-zoom/d3-zoom-tests.ts index 185b9fd45a..02f7120e79 100644 --- a/types/d3-zoom/d3-zoom-tests.ts +++ b/types/d3-zoom/d3-zoom-tests.ts @@ -385,6 +385,106 @@ svgZoom.translateBy( return 30; }); +// translateTo() ------------------------------------------------------------------------------------- + +// use on selection +svgZoom.translateTo(svgOverlay, 20, 50); +// svgZoom.translateTo(groupsSelection, 20, 50); // fails, as groupSelection mismachtes DOM Element type and datum type + +svgZoom.translateTo( + svgOverlay, + 20, + 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.translateTo( + 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 30; + }, + 50); +svgZoom.translateTo( + 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 30; + }, + 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; + }); + +// use on transition +svgZoom.translateTo(svgOverlayTransition, 20, 50); +// svgZoom.translateTo(groupsTransition, 20, 50); // fails, as groupTransition mismachtes DOM Element type and datum type + +svgZoom.translateTo( + svgOverlayTransition, + 20, + 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.translateTo( + 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; + }, + 50); +svgZoom.translateTo( + 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; + }, + 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; + }); + // scaleBy() ------------------------------------------------------------------------------------- // use on selection diff --git a/types/d3-zoom/index.d.ts b/types/d3-zoom/index.d.ts index a0980344bb..a633644ded 100644 --- a/types/d3-zoom/index.d.ts +++ b/types/d3-zoom/index.d.ts @@ -1,9 +1,9 @@ -// Type definitions for d3JS d3-zoom module 1.3 +// Type definitions for d3JS d3-zoom module 1.5 // Project: https://github.com/d3/d3-zoom/ // Definitions by: Tom Wanzek , Alex Ford , Boris Yankov // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -// Last module patch version validated against: 1.3.0 +// Last module patch version validated against: 1.5.0 import { ArrayLike, Selection, TransitionLike, ValueFn } from 'd3-selection'; import { ZoomView, ZoomInterpolator } from 'd3-interpolate'; @@ -127,7 +127,7 @@ export interface ZoomBehavior, x: number, y: number): void; /** * Translates the current zoom transform of the selected elements by x and y, - * such that the new t(x1) = t(x0) + k × x and t(y1) = t(y0) + k × y. + * such that the new t(x1) = t(x0) + kx and t(y1) = t(y0) + ky. * * x is provided by a value function evaluated for each element in the selection. * y is provided as a constant for all elements. * * This method is a convenience method for zoom.transform. - * In contrast to zoom.transform, however, it is subject to the constraints imposed by zoom.extent, zoom.scaleExten, and zoom.translateExtent. + * In contrast to zoom.transform, however, it is subject to the constraints imposed by zoom.extent, zoom.scaleExtent, and zoom.translateExtent. * * @param selection A D3 selection of elements. * @param x A value function which is evaluated for each selected element, @@ -156,13 +156,13 @@ export interface ZoomBehavior, x: ValueFn, y: number): void; /** * Translates the current zoom transform of the selected elements by x and y, - * such that the new t(x1) = t(x0) + k × x and t(y1) = t(y0) + k × y. + * such that the new t(x1) = t(x0) + kx and t(y1) = t(y0) + ky. * * x is provided as a constant for all elements. * y is provided by a value function evaluated for each element in the selection. * * This method is a convenience method for zoom.transform. - * In contrast to zoom.transform, however, it is subject to the constraints imposed by zoom.extent, zoom.scaleExten, and zoom.translateExtent. + * In contrast to zoom.transform, however, it is subject to the constraints imposed by zoom.extent, zoom.scaleExtent, and zoom.translateExtent. * * @param selection A D3 selection of elements. * @param x Amount of translation in x-direction. @@ -173,13 +173,13 @@ export interface ZoomBehavior, x: number, y: ValueFn): void; /** * Translates the current zoom transform of the selected elements by x and y, - * such that the new t(x1) = t(x0) + k × x and t(y1) = t(y0) + k × y. + * such that the new t(x1) = t(x0) + kx and t(y1) = t(y0) + ky. * * x is provided by a value function evaluated for each element in the selection. * y is provided by a value function evaluated for each element in the selection. * * This method is a convenience method for zoom.transform. - * In contrast to zoom.transform, however, it is subject to the constraints imposed by zoom.extent, zoom.scaleExten, and zoom.translateExtent. + * In contrast to zoom.transform, however, it is subject to the constraints imposed by zoom.extent, zoom.scaleExtent, and zoom.translateExtent. * * @param selection A D3 selection of elements. * @param x A value function which is evaluated for each selected element, @@ -192,13 +192,13 @@ export interface ZoomBehavior, x: ValueFn, y: ValueFn): void; /** * Defines a “zoom” tween translating the current transform for the transitioning elements by x and y, - * such that the new t(x1) = t(x0) + k × x and t(y1) = t(y0) + k × y. + * such that the new t(x1) = t(x0) + kx and t(y1) = t(y0) + ky. * * x is provided as a constant for all elements. * y is provided as a constant for all elements. * * This method is a convenience method for zoom.transform. - * In contrast to zoom.transform, however, it is subject to the constraints imposed by zoom.extent, zoom.scaleExten, and zoom.translateExtent. + * In contrast to zoom.transform, however, it is subject to the constraints imposed by zoom.extent, zoom.scaleExtent, and zoom.translateExtent. * * @param transition A D3 transition on elements. * @param x Amount of translation in x-direction. @@ -207,13 +207,13 @@ export interface ZoomBehavior, x: number, y: number): void; /** * Defines a “zoom” tween translating the current transform for the transitioning elements by x and y, - * such that the new t(x1) = t(x0) + k × x and t(y1) = t(y0) + k × y. + * such that the new t(x1) = t(x0) + kx and t(y1) = t(y0) + ky. * * x is provided by a value function evaluated for each element in the selection. * y is provided as a constant for all elements. * * This method is a convenience method for zoom.transform. - * In contrast to zoom.transform, however, it is subject to the constraints imposed by zoom.extent, zoom.scaleExten, and zoom.translateExtent. + * In contrast to zoom.transform, however, it is subject to the constraints imposed by zoom.extent, zoom.scaleExtent, and zoom.translateExtent. * * @param transition A D3 transition on elements. * @param x A value function which is evaluated for each selected element, @@ -224,13 +224,13 @@ export interface ZoomBehavior, x: ValueFn, y: number): void; /** * Defines a “zoom” tween translating the current transform for the transitioning elements by x and y, - * such that the new t(x1) = t(x0) + k × x and t(y1) = t(y0) + k × y. + * such that the new t(x1) = t(x0) + kx and t(y1) = t(y0) + ky. * * x is provided as a constant for all elements. * y is provided by a value function evaluated for each element in the selection. * * This method is a convenience method for zoom.transform. - * In contrast to zoom.transform, however, it is subject to the constraints imposed by zoom.extent, zoom.scaleExten, and zoom.translateExtent. + * In contrast to zoom.transform, however, it is subject to the constraints imposed by zoom.extent, zoom.scaleExtent, and zoom.translateExtent. * * @param transition A D3 transition on elements. * @param x Amount of translation in x-direction. @@ -241,13 +241,13 @@ export interface ZoomBehavior, x: number, y: ValueFn): void; /** * Defines a “zoom” tween translating the current transform for the transitioning elements by x and y, - * such that the new t(x1) = t(x0) + k × x and t(y1) = t(y0) + k × y. + * such that the new t(x1) = t(x0) + kx and t(y1) = t(y0) + ky. * * x is provided by a value function evaluated for each element in the selection. * y is provided by a value function evaluated for each element in the selection. * * This method is a convenience method for zoom.transform. - * In contrast to zoom.transform, however, it is subject to the constraints imposed by zoom.extent, zoom.scaleExten, and zoom.translateExtent. + * In contrast to zoom.transform, however, it is subject to the constraints imposed by zoom.extent, zoom.scaleExtent, and zoom.translateExtent. * * @param transition A D3 transition on elements. * @param x A value function which is evaluated for each selected element, @@ -260,24 +260,158 @@ export interface ZoomBehavior, x: ValueFn, y: ValueFn): void; /** - * Scales the current zoom transform of the selected elements by k, such that the new k(1) = k(0) × k. + * Translates the current zoom transform of the selected elements such that the specified position ⟨x,y⟩ appears at the center of the viewport extent. + * The new tx = cx - kx and ty = cy - ky, where ⟨cx,cy⟩ is the center. + * + * x is provided as a constant for all elements. + * y is provided as a constant for all elements. + * + * @param selection A D3 selection of elements. + * @param x Target x-position of translation. + * @param y Target y-position of translation. + */ + translateTo(selection: Selection, x: number, y: number): void; + /** + * Translates the current zoom transform of the selected elements such that the specified position ⟨x,y⟩ appears at the center of the viewport extent. + * The new tx = cx - kx and ty = cy - ky, where ⟨cx,cy⟩ is the center. + * + * x is provided by a value function evaluated for each element in the selection. + * y is provided as a constant for all elements. + * + * This method is a convenience method for zoom.transform. + * In contrast to zoom.transform, however, it is subject to the constraints imposed by zoom.extent, zoom.scaleExtent, and zoom.translateExtent. + * + * @param selection A D3 selection of elements. + * @param x A value function which is evaluated for each selected element, + * in order, being passed the current datum (d), the current index (i), and the current group (nodes), + * with this as the current DOM element.The function returns the target x-position of translation. + * @param y Target y-position of translation. + */ + translateTo(selection: Selection, x: ValueFn, y: number): void; + /** + * Translates the current zoom transform of the selected elements such that the specified position ⟨x,y⟩ appears at the center of the viewport extent. + * The new tx = cx - kx and ty = cy - ky, where ⟨cx,cy⟩ is the center. + * + * x is provided as a constant for all elements. + * y is provided by a value function evaluated for each element in the selection. + * + * This method is a convenience method for zoom.transform. + * In contrast to zoom.transform, however, it is subject to the constraints imposed by zoom.extent, zoom.scaleExtent, and zoom.translateExtent. + * + * @param selection A D3 selection of elements. + * @param x Target x-position of translation. + * @param y A value function which is evaluated for each selected element, + * in order, being passed the current datum (d), the current index (i), and the current group (nodes), + * with this as the current DOM element.The function returns the target y-position of translation. + */ + translateTo(selection: Selection, x: number, y: ValueFn): void; + /** + * Translates the current zoom transform of the selected elements such that the specified position ⟨x,y⟩ appears at the center of the viewport extent. + * The new tx = cx - kx and ty = cy - ky, where ⟨cx,cy⟩ is the center. + * + * x is provided by a value function evaluated for each element in the selection. + * y is provided by a value function evaluated for each element in the selection. + * + * This method is a convenience method for zoom.transform. + * In contrast to zoom.transform, however, it is subject to the constraints imposed by zoom.extent, zoom.scaleExtent, and zoom.translateExtent. + * + * @param selection A D3 selection of elements. + * @param x A value function which is evaluated for each selected element, + * in order, being passed the current datum (d), the current index (i), and the current group (nodes), + * with this as the current DOM element.The function returns the target x-position of translation. + * @param y A value function which is evaluated for each selected element, + * in order, being passed the current datum (d), the current index (i), and the current group (nodes), + * with this as the current DOM element.The function returns the target y-position of translation. + */ + translateTo(selection: Selection, x: ValueFn, y: ValueFn): void; + /** + * Defines a “zoom” tween translating the current transform for the transitioning elements such that the specified position ⟨x,y⟩ appears at the center of the viewport extent. + * The new tx = cx - kx and ty = cy - ky, where ⟨cx,cy⟩ is the center. + * + * x is provided as a constant for all elements. + * y is provided as a constant for all elements. + * + * This method is a convenience method for zoom.transform. + * In contrast to zoom.transform, however, it is subject to the constraints imposed by zoom.extent, zoom.scaleExtent, and zoom.translateExtent. + * + * @param transition A D3 transition on elements. + * @param x Target x-position of translation. + * @param y Target y-position of translation. + */ + translateTo(transition: TransitionLike, x: number, y: number): void; + /** + * Defines a “zoom” tween translating the current transform for the transitioning elements such that the specified position ⟨x,y⟩ appears at the center of the viewport extent. + * The new tx = cx - kx and ty = cy - ky, where ⟨cx,cy⟩ is the center. + * + * x is provided by a value function evaluated for each element in the selection. + * y is provided as a constant for all elements. + * + * This method is a convenience method for zoom.transform. + * In contrast to zoom.transform, however, it is subject to the constraints imposed by zoom.extent, zoom.scaleExtent, and zoom.translateExtent. + * + * @param transition A D3 transition on elements. + * @param x A value function which is evaluated for each selected element, + * in order, being passed the current datum (d), the current index (i), and the current group (nodes), + * with this as the current DOM element.The function returns the target x-position of translation. + * @param y Target y-position of translation. + */ + translateTo(transition: TransitionLike, x: ValueFn, y: number): void; + /** + * Defines a “zoom” tween translating the current transform for the transitioning elements such that the specified position ⟨x,y⟩ appears at the center of the viewport extent. + * The new tx = cx - kx and ty = cy - ky, where ⟨cx,cy⟩ is the center. + * + * x is provided as a constant for all elements. + * y is provided by a value function evaluated for each element in the selection. + * + * This method is a convenience method for zoom.transform. + * In contrast to zoom.transform, however, it is subject to the constraints imposed by zoom.extent, zoom.scaleExtent, and zoom.translateExtent. + * + * @param transition A D3 transition on elements. + * @param x Target x-position of translation. + * @param y A value function which is evaluated for each selected element, + * in order, being passed the current datum (d), the current index (i), and the current group (nodes), + * with this as the current DOM element.The function returns the target y-position of translation. + */ + translateTo(transition: TransitionLike, x: number, y: ValueFn): void; + /** + * Defines a “zoom” tween translating the current transform for the transitioning elements such that the specified position ⟨x,y⟩ appears at the center of the viewport extent. + * The new tx = cx - kx and ty = cy - ky, where ⟨cx,cy⟩ is the center. + * + * x is provided by a value function evaluated for each element in the selection. + * y is provided by a value function evaluated for each element in the selection. + * + * This method is a convenience method for zoom.transform. + * In contrast to zoom.transform, however, it is subject to the constraints imposed by zoom.extent, zoom.scaleExtent, and zoom.translateExtent. + * + * @param transition A D3 transition on elements. + * @param x A value function which is evaluated for each selected element, + * in order, being passed the current datum (d), the current index (i), and the current group (nodes), + * with this as the current DOM element.The function returns the target x-position of translation. + * @param y A value function which is evaluated for each selected element, + * in order, being passed the current datum (d), the current index (i), and the current group (nodes), + * with this as the current DOM element.The function returns the target y-position of translation. + */ + translateTo(transition: TransitionLike, x: ValueFn, y: ValueFn): void; + + /** + * Scales the current zoom transform of the selected elements by k, such that the new k(1) = k(0)k. * * k is provided as a constant for all elements. * * This method is a convenience method for zoom.transform. - * In contrast to zoom.transform, however, it is subject to the constraints imposed by zoom.extent, zoom.scaleExten, and zoom.translateExtent. + * In contrast to zoom.transform, however, it is subject to the constraints imposed by zoom.extent, zoom.scaleExtent, and zoom.translateExtent. * * @param selection A D3 selection of elements. * @param k Scale factor. */ scaleBy(selection: Selection, k: number): void; /** - * Scales the current zoom transform of the selected elements by k, such that the new k(1) = k(0) × k. + * Scales the current zoom transform of the selected elements by k, such that the new k(1) = k(0)k. * * k is provided by a value function evaluated for each element in the selection. * * This method is a convenience method for zoom.transform. - * In contrast to zoom.transform, however, it is subject to the constraints imposed by zoom.extent, zoom.scaleExten, and zoom.translateExtent. + * In contrast to zoom.transform, however, it is subject to the constraints imposed by zoom.extent, zoom.scaleExtent, and zoom.translateExtent. * * @param selection A D3 selection of elements. * @param k A value function which is evaluated for each selected element, @@ -286,24 +420,24 @@ export interface ZoomBehavior, k: ValueFn): void; /** - * Defines a “zoom” tween translating scaling the current transform of the selected elements by k, such that the new k(1) = k(0) × k. + * Defines a “zoom” tween translating scaling the current transform of the selected elements by k, such that the new k(1) = k(0)k. * * k is provided as a constant for all elements. * * This method is a convenience method for zoom.transform. - * In contrast to zoom.transform, however, it is subject to the constraints imposed by zoom.extent, zoom.scaleExten, and zoom.translateExtent. + * In contrast to zoom.transform, however, it is subject to the constraints imposed by zoom.extent, zoom.scaleExtent, and zoom.translateExtent. * * @param transition A D3 transition on elements. * @param k Scale factor. */ scaleBy(transition: TransitionLike, k: number): void; /** - * Defines a “zoom” tween translating scaling the current transform of the selected elements by k, such that the new k(1) = k(0) × k. + * Defines a “zoom” tween translating scaling the current transform of the selected elements by k, such that the new k(1) = k(0)k. * * k is provided by a value function evaluated for each element in the selection. * * This method is a convenience method for zoom.transform. - * In contrast to zoom.transform, however, it is subject to the constraints imposed by zoom.extent, zoom.scaleExten, and zoom.translateExtent. + * In contrast to zoom.transform, however, it is subject to the constraints imposed by zoom.extent, zoom.scaleExtent, and zoom.translateExtent. * * @param transition A D3 transition on elements. * @param k A value function which is evaluated for each selected element, @@ -318,7 +452,7 @@ export interface ZoomBehavior, Alex Ford , Boris Yankov // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped diff --git a/types/dagre/index.d.ts b/types/dagre/index.d.ts index 7408d145cf..2c6c6e38ab 100644 --- a/types/dagre/index.d.ts +++ b/types/dagre/index.d.ts @@ -11,16 +11,33 @@ export namespace graphlib { edge(id: any): any; nodes(): string[]; node(id: any): any; - setDefaultEdgeLabel(callback: () => void): Graph; - setEdge(sourceId: string, targetId: string, options?: { [key: string]: any }): Graph; - setGraph(options: { [key: string]: any }): Graph; + setDefaultEdgeLabel(callback: string|(() => string|void)): Graph; + setDefaultNodeLabel(callback: string|(() => string|void)): Graph; + setEdge(sourceId: string, targetId: string, options?: { [key: string]: any }, value?: string): Graph; + setEdge(params: {v: string, w: string, name?: string}, value?: string): Graph; + setGraph(label: GraphLabel): Graph; setNode(id: string, node: { [key: string]: any }): Graph; + graph(): GraphLabel; + + constructor(opt?: {directed?: boolean, multigraph?: boolean, compound?: boolean}); + setParent(name: string, parentName: string): void; + hasNode(name: string): boolean; } } +export interface GraphLabel { + width?: number; + height?: number; + compound?: boolean; + rankdir?: string; + nodesep?: number; + edgesep?: number; +} + export function layout(graph: graphlib.Graph): void; export interface Edge { v: string; w: string; + name?: string; } diff --git a/types/datatables.net-rowreorder/datatables.net-rowreorder-tests.ts b/types/datatables.net-rowreorder/datatables.net-rowreorder-tests.ts new file mode 100644 index 0000000000..bb0926bfda --- /dev/null +++ b/types/datatables.net-rowreorder/datatables.net-rowreorder-tests.ts @@ -0,0 +1,14 @@ +$(document).ready(() => { + const config: DataTables.Settings = { + // reorder extension options + rowReorder: { + dataSrc: "somesrc", + editor: {}, + enable: true, + formOptions: {}, + selector: "someselector", + snapX: true, + update: true, + }, + }; +}); diff --git a/types/datatables.net-rowreorder/index.d.ts b/types/datatables.net-rowreorder/index.d.ts new file mode 100644 index 0000000000..110da7a747 --- /dev/null +++ b/types/datatables.net-rowreorder/index.d.ts @@ -0,0 +1,48 @@ +// Type definitions for JQuery DataTables RowReorder extension 1.1 +// Project: http://datatables.net/extensions/rowreorder/ +// Definitions by: Vincent Biret +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.3 + +/// +/// + +declare namespace DataTables { + interface Settings { + /** + * Enable and configure the RowReorder extension for DataTables + */ + rowReorder?: RowReorderSettings; + } + + interface RowReorderSettings { + /** + * Configure the data point that will be used for the reordering data + */ + dataSrc?: string; + /** + * Attach an Editor instance for database updating + */ + editor?: any; + /** + * Enable / disable RowReorder's user interaction + */ + enable?: boolean; + /** + * Set the options for the Editor form when submitting data + */ + formOptions?: any; + /** + * Define the selector used to pick the elements that will start a drag + */ + selector?: string; + /** + * Horizontal position control of the row being dragged + */ + snapX?: number | boolean; + /** + * Control automatic of data when a row is dropped + */ + update?: boolean; + } +} diff --git a/types/datatables.net-rowreorder/tsconfig.json b/types/datatables.net-rowreorder/tsconfig.json new file mode 100644 index 0000000000..c0b35cadfe --- /dev/null +++ b/types/datatables.net-rowreorder/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", + "datatables.net-rowreorder-tests.ts" + ] +} \ No newline at end of file diff --git a/types/datatables.net-rowreorder/tslint.json b/types/datatables.net-rowreorder/tslint.json new file mode 100644 index 0000000000..21764ccb0d --- /dev/null +++ b/types/datatables.net-rowreorder/tslint.json @@ -0,0 +1,5 @@ +{ + "extends": "dtslint/dt.json", + "rules": { + } +} \ No newline at end of file diff --git a/types/deasync/deasync-tests.ts b/types/deasync/deasync-tests.ts new file mode 100644 index 0000000000..e4e77561e9 --- /dev/null +++ b/types/deasync/deasync-tests.ts @@ -0,0 +1,24 @@ +import * as deasync from "deasync"; + +function asyncFunction(input: number, cb: (res: number) => void) {} +function handle(res: number) {} + +// base case +asyncFunction(42, handle); + +// deasync +let wrapped = deasync(asyncFunction); +handle(wrapped(42)); + +// deasync.loopWhile +let done = false; +asyncFunction(42, () => { + done = true; +}); +deasync.loopWhile(() => !done); + +// deasync.runLoopOnce +deasync.runLoopOnce(); + +// deasync.sleep +deasync.sleep(100); diff --git a/types/deasync/index.d.ts b/types/deasync/index.d.ts new file mode 100644 index 0000000000..20440203e7 --- /dev/null +++ b/types/deasync/index.d.ts @@ -0,0 +1,14 @@ +// Type definitions for deasync 0.1 +// Project: https://github.com/abbr/deasync +// Definitions by: Matt Rollins +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.1 + +export = deasync; + +declare function deasync(fn: (...args: any[]) => void): (...args: any[]) => any; +declare namespace deasync { + function loopWhile(pred: () => boolean): void; + function runLoopOnce(): void; + function sleep(ms: number): void; +} diff --git a/types/deasync/tsconfig.json b/types/deasync/tsconfig.json new file mode 100644 index 0000000000..5b96318954 --- /dev/null +++ b/types/deasync/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", + "deasync-tests.ts" + ] +} diff --git a/types/deasync/tslint.json b/types/deasync/tslint.json new file mode 100644 index 0000000000..c6c6df5352 --- /dev/null +++ b/types/deasync/tslint.json @@ -0,0 +1,4 @@ +{ + "extends": "dtslint/dt.json", + "rules": {} +} diff --git a/types/debessmann/debessmann-tests.ts b/types/debessmann/debessmann-tests.ts index 802257992e..4a247827fd 100644 --- a/types/debessmann/debessmann-tests.ts +++ b/types/debessmann/debessmann-tests.ts @@ -1,4 +1,4 @@ -import {DM, Event, EventId} from 'debessmann'; +import { DM, Event, EventId } from 'debessmann'; let eventId: EventId = {seq: 0, time: new Date()}; let e: Event = {_id: eventId, headers: {header1: 'header1Val'}}; diff --git a/types/decay/decay-tests.ts b/types/decay/decay-tests.ts index 20f33210ac..af45c63923 100644 --- a/types/decay/decay-tests.ts +++ b/types/decay/decay-tests.ts @@ -1,4 +1,4 @@ -import {redditHot, hackerHot, wilsonScore} from 'decay'; +import { redditHot, hackerHot, wilsonScore } from 'decay'; const upvotes = 42; const downvotes = 12; diff --git a/types/decorum/decorum-tests.ts b/types/decorum/decorum-tests.ts index 8cd03e046c..d6f2565fa5 100644 --- a/types/decorum/decorum-tests.ts +++ b/types/decorum/decorum-tests.ts @@ -1,4 +1,4 @@ -import {Required} from 'decorum'; +import { Required } from 'decorum'; import {Email} from 'decorum'; import {MinLength} from 'decorum'; import {MaxLength} from 'decorum'; diff --git a/types/delay/delay-tests.ts b/types/delay/delay-tests.ts new file mode 100644 index 0000000000..9714bfd86d --- /dev/null +++ b/types/delay/delay-tests.ts @@ -0,0 +1,47 @@ +import delay = require('delay'); + +delay(200) + .then(() => { + }); + +let str: string; +let num: number; +Promise.resolve(delay(100)) + .then(() => { + }); + +Promise.resolve("foo") + .then(delay(100)) + .then(result => { + str = result; + }); + +Promise.resolve('foo') + .then(delay(100, 10)) + .then(result => { + num = result; + }); + +Promise.resolve('foo') + .then(delay.reject(100)) + .then(x => 10) + .catch(err => { + }); + +Promise.resolve('foo') + .then(delay.reject(100, 'bar')) + .then(x => 10) + .catch(err => { + }); + +(async () => { + const delaying = delay(1000); + delaying.cancel(); + try { + await delaying; + } catch (err) { + // `err` is an instance of `delay.CancelError` + } +})(); + +throw new delay.CancelError('bar'); diff --git a/types/delay/index.d.ts b/types/delay/index.d.ts new file mode 100644 index 0000000000..f84c7ab5e4 --- /dev/null +++ b/types/delay/index.d.ts @@ -0,0 +1,30 @@ +// Type definitions for delay 2.0 +// Project: https://github.com/sindresorhus/delay#readme +// Definitions by: BendingBender +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.3 + +export = delay; + +declare function delay(ms: number): delay.PDelayedPassThroughThunk; +declare function delay(ms: number, value: T): delay.PDelayedThunk; + +declare namespace delay { + function reject(ms: number, rejectionValue?: any): PDelayedThunk; + + class CancelError extends Error { + readonly name: 'CancelError'; + constructor(message?: string); + } + + type PDelayedThunk = ((value: any) => DelayedPromiseLike) & DelayedPromiseLike; + + type PDelayedPassThroughThunk = ((value: TValue) => DelayedPromiseLike) & DelayedPromiseLike; + + interface DelayedPromiseLike { + then(onfulfilled?: ((value: T) => TResult1 | PromiseLike) | undefined | null, + onrejected?: ((reason: any) => TResult2 | PromiseLike) | undefined | null): Promise; + catch(onrejected?: ((reason: any) => TResult | PromiseLike) | undefined | null): Promise; + cancel(): void; + } +} diff --git a/types/delay/tsconfig.json b/types/delay/tsconfig.json new file mode 100644 index 0000000000..2004ba50ba --- /dev/null +++ b/types/delay/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", + "delay-tests.ts" + ] +} diff --git a/types/delay/tslint.json b/types/delay/tslint.json new file mode 100644 index 0000000000..3db14f85ea --- /dev/null +++ b/types/delay/tslint.json @@ -0,0 +1 @@ +{ "extends": "dtslint/dt.json" } diff --git a/types/diacritics/diacritics-tests.ts b/types/diacritics/diacritics-tests.ts new file mode 100644 index 0000000000..c6419c8593 --- /dev/null +++ b/types/diacritics/diacritics-tests.ts @@ -0,0 +1,12 @@ +import * as diacritics from "diacritics"; + +const replacementListItem = diacritics.replacementList[1]; + +// tslint:disable-next-line:no-unused-expression +replacementListItem.base === "0"; +replacementListItem.chars === "\u07C0"; + +const mapItem = diacritics.diacriticsMap["A"]; + +// tslint:disable-next-line:no-unused-expression +diacritics.remove("foo") === "bar"; diff --git a/types/diacritics/index.d.ts b/types/diacritics/index.d.ts new file mode 100644 index 0000000000..3031c5f493 --- /dev/null +++ b/types/diacritics/index.d.ts @@ -0,0 +1,14 @@ +// Type definitions for diacritics 1.3 +// Project: https://github.com/andrewrk/node-diacritics +// Definitions by: Oto Ciulis +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +export function remove(str: string): string; +export const replacementList: Array<{ + base: string; + chars: string; +}>; + +export const diacriticsMap: { + [key: string]: string; +}; diff --git a/types/diacritics/tsconfig.json b/types/diacritics/tsconfig.json new file mode 100644 index 0000000000..c5df557fe5 --- /dev/null +++ b/types/diacritics/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", + "diacritics-tests.ts" + ] +} \ No newline at end of file diff --git a/types/diacritics/tslint.json b/types/diacritics/tslint.json new file mode 100644 index 0000000000..2750cc0197 --- /dev/null +++ b/types/diacritics/tslint.json @@ -0,0 +1 @@ +{ "extends": "dtslint/dt.json" } \ No newline at end of file diff --git a/types/dockerode/dockerode-tests.ts b/types/dockerode/dockerode-tests.ts index ef2ed924d1..14ea3ca639 100644 --- a/types/dockerode/dockerode-tests.ts +++ b/types/dockerode/dockerode-tests.ts @@ -74,6 +74,10 @@ docker.buildImage('archive.tar', { t: 'imageName' }, (err, response) => { // NOOP }); +docker.buildImage({context: '.', src: ['Dockerfile', 'test.sh']}, { t: 'imageName' }, (err, response) => { + // NOOP +}); + docker.createContainer({ Tty: true }, (err, container) => { container.start((err, data) => { // NOOP diff --git a/types/dockerode/index.d.ts b/types/dockerode/index.d.ts index 1b456e8f45..aa6c03bf29 100644 --- a/types/dockerode/index.d.ts +++ b/types/dockerode/index.d.ts @@ -1,6 +1,8 @@ // Type definitions for dockerode 2.4 // Project: https://github.com/apocas/dockerode -// Definitions by: Carl Winkler , Nicolas Laplante +// Definitions by: Carl Winkler +// Nicolas Laplante +// ByeongHun Yoo // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped // TypeScript Version: 2.2 @@ -427,6 +429,15 @@ declare namespace Dockerode { GlobalIPv6PrefixLen: number; MacAddress: string; } + }; + Node?: { + ID: string; + IP: string; + Addr: string; + Name: string; + Cpus: number; + Memory: number; + Labels: any; } }; } @@ -795,6 +806,11 @@ declare namespace Dockerode { tail?: number; timestamps?: boolean; } + + interface ImageBuildContext { + context: string; + src: string[]; + } } type Callback = (error?: any, result?: T) => void; @@ -821,9 +837,9 @@ declare class Dockerode { checkAuth(options: any, callback: Callback): void; checkAuth(options: any): Promise; - buildImage(file: string | NodeJS.ReadableStream, options: {}, callback: Callback): void; - buildImage(file: string | NodeJS.ReadableStream, callback: Callback): void; - buildImage(file: string | NodeJS.ReadableStream, options?: {}): Promise; + buildImage(file: string | NodeJS.ReadableStream | Dockerode.ImageBuildContext, options: {}, callback: Callback): void; + buildImage(file: string | NodeJS.ReadableStream | Dockerode.ImageBuildContext, callback: Callback): void; + buildImage(file: string | NodeJS.ReadableStream | Dockerode.ImageBuildContext, options?: {}): Promise; getContainer(id: string): Dockerode.Container; diff --git a/types/documentdb/documentdb-tests.ts b/types/documentdb/documentdb-tests.ts index 3395716305..3ad362e4a0 100644 --- a/types/documentdb/documentdb-tests.ts +++ b/types/documentdb/documentdb-tests.ts @@ -240,3 +240,15 @@ const rpr2 = new ddb.RangePartitionResolver((obj: any) => obj.foo, [ partitionKe const rangePartitionKey1: any = rpr1.getPartitionKey(document1); const rangeCollectionLink1: string = rpr1.resolveForCreate(hashPartitionKey1); const rangeCollectionLinks1: string[] = rpr1.resolveForRead(hashPartitionKey1); + +/** UriFactory methods */ +const dbUri = ddb.UriFactory.createDatabaseUri('dbfoo'); +const colUri = ddb.UriFactory.createDocumentCollectionUri('dbfoo', 'colbar'); +const docUri = ddb.UriFactory.createDocumentUri('dbfoo', 'colbar', 'doc1'); +const permUri = ddb.UriFactory.createPermissionUri('dbfoo', 'userId', 'permission1'); +const sprocUri = ddb.UriFactory.createStoredProcedureUri('dbfoo', 'colbar', 'sproc1'); +const triggerUri = ddb.UriFactory.createTriggerUri('dbfoo', 'colbar', 'trigger1'); +const udfUri = ddb.UriFactory.createUserDefinedFunctionUri('dbfoo', 'colbar', 'udf1'); +const conflictUri = ddb.UriFactory.createConflictUri('dbfoo', 'colbar', 'conflict1'); +const attachUri = ddb.UriFactory.createAttachmentUri('dbfoo', 'colbar', 'doc1', 'attachment1'); +const partitionKeyRangeUri = ddb.UriFactory.createPartitionKeyRangesUri('dbfoo', 'colbar'); diff --git a/types/documentdb/index.d.ts b/types/documentdb/index.d.ts index 7e73926c7f..140470fbda 100644 --- a/types/documentdb/index.d.ts +++ b/types/documentdb/index.d.ts @@ -1,6 +1,6 @@ // Type definitions for DocumentDB 1.10 // Project: https://github.com/Azure/azure-documentdb-node -// Definitions by: Noel Abrahams , Brett Gutstein , Chris Stone +// Definitions by: Noel Abrahams , Brett Gutstein , Chris Stone , Yifan Wu // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped/documentdb /// @@ -1340,6 +1340,109 @@ export class DocumentClient { getWriteEndpoint(callback: RequestCallback): void; } +export class UriFactory { + /** + * Given a database id, this creates a database link. + * @param {string} databaseId -The database id + * @returns {string} -A database link in the format of dbs/{0} with {0} being a Uri escaped version of the databaseId + * @description Would be used when creating or deleting a DocumentCollection or a User in Azure DocumentDB database service + */ + static createDatabaseUri(databaseId: string): string; + /** + * Given a database and collection id, this creates a collection link. + * @param {string} databaseId -The database id + * @param {string} collectionId -The collection id + * @returns {string} A collection link in the format of dbs/{0}/colls/{1} with {0} being a Uri escaped version of the databaseId and {1} being collectionId + * @description Would be used when updating or deleting a DocumentCollection, creating a Document, a StoredProcedure, a + * Trigger, a UserDefinedFunction, or when executing a query with CreateDocumentQuery in Azure DocumentDB database service. + */ + static createDocumentCollectionUri(databaseId: string, collectionId: string): string; + /** + * Given a database and collection id, this creates a collection link. + * @param {string} databaseId -The database id + * @param {string} collectionId -The collection id + * @param {string} documentId -The document id + * @returns {string} -A document link in the format of dbs/{0}/colls/{1}/docs/{2} with {0} + * being a Uri escaped version of the databaseId, {1} being collectionId and {2} being the documentId + * @description Would be used when creating an Attachment, or when replacing or deleting a Document in Azure DocumentDB database service + */ + static createDocumentUri(databaseId: string, collectionId: string, documentId: string): string; + /** + * Given a database, collection and document id, this creates a document link. + * @param {string} databaseId -The database Id + * @param {string} userId -The user Id + * @param {string} permissionId - The permissionId + * @returns {string} A permission link in the format of dbs/{0}/users/{1}/permissions/{2} with {0} being a Uri escaped version of the databaseId, {1} being userId and {2} being permissionId + * @description Would be used when replacing or deleting a Permission in Azure DocumentDB database service. + */ + static createPermissionUri(databaseId: string, userId: string, permissionId: string): string; + + /** + * Given a database, collection and stored proc id, this creates a stored proc link. + * @param {string} databaseId -The database Id + * @param {string} collectionId -The collection Id + * @param {string} storedProcedureId -The stored procedure Id + * @returns {string} -A stored procedure link in the format of dbs/{0}/colls/{1}/sprocs/{2} + * with {0} being a Uri escaped version of the databaseId, + * {1} being collectionId and {2} being the storedProcedureId + * @description Would be used when replacing, executing, or deleting a StoredProcedure in Azure DocumentDB database service. + */ + static createStoredProcedureUri(databaseId: string, collectionId: string, storedProcedureId: string): string; + + /** + * @summary Given a database, collection and trigger id, this creates a trigger link. + * @param {string} databaseId -The database Id + * @param {string} collectionId -The collection Id + * @param {string} triggerId -The trigger Id + * @returns {string} -A trigger link in the format of dbs/{0}/colls/{1}/triggers/{2} + * with {0} being a Uri escaped version of the databaseId, + * {1} being collectionId and {2} being the triggerId + * @description Would be used when replacing, executing, or deleting a Trigger in Azure DocumentDB database service + */ + static createTriggerUri(databaseId: string, collectionId: string, triggerId: string): string; + + /** + * @summary Given a database, collection and udf id, this creates a udf link. + * @param {string} databaseId -The database Id + * @param {string} collectionId -The collection Id + * @param {string} udfId -The User Defined Function Id + * @returns {string} -A udf link in the format of dbs/{0}/colls/{1}/udfs/{2} with {0} being a Uri escaped version of the databaseId, {1} being collectionId and {2} being the udfId + * @description Would be used when replacing, executing, or deleting a UserDefinedFunction in Azure DocumentDB database service + */ + static createUserDefinedFunctionUri(databaseId: string, collectionId: string, udfId: string): string; + + /** + * @summary + * @param {string} databaseId -The database Id + * @param {string} collectionId -The collection Id + * @param {string} conflictId -The conflict Id + * @returns {string} -A conflict link in the format of dbs/{0}/colls/{1}/conflicts/{2} + * with {0} being a Uri escaped version of the databaseId, {1} being collectionId and {2} being the conflictId + * @description Would be used when creating a Conflict in Azure DocumentDB database service. + */ + static createConflictUri(databaseId: string, collectionId: string, conflictId: string): string; + + /** + * @summary Given a database, collection and conflict id, this creates a conflict link. + * @param {string} databaseId -The database Id + * @param {string} collectionId -The collection Id + * @param {string} documentId -The document Id\ + * @param {string} attachmentId -The attachment Id + * @returns {string} -A conflict link in the format of dbs/{0}/colls/{1}/conflicts/{2} with {0} being a Uri escaped version of the databaseId, + * {1} being collectionId and {2} being the conflictId + * @description Would be used when creating a Conflict in Azure DocumentDB database service. + */ + static createAttachmentUri(databaseId: string, collectionId: string, documentId: string, attachmentId: string): string; + + /** + * @summary Given a database and collection, this creates a partition key ranges link in the Azure DocumentDB database service. + * @param {string} databaseId -The database Id + * @param {string} collectionId -The collection Id + * @returns {string} -A partition key ranges link in the format of dbs/{0}/colls/{1}/pkranges with {0} being a Uri escaped version of the databaseId and {1} being collectionId + */ + static createPartitionKeyRangesUri(databaseId: string, collectionId: string): string; +} + export type MediaReadMode = 'Buffered' | 'Streamed'; export type ConsistencyLevel = 'Strong' | 'BoundedStaleness' | 'Session' | 'Eventual'; export type IndexingMode = 'Consistent' | 'Lazy'; diff --git a/types/dookie/dookie-tests.ts b/types/dookie/dookie-tests.ts index 476538b8de..e672d59de6 100644 --- a/types/dookie/dookie-tests.ts +++ b/types/dookie/dookie-tests.ts @@ -1,4 +1,4 @@ -import {push, pull} from 'dookie'; +import { push, pull } from 'dookie'; (async () => { await push('mongodb://localhost:27017/test', {test: [{ok: 1}, {ok: 2}]}); diff --git a/types/dot-prop/dot-prop-tests.ts b/types/dot-prop/dot-prop-tests.ts index b7687bb64b..420fe2d320 100644 --- a/types/dot-prop/dot-prop-tests.ts +++ b/types/dot-prop/dot-prop-tests.ts @@ -1,11 +1,23 @@ +/// +import dotProp = require('dot-prop'); +import { get, has, set } from 'dot-prop'; -import * as dotProp from 'dot-prop'; - -dotProp.get({foo: {bar: 'unicorn'}}, 'foo.bar'); +get({foo: {bar: 'unicorn'}}, 'foo.bar'); dotProp.get({foo: {bar: 'a'}}, 'foo.notDefined.deep'); +dotProp.get({foo: {bar: 'a'}}, 'foo.notDefined.deep', 'default value'); dotProp.get({foo: {'dot.dot': 'unicorn'}}, 'foo.dot\\.dot'); const obj = {foo: {bar: 'a'}}; -dotProp.set(obj, 'foo.bar', 'b'); +set(obj, 'foo.bar', 'b'); +console.log(obj); dotProp.set(obj, 'foo.baz', 'x'); -dotProp.set(obj, 'foo.dot\\.dot', 'unicorn'); +console.log(obj); + +has({foo: {bar: 'unicorn'}}, 'foo.bar'); +dotProp.has({foo: {bar: 'unicorn'}}, 'foo.bar'); + +dotProp.delete(obj, 'foo.bar'); +console.log(obj); +( obj).foo.bar = {x: 'y', y: 'x'}; +dotProp.delete(obj, 'foo.bar.x'); +console.log(obj); diff --git a/types/dot-prop/index.d.ts b/types/dot-prop/index.d.ts index b8d9ce406c..31877dbd9e 100644 --- a/types/dot-prop/index.d.ts +++ b/types/dot-prop/index.d.ts @@ -1,8 +1,17 @@ -// Type definitions for dot-prop -// Project: https://github.com/sindresorhus/dot-prop +// Type definitions for dot-prop 4.1 +// Project: https://github.com/sindresorhus/dot-prop#readme // Definitions by: Sam Verschueren +// BendingBender // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.2 +interface DotProp { + get(obj: object, path: string, defaultValue?: any): any; + set(obj: object, path: string, value: any): void; + has(obj: object, path: string): boolean; + delete(obj: object, path: string): boolean; +} -export declare function get(object: any, path: string): any; -export declare function set(object: any, path: string, value: any): void; +declare const dotProp: DotProp; + +export = dotProp; diff --git a/types/dot-prop/tsconfig.json b/types/dot-prop/tsconfig.json index f404606239..9569bb6470 100644 --- a/types/dot-prop/tsconfig.json +++ b/types/dot-prop/tsconfig.json @@ -6,7 +6,7 @@ ], "noImplicitAny": true, "noImplicitThis": true, - "strictNullChecks": false, + "strictNullChecks": true, "baseUrl": "../", "typeRoots": [ "../" @@ -19,4 +19,4 @@ "index.d.ts", "dot-prop-tests.ts" ] -} \ No newline at end of file +} diff --git a/types/dot-prop/tslint.json b/types/dot-prop/tslint.json new file mode 100644 index 0000000000..3db14f85ea --- /dev/null +++ b/types/dot-prop/tslint.json @@ -0,0 +1 @@ +{ "extends": "dtslint/dt.json" } diff --git a/types/dot-prop/v2/dot-prop-tests.ts b/types/dot-prop/v2/dot-prop-tests.ts new file mode 100644 index 0000000000..f9991f8d5b --- /dev/null +++ b/types/dot-prop/v2/dot-prop-tests.ts @@ -0,0 +1,10 @@ +import * as dotProp from 'dot-prop'; + +dotProp.get({foo: {bar: 'unicorn'}}, 'foo.bar'); +dotProp.get({foo: {bar: 'a'}}, 'foo.notDefined.deep'); +dotProp.get({foo: {'dot.dot': 'unicorn'}}, 'foo.dot\\.dot'); + +const obj = {foo: {bar: 'a'}}; +dotProp.set(obj, 'foo.bar', 'b'); +dotProp.set(obj, 'foo.baz', 'x'); +dotProp.set(obj, 'foo.dot\\.dot', 'unicorn'); diff --git a/types/dot-prop/v2/index.d.ts b/types/dot-prop/v2/index.d.ts new file mode 100644 index 0000000000..86964e32a7 --- /dev/null +++ b/types/dot-prop/v2/index.d.ts @@ -0,0 +1,7 @@ +// Type definitions for dot-prop 2.x +// Project: https://github.com/sindresorhus/dot-prop +// Definitions by: Sam Verschueren +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +export function get(object: any, path: string): any; +export function set(object: any, path: string, value: any): void; diff --git a/types/dot-prop/v2/tsconfig.json b/types/dot-prop/v2/tsconfig.json new file mode 100644 index 0000000000..2e274e84da --- /dev/null +++ b/types/dot-prop/v2/tsconfig.json @@ -0,0 +1,25 @@ +{ + "compilerOptions": { + "module": "commonjs", + "lib": [ + "es6" + ], + "noImplicitAny": true, + "noImplicitThis": true, + "strictNullChecks": false, + "baseUrl": "../../", + "typeRoots": [ + "../../" + ], + "paths": { + "dot-prop": ["dot-prop/v2"] + }, + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true + }, + "files": [ + "index.d.ts", + "dot-prop-tests.ts" + ] +} diff --git a/types/dot-prop/v2/tslint.json b/types/dot-prop/v2/tslint.json new file mode 100644 index 0000000000..3db14f85ea --- /dev/null +++ b/types/dot-prop/v2/tslint.json @@ -0,0 +1 @@ +{ "extends": "dtslint/dt.json" } diff --git a/types/draft-js/draft-js-tests.tsx b/types/draft-js/draft-js-tests.tsx index 4315611765..46f90a8a31 100644 --- a/types/draft-js/draft-js-tests.tsx +++ b/types/draft-js/draft-js-tests.tsx @@ -1,6 +1,6 @@ import * as React from "react"; import * as ReactDOM from "react-dom"; -import {Map} from "immutable"; +import { Map } from "immutable"; import { ContentBlock, diff --git a/types/draft-js/index.d.ts b/types/draft-js/index.d.ts index 1019df8fce..00c9302740 100644 --- a/types/draft-js/index.d.ts +++ b/types/draft-js/index.d.ts @@ -5,6 +5,7 @@ // Yale Cason // Ryan Schwers // Michael Wu +// Willis Plummer // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped // TypeScript Version: 2.3 @@ -863,7 +864,7 @@ declare namespace Draft { static getDataObjectForLinkURL(uri: URI): Object; static handleKeyCommand(editorState: EditorState, command: DraftEditorCommand): EditorState; - static handleKeyCommand(editorState: EditorState, command: string): EditorState; + static handleKeyCommand(editorState: EditorState, command: string): null; static insertSoftNewline(editorState: EditorState): EditorState; @@ -888,7 +889,7 @@ declare namespace Draft { */ static toggleInlineStyle(editorState: EditorState, inlineStyle: string): EditorState; - static toggleLink(editorState: EditorState, targetSelection: SelectionState, entityKey: string): EditorState; + static toggleLink(editorState: EditorState, targetSelection: SelectionState, entityKey: string | null): EditorState; /** * When a collapsed cursor is at the start of an empty styled block, allow @@ -902,6 +903,7 @@ declare namespace Draft { } import Editor = Draft.Component.Base.DraftEditor; +import EditorProps = Draft.Component.Base.DraftEditorProps; import EditorBlock = Draft.Component.Components.DraftEditorBlock; import EditorState = Draft.Model.ImmutableData.EditorState; @@ -935,6 +937,7 @@ import getVisibleSelectionRect = Draft.Component.Selection.getVisibleSelectionRe export { Editor, + EditorProps, EditorBlock, EditorState, diff --git a/types/duplexer3/duplexer3-tests.ts b/types/duplexer3/duplexer3-tests.ts new file mode 100644 index 0000000000..557437597c --- /dev/null +++ b/types/duplexer3/duplexer3-tests.ts @@ -0,0 +1,47 @@ +import * as stream from 'stream'; +import duplexer3 = require('duplexer3'); + +const writable = new stream.Writable({objectMode: true}); +const readable = new stream.Readable({objectMode: true}); + +writable._write = (input, encoding, done) => { + if (readable.push(input)) { + return done(); + } else { + readable.once('drain', <(...args: any[]) => void> done); + } +}; + +readable._read = n => { + // no-op +}; + +// simulate the readable thing closing after a bit +writable.once('finish', () => { + setTimeout(() => { + readable.push(null); + }, 500); +}); + +const duplex = duplexer3(writable, readable); +const duplex2 = duplexer3({bubbleErrors: true, allowHalfOpen: true}, writable, readable); + +duplex.on('data', e => { + console.log('got data', JSON.stringify(e)); +}); + +duplex.on('finish', () => { + console.log('got finish event'); +}); + +duplex.on('end', () => { + console.log('got end event'); +}); + +duplex.write('oh, hi there', () => { + console.log('finished writing'); +}); + +duplex.end(() => { + console.log('finished ending'); +}); diff --git a/types/duplexer3/index.d.ts b/types/duplexer3/index.d.ts new file mode 100644 index 0000000000..82693b86bf --- /dev/null +++ b/types/duplexer3/index.d.ts @@ -0,0 +1,18 @@ +// Type definitions for duplexer3 0.1 +// Project: https://github.com/floatdrop/duplexer3 +// Definitions by: BendingBender +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +/// +import * as stream from 'stream'; + +export = duplexer3; + +declare function duplexer3(writableStream: NodeJS.WritableStream, readableStream: NodeJS.ReadableStream): stream.Duplex; +declare function duplexer3(options: duplexer3.Options, writableStream: NodeJS.WritableStream, readableStream: NodeJS.ReadableStream): stream.Duplex; + +declare namespace duplexer3 { + interface Options extends stream.DuplexOptions { + bubbleErrors?: boolean; + } +} diff --git a/types/duplexer3/tsconfig.json b/types/duplexer3/tsconfig.json new file mode 100644 index 0000000000..36ac16d2c7 --- /dev/null +++ b/types/duplexer3/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", + "duplexer3-tests.ts" + ] +} diff --git a/types/duplexer3/tslint.json b/types/duplexer3/tslint.json new file mode 100644 index 0000000000..3db14f85ea --- /dev/null +++ b/types/duplexer3/tslint.json @@ -0,0 +1 @@ +{ "extends": "dtslint/dt.json" } diff --git a/types/dygraphs/index.d.ts b/types/dygraphs/index.d.ts index fb6f4b997d..33db704b3b 100644 --- a/types/dygraphs/index.d.ts +++ b/types/dygraphs/index.d.ts @@ -1,4 +1,4 @@ -// Type definitions for dygraphs 1.1.1 +// Type definitions for dygraphs 1.1.2 // Project: http://dygraphs.com // Definitions by: Dan Vanderkam // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped @@ -8,7 +8,7 @@ declare namespace dygraphs { type DataArray = number[][]; - type Data = string|DataArray|google.visualization.DataTable; + type Data = string | DataArray | google.visualization.DataTable; interface PerSeriesOptions { /** @@ -112,7 +112,7 @@ declare namespace dygraphs { * Function to call to format the tick values that appear along an axis. This is usually set * on a per-axis basis. */ - axisLabelFormatter?: (v: number|Date, granularity: number, opts: (name: string) => any, dygraph: Dygraph) => any; + axisLabelFormatter?: (v: number | Date, granularity: number, opts: (name: string) => any, dygraph: Dygraph) => any; /** * Width (in pixels) of the containing divs for x- and y-axis labels. For the y-axis, this @@ -224,7 +224,7 @@ declare namespace dygraphs { pixels: number, opts: (name: string) => any, dygraph: Dygraph, - vals: number[]) => Array<{v: number, label: string}>; + vals: number[]) => Array<{ v: number, label: string }>; /** @@ -267,6 +267,58 @@ declare namespace dygraphs { labelsKMG2?: boolean; } + interface SeriesLegendData { + /** + * Assigned or generated series color + */ + color: string; + /** + * Series line dash + */ + dashHTML: string; + /** + * Whether currently focused or not + */ + isHighlighted: boolean; + /** + * Whether the series line is inside the selected/zoomed region + */ + isVisible: boolean; + /** + * Assigned label to this series + */ + label: string; + /** + * Generated label html for this series + */ + labelHTML: string; + /** + * y value of this series + */ + y: number; + /** + * Generated html for y value + */ + yHTML: string; + } + interface LegendData { + /** + * x value of highlighted points + */ + x: number; + /** + * Generated HTML for x value + */ + xHTML: string; + /** + * Series data for the highlighted points + */ + series: SeriesLegendData[]; + /** + * Dygraph object for this graph + */ + dygraph: Dygraph; + } interface Options extends PerSeriesOptions, PerAxisOptions { /** * Set this option to animate the transition between zoom windows. Applies to programmatic @@ -510,14 +562,14 @@ declare namespace dygraphs { * Show data labels in an external div, rather than on the graph. This value can either be a * div element or a div id. */ - labelsDiv?: string|HTMLElement; + labelsDiv?: string | HTMLElement; /** * Additional styles to apply to the currently-highlighted points div. For example, { * 'fontWeight': 'bold' } will make the labels bold. In general, it is better to use CSS to * style the .dygraph-legend class than to use this property. */ - labelsDivStyles?: {[cssProperty: string]: string}; + labelsDivStyles?: { [cssProperty: string]: string }; /** * Width (in pixels) of the div which shows information on the currently-highlighted points. @@ -547,6 +599,11 @@ declare namespace dygraphs { */ legend?: 'always' | 'follow' | 'onmouseover'; + /** + * for details see https://github.com/danvk/dygraphs/pull/683 + */ + legendFormatter?: (legendData: LegendData) => string; + /** * A value representing the farthest a graph may be panned, in percent of the display. For * example, a value of 0.1 means that the graph can only be panned 10% pased the edges of the @@ -813,7 +870,7 @@ declare namespace dygraphs { * you specified in your CSV file, e.g. "2010-09-13". * You must set either x or xval. */ - x?: number|string; + x?: number | string; /** * numeric value of the point, or millis since epoch. @@ -867,7 +924,7 @@ declare namespace dygraphs { declare class Dygraph { constructor( container: HTMLElement | string, - data: dygraphs.Data|(()=>dygraphs.Data), + data: dygraphs.Data | (() => dygraphs.Data), options?: dygraphs.Options); /** @@ -1104,7 +1161,7 @@ declare class Dygraph { * over the graph, disabling closest-series highlighting. Call clearSelection() * to unlock it. */ - setSelection(row: number|boolean, seriesName?: string, locked?: boolean): void; + setSelection(row: number | boolean, seriesName?: string, locked?: boolean): void; /** * Clears the current selection (i.e. points that were highlighted by moving diff --git a/types/easy-session/index.d.ts b/types/easy-session/index.d.ts index 0d96c61783..9a449b5322 100644 --- a/types/easy-session/index.d.ts +++ b/types/easy-session/index.d.ts @@ -2,6 +2,7 @@ // Project: https://github.com/DeadAlready/node-easy-session // Definitions by: Karl Düüna // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.2 /// diff --git a/types/ebongarde-root/ebongarde-root-tests.ts b/types/ebongarde-root/ebongarde-root-tests.ts index f40eec7172..7286f811c6 100644 --- a/types/ebongarde-root/ebongarde-root-tests.ts +++ b/types/ebongarde-root/ebongarde-root-tests.ts @@ -1,3 +1,3 @@ -import {ROOT} from 'ebongarde-root'; +import { ROOT } from 'ebongarde-root'; console.log(ROOT); diff --git a/types/electron-json-storage/electron-json-storage-tests.ts b/types/electron-json-storage/electron-json-storage-tests.ts index dd0504f8b6..3abc584a46 100644 --- a/types/electron-json-storage/electron-json-storage-tests.ts +++ b/types/electron-json-storage/electron-json-storage-tests.ts @@ -1,5 +1,3 @@ -/// - import electron = require('electron'); import storage = require('electron-json-storage'); diff --git a/types/electron-json-storage/index.d.ts b/types/electron-json-storage/index.d.ts index 23b26920af..428b784638 100644 --- a/types/electron-json-storage/index.d.ts +++ b/types/electron-json-storage/index.d.ts @@ -2,7 +2,7 @@ // Project: https://github.com/jviotti/electron-json-storage // Definitions by: Sam Saint-Pettersen // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped - +// TypeScript Version: 2.1 export declare function get(key: string, callback: (error: any, data: Object) => void): void; export declare function set(key: string, json: Object, callback: (error: any) => void): void; diff --git a/types/electron-json-storage/package.json b/types/electron-json-storage/package.json new file mode 100644 index 0000000000..b68da5cd37 --- /dev/null +++ b/types/electron-json-storage/package.json @@ -0,0 +1,5 @@ +{ + "dependencies": { + "electron": "^1.7.5" + } +} diff --git a/types/electron-notifications/index.d.ts b/types/electron-notifications/index.d.ts index 3bda7f4ef9..870fcb1bbc 100644 --- a/types/electron-notifications/index.d.ts +++ b/types/electron-notifications/index.d.ts @@ -2,6 +2,7 @@ // Project: https://github.com/blainesch/electron-notifications // Definitions by: Daniel Pereira // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.1 import * as Electron from 'electron'; diff --git a/types/electron-notifications/package.json b/types/electron-notifications/package.json new file mode 100644 index 0000000000..b68da5cd37 --- /dev/null +++ b/types/electron-notifications/package.json @@ -0,0 +1,5 @@ +{ + "dependencies": { + "electron": "^1.7.5" + } +} diff --git a/types/electron-notify/index.d.ts b/types/electron-notify/index.d.ts index 225ab9de9e..16f786d379 100644 --- a/types/electron-notify/index.d.ts +++ b/types/electron-notify/index.d.ts @@ -2,6 +2,7 @@ // Project: https://github.com/hankbao/electron-notify // Definitions by: Daniel Pereira // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.1 /// @@ -18,7 +19,7 @@ export interface ICustomConfig { appIcon?: string, pathToModule?: string, logging?: boolean, - defaultWindow?: Electron.BrowserWindowOptions, + defaultWindow?: Electron.BrowserWindowConstructorOptions, defaultStyleContainer?: any, defaultStyleAppIcon?: any, defaultStyleImage?: any, @@ -57,4 +58,4 @@ export function closeAll(): void; export function getTemplatePath(): string; -export function setTemplatePath(path: string): void; \ No newline at end of file +export function setTemplatePath(path: string): void; diff --git a/types/electron-notify/package.json b/types/electron-notify/package.json new file mode 100644 index 0000000000..b68da5cd37 --- /dev/null +++ b/types/electron-notify/package.json @@ -0,0 +1,5 @@ +{ + "dependencies": { + "electron": "^1.7.5" + } +} diff --git a/types/electron-window-state/electron-window-state-tests.ts b/types/electron-window-state/electron-window-state-tests.ts index 8a345d0ec9..62ba0599f7 100644 --- a/types/electron-window-state/electron-window-state-tests.ts +++ b/types/electron-window-state/electron-window-state-tests.ts @@ -1,6 +1,6 @@ -import {app, BrowserWindow} from 'electron'; +import { app, BrowserWindow } from 'electron'; import windowStateKeeper = require('electron-window-state'); let win: Electron.BrowserWindow = null; diff --git a/types/electron-window-state/index.d.ts b/types/electron-window-state/index.d.ts index 1ff10ed7d5..1ff0a15878 100644 --- a/types/electron-window-state/index.d.ts +++ b/types/electron-window-state/index.d.ts @@ -2,6 +2,7 @@ // Project: https://github.com/mawie81/electron-window-state // Definitions by: rhysd // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.1 /// diff --git a/types/electron-window-state/package.json b/types/electron-window-state/package.json new file mode 100644 index 0000000000..b68da5cd37 --- /dev/null +++ b/types/electron-window-state/package.json @@ -0,0 +1,5 @@ +{ + "dependencies": { + "electron": "^1.7.5" + } +} diff --git a/types/email-templates/email-templates-tests.ts b/types/email-templates/email-templates-tests.ts index 9f9097609e..3c4493402c 100644 --- a/types/email-templates/email-templates-tests.ts +++ b/types/email-templates/email-templates-tests.ts @@ -1,9 +1,9 @@ import EmailTemplates = require('email-templates'); -var EmailTemplate = EmailTemplates.EmailTemplate; -var template = new EmailTemplate("./"); -var templateWithOptions = new EmailTemplate('./', {sassOptions: {}, juiceOptions: {}}); -var users = [ +const EmailTemplate = EmailTemplates.EmailTemplate; +const template = new EmailTemplate("./"); +const templateWithOptions = new EmailTemplate('./', {disableJuice: true, sassOptions: {}, juiceOptions: {}}); +const users = [ { email: 'pappa.pizza@spaghetti.com', name: { @@ -18,8 +18,12 @@ var users = [ last: 'Geppetto' } } -] +]; -var templates = users.map(function(user) { - return template.render(user); -}) +const templates = users.map((user) => { + return template.render(user) + .then((results) => { + const {html, subject, text} = results; + return html; + }); +}); diff --git a/types/email-templates/index.d.ts b/types/email-templates/index.d.ts index 5fdd7054f3..d76c23aed3 100644 --- a/types/email-templates/index.d.ts +++ b/types/email-templates/index.d.ts @@ -1,6 +1,7 @@ -// Type definitions for node-email-templates +// Type definitions for node-email-templates 2.6 // Project: https://github.com/niftylettuce/node-email-templates // Definitions by: Cyril Schumacher +// Matus Gura // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped /** @@ -28,23 +29,18 @@ interface EmailTemplateResults { } /** - * @summary Interface for callback of email callback. - * @interface + * @summary Callback signature. */ -interface EmailTemplateCallback { - /** - * @summary Callback signature. - */ - (err: Object, results: EmailTemplateResults): void; -} +type EmailTemplateCallback = (err: any, results: EmailTemplateResults) => void; /** * @summary Interface for email-template options * @interface */ interface EmailTemplateOptions { - sassOptions?: any; + disableJuice?: boolean; juiceOptions?: any; + sassOptions?: any; } declare module "email-templates" { @@ -52,7 +48,7 @@ declare module "email-templates" { * @summary Email template class. * @class */ - export class EmailTemplate { + class EmailTemplate { /** * @summary Constructor. * @param {string} templateDir The template directory. @@ -61,9 +57,96 @@ declare module "email-templates" { /** * @summary Render a single template. - * @param {EmailTemplateCallback|Object} locals The variables or callback function. - * @param {EmailTemplateCallback} callback The callback function. + * @param locals The template variables. + * @param locale The language code. */ - render(locals: EmailTemplateCallback|Object, callback?: EmailTemplateCallback): void | Promise; + render(locals: any, locale?: string): Promise; + + /** + * @summary Render a single template. + * @param callback The callback function. + */ + render(callback: EmailTemplateCallback): void; + + /** + * @summary Render a single template. + * @param locals The template variables. + * @param callback The callback function. + */ + render(locals: any, callback: EmailTemplateCallback): void; + + /** + * @summary Render a single template. + * @param locals The template variables. + * @param locale The language code. + * @param callback The callback function. + */ + render(locals: any, locale: string, callback: EmailTemplateCallback): void; + + /** + * @summary Render text + * @param locals The template variables. + * @param locale The language code. + */ + renderText(locals: any, locale?: string): Promise; + + /** + * @summary Render text + * @param locals The template variables. + * @param callback The language code. + */ + renderText(locals: any, callback: EmailTemplateCallback): void; + + /** + * @summary Render text + * @param locals The template variables. + * @param locale The language code. + * @param callback The language code. + */ + renderText(locals: any, locale: string, callback: EmailTemplateCallback): void; + + /** + * @summary Render subject + * @param locals The template variables. + * @param locale The language code. + */ + renderSubject(locals: any, locale?: string): Promise; + + /** + * @summary Render subject + * @param locals The template variables. + * @param callback The language code. + */ + renderSubject(locals: any, callback: EmailTemplateCallback): void; + + /** + * @summary Render subject + * @param locals The template variables. + * @param locale The language code. + * @param callback The language code. + */ + renderSubject(locals: any, locale: string, callback: EmailTemplateCallback): void; + + /** + * @summary Render HTML + * @param locals The template variables. + * @param locale The language code. + */ + renderHtml(locals: any, locale?: string): Promise; + + /** + * @summary Render HTML + * @param locals The template variables. + * @param callback The language code. + */ + renderHtml(locals: any, callback: EmailTemplateCallback): void; + + /** + * @summary Render HTML + * @param locals The template variables. + * @param locale The language code. + * @param callback The language code. + */ + renderHtml(locals: any, locale: string, callback: EmailTemplateCallback): void; } } diff --git a/types/email-templates/tsconfig.json b/types/email-templates/tsconfig.json index bc97b20dbc..cf59410224 100644 --- a/types/email-templates/tsconfig.json +++ b/types/email-templates/tsconfig.json @@ -19,4 +19,4 @@ "index.d.ts", "email-templates-tests.ts" ] -} \ No newline at end of file +} diff --git a/types/email-templates/tslint.json b/types/email-templates/tslint.json new file mode 100644 index 0000000000..e765bc9e16 --- /dev/null +++ b/types/email-templates/tslint.json @@ -0,0 +1,6 @@ +{ + "extends": "dtslint/dt.json", + "rules": { + "no-single-declare-module": false + } +} diff --git a/types/ember-testing-helpers/ember-testing-helpers-tests.ts b/types/ember-testing-helpers/ember-testing-helpers-tests.ts index 9088097b25..70ff59a2d8 100644 --- a/types/ember-testing-helpers/ember-testing-helpers-tests.ts +++ b/types/ember-testing-helpers/ember-testing-helpers-tests.ts @@ -1,10 +1,12 @@ +import RSVP from 'rsvp'; + function testAndThen() { - const result: RSVP.Promise = andThen(() => "some string"); + const result: RSVP.Promise = andThen(() => 'some string'); result.then(s => s.length); } function testClick() { - const result: RSVP.Promise = click('someString'); + const result: RSVP.Promise = click('someString'); result.then(() => {}); } @@ -26,7 +28,7 @@ function testCurrentURL() { function testFillIn() { const textResult = fillIn('.foo', 'waffles'); textResult.then(() => true); - const contextResult = fillIn('.bar', { }, 'pancakes'); + const contextResult = fillIn('.bar', {}, 'pancakes'); contextResult.catch(reason => false); } @@ -55,7 +57,7 @@ function testKeyEvent() { function testPauseTest() { pauseTest().finally(() => { const foo = 'fighters'; - }) + }); } function testResumeTest() { @@ -70,7 +72,7 @@ function testTriggerEvent() { } function testVisit() { - visit('some/url').then(() => {}) + visit('some/url').then(() => {}); } function testWait() { diff --git a/types/ember-testing-helpers/index.d.ts b/types/ember-testing-helpers/index.d.ts index 3fd1d4e23f..e45d844487 100644 --- a/types/ember-testing-helpers/index.d.ts +++ b/types/ember-testing-helpers/index.d.ts @@ -1,5 +1,5 @@ // Type definitions for ember-testing/lib/helpers -// Project: Ember.js Testing Helpers: https://github.com/emberjs/ember.js/tree/master/packages/ember-testing/lib/helpers +// Project: https://github.com/emberjs/ember.js/tree/master/packages/ember-testing/lib/helpers // Definitions by: Chris Krycho // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped // TypeScript Version: 2.3 @@ -9,55 +9,61 @@ // not easily or straightforwardly exported from the Ember type definitions. /// -/// + +import RSVP from 'rsvp'; type KeyEventType = 'keydown' | 'keyup' | 'keypress'; -type VoidWaitResult = RSVP.Promise; +type WaitResult = RSVP.Promise; declare global { - // https://github.com/emberjs/ember.js/blob/master/packages/ember-testing/lib/helpers/and_then.js - function andThen(callback: (...args: any[]) => T): RSVP.Promise; + // https://github.com/emberjs/ember.js/blob/master/packages/ember-testing/lib/helpers/and_then.js + function andThen(callback: (...args: any[]) => T): RSVP.Promise; - // https://github.com/emberjs/ember.js/blob/master/packages/ember-testing/lib/helpers/click.js - function click(selector: string, context?: Object): VoidWaitResult; + // https://github.com/emberjs/ember.js/blob/master/packages/ember-testing/lib/helpers/click.js + function click(selector: string, context?: Object): WaitResult; - // https://github.com/emberjs/ember.js/blob/master/packages/ember-testing/lib/helpers/current_path.js - function currentPath(): string; + // https://github.com/emberjs/ember.js/blob/master/packages/ember-testing/lib/helpers/current_path.js + function currentPath(): string; - // https://github.com/emberjs/ember.js/blob/master/packages/ember-testing/lib/helpers/current_route_name.js - function currentRouteName(): string; + // https://github.com/emberjs/ember.js/blob/master/packages/ember-testing/lib/helpers/current_route_name.js + function currentRouteName(): string; - // https://github.com/emberjs/ember.js/blob/master/packages/ember-testing/lib/helpers/current_url.js - function currentURL(): string; + // https://github.com/emberjs/ember.js/blob/master/packages/ember-testing/lib/helpers/current_url.js + function currentURL(): string; - // https://github.com/emberjs/ember.js/blob/master/packages/ember-testing/lib/helpers/fill_in.js - function fillIn(selector: string, context: Object, text: string): VoidWaitResult; - function fillIn(selector: string, text: string): VoidWaitResult; + // https://github.com/emberjs/ember.js/blob/master/packages/ember-testing/lib/helpers/fill_in.js + function fillIn(selector: string, context: Object, text: string): WaitResult; + function fillIn(selector: string, text: string): WaitResult; - // https://github.com/emberjs/ember.js/blob/master/packages/ember-testing/lib/helpers/find.js - function find(selector: string, context?: Object): JQuery; + // https://github.com/emberjs/ember.js/blob/master/packages/ember-testing/lib/helpers/find.js + function find(selector: string, context?: Object): JQuery; - // https://github.com/emberjs/ember.js/blob/master/packages/ember-testing/lib/helpers/find_with_assert.js - function findWithAssert(selector: string, context?: Object): JQuery; + // https://github.com/emberjs/ember.js/blob/master/packages/ember-testing/lib/helpers/find_with_assert.js + function findWithAssert(selector: string, context?: Object): JQuery; - // https://github.com/emberjs/ember.js/blob/master/packages/ember-testing/lib/helpers/key_event.js - function keyEvent(selector: string, type: KeyEventType, keyCode: number): VoidWaitResult; + // https://github.com/emberjs/ember.js/blob/master/packages/ember-testing/lib/helpers/key_event.js + function keyEvent(selector: string, type: KeyEventType, keyCode: number): WaitResult; - // https://github.com/emberjs/ember.js/blob/master/packages/ember-testing/lib/helpers/pause_test.js - function pauseTest(): RSVP.Promise<{}>; - function resumeTest(): void; + // https://github.com/emberjs/ember.js/blob/master/packages/ember-testing/lib/helpers/pause_test.js + function pauseTest(): RSVP.Promise<{}, never>; + function resumeTest(): void; - // https://github.com/emberjs/ember.js/blob/master/packages/ember-testing/lib/helpers/trigger_event.js - function triggerEvent(selector: string, context: Object, type: string, options: Object): VoidWaitResult; - function triggerEvent(selector: string, context: Object, type: string): VoidWaitResult; - function triggerEvent(selector: string, type: string, options: Object): VoidWaitResult; - function triggerEvent(selector: string, type: string): VoidWaitResult; + // https://github.com/emberjs/ember.js/blob/master/packages/ember-testing/lib/helpers/trigger_event.js + function triggerEvent( + selector: string, + context: Object, + type: string, + options: Object + ): WaitResult; + function triggerEvent(selector: string, context: Object, type: string): WaitResult; + function triggerEvent(selector: string, type: string, options: Object): WaitResult; + function triggerEvent(selector: string, type: string): WaitResult; - // https://github.com/emberjs/ember.js/blob/master/packages/ember-testing/lib/helpers/visit.js - function visit(route: string): VoidWaitResult; + // https://github.com/emberjs/ember.js/blob/master/packages/ember-testing/lib/helpers/visit.js + function visit(route: string): WaitResult; - // https://github.com/emberjs/ember.js/blob/master/packages/ember-testing/lib/helpers/wait.js - function wait(value: T): RSVP.Promise; + // https://github.com/emberjs/ember.js/blob/master/packages/ember-testing/lib/helpers/wait.js + function wait(value: T): WaitResult; } export {}; diff --git a/types/ember/ember-tests.ts b/types/ember/ember-tests.ts index 4119e1d7ec..b5097848ff 100644 --- a/types/ember/ember-tests.ts +++ b/types/ember/ember-tests.ts @@ -1,183 +1,188 @@ +import Ember from 'ember'; + let App: any; -App = Em.Application.create(); +App = Ember.Application.create(); -App.president = Em.Object.create({ - name: 'Barack Obama' +App.president = Ember.Object.create({ + name: 'Barack Obama', }); -App.country = Em.Object.create({ - presidentNameBinding: 'MyApp.president.name' +App.country = Ember.Object.create({ + presidentNameBinding: 'MyApp.president.name', }); App.country.get('presidentName'); -App.president = Em.Object.create({ +App.president = Ember.Object.create({ firstName: 'Barack', lastName: 'Obama', - fullName: function() { + fullName: Ember.computed(function() { return this.get('firstName') + ' ' + this.get('lastName'); - }.property() + }), }); App.president.get('fullName'); -declare class MyPerson extends Em.Object { +declare class MyPerson extends Ember.Object { static createMan(): MyPerson; } -const Person1 = Em.Object.extend({ +const Person1 = Ember.Object.extend({ say: (thing: string) => { alert(thing); - } + }, }); -declare class MyPerson2 extends Em.Object { +declare class MyPerson2 extends Ember.Object { helloWorld(): void; } const tom = Person1.create({ name: 'Tom Dale', helloWorld() { this.say('Hi my name is ' + this.get('name')); - } + }, }); tom.helloWorld(); Person1.reopen({ isPerson: true }); -Person1.create().get('isPerson'); +Person1.create().get('isPerson'); Person1.reopenClass({ createMan: () => { return Person1.create({ isMan: true }); - } + }, }); // ReSharper disable once DuplicatingLocalDeclaration Person1.createMan().get('isMan'); -const person = Person1.create({ +const person = Person1.create({ firstName: 'Yehuda', - lastName: 'Katz' + lastName: 'Katz', }); -person.addObserver('fullName', null, () => { }); +person.addObserver('fullName', null, () => {}); person.set('firstName', 'Brohuda'); -App.todosController = Em.Object.create({ - todos: [ - Em.Object.create({ isDone: false }) - ], - remaining: (function() { +App.todosController = Ember.Object.create({ + todos: [Ember.Object.create({ isDone: false })], + remaining: Ember.computed('todos.@each.isDone', function() { const todos = this.get('todos'); return todos.filterProperty('isDone', false).get('length'); - }).property('todos.@each.isDone') + }), }); const todos = App.todosController.get('todos'); let todo = todos.objectAt(0); todo.set('isDone', true); App.todosController.get('remaining'); -todo = Em.Object.create({ isDone: false }); +todo = Ember.Object.create({ isDone: false }); todos.pushObject(todo); App.todosController.get('remaining'); -App.wife = Em.Object.create({ - householdIncome: 80000 +App.wife = Ember.Object.create({ + householdIncome: 80000, }); -App.husband = Em.Object.create({ - householdIncomeBinding: 'App.wife.householdIncome' +App.husband = Ember.Object.create({ + householdIncomeBinding: 'App.wife.householdIncome', }); App.husband.get('householdIncome'); App.husband.set('householdIncome', 90000); App.wife.get('householdIncome'); -App.user = Em.Object.create({ - fullName: 'Kara Gates' +App.user = Ember.Object.create({ + fullName: 'Kara Gates', }); App.user.set('fullName', 'Krang Gates'); App.userView.set('userName', 'Truckasaurus Gates'); App.user.get('fullName'); -App = Em.Application.create({ - rootElement: '#sidebar' +App = Ember.Application.create({ + rootElement: '#sidebar', }); -App.userController = Em.Object.create({ - content: Em.Object.create({ +App.userController = Ember.Object.create({ + content: Ember.Object.create({ firstName: 'Albert', lastName: 'Hofmann', posts: 25, - hobbies: 'Riding bicycles' - }) + hobbies: 'Riding bicycles', + }), }); -Ember.Helper.helper((params) => { - let cents = params[0]; - return `${cents * 0.01}`; +Ember.Helper.helper(params => { + let cents = params[0]; + return `${cents * 0.01}`; }); Ember.Helper.helper((params, hash) => { - let cents = params[0]; - let currency = hash.currency; - return `${currency}${cents * 0.01}`; + let cents = params[0]; + let currency = hash.currency; + return `${currency}${cents * 0.01}`; }); -Handlebars.registerHelper('highlight', (property: string, options: any) => - new Handlebars.SafeString('' + "some value" + '')); +Handlebars.registerHelper( + 'highlight', + (property: string, options: any) => + new Handlebars.SafeString('' + 'some value' + '') +); const coolView = App.CoolView.create(); -const Person2 = Em.Object.extend({ +const Person2 = Ember.Object.extend({ sayHello() { console.log('Hello from ' + this.get('name')); - } + }, }); -const people = [ +const people = Ember.A([ Person2.create({ name: 'Juan' }), Person2.create({ name: 'Charles' }), - Person2.create({ name: 'Majd' }) -]; + Person2.create({ name: 'Majd' }), +]); people.invoke('sayHello'); -const arr = [Em.Object.create(), Em.Object.create()]; +const arr = Ember.A([Ember.Object.create(), Ember.Object.create()]); arr.setEach('name', 'unknown'); arr.getEach('name'); -const Person3 = Em.Object.extend({ +const Person3 = Ember.Object.extend({ name: null, - isHappy: false + isHappy: false, }); -const people2 = [ +const people2 = Ember.A([ Person3.create({ name: 'Yehuda', isHappy: true }), - Person3.create({ name: 'Majd', isHappy: false }) -]; -people2.every((person: Em.Object) => { + Person3.create({ name: 'Majd', isHappy: false }), +]); +const isHappy = (person: Ember.Object): Boolean => { return !!person.get('isHappy'); -}); -people2.some((person: Em.Object) => { - return !!person.get('isHappy'); -}); +}; +people2.every(isHappy); +people2.any(isHappy); people2.everyProperty('isHappy', true); people2.someProperty('isHappy', true); // Examples taken from http://emberjs.com/api/classes/Em.RSVP.Promise.html -const promise = new Em.RSVP.Promise((resolve: Function, reject: Function) => { - // on success - resolve('ok!'); +const promise = new Ember.RSVP.Promise((resolve: Function, reject: Function) => { + // on success + resolve('ok!'); - // on failure - reject('no-k!'); + // on failure + reject('no-k!'); }); -promise.then((value: any) => { - // on fulfillment -}, (reason: any) => { - // on rejection -}); +promise.then( + (value: any) => { + // on fulfillment + }, + (reason: any) => { + // on rejection + } +); const mix1 = Ember.Mixin.create({ - foo: 1 + foo: 1, }); const mix2 = Ember.Mixin.create({ - bar: 2 + bar: 2, }); -const component1 = Ember.Component.extend( mix1, mix2, { - lyft: Ember.inject.service(), - cars: Ember.computed.readOnly('lyft.cars') +const component1 = Ember.Component.extend(mix1, mix2, { + lyft: Ember.inject.service(), + cars: Ember.computed.readOnly('lyft.cars'), }); diff --git a/types/ember/index.d.ts b/types/ember/index.d.ts index 41f8fe6d45..56b21e7405 100644 --- a/types/ember/index.d.ts +++ b/types/ember/index.d.ts @@ -3,24 +3,28 @@ // Definitions by: Jed Mao // bttf // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -// TypeScript Version: 2.3 +// TypeScript Version: 2.4 /// /// +// Capitalization is intentional: this makes it much easier to re-export RSVP on +// the Ember namespace. +import Rsvp from 'rsvp'; + declare namespace EmberStates { interface Transition { targetName: string; urlMethod: string; intent: any; - params: {}|any; + params: {} | any; pivotHandler: any; resolveIndex: number; handlerInfos: any; - resolvedModels: {}|any; + resolvedModels: {} | any; isActive: boolean; state: any; - queryParams: {}|any; + queryParams: {} | any; queryParamsOnly: boolean; isTransition: boolean; @@ -33,7 +37,7 @@ declare namespace EmberStates { Transition object can be externally `abort`ed, while the promise cannot. */ - promise: Ember.RSVP.Promise; + promise: Rsvp.Promise; /** Custom state can be stored on a Transition's `data` object. @@ -57,7 +61,7 @@ declare namespace EmberStates { @arg {String} label optional string for labeling the promise. Useful for tooling. @return {Promise} */ - then(onFulfilled: Function, onRejected?: Function, label?: string): Ember.RSVP.Promise; + then(onFulfilled: Function, onRejected?: Function, label?: string): Rsvp.Promise; /** Forwards to the internal `promise` property which you can @@ -70,7 +74,7 @@ declare namespace EmberStates { Useful for tooling. @return {Promise} */ - catch(onRejection: Function, label?: string): Ember.RSVP.Promise; + catch(onRejection: Function, label?: string): Rsvp.Promise; /** Forwards to the internal `promise` property which you can @@ -83,7 +87,7 @@ declare namespace EmberStates { Useful for tooling. @return {Promise} */ - finally(callback: Function, label?: string): Ember.RSVP.Promise; + finally(callback: Function, label?: string): Rsvp.Promise; /** Aborts the Transition. Note you can also implicitly abort a transition @@ -150,7 +154,7 @@ declare namespace EmberStates { @return {Promise} a promise that fulfills with the same value that the final redirecting transition fulfills with */ - followRedirects(): Ember.RSVP.Promise; + followRedirects(): Rsvp.Promise; } } @@ -165,7 +169,7 @@ declare namespace EmberTesting { exception(error: string): void; } - class QUnitAdapter extends Adapter { } + class QUnitAdapter extends Adapter {} } } @@ -202,16 +206,26 @@ interface Array { clear(): any[]; compact(): any[]; contains(obj: any): boolean; - enumerableContentDidChange(start: number, removing: Ember.Enumerable | number, adding: Ember.Enumerable | number): any; - enumerableContentDidChange(removing: Ember.Enumerable | number, adding: Ember.Enumerable | number): any; - enumerableContentWillChange(removing: Ember.Enumerable | number, adding: Ember.Enumerable | number): Ember.Enumerable; - every(callback: Function, target?: any): boolean; + enumerableContentDidChange( + start: number, + removing: Ember.Enumerable | number, + adding: Ember.Enumerable | number + ): any; + enumerableContentDidChange( + removing: Ember.Enumerable | number, + adding: Ember.Enumerable | number + ): any; + enumerableContentWillChange( + removing: Ember.Enumerable | number, + adding: Ember.Enumerable | number + ): Ember.Enumerable; + every(callback: ItemIndexEnumerableCallback, target?: any): boolean; everyBy(key: string, value?: string): boolean; everyProperty(key: string, value?: any): boolean; filter(callback: Function, target?: any): any[]; filterBy(key: string, value?: string): any[]; - /** + /** Returns the first item in the array for which the callback returns true. This method works similar to the `filter()` method defined in JavaScript 1.6 except that it will stop working on the array once a match is found. @@ -315,7 +329,10 @@ interface ApplicationCreateArguments { LOG_TRANSITIONS_INTERNAL?: boolean; } -type ApplicationInitializerFunction = (container: Ember.Container, application: Ember.Application) => void; +type ApplicationInitializerFunction = ( + container: Ember.Container, + application: Ember.Application +) => void; interface ApplicationInitializerArguments { name?: string; @@ -339,15 +356,23 @@ interface CoreObjectArguments { } interface EnumerableConfigurationOptions { - willChange?: boolean ; - didChange?: boolean ; + willChange?: boolean; + didChange?: boolean; } -type ItemIndexEnumerableCallbackTarget = (callback: ItemIndexEnumerableCallback, target?: any) => any[]; +type ItemIndexEnumerableCallbackTarget = ( + callback: ItemIndexEnumerableCallback, + target?: any +) => any[]; type ItemIndexEnumerableCallback = (item: any, index: number, enumerable: Ember.Enumerable) => void; -type ReduceCallback = (previousValue: any, item: any, index: number, enumerable: Ember.Enumerable) => void; +type ReduceCallback = ( + previousValue: any, + item: any, + index: number, + enumerable: Ember.Enumerable +) => void; interface TransitionsHash { contexts: any[]; @@ -374,7 +399,12 @@ interface RenderOptions { view?: string; } -type ModifyObserver = (obj: any, path: string | null, target: Function | any, method?: Function | string) => void; +type ModifyObserver = ( + obj: any, + path: string | null, + target: Function | any, + method?: Function | string +) => void; declare namespace Ember { /** @@ -512,24 +542,31 @@ declare namespace Ember { class Array implements Enumerable { addArrayObserver(target: any, opts?: EnumerableConfigurationOptions): any[]; addEnumerableObserver(target: any, opts: EnumerableConfigurationOptions): Enumerable; - any(callback: Function, target?: any): boolean; + any(callback: ItemIndexEnumerableCallback, target?: any): boolean; anyBy(key: string, value?: string): boolean; arrayContentDidChange(startIdx: number, removeAmt: number, addAmt: number): any[]; arrayContentWillChange(startIdx: number, removeAmt: number, addAmt: number): any[]; someProperty(key: string, value?: string): boolean; compact(): any[]; contains(obj: any): boolean; - enumerableContentDidChange(start: number, removing: Enumerable | number, adding: Enumerable | number): any; + enumerableContentDidChange( + start: number, + removing: Enumerable | number, + adding: Enumerable | number + ): any; enumerableContentDidChange(removing: Enumerable | number, adding: Enumerable | number): any; - enumerableContentWillChange(removing: Enumerable | number, adding: Enumerable | number): Enumerable; - every(callback: Function, target?: any): boolean; + enumerableContentWillChange( + removing: Enumerable | number, + adding: Enumerable | number + ): Enumerable; + every(callback: ItemIndexEnumerableCallback, target?: any): boolean; everyBy(key: string, value?: string): boolean; everyProperty(key: string, value?: string): boolean; - filter(callback: Function, target: any): any[]; + filter(callback: ItemIndexEnumerableCallback, target: any): any[]; filterBy(key: string, value?: string): any[]; - find(callback: Function, target?: any): any; + find(callback: ItemIndexEnumerableCallback, target?: any): any; findBy(key: string, value?: string): any; - forEach(callback: Function, target?: any): any; + forEach(callback: ItemIndexEnumerableCallback, target?: any): any; getEach(key: string): any[]; indexOf(object: any, startAt: number): number; invoke(methodName: string, ...args: any[]): any[]; @@ -546,7 +583,7 @@ declare namespace Ember { removeEnumerableObserver(target: any, opts: EnumerableConfigurationOptions): Enumerable; setEach(key: string, value?: any): any; slice(beginIndex?: number, endIndex?: number): any[]; - some(callback: Function, target?: any): boolean; + some(callback: ItemIndexEnumerableCallback, target?: any): boolean; toArray(): any[]; uniq(): Enumerable; without(value: any): Enumerable; @@ -580,7 +617,7 @@ declare namespace Ember { static isMethod: boolean; addArrayObserver(target: any, opts?: EnumerableConfigurationOptions): any[]; addEnumerableObserver(target: any, opts: EnumerableConfigurationOptions): Enumerable; - any(callback: Function, target?: any): boolean; + any(callback: ItemIndexEnumerableCallback, target?: any): boolean; anyBy(key: string, value?: string): boolean; arrayContentDidChange(startIdx: number, removeAmt: number, addAmt: number): any[]; arrayContentWillChange(startIdx: number, removeAmt: number, addAmt: number): any[]; @@ -588,17 +625,24 @@ declare namespace Ember { clear(): any[]; compact(): any[]; contains(obj: any): boolean; - enumerableContentDidChange(start: number, removing: Enumerable | number, adding: Enumerable | number): any; + enumerableContentDidChange( + start: number, + removing: Enumerable | number, + adding: Enumerable | number + ): any; enumerableContentDidChange(removing: Enumerable | number, adding: Enumerable | number): any; - enumerableContentWillChange(removing: Enumerable | number, adding: Enumerable | number): Enumerable; - every(callback: Function, target?: any): boolean; + enumerableContentWillChange( + removing: Enumerable | number, + adding: Enumerable | number + ): Enumerable; + every(callback: ItemIndexEnumerableCallback, target?: any): boolean; everyBy(key: string, value?: string): boolean; everyProperty(key: string, value?: string): boolean; - filter(callback: Function, target: any): any[]; + filter(callback: ItemIndexEnumerableCallback, target: any): any[]; filterBy(key: string, value?: string): any[]; - find(callback: Function, target: any): any; + find(callback: ItemIndexEnumerableCallback, $target: any): any; findBy(key: string, value?: string): any; - forEach(callback: Function, target?: any): any; + forEach(callback: ItemIndexEnumerableCallback, target?: any): any; getEach(key: string): any[]; indexOf(object: any, startAt: number): number; insertAt(idx: number, object: any): any[]; @@ -626,7 +670,7 @@ declare namespace Ember { setObjects(objects: any[]): any[]; shiftObject(): any; slice(beginIndex?: number, endIndex?: number): any[]; - some(callback: Function, target?: any): boolean; + some(callback: ItemIndexEnumerableCallback, target?: any): boolean; toArray(): any[]; uniq(): Enumerable; unshiftObject(object: any): any; @@ -877,7 +921,7 @@ declare namespace Ember { @param {Object} [args] - Object containing values to use within the new class Non-static method because Ember classes aren't currently 'real' TypeScript classes. **/ - extend(mixin1 ?: Mixin, mixin2 ?: Mixin, args ?: CoreObjectArguments): T; + extend(mixin1?: Mixin, mixin2?: Mixin, args?: CoreObjectArguments): T; /** Equivalent to doing extend(arguments).create(). If possible use the normal create method instead. @@ -958,7 +1002,7 @@ declare namespace Ember { The default implementation handles simple properties. You generally won't need to create or subclass this directly. **/ - class Descriptor { } + class Descriptor {} namespace ENV { const EXTEND_PROTOTYPES: typeof Ember.EXTEND_PROTOTYPES; const LOG_BINDINGS: boolean; @@ -1002,22 +1046,29 @@ declare namespace Ember { **/ class Enumerable { addEnumerableObserver(target: any, opts: EnumerableConfigurationOptions): Enumerable; - any(callback: Function, target?: any): boolean; + any(callback: ItemIndexEnumerableCallback, target?: any): boolean; anyBy(key: string, value?: string): boolean; someProperty(key: string, value?: string): boolean; compact(): any[]; contains(obj: any): boolean; - enumerableContentDidChange(start: number, removing: Enumerable | number, adding: Enumerable | number): any; + enumerableContentDidChange( + start: number, + removing: Enumerable | number, + adding: Enumerable | number + ): any; enumerableContentDidChange(removing: Enumerable | number, adding: Enumerable | number): any; - enumerableContentWillChange(removing: Enumerable | number, adding: Enumerable | number): Enumerable; - every(callback: Function, target?: any): boolean; + enumerableContentWillChange( + removing: Enumerable | number, + adding: Enumerable | number + ): Enumerable; + every(callback: ItemIndexEnumerableCallback, target?: any): boolean; everyBy(key: string, value?: string): boolean; everyProperty(key: string, value?: string): boolean; - filter(callback: Function, target: any): any[]; + filter(callback: ItemIndexEnumerableCallback, target: any): any[]; filterBy(key: string, value?: string): any[]; - find(callback: Function, target: any): any; + find(callback: ItemIndexEnumerableCallback, target: any): any; findBy(key: string, value?: string): any; - forEach(callback: Function, target?: any): any; + forEach(callback: ItemIndexEnumerableCallback, target?: any): any; getEach(key: string): any[]; invoke(methodName: string, ...args: any[]): any[]; map: ItemIndexEnumerableCallbackTarget; @@ -1028,7 +1079,7 @@ declare namespace Ember { rejectBy(key: string, value?: string): any[]; removeEnumerableObserver(target: any, opts: EnumerableConfigurationOptions): Enumerable; setEach(key: string, value?: any): any; - some(callback: Function, target?: any): boolean; + some(callback: ItemIndexEnumerableCallback, target?: any): boolean; toArray(): any[]; uniq(): Enumerable; without(value: any): Enumerable; @@ -1085,8 +1136,8 @@ declare namespace Ember { function compile(string: string): Function; function compile(environment: any, options?: any, context?: any, asObject?: any): any; function precompile(string: string, options: any): void; - class Compiler { } - class JavaScriptCompiler { } + class Compiler {} + class JavaScriptCompiler {} function registerPartial(name: string, str: any): void; function K(): any; function createFrame(objec: any): any; @@ -1135,13 +1186,13 @@ declare namespace Ember { } const IS_BINDING: RegExp; const inject: { - controller(name?: string): Controller; - service(name?: string): Service; + controller(name?: string): Controller; + service(name?: string): Service; }; class Helper extends Object { - static helper( h: (params: any, hash?: any) => any): Helper; - compute(params: any[], hash: any): any; - recompute(params: any[], hash: any): any; + static helper(h: (params: any, hash?: any) => any): Helper; + compute(params: any[], hash: any): any; + recompute(params: any[], hash: any): any; } class Instrumentation { getProperties(obj: any, list: any[]): {}; @@ -1195,7 +1246,7 @@ declare namespace Ember { class MutableArray implements Array, MutableEnumberable { addArrayObserver(target: any, opts?: EnumerableConfigurationOptions): any[]; addEnumerableObserver(target: any, opts: EnumerableConfigurationOptions): Enumerable; - any(callback: Function, target?: any): boolean; + any(callback: ItemIndexEnumerableCallback, target?: any): boolean; anyBy(key: string, value?: string): boolean; arrayContentDidChange(startIdx: number, removeAmt: number, addAmt: number): any[]; arrayContentWillChange(startIdx: number, removeAmt: number, addAmt: number): any[]; @@ -1203,17 +1254,24 @@ declare namespace Ember { clear(): any[]; compact(): any[]; contains(obj: any): boolean; - enumerableContentDidChange(start: number, removing: Enumerable | number, adding: Enumerable | number): any; + enumerableContentDidChange( + start: number, + removing: Enumerable | number, + adding: Enumerable | number + ): any; enumerableContentDidChange(removing: Enumerable | number, adding: Enumerable | number): any; - enumerableContentWillChange(removing: Enumerable | number, adding: Enumerable | number): Enumerable; - every(callback: Function, target?: any): boolean; + enumerableContentWillChange( + removing: Enumerable | number, + adding: Enumerable | number + ): Enumerable; + every(callback: ItemIndexEnumerableCallback, target?: any): boolean; everyBy(key: string, value?: string): boolean; everyProperty(key: string, value?: string): boolean; - filter(callback: Function, target: any): any[]; + filter(callback: ItemIndexEnumerableCallback, target: any): any[]; filterBy(key: string, value?: string): any[]; - find(callback: Function, target: any): any; + find(callback: ItemIndexEnumerableCallback, target: any): any; findBy(key: string, value?: string): any; - forEach(callback: Function, target?: any): any; + forEach(callback: ItemIndexEnumerableCallback, target?: any): any; getEach(key: string): any[]; indexOf(object: any, startAt: number): number; insertAt(idx: number, object: any): any[]; @@ -1239,7 +1297,7 @@ declare namespace Ember { setObjects(objects: any[]): any[]; shiftObject(): any; slice(beginIndex?: number, endIndex?: number): any[]; - some(callback: Function, target?: any): boolean; + some(callback: ItemIndexEnumerableCallback, target?: any): boolean; toArray(): any[]; uniq(): Enumerable; unshiftObject(object: any): any; @@ -1261,22 +1319,29 @@ declare namespace Ember { addEnumerableObserver(target: any, opts: EnumerableConfigurationOptions): Enumerable; addObject(object: any): any; addObjects(objects: Enumerable): MutableEnumberable; - any(callback: Function, target?: any): boolean; + any(callback: ItemIndexEnumerableCallback, target?: any): boolean; anyBy(key: string, value?: string): boolean; someProperty(key: string, value?: string): boolean; compact(): any[]; contains(obj: any): boolean; - enumerableContentDidChange(start: number, removing: Enumerable | number, adding: Enumerable | number): any; + enumerableContentDidChange( + start: number, + removing: Enumerable | number, + adding: Enumerable | number + ): any; enumerableContentDidChange(removing: Enumerable | number, adding: Enumerable | number): any; - enumerableContentWillChange(removing: Enumerable | number, adding: Enumerable | number): Enumerable; - every(callback: Function, target?: any): boolean; + enumerableContentWillChange( + removing: Enumerable | number, + adding: Enumerable | number + ): Enumerable; + every(callback: ItemIndexEnumerableCallback, target?: any): boolean; everyBy(key: string, value?: string): boolean; everyProperty(key: string, value?: string): boolean; - filter(callback: Function, target: any): any[]; + filter(callback: ItemIndexEnumerableCallback, target: any): any[]; filterBy(key: string, value?: string): any[]; - find(callback: Function, target: any): any; + find(callback: ItemIndexEnumerableCallback, target: any): any; findBy(key: string, value?: string): any; - forEach(callback: Function, target?: any): any; + forEach(callback: ItemIndexEnumerableCallback, target?: any): any; getEach(key: string): any[]; invoke(methodName: string, ...args: any[]): any[]; map: ItemIndexEnumerableCallbackTarget; @@ -1289,7 +1354,7 @@ declare namespace Ember { removeObject(object: any): any; removeObjects(objects: Enumerable): MutableEnumberable; setEach(key: string, value?: any): any; - some(callback: Function, target?: any): boolean; + some(callback: ItemIndexEnumerableCallback, target?: any): boolean; toArray(): any[]; uniq(): Enumerable; without(value: any): Enumerable; @@ -1320,7 +1385,7 @@ declare namespace Ember { static activate(): void; addArrayObserver(target: any, opts?: EnumerableConfigurationOptions): any[]; addEnumerableObserver(target: any, opts: EnumerableConfigurationOptions): Enumerable; - any(callback: Function, target?: any): boolean; + any(callback: ItemIndexEnumerableCallback, target?: any): boolean; anyBy(key: string, value?: string): boolean; arrayContentDidChange(startIdx: number, removeAmt: number, addAmt: number): any[]; arrayContentWillChange(startIdx: number, removeAmt: number, addAmt: number): any[]; @@ -1328,17 +1393,24 @@ declare namespace Ember { clear(): any[]; compact(): any[]; contains(obj: any): boolean; - enumerableContentDidChange(start: number, removing: Enumerable | number, adding: Enumerable | number): any; + enumerableContentDidChange( + start: number, + removing: Enumerable | number, + adding: Enumerable | number + ): any; enumerableContentDidChange(removing: Enumerable | number, adding: Enumerable | number): any; - enumerableContentWillChange(removing: Enumerable | number, adding: Enumerable | number): Enumerable; - every(callback: Function, target?: any): boolean; + enumerableContentWillChange( + removing: Enumerable | number, + adding: Enumerable | number + ): Enumerable; + every(callback: ItemIndexEnumerableCallback, target?: any): boolean; everyBy(key: string, value?: string): boolean; everyProperty(key: string, value?: any): boolean; - filter(callback: Function, target: any): any[]; + filter(callback: ItemIndexEnumerableCallback, target: any): any[]; filterBy(key: string, value?: string): any[]; - find(callback: Function, target: any): any; + find(callback: ItemIndexEnumerableCallback, target: any): any; findBy(key: string, value?: string): any; - forEach(callback: Function, target?: any): any; + forEach(callback: ItemIndexEnumerableCallback, target?: any): any; getEach(key: string): any[]; indexOf(object: any, startAt: number): number; insertAt(idx: number, object: any): any[]; @@ -1364,7 +1436,7 @@ declare namespace Ember { setObjects(objects: any[]): any[]; shiftObject(): any; slice(beginIndex?: number, endIndex?: number): any[]; - some(callback: Function, target?: any): boolean; + some(callback: ItemIndexEnumerableCallback, target?: any): boolean; toArray(): any[]; uniq(): Enumerable; unshiftObject(object: any): any; @@ -1512,99 +1584,7 @@ declare namespace Ember { } // FYI - RSVP source comes from https://github.com/tildeio/rsvp.js/blob/master/lib/rsvp/promise.js - namespace RSVP { - type PromiseResolve = (value?: T) => void; - type PromiseReject = (reason?: U) => void; - type PromiseResolverFunction = (resolve: PromiseResolve, reject: PromiseReject) => void; - - interface Thenable { - then(onFulfilled?: (value: T) => V | Thenable, onRejected?: (error: any) => X | Thenable): Thenable; - then(onFulfilled?: (value: T) => V | Thenable, onRejected?: (error: any) => void): Thenable; - } - - class Promise implements Thenable { - /** - Promise objects represent the eventual result of an asynchronous operation. The - primary way of interacting with a promise is through its `then` method, which - registers callbacks to receive either a promise's eventual value or the reason - why the promise cannot be fulfilled. - @class RSVP.Promise - @param {function} resolver - @param {String} label optional string for labeling the promise. - Useful for tooling. - @constructor - */ - constructor(resolver: PromiseResolverFunction, label?: string); - - /** - The primary way of interacting with a promise is through its `then` method, - which registers callbacks to receive either a promise's eventual value or the - reason why the promise cannot be fulfilled. - @method then - @param {Function} onFulfilled - @param {Function} onRejected - @param {String} label optional string for labeling the promise. - Useful for tooling. - @return {Promise} - */ - then(onFulfilled?: (value: T) => V | Thenable, onRejected?: (error: any) => X | Thenable): Promise; - // tslint:disable-next-line - then(onFulfilled?: (value: T) => V | Thenable, onRejected?: (error: any) => void): Promise; - /** - `catch` is simply sugar for `then(undefined, onRejection)` which makes it the same - as the catch block of a try/catch statement. - - @method catch - @param {Function} onRejection - @param {String} label optional string for labeling the promise. - Useful for tooling. - @return {Promise} - */ - catch(onRejection: (a: any) => U, label?: string): Promise; - - /** - `finally` will be invoked regardless of the promise's fate just as native - try/catch/finally behaves - - @method finally - @param {Function} callback - @param {String} label optional string for labeling the promise. - Useful for tooling. - @return {Promise} - */ - finally(callback: (a: T) => V, label?: string): Promise; - - static all(promises: GlobalArray<(Q | Thenable)>): Promise; - static race(promises: GlobalArray>): 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?: Q | Thenable): 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: Q | Thenable, label?: string): Promise; - - /** - `RSVP.Promise.reject` returns a promise rejected with the passed `reason`. - */ - static reject(reason?: any): Promise; - } - - function all(promises: GlobalArray>): Promise; - } + const RSVP: typeof Rsvp; /** The `Ember.Route` class is used to define individual routes. Refer to @@ -1641,7 +1621,7 @@ declare namespace Ember { resolves. Otherwise, non-promise return values are not utilized in any way. */ - afterModel(resolvedModel: any, transition: EmberStates.Transition): RSVP.Promise; + afterModel(resolvedModel: any, transition: EmberStates.Transition): Rsvp.Promise; /** This hook is the first of the route entry validation hooks @@ -1670,7 +1650,7 @@ declare namespace Ember { resolves. Otherwise, non-promise return values are not utilized in any way. */ - beforeModel(transition: EmberStates.Transition): RSVP.Promise; + beforeModel(transition: EmberStates.Transition): Rsvp.Promise; /** The controller associated with this route. @@ -1735,7 +1715,7 @@ declare namespace Ember { @method disconnectOutlet @param {Object|String} options the options hash or outlet name */ - disconnectOutlet(options: DisconnectOutletOptions|string): void; + disconnectOutlet(options: DisconnectOutletOptions | string): void; /** @method findModel @@ -1783,7 +1763,7 @@ declare namespace Ember { the promise resolves, and the resolved value of the promise will be used as the model for this route. */ - model(params: {}, transition: EmberStates.Transition): any|RSVP.Promise; + model(params: {}, transition: EmberStates.Transition): any | Rsvp.Promise; /** Returns the model of a parent (or any ancestor) route @@ -2262,7 +2242,7 @@ declare namespace Ember { class Adapter extends Ember.Object { constructor(); } - class Promise extends Ember.RSVP.Promise { + class Promise extends Rsvp.Promise { constructor(); } function oninjectHelpers(callback: Function): void; @@ -2349,7 +2329,13 @@ declare namespace Ember { actionContext: any; } const ViewUtils: {}; // TODO: define interface - function addListener(obj: any, eventName: string, target: Function | any, method: Function | string, once?: boolean): void; + function addListener( + obj: any, + eventName: string, + target: Function | any, + method: Function | string, + once?: boolean + ): void; const addObserver: ModifyObserver; /** Ember.alias is deprecated. Please use Ember.aliasMethod or Ember.computed.alias instead. @@ -2373,11 +2359,16 @@ declare namespace Ember { defaultTo(defaultPath: string): ComputedProperty; empty(dependentKey: string): ComputedProperty; equal(dependentKey: string, value: any): ComputedProperty; + filter( + dependentKey: string, + callback: (item: any, index?: number, array?: any[]) => boolean + ): ComputedProperty; + filterBy(dependentKey: string, propertyKey: string, value: any): ComputedProperty; gt(dependentKey: string, value: number): ComputedProperty; gte(dependentKey: string, value: number): ComputedProperty; lt(dependentKey: string, value: number): ComputedProperty; lte(dependentKey: string, value: number): ComputedProperty; - map(...args: string[]): ComputedProperty; + map(dependentKey: string, callback: (item: any, index: number) => T): ComputedProperty; match(dependentKey: string, regexp: RegExp): ComputedProperty; none(dependentKey: string): ComputedProperty; not(dependentKey: string): ComputedProperty; @@ -2387,7 +2378,11 @@ declare namespace Ember { readOnly(dependentString: string): ComputedProperty; }; // ReSharper restore DuplicatingLocalDeclaration - function controllerFor(container: Container, controllerName: string, lookupOptions?: {}): Controller; + function controllerFor( + container: Container, + controllerName: string, + lookupOptions?: {} + ): Controller; function copy(obj: any, deep: boolean): any; /** Creates an instance of the CoreObject class. @@ -2406,9 +2401,15 @@ declare namespace Ember { const empty: typeof deprecateFunc; function endPropertyChanges(): void; function finishChains(obj: any): void; - function generateController(container: Container, controllerName: string, context: any): Controller; + function generateController( + container: Container, + controllerName: string, + context: any + ): Controller; function generateGuid(obj: any, prefix?: string): string; function get(obj: any, keyName: string): any; + function getProperties(obj: any, ...args: string[]): object; + function getProperties(obj: any, keys: string[]): object; /** getPath is deprecated since get now supports paths. **/ @@ -2460,13 +2461,20 @@ declare namespace Ember { function propertyIsEnumerable(prop: string): boolean; function propertyWillChange(obj: any, keyName: string): void; function removeChainWatcher(obj: any, keyName: string, node: any): void; - function removeListener(obj: any, eventName: string, target: Function | any, method: Function | string): void; + function removeListener( + obj: any, + eventName: string, + target: Function | any, + method: Function | string + ): void; function removeObserver(obj: any, path: string, target: any, method: Function): any; function required(): Descriptor; function rewatch(obj: any): void; + + type RunMethod = (...args: any[]) => T; const run: { - (method: Function): void; - (target: any, method: Function): void; + (method: RunMethod | string): T; + (target: any, method: RunMethod | string): T; begin(): void; cancel(timer: any): void; debounce(target: any, method: Function | string, ...args: any[]): void; @@ -2493,7 +2501,12 @@ declare namespace Ember { function subscribe(pattern: string, object: any): void; function toLocaleString(): string; function toString(): string; - function tryCatchFinally(tryable: Function, catchable: Function, finalizer: Function, binding?: any): any; + function tryCatchFinally( + tryable: Function, + catchable: Function, + finalizer: Function, + binding?: any + ): any; function tryInvoke(obj: any, methodName: string, args?: any[]): any; function trySet(obj: any, path: string, value: any): void; /** @@ -2522,12 +2535,4 @@ declare namespace Ember { function assign(original: any, ...sources: any[]): any; } -import Em = Ember; - -/** - * External ambient module - to allow "import Ember from 'ember';" to work correctly - */ - -declare module "ember" { - export default Ember; -} +export default Ember; diff --git a/types/engine.io-client/engine.io-client-tests.ts b/types/engine.io-client/engine.io-client-tests.ts new file mode 100644 index 0000000000..4a73136cef --- /dev/null +++ b/types/engine.io-client/engine.io-client-tests.ts @@ -0,0 +1,77 @@ +import engine = require('engine.io'); +import client = require('engine.io-client'); + +let server: engine.Server; +let socket: client.Socket; +let options: client.SocketOptions = {}; + +options.agent = false; +options.upgrade = true; +options.forceJSONP = false; +options.jsonp = false; +options.forceBase64 = false; +options.enablesXDR = false; +options.timestampRequests = true; +options.timestampParam = 't'; +options.policyPort = 843; +options.path = '/engine.io'; +options.transports = ['websocket']; +options.transportOptions = {}; +options.rememberUpgrade = true; +options.pfx = ''; +options.key = ''; +options.passphrase = ''; +options.cert = ''; +options.ca = ''; +options.ciphers = undefined; +options.rejectUnauthorized = true; +options.perMessageDeflate = false; +options.extraHeaders = {foo: 'bar'}; +options.onlyBinaryUpgrades = true; +options.forceNode = false; +options.localAddress = 'localhost'; + +socket = client("ws://localhost:32767", options); +socket.on('close', (mes, detail) => { + console.log('CLOSE', mes, detail); +}); +socket.on('error', (err) => { + console.log('ERROR', err); +}); + +server = engine.listen(8000, {pingTimeout: 100, pingInterval: 30}); +server.on("connection", socket => { + socket.send('hello'); +}); + +socket = client("ws://localhost:8000"); +socket.on("message", (data) => { + console.log('MESSAGE', data); +}); +socket.on('close', (mes, detail) => { + console.log('CLOSE', mes, detail); +}); +socket.on('ping', () => { + console.log('client ping callback'); +}); +socket.on('pong', () => { + console.log('client pong callback'); +}); +socket.on('flush', () => { + console.log('client flush callback'); +}); +socket.on('drain', () => { + console.log('client drain callback'); +}); +socket.on("open", () => { + socket.send("hi", {compress: false}, () => { + console.log('client send callback'); + setTimeout(() => { + socket.close(); + setTimeout(() => { + server.close(); + server.httpServer!.close(); + }, 200); + }, 200); + }); +}); diff --git a/types/engine.io-client/index.d.ts b/types/engine.io-client/index.d.ts new file mode 100644 index 0000000000..0407c86fed --- /dev/null +++ b/types/engine.io-client/index.d.ts @@ -0,0 +1,184 @@ +// Type definitions for engine.io-client 3.1 +// Project: https://github.com/socketio/engine.io-client +// Definitions by: KentarouTakeda +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +/// + +import http = require('http'); + +declare namespace client { + type Transport = 'polling'|'websocket'; + type Message = string|ArrayBuffer|ArrayBufferView|Blob; + interface MessageOptions { + compress?: boolean; + } + interface SocketOptions { + /** + * http.Agent to use, defaults to false (NodeJS only) + */ + agent?: http.Agent|false; + /** + * defaults to true, whether the client should try to upgrade the transport from long-polling to something better. + */ + upgrade?: boolean; + /** + * forces JSONP for polling transport. + */ + forceJSONP?: boolean; + /** + * determines whether to use JSONP when necessary for polling. + * If disabled (by settings to false) an error will be emitted (saying "No transports available") + * if no other transports are available. If another transport is available + * for opening a connection (e.g. WebSocket) that transport will be used instead. + */ + jsonp?: boolean; + /** + * forces base 64 encoding for polling transport even when XHR2 responseType is available and WebSocket even if the used standard supports binary. + */ + forceBase64?: boolean; + /** + * enables XDomainRequest for IE8 to avoid loading bar flashing with click sound. default to false because XDomainRequest has a flaw of not sending cookie. + */ + enablesXDR?: boolean; + /** + * whether to add the timestamp with each transport request. Note: polling requests are always stamped unless this option is explicitly set to false (false) + */ + timestampRequests?: boolean; + /** + * timestamp parameter (t) + */ + timestampParam?: string; + /** + * port the policy server listens on (843) + */ + policyPort?: number; + /** + * path to connect to, default is /engine.io + */ + path?: string; + /** + * a list of transports to try (in order). Defaults to ['polling', 'websocket']. Engine always attempts to connect directly with the first one, provided the feature detection test for it passes. + */ + transports?: Transport[]; + /** + * hash of options, indexed by transport name, overriding the common options for the given transport + */ + transportOptions?: {[key: string]: SocketOptions}; + /** + * defaults to false. If true and if the previous websocket connection to the server succeeded, + * the connection attempt will bypass the normal upgrade process and will initially try websocket. + * A connection attempt following a transport error will use the normal upgrade process. + * It is recommended you turn this on only when using SSL/TLS connections, + * or if you know that your network does not block websockets. + */ + rememberUpgrade?: boolean; + /** + * Certificate, Private key and CA certificates to use for SSL. Can be used in Node.js client environment to manually specify certificate information. + */ + pfx?: string; + /** + * Private key to use for SSL. Can be used in Node.js client environment to manually specify certificate information. + */ + key?: string; + /** + * A string of passphrase for the private key or pfx. Can be used in Node.js client environment to manually specify certificate information. + */ + passphrase?: string; + /** + * Public x509 certificate to use. Can be used in Node.js client environment to manually specify certificate information. + */ + cert?: string; + /** + * An authority certificate or array of authority certificates to check the remote host against. + * Can be used in Node.js client environment to manually specify certificate information. + */ + ca?: string|string[]; + /** + * A string describing the ciphers to use or exclude. Consult the cipher format list for details on the format. + * Can be used in Node.js client environment to manually specify certificate information. + */ + ciphers?: string; + /** + * If true, the server certificate is verified against the list of supplied CAs. + * An 'error' event is emitted if verification fails. Verification happens at the connection level, + * before the HTTP request is sent. Can be used in Node.js client environment to manually specify certificate information. + */ + rejectUnauthorized?: boolean; + /** + * parameters of the WebSocket permessage-deflate extension (see ws module api docs). Set to false to disable. (true) + */ + perMessageDeflate?: any; + /** + * Headers that will be passed for each request to the server (via xhr-polling and via websockets). + * These values then can be used during handshake or for special proxies. Can only be used in Node.js client environment. + */ + extraHeaders?: {[header: string]: string}; + /** + * whether transport upgrades should be restricted to transports supporting binary data (false) + */ + onlyBinaryUpgrades?: boolean; + /** + * Uses NodeJS implementation for websockets - even if there is a native Browser-Websocket available, + * which is preferred by default over the NodeJS implementation. (This is useful when using hybrid platforms + * like nw.js or electron) (false, NodeJS only) + */ + forceNode?: boolean; + /** + * the local IP address to connect to + */ + localAddress?: string; + } + + interface UpgradeError extends Error { + transport: string; + } + + class Socket { + protocol?: number; + binaryType?: 'arraybuffer'|'blob'; + + /* + * open: Fired upon successful connection. + * flush: Fired upon completing a buffer flush + * drain: Fired after drain event of transport if writeBuffer is empty + * ping: Fired upon flushing a ping packet (ie: actual packet write out) + * pong: Fired upon receiving a pong packet. + */ + on(ev: 'open'|'flush'|'drain'|'ping'|'pong' , cb: () => void): this; + /* + * Fired when data is received from the server. + */ + on(ev: 'message' , cb: (data: string|ArrayBuffer) => void): this; + /* + * Fired upon disconnection. In compliance with the WebSocket API spec, this event may be fired even if the open event does not occur (i.e. due to connection error or close()). + */ + on(ev: 'close' , cb: (mes: string, detail?: Error) => void): this; + /* + * Fired when an error occurs. + */ + on(ev: 'error' , cb: (err: Error) => void): this; + /* + * Fired if an error occurs with a transport we're trying to upgrade to. + */ + on(ev: 'upgradeError' , cb: (err: UpgradeError) => void): this; + /* + * Fired upon upgrade success, after the new transport is set + */ + on(ev: 'upgrade' , cb: (transport: any) => void): this; + + /** + * Sends a message to the server + */ + send(message: Message, opts?: MessageOptions, cb?: () => void): this; + + /** + * Disconnects the client. + */ + close(): this; + } +} + +declare function client(url?: string, opts?: client.SocketOptions): client.Socket; + +export = client; diff --git a/types/engine.io-client/tsconfig.json b/types/engine.io-client/tsconfig.json new file mode 100644 index 0000000000..aacd3365c5 --- /dev/null +++ b/types/engine.io-client/tsconfig.json @@ -0,0 +1,25 @@ +{ + "compilerOptions": { + "module": "commonjs", + "lib": [ + "dom", + "es6" + ], + "noImplicitAny": true, + "noImplicitThis": true, + "strictNullChecks": true, + "noImplicitReturns": true, + "strict": true, + "baseUrl": "../", + "typeRoots": [ + "../" + ], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true + }, + "files": [ + "index.d.ts", + "engine.io-client-tests.ts" + ] +} diff --git a/types/engine.io-client/tslint.json b/types/engine.io-client/tslint.json new file mode 100644 index 0000000000..3db14f85ea --- /dev/null +++ b/types/engine.io-client/tslint.json @@ -0,0 +1 @@ +{ "extends": "dtslint/dt.json" } diff --git a/types/engine.io/engine.io-tests.ts b/types/engine.io/engine.io-tests.ts new file mode 100644 index 0000000000..4199393b5d --- /dev/null +++ b/types/engine.io/engine.io-tests.ts @@ -0,0 +1,168 @@ +import engine = require('engine.io'); +import http = require('http'); + +let serverOptions: engine.ServerOptions; +let server: engine.Server; +let httpServer: http.Server; +let attachOptions: engine.AttachOptions; +let serverAttachOptions: engine.ServerAttachOptions; + +serverOptions = {}; +serverOptions = { + pingTimeout: 60000, + pingInterval: 25000, + upgradeTimeout: 10000, + maxHttpBufferSize: 10E7, + transports: ['polling', 'websocket'], + allowUpgrades: true, + perMessageDeflate: true, + httpCompression: true, + cookie: 'io', + cookiePath: '/', + wsEngine: 'ws', + initialPacket: new Buffer([0, 1, 2, 3, 4, 5]), + allowRequest: (req, cb) => { + console.log(req.url); + cb(null, true); + } +}; +attachOptions = { + path: '/engine.io' , + destroyUpgrade: true, + destroyUpgradeTimeout: 1000, +}; +attachOptions.handlePreflightRequest = true; +attachOptions.handlePreflightRequest = false; +attachOptions.handlePreflightRequest = (server, req, res) => { + console.log(server.clientsCount); + console.log(req.httpVersion); + console.log(res.finished); +}; +serverAttachOptions = Object.assign({}, serverOptions, attachOptions); + +console.log(engine.protocol); + +httpServer = http.createServer(); +httpServer.listen(8000); + +server = engine(httpServer); +server.close(); + +server = engine(httpServer, serverOptions); +server.close(); + +httpServer.close(); + +server = engine.listen(8000); +server.httpServer!.close(); +server.close(); + +server = engine.listen(8000, serverOptions); +server.httpServer!.close(); +server.close(); + +server = engine.listen(8000, serverOptions, () => {}); +server.httpServer!.close(); +server.close(); + +httpServer = http.createServer(); +httpServer.listen(8000); +server = engine.attach(httpServer); +server.close(); +httpServer.close(); + +httpServer = http.createServer(); +httpServer.listen(8000); +server = engine.attach(httpServer, serverOptions); +server.close(); +httpServer.close(); + +httpServer = http.createServer(); +httpServer.listen(8000); +server = engine.attach(httpServer, attachOptions); +server.close(); +httpServer.close(); + +httpServer = http.createServer(); +httpServer.listen(8000); +server = engine.attach(httpServer, serverAttachOptions); +server.close(); +httpServer.close(); + +server = new engine.Server(); +server.close(); + +server = new engine.Server(); +server.close(); + +httpServer = http.createServer(); +httpServer.listen(8000); +server = new engine.Server(serverOptions); +server.attach(httpServer); +server.attach(httpServer, attachOptions); +server.close(); +httpServer.close(); + +server.generateId = (req) => Math.floor(Math.random() * 100000).toString(); + +httpServer = http.createServer(); +httpServer.listen(8000); +server = new engine.Server(serverOptions); +httpServer.on('upgrade', (req, socket, head) => { + server.handleUpgrade(req, socket, head); +}); +httpServer.on('request', (req, res) => { + server.handleRequest(req, res); +}); + +console.log(server.clients); +console.log(server.clientsCount); + +server.on('connection', (socket) => { + console.log(socket.id); + console.log(socket.server.getMaxListeners()); + console.log(socket.request.headers); + console.log(socket.upgraded); + console.log(socket.readyState); + console.log(server.clients[socket.id].id); + + socket.on('close', (reason, description) => { + console.log('CLOSE', reason, description && description.message); + }); + socket.on('message', (message) => { + console.log('MESSAGE', message); + }); + socket.on('error', err => { + console.log('ERROR', err); + }); + socket.on('flush', buffer => { + console.log('FLUSH', buffer); + }); + socket.on('drain', () => { + console.log('DRAIN'); + }); + socket.on('packet', packet => { + console.log('PACKET', packet.type, packet.data); + }); + socket.on('packetCreate', packet => { + console.log('PACKETCREATE', packet.type, packet.data); + }); + + socket.send('utf 8 string', {compress: false}, () => { + console.log("SENDCALLBACK"); + }); + socket.send(new Buffer([0, 1, 2, 3, 4, 5])); // binary data +}); + +server.once('flush', (socket, buffer) => { + console.log(socket.id); + console.log(buffer[0].type); + console.log(buffer[0].options); + console.log(buffer[0].data); +}); +server.once('drain', (socket) => { + console.log(socket.id); +}); + +server.close(); +httpServer.close(); diff --git a/types/engine.io/index.d.ts b/types/engine.io/index.d.ts new file mode 100644 index 0000000000..2d1be7643e --- /dev/null +++ b/types/engine.io/index.d.ts @@ -0,0 +1,229 @@ +// Type definitions for engine.io 3.1 +// Project: https://github.com/socketio/engine.io +// Definitions by: KentarouTakeda +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +/// + +import http = require('http'); +import net = require('net'); +import { EventEmitter } from "events"; + +declare namespace engine { + type Message = string|Buffer|ArrayBuffer|ArrayBufferView; + type Transport = "polling"|"websocket"; + interface Packet { + type: string; + options?: MessageOptions; + data?: Message; + } + type AllowRequestFunction = (req: http.IncomingMessage, fn: (err: string|null|undefined, success: boolean) => void) => void; + + interface ServerOptions { + /** + * how many ms without a pong packet to consider the connection closed (60000) + */ + pingTimeout?: number; + /** + * how many ms before sending a new ping packet (25000) + */ + pingInterval?: number; + /** + * how many ms before an uncompleted transport upgrade is cancelled (10000) + */ + upgradeTimeout?: number; + /** + * how many bytes or characters a message can be, before closing the session (to avoid DoS). Default value is 10E7. + */ + maxHttpBufferSize?: number; + /** + * A function that receives a given handshake or upgrade request as its first parameter, + * and can decide whether to continue or not. The second argument is a function that needs + * to be called with the decided information: fn(err, success), where success is a boolean + * value where false means that the request is rejected, and err is an error code. + */ + allowRequest?: AllowRequestFunction; + /** + * to allow connections to (['polling', 'websocket']) + */ + transports?: engine.Transport[]; + /** + * whether to allow transport upgrades (true) + */ + allowUpgrades?: boolean; + /** + * parameters of the WebSocket permessage-deflate extension (see ws module api docs). Set to false to disable. (true) + */ + perMessageDeflate?: any; + /** + * parameters of the http compression for the polling transports (see zlib api docs). Set to false to disable. (true) + */ + httpCompression?: any; + /** + * name of the HTTP cookie that contains the client sid to send as part of handshake response headers. Set to false to not send one. (io) + */ + cookie?: string|boolean; + /** + * path of the above cookie option. If false, no path will be sent, + * which means browsers will only send the cookie on the engine.io + * attached path (/engine.io). Set false to not save io cookie + * on all requests. (/) + */ + cookiePath?: string|boolean; + /** + * If true HttpOnly io cookie cannot be accessed by client-side APIs, + * such as JavaScript. (true) This option has no effect + * if cookie or cookiePath is set to false. + */ + cookieHttpOnly?: boolean; + /** + * what WebSocket server implementation to use. Specified module must + * conform to the ws interface (see ws module api docs). Default value is ws. + * An alternative c++ addon is also available by installing uws module. + */ + wsEngine?: "ws"|"uws"; + /** + * an optional packet which will be concatenated to the handshake packet emitted by Engine.IO. + */ + initialPacket?: Message; + } + interface AttachOptions { + /** + * name of the path to capture (/engine.io). + */ + path?: string; + /** + * destroy unhandled upgrade requests (true) + */ + destroyUpgrade?: boolean; + /** + * milliseconds after which unhandled requests are ended (1000) + */ + destroyUpgradeTimeout?: number; + /** + * whether to let engine.io handle the OPTIONS requests. You can also pass a custom function to handle the requests (true) + */ + handlePreflightRequest?: boolean|((server: Server, req: http.IncomingMessage, res: http.ServerResponse) => void); + } + interface ServerAttachOptions extends ServerOptions, AttachOptions {} + + interface MessageOptions { + compress?: boolean; + } + + /** + * The main server/manager. Inherits from EventEmitter. + */ + class Server extends EventEmitter { + /** + * hash of connected clients by id. + */ + clients: {[sid: string]: Socket}; + /** + * number of connected clients. + */ + clientsCount: number; + + /** + * Initializes the server + */ + constructor(opts?: engine.ServerOptions); + /** + * Fired when a new connection is established. + */ + on(ev: 'connection'|'drain', fn: (socket: Socket) => void): this; + on(ev: 'flush', fn: (socket: Socket, buffer: Packet[]) => void): this; + /** + * Closes all clients + */ + close(): this; + readonly httpServer?: http.Server; + /** + * Called internally when a Engine request is intercepted. + */ + handleRequest(req: http.IncomingMessage, res: http.ServerResponse): this; + /** + * Called internally when a Engine ws upgrade is intercepted. + */ + handleUpgrade(req: http.IncomingMessage, socket: net.Socket, head: Buffer): this; + /** + * Attach this Server instance to an http.Server + * Captures upgrade requests for a http.Server. In other words, makes a regular http.Server WebSocket-compatible. + */ + attach(http: http.Server, opts?: AttachOptions): this; + /** + * Generate a socket id. + * Overwrite this method to generate your custom socket id. + */ + generateId(req: http.IncomingMessage): string; + } + + /** + * A representation of a client. Inherits from EventEmitter. + */ + class Socket extends EventEmitter { + /** + * unique identifier + */ + id: string; + /** + * engine parent reference + */ + server: Server; + /** + * request that originated the Socket + */ + request: http.IncomingMessage; + /** + * whether the transport has been upgraded + */ + upgraded: boolean; + /** + * readyState + */ + readyState: 'opening'|'open'|'closing'|'closed'; + + /** + * Sends a message, performing message = toString(arguments[0]) unless sending binary data, which is sent as is. + */ + send(message: Message, opts?: MessageOptions, fn?: ((transport: any) => void)): void; + + /** + * Disconnects the client + */ + close(): this; + + /** + * Fired when the client is disconnected. + */ + on(ev: "close", fn: (reason: string, description?: Error) => void): this; + /** + * Fired when the client sends a message. + */ + on(ev: "message", fn: (data: string|Buffer) => void): this; + /** + * Fired when an error occurs. + */ + on(ev: "error", fn: (err: Error) => void): this; + /** + * Called when the write buffer is being flushed. + */ + on(ev: "flush", fn: (buffer: Packet[]) => void): this; + /** + * Called when the write buffer is drained + */ + on(ev: "drain", fn: () => void): this; + /** + * packet: Called when a socket received a packet (message, ping) + * packetCreate: Called before a socket sends a packet (message, pong) + */ + on(ev: "packet" | "packetCreate", fn: (packet: Packet) => void): this; + } + function attach(http: net.Server, opyts?: engine.ServerAttachOptions): engine.Server; + function listen(port: number, opts?: engine.ServerOptions, fn?: () => void): engine.Server; + const protocol: number; +} + +declare function engine(httpServer?: net.Server, opts?: engine.ServerOptions): engine.Server; + +export = engine; diff --git a/types/engine.io/tsconfig.json b/types/engine.io/tsconfig.json new file mode 100644 index 0000000000..4ec2d12abc --- /dev/null +++ b/types/engine.io/tsconfig.json @@ -0,0 +1,23 @@ +{ + "compilerOptions": { + "module": "commonjs", + "lib": [ + "es6" + ], + "noImplicitAny": true, + "noImplicitThis": true, + "strictNullChecks": true, + "strict": true, + "baseUrl": "../", + "typeRoots": [ + "../" + ], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true + }, + "files": [ + "index.d.ts", + "engine.io-tests.ts" + ] +} diff --git a/types/engine.io/tslint.json b/types/engine.io/tslint.json new file mode 100644 index 0000000000..3db14f85ea --- /dev/null +++ b/types/engine.io/tslint.json @@ -0,0 +1 @@ +{ "extends": "dtslint/dt.json" } diff --git a/types/enzyme/index.d.ts b/types/enzyme/index.d.ts index 01ecfa90d8..e1fdba2027 100644 --- a/types/enzyme/index.d.ts +++ b/types/enzyme/index.d.ts @@ -3,7 +3,6 @@ // Definitions by: Marian Palkus // Cap3 // Ivo Stratev -// Tom Crockett // jwbay // huhuanming // MartynasZilinskas @@ -11,7 +10,7 @@ // TypeScript Version: 2.3 /// -import { ReactElement, Component, HTMLAttributes as ReactHTMLAttributes, SVGAttributes as ReactSVGAttributes } from "react"; +import { ReactElement, Component, AllHTMLAttributes as ReactHTMLAttributes, SVGAttributes as ReactSVGAttributes } from "react"; export type HTMLAttributes = ReactHTMLAttributes<{}> & ReactSVGAttributes<{}>; diff --git a/types/epub/index.d.ts b/types/epub/index.d.ts index fe4f36ce87..2c2480e91a 100644 --- a/types/epub/index.d.ts +++ b/types/epub/index.d.ts @@ -32,7 +32,7 @@ **/ declare module "epub" { - import {EventEmitter} from "events"; + import { EventEmitter } from "events"; interface TocElement { level: number; diff --git a/types/esprima/index.d.ts b/types/esprima/index.d.ts index f03fd096f9..2d5f933cad 100644 --- a/types/esprima/index.d.ts +++ b/types/esprima/index.d.ts @@ -13,7 +13,7 @@ declare namespace esprima { const version: string; - function parse(code: string, options?: Options): ESTree.Program; + function parse(code: string, options?: Options, delegate?: (node: ESTree.Node, meta: any) => void): ESTree.Program; function tokenize(code: string, options?: Options): Array; interface Token { @@ -101,4 +101,4 @@ declare namespace esprima { YieldExpression: 'YieldExpression' }; -} \ No newline at end of file +} diff --git a/types/estree/estree-tests.ts b/types/estree/estree-tests.ts index ace67225a4..ac2516f18b 100644 --- a/types/estree/estree-tests.ts +++ b/types/estree/estree-tests.ts @@ -89,6 +89,7 @@ declare var awaitExpression: ESTree.AwaitExpression; declare var toplevelStatement: ESTree.Statement | ESTree.ModuleDeclaration; declare var expressionOrPattern: ESTree.Expression | ESTree.Pattern; declare var variableDeclaratorOrExpression: ESTree.VariableDeclaration | ESTree.Expression; +declare var variableDeclaratorOrPattern: ESTree.VariableDeclaration | ESTree.Pattern; declare var literalOrIdentifier: ESTree.Literal | ESTree.Identifier; declare var blockStatementOrExpression: ESTree.BlockStatement | ESTree.Expression; declare var identifierOrExpression: ESTree.Identifier | ESTree.Expression; @@ -156,7 +157,7 @@ var expressionMaybe: ESTree.Expression | null | undefined = forStatement.update; // ForInStatement var forInStatement: ESTree.ForInStatement; -variableDeclaratorOrExpression = forInStatement.left; +variableDeclaratorOrPattern = forInStatement.left; expression = forInStatement.right; // Expression @@ -723,3 +724,33 @@ switch (moduleSpecifier.type) { default: never = moduleSpecifier; } + +switch (forInStatement.left.type) { + case 'Identifier': + identifier = forInStatement.left; + break; + case 'ObjectPattern': + objectPattern = forInStatement.left; + break; + case 'ArrayPattern': + arrayPattern = forInStatement.left; + break; + case 'MemberExpression': + memberExpression = forInStatement.left; + break; +} + +switch (forOfStatement.left.type) { + case 'Identifier': + identifier = forOfStatement.left; + break; + case 'ObjectPattern': + objectPattern = forOfStatement.left; + break; + case 'ArrayPattern': + arrayPattern = forOfStatement.left; + break; + case 'MemberExpression': + memberExpression = forOfStatement.left; + break; +} diff --git a/types/estree/index.d.ts b/types/estree/index.d.ts index b7a4005add..23c5b19f86 100644 --- a/types/estree/index.d.ts +++ b/types/estree/index.d.ts @@ -58,6 +58,7 @@ export interface Program extends BaseNode { type: "Program"; sourceType: "script" | "module"; body: Array; + comments?: Array; } interface BaseFunction extends BaseNode { @@ -89,6 +90,7 @@ export interface EmptyStatement extends BaseStatement { export interface BlockStatement extends BaseStatement { type: "BlockStatement"; body: Array; + innerComments?: Array; } export interface ExpressionStatement extends BaseStatement { @@ -169,7 +171,7 @@ export interface ForStatement extends BaseStatement { } interface BaseForXStatement extends BaseStatement { - left: VariableDeclaration | Expression; + left: VariableDeclaration | Pattern; right: Expression; body: Statement; } diff --git a/types/ethjs-signer/ethjs-signer-tests.ts b/types/ethjs-signer/ethjs-signer-tests.ts new file mode 100644 index 0000000000..7f6939fc3b --- /dev/null +++ b/types/ethjs-signer/ethjs-signer-tests.ts @@ -0,0 +1,16 @@ +import { sign, recover } from "ethjs-signer"; + +const nonce = 0; +const privateKey = '0xecbcd9838f7f2afa6e809df8d7cdae69aa5dfc14d563ee98e97effd3f6a652f2'; + +const transaction = { + to: '0xce31a19193d4b23f4e9d6163d7247243bAF801c3', + value: 300000, + gasPrice: 2000000, + nonce +}; + +const signedTransactionString = sign(transaction, privateKey) as string; +const signedTransaction = sign(transaction, privateKey, true) as any[]; + +const publicKey = recover(signedTransactionString, -1, signedTransaction[7], signedTransaction[8]); diff --git a/types/ethjs-signer/index.d.ts b/types/ethjs-signer/index.d.ts new file mode 100644 index 0000000000..969ed9e9ea --- /dev/null +++ b/types/ethjs-signer/index.d.ts @@ -0,0 +1,18 @@ +// Type definitions for ethjs-signer 0.1 +// Project: https://github.com/ethjs/ethjs-signer/ +// Definitions by: Bryson Thill +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.3 + +/// + +/** + * Signs a raw transaction and return it either as a serialized hex string or raw tx object. + */ +export function sign(transaction: object, privateKey: string, toObject?: false): string; +export function sign(transaction: object, privateKey: string, toObject: true): any[]; + +/** + * Recovers a ECDSA public key from a raw transaction. + */ +export function recover(rawTx: string | Buffer, v: number, r: Buffer, s: Buffer): Buffer; diff --git a/types/ethjs-signer/tsconfig.json b/types/ethjs-signer/tsconfig.json new file mode 100644 index 0000000000..202b9ca11a --- /dev/null +++ b/types/ethjs-signer/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", + "ethjs-signer-tests.ts" + ] +} \ No newline at end of file diff --git a/types/ethjs-signer/tslint.json b/types/ethjs-signer/tslint.json new file mode 100644 index 0000000000..e60c15844f --- /dev/null +++ b/types/ethjs-signer/tslint.json @@ -0,0 +1,3 @@ +{ + "extends": "dtslint/dt.json" +} \ No newline at end of file diff --git a/types/exceljs/exceljs-tests.ts b/types/exceljs/exceljs-tests.ts index 95147c7726..684fad8719 100644 --- a/types/exceljs/exceljs-tests.ts +++ b/types/exceljs/exceljs-tests.ts @@ -1,4 +1,7 @@ import * as Excel from 'exceljs'; +import * as stream from 'stream'; +import * as fs from 'fs'; +import * as Bluebird from 'bluebird'; // most examples taken and adapted from README.md @@ -18,65 +21,447 @@ workbook.views = [ } ]; -const worksheet: Excel.Worksheet = workbook.addWorksheet('My Sheet'); +const worksheet = workbook.addWorksheet('My Sheet'); + +workbook.eachSheet((worksheet, sheetId) => null); + const worksheet2 = workbook.getWorksheet('My Sheet'); const worksheet3 = workbook.getWorksheet(1); -const sheet = workbook.addWorksheet('My Sheet', {views: [{showGridLines: false}]}); +const sheet1 = workbook.addWorksheet('My Sheet', { + pageSetup: { fitToPage: true, fitToHeight: 5, fitToWidth: 7 }, + properties: { tabColor: { argb: 'FFC0000' } }, +}); +const sheet2 = workbook.addWorksheet('My Sheet', { + pageSetup: { paperSize: 9, orientation: 'landscape' }, + views: [ + { state: 'frozen', xSplit: 1, ySplit: 1 }, + { state: 'normal', showGridLines: false }, + { state: 'split', activePane: 'bottomLeft', } + ] +}); + +worksheet.properties.outlineLevelCol = 2; +worksheet.properties.defaultRowHeight = 15; + +worksheet.pageSetup.margins = { + left: 0.7, right: 0.7, + top: 0.75, bottom: 0.75, + header: 0.3, footer: 0.3 +}; + +worksheet.pageSetup.printArea = 'A1:G20'; +worksheet.pageSetup.printTitlesRow = '1:3'; + +worksheet.views = [ + { state: 'frozen', xSplit: 2, ySplit: 3, topLeftCell: 'G10', activeCell: 'A1' }, + { state: 'split', xSplit: 2000, ySplit: 3000, topLeftCell: 'G10', activeCell: 'A1' }, +]; + +worksheet.autoFilter = { from: 'A1', to: 'C1' }; +worksheet.autoFilter = { from: { row: 3, column: 1 }, to: { row: 5, column: 12 } }; +worksheet.autoFilter = { from: 'D3', to: { row: 7, column: 5 } }; + +worksheet.columns = [ + { header: 'Id', key: 'id', width: 10 }, + { header: 'Name', key: 'name', width: 32 }, + { header: 'D.O.B.', key: 'DOB', width: 10, outlineLevel: 1 } +]; + +const idCol = worksheet.getColumn('id'); +const nameCol = worksheet.getColumn('B'); +const dobCol = worksheet.getColumn(3); + +dobCol.header = 'Date of Birth'; +dobCol.header = ['Date of Birth', 'A.K.A. D.O.B.']; +dobCol.key = 'dob'; +dobCol.width = 15; +dobCol.hidden = true; +worksheet.getColumn(4).outlineLevel = 0; +const cl1 = worksheet.getColumn(4).collapsed; + +dobCol.eachCell((cell, rowNumber) => null); + +dobCol.eachCell({ includeEmpty: true }, (cell, rowNumber) => null); + +worksheet.spliceColumns(3, 2); + +const newCol3Values = [1, 2, 3, 4, 5]; +const newCol4Values = ['one', 'two', 'three', 'four', 'five']; +worksheet.spliceColumns(3, 1, newCol3Values, newCol4Values); + +worksheet.addRow({ id: 1, name: 'John Doe', dob: new Date(1970, 1, 1) }); +worksheet.addRow({ id: 2, name: 'Jane Doe', dob: new Date(1965, 1, 7) }); +worksheet.addRow([3, 'Sam', new Date()]); +const rowValues = []; +rowValues[1] = 4; +rowValues[5] = 'Kyle'; +rowValues[9] = new Date(); +worksheet.addRow(rowValues); +const rows = [ + [5, 'Bob', new Date()], + { id: 6, name: 'Barbara', dob: new Date() }, +]; +worksheet.addRows(rows); + +const row = worksheet.getRow(5); +const row1 = worksheet.lastRow; + +row.height = 42.5; +row.hidden = true; +worksheet.getRow(4).outlineLevel = 0; +worksheet.getRow(5).outlineLevel = 1; +worksheet.getRow(4).collapsed; +worksheet.getRow(4).number; -const row: Excel.Row = worksheet.addRow([3, 'Sam', new Date()]); row.getCell(1).value = 5; +row.getCell('name').value = 'Zeb'; +row.getCell('C').value = new Date(); -worksheet.eachRow((row: Excel.Row, rowNumber: number): void => { - // nothing -}); +const row2 = worksheet.getRow(4).values; -row.eachCell((cell: Excel.Cell, colNumber: number): void => { - // nothing -}); +row.values = [1, 2, 3]; + +const values = []; +values[5] = 7; +values[10] = 'Hello, World!'; +row.values = values; + +row.values = { id: 13, name: 'Thing 1', dob: new Date() }; + +worksheet.eachRow((row, rowNumber) => null); +worksheet.eachRow({ includeEmpty: true }, (row, rowNumber) => null); + +row.eachCell((cell, colNumber) => null); +row.eachCell({ includeEmpty: true }, (cell, colNumber) => null); + +worksheet.spliceRows(4, 3); + +const newRow3Values = [1, 2, 3, 4, 5]; +const newRow4Values = ['one', 'two', 'three', 'four', 'five']; +worksheet.spliceRows(3, 1, newRow3Values, newRow4Values); + +row.splice(3, 2); + +row.splice(4, 1, 'new value 1', 'new value 2'); + +row.commit(); + +const rowSize = row.cellCount; +const numValues = row.actualCellCount; + +worksheet.getCell('C3').value = new Date(1968, 5, 1); +const isDate = worksheet.getCell('C3').type === Excel.ValueType.Date; worksheet.mergeCells('A4:B5'); -worksheet.getCell('A1').numFmt = '0.00%'; -worksheet.getCell('A1').font = { - name: 'Comic Sans MS', - family: 4, - size: 16, - underline: true, - bold: true +worksheet.getCell('B5').value = 'Hello, World!'; +const master = worksheet.getCell('B5').master === worksheet.getCell('A4'); + +worksheet.unMergeCells('A4'); + +worksheet.mergeCells('G10', 'H11'); +worksheet.mergeCells(10, 11, 12, 13); + +worksheet.getCell('A1').name = 'PI'; +worksheet.getCell('A1').names = ['thing1', 'thing2']; +worksheet.getCell('A1').removeName('thing1'); + +worksheet.getCell('A1').dataValidation = { + type: 'list', + allowBlank: true, + formulae: ['"One,Two,Three,Four"'] }; +worksheet.getCell('A1').dataValidation = { + type: 'list', + allowBlank: true, + formulae: ['$D$5:$F$5'] +}; + +worksheet.getCell('A1').dataValidation = { + type: 'whole', + operator: 'notEqual', + showErrorMessage: true, + formulae: [5], + errorStyle: 'error', + errorTitle: 'Five', + error: 'The value must not be Five' +}; + +worksheet.getCell('A1').dataValidation = { + type: 'decimal', + operator: 'between', + allowBlank: true, + showInputMessage: true, + formulae: [1.5, 7], + promptTitle: 'Decimal', + prompt: 'The value must between 1.5 and 7' +}; + +worksheet.getCell('A1').dataValidation = { + type: 'textLength', + operator: 'lessThan', + showErrorMessage: true, + allowBlank: true, + formulae: [15] +}; + +worksheet.getCell('A1').dataValidation = { + type: 'date', + operator: 'lessThan', + showErrorMessage: true, + allowBlank: true, + formulae: [new Date(2016, 0, 1)] +}; + +worksheet.getCell('A1').value = null; +worksheet.getCell('A1').value = 5; +worksheet.getCell('A2').value = 3.14159; +worksheet.getCell('A1').value = 'Hello, World!'; +worksheet.getCell('A1').value = new Date(2017, 2, 15); +worksheet.getCell('A1').value = { text: 'www.mylink.com', hyperlink: 'http://www.mylink.com' }; +worksheet.getCell('A1').value = { text: 'Sheet2', hyperlink: '#\\"Sheet2\\"!A1' }; +worksheet.getCell('A3').value = { formula: 'A1+A2', result: 7 }; +worksheet.getCell('B3').value = { sharedFormula: 'A3', result: 10 }; +worksheet.getCell('A1').value = true; +worksheet.getCell('A2').value = false; +worksheet.getCell('A1').value = { error: '#N/A' }; +worksheet.getCell('A2').value = { error: '#VALUE!' }; +worksheet.getCell('A1').value = { + richText: [ + { text: 'This is ' }, + { font: { italic: true }, text: 'italic' } + ], +}; +worksheet.getCell('A3').formula === 'A1+A2'; +worksheet.getCell('A3').result === 7; + +const isMaster = worksheet.getCell('A3').formulaType === Excel.FormulaType.Master; +const isShared = worksheet.getCell('B3').formulaType === Excel.FormulaType.Shared; + +worksheet.getCell('A1').numFmt = '0.00%'; +worksheet.columns = [ + { header: 'Id', key: 'id', width: 10 }, + { header: 'Name', key: 'name', width: 32, style: { font: { name: 'Arial Black' } } }, + { header: 'D.O.B.', key: 'DOB', width: 10, style: { numFmt: 'dd/mm/yyyy' } } +]; + +worksheet.getColumn(3).numFmt = '"£"#,##0.00;[Red]\-"£"#,##0.00'; + +worksheet.getRow(2).font = { + name: 'Comic Sans MS', + family: 4, + size: 16, + underline: 'double', + bold: true, +}; + +worksheet.getCell('A1').numFmt = '# ?/?'; +worksheet.getCell('B1').numFmt = '0.00%'; + +worksheet.getCell('A1').font = { + name: 'Comic Sans MS', + family: 4, + size: 16, + underline: true, + bold: true +}; + +worksheet.getCell('A2').font = { + name: 'Arial Black', + color: { argb: 'FF00FF00' }, + family: 2, + size: 14, + italic: true +}; + +const font = { name: 'Arial', size: 12 }; +worksheet.getCell('A3').font = font; +font.size = 20; + worksheet.getCell('A1').alignment = { vertical: 'top', horizontal: 'left' }; worksheet.getCell('B1').alignment = { vertical: 'middle', horizontal: 'center' }; worksheet.getCell('C1').alignment = { vertical: 'bottom', horizontal: 'right' }; worksheet.getCell('D1').alignment = { wrapText: true }; worksheet.getCell('E1').alignment = { indent: 1 }; +worksheet.getCell('F1').alignment = { textRotation: 30 }; +worksheet.getCell('G1').alignment = { textRotation: -45 }; +worksheet.getCell('H1').alignment = { textRotation: 'vertical' }; worksheet.getCell('A1').border = { - top: {style: 'thin'}, - left: {style: 'thin'}, - bottom: {style: 'thin'}, - right: {style: 'thin'} + top: { style: 'thin' }, + left: { style: 'thin' }, + bottom: { style: 'thin' }, + right: { style: 'thin' } }; worksheet.getCell('A3').border = { - top: {style: 'double', color: {argb: 'FF00FF00'}}, - left: {style: 'double', color: {argb: 'FF00FF00'}}, - bottom: {style: 'double', color: {argb: 'FF00FF00'}}, - right: {style: 'double', color: {argb: 'FF00FF00'}} + top: { style: 'double', color: { argb: 'FF00FF00' } }, + left: { style: 'double', color: { argb: 'FF00FF00' } }, + bottom: { style: 'double', color: { argb: 'FF00FF00' } }, + right: { style: 'double', color: { argb: 'FF00FF00' } } +}; + +worksheet.getCell('A5').border = { + diagonal: { up: true, down: true, style: 'thick', color: { argb: 'FFFF0000' } } }; worksheet.getCell('A1').fill = { - type: 'pattern', - pattern: 'solid', - fgColor: {argb: 'FFFF0000'} + type: 'pattern', + pattern: 'darkVertical', + fgColor: { argb: 'FFFF0000' } }; -workbook.xlsx.readFile("/home/john/bla.xlsx") - .then((): void => { - // use workbook - }); +worksheet.getCell('A2').fill = { + type: 'pattern', + pattern: 'darkTrellis', + fgColor: { argb: 'FFFFFF00' }, + bgColor: { argb: 'FF0000FF' } +}; -workbook.xlsx.writeFile("/home/john/bla.xlsx") - .then((): void => { - // done - }); +worksheet.getCell('A3').fill = { + type: 'gradient', + gradient: 'angle', + degree: 0, + stops: [ + { position: 0, color: { argb: 'FF0000FF' } }, + { position: 0.5, color: { argb: 'FFFFFFFF' } }, + { position: 1, color: { argb: 'FF0000FF' } } + ] +}; + +worksheet.getCell('A2').fill = { + type: 'gradient', + gradient: 'path', + center: { left: 0.5, top: 0.5 }, + stops: [ + { position: 0, color: { argb: 'FFFF0000' } }, + { position: 1, color: { argb: 'FF00FF00' } } + ] +}; + +worksheet.getCell('A1').value = { + richText: [ + { + text: 'This is ', + font: { name: 'Calibri', size: 12, color: { theme: 0 }, family: 2, scheme: 'minor' }, + }, + { + text: 'a', + font: { italic: true, size: 12, color: { theme: 0 }, name: 'Calibri', scheme: 'minor' }, + }, + { + text: ' ', + font: { size: 12, color: { theme: 1 }, name: 'Calibri', family: 2, scheme: 'minor' }, + }, + { + text: 'colorful', + font: { size: 12, color: { argb: 'FFFF6600' }, name: 'Calibri', scheme: 'minor' }, + }, + { + text: ' text ', + font: { size: 12, color: { theme: 1 }, name: 'Calibri', family: 2, scheme: 'minor' }, + }, + { + text: 'with', + font: { size: 12, color: { argb: 'FFCCFFCC' }, name: 'Calibri', scheme: 'minor' }, + }, + { + text: ' in-cell ', + font: { size: 12, color: { theme: 1 }, name: 'Calibri', family: 2, scheme: 'minor' }, + }, + { + text: 'format', + font: { bold: true, size: 12, name: 'Calibri', family: 2, scheme: 'minor' }, + } + ] +}; + +worksheet.columns = [ + { header: 'Id', key: 'id', width: 10 }, + { header: 'Name', key: 'name', width: 32 }, + { header: 'D.O.B.', key: 'DOB', width: 10, outlineLevel: 1 } +]; +worksheet.getColumn(3).outlineLevel = 1; +worksheet.getRow(3).outlineLevel = 1; +worksheet.properties.outlineLevelCol = 1; +worksheet.properties.outlineLevelRow = 1; + +const imageId1 = workbook.addImage({ + filename: 'path/to/image.jpg', + extension: 'jpeg', +}); +const imageId2 = workbook.addImage({ + buffer: fs.readFileSync('path/to.image.png'), + extension: 'png', +}); + +worksheet.addBackgroundImage(imageId1); +worksheet.addImage(imageId2, 'B2:D6'); +worksheet.addImage(imageId2, { + tl: { col: 1.5, row: 1.5 }, + br: { col: 3.5, row: 5.5 } +}); + +workbook.xlsx.readFile('./1.xlsx').then(() => null); +(new stream.Stream()).pipe(workbook.xlsx.createInputStream()); + +workbook.xlsx.writeFile('./1.xlsx').then(() => null); +workbook.xlsx.write(new stream.Stream()).then(() => null); + +workbook.csv.readFile('./1.xlsx').then(worksheet => null); +workbook.csv.read(new stream.Stream()).then(worksheet => null); + +(new stream.Stream()).pipe(workbook.csv.createInputStream()); + +const options1 = { dateFormats: ['DD/MM/YYYY'] }; +workbook.csv.readFile('./1.xlsx', options1).then(worksheet => null); + +const options2 = { + map(value: any, index: number) { + switch (index) { + case 0: + // column 1 is string + return value; + case 1: + // column 2 is a date + return new Date(value); + case 2: + // column 3 is JSON of a formula value + return JSON.parse(value); + default: + // the rest are numbers + return parseFloat(value); + } + } +}; +workbook.csv.readFile('./1.xlsx', options2).then(worksheet => null); + +workbook.csv.writeFile('./1.xlsx').then(() => null); + +// write to a stream +workbook.csv.write(new stream.Stream()).then(() => null); + +const workbookWriter = new Excel.stream.xlsx.WorkbookWriter({ + filename: './streamed-workbook.xlsx', + useStyles: true, + useSharedStrings: true +}); + +worksheet.addRow({ + id: 'i', + name: 'theName', + etc: 'someOtherDetail' +}).commit(); + +worksheet.mergeCells('A1:B2'); +worksheet.getCell('A1').value = 'I am merged'; +worksheet.getCell('C1').value = 'I am not'; +worksheet.getCell('C2').value = 'Neither am I'; +worksheet.getRow(2).commit(); + +worksheet.commit(); + +workbook.commit().then(() => null); + +Excel.config.setValue('promise', Bluebird); diff --git a/types/exceljs/index.d.ts b/types/exceljs/index.d.ts index 259eaccae1..2d8c482cf6 100644 --- a/types/exceljs/index.d.ts +++ b/types/exceljs/index.d.ts @@ -1,7 +1,353 @@ -// Type definitions for exceljs 0.4 +// Type definitions for exceljs 0.5 // Project: https://github.com/guyonroche/exceljs // Definitions by: Rogier Schouten +// Ali Taheri Moghaddar // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.3 + +/// + +import { Writable, Stream } from 'stream'; + +export const enum RelationshipType { + None = 0, + OfficeDocument = 1, + Worksheet = 2, + CalcChain = 3, + SharedStrings = 4, + Styles = 5, + Theme = 6, + Hyperlink = 7 +} + +export const enum DocumentType { + Xlsx = 1 +} + +export const enum PaperSize { + Legal = 5, + Executive = 7, + A4 = 9, + A5 = 11, + B5 = 13, + Envelope_10 = 20, + Envelope_DL = 27, + Envelope_C5 = 28, + Envelope_B5 = 34, + Envelope_Monarch = 37, + Double_Japan_Postcard_Rotated = 82, + K16_197x273_mm = 119, +} + +export interface WorksheetViewCommon { + /** + * Sets the worksheet view's orientation to right-to-left, `false` by default + */ + rightToLeft?: boolean; + + /** + * The currently selected cell + */ + activeCell?: string; + + /** + * Shows or hides the ruler in Page Layout, `true` by default + */ + showRuler?: boolean; + + /** + * Shows or hides the row and column headers (e.g. A1, B1 at the top and 1,2,3 on the left, + * `true` by default + */ + showRowColHeaders?: boolean; + + /** + * Shows or hides the gridlines (shown for cells where borders have not been defined), + * `true` by default + */ + showGridLines?: boolean; + + /** + * Percentage zoom to use for the view, `100` by default + */ + zoomScale?: number; + + /** + * Normal zoom for the view, `100` by default + */ + zoomScaleNormal?: number; +} + +export interface WorksheetViewNormal { + /** + * Controls the view state + */ + state?: 'normal'; + + /** + * Presentation style + */ + style?: 'pageBreakPreview' | 'pageLayout'; +} + +export interface WorksheetViewFrozen { + /** + * Where a number of rows and columns to the top and left are frozen in place. + * Only the bottom left section will scroll + */ + state: 'frozen'; + + /** + * Presentation style + */ + style?: 'pageBreakPreview'; + + /** + * How many columns to freeze. To freeze rows only, set this to 0 or undefined + */ + xSplit?: number; + + /** + * How many rows to freeze. To freeze columns only, set this to 0 or undefined + */ + ySplit?: number; + + /** + * Which cell will be top-left in the bottom-right pane. Note: cannot be a frozen cell. + * Defaults to first unfrozen cell + */ + topLeftCell?: string; +} + +export interface WorksheetViewSplit { + /** + * Where the view is split into 4 sections, each semi-independently scrollable. + */ + state: 'split'; + + /** + * Presentation style + */ + style?: 'pageBreakPreview' | 'pageLayout'; + + /** + * How many points from the left to place the splitter. + * To split vertically, set this to 0 or undefined + */ + xSplit?: number; + + /** + * How many points from the top to place the splitter. + * To split horizontally, set this to 0 or undefined + */ + ySplit?: number; + + /** + * Which cell will be top-left in the bottom-right pane + */ + topLeftCell?: string; + + /** + * Which pane will be active + */ + activePane?: 'topLeft' | 'topRight' | 'bottomLeft' | 'bottomRight'; +} + +export type WorksheetView = + & WorksheetViewCommon + & (WorksheetViewNormal | WorksheetViewFrozen | WorksheetViewSplit); + +export interface WorkbookView { + x?: number; + y?: number; + width?: number; + height?: number; + firstSheet?: number; + activeTab?: number; + visibility?: string; +} + +export type FillPatterns = + | 'none' | 'solid' + | 'darkVertical' | 'darkHorizontal' | 'darkGrid' | 'darkTrellis' | 'darkDown' | 'darkUp' + | 'lightVertical' | 'lightHorizontal' | 'lightGrid' | 'lightTrellis' | 'lightDown' | 'lightUp' + | 'darkGray' | 'mediumGray' | 'lightGray' | 'gray125' | 'gray0625'; + +export interface FillPattern { + type: 'pattern'; + pattern: FillPatterns; + fgColor?: Color; + bgColor?: Color; +} + +export interface GradientStop { + position: number; + color: Color; +} + +export interface FillGradientAngle { + type: 'gradient'; + gradient: 'angle'; + + /** + * For 'angle' gradient, specifies the direction of the gradient. 0 is from the left to the right. + * Values from 1 - 359 rotates the direction clockwise + */ + degree: number; + + /** + * Specifies the gradient colour sequence. Is an array of objects containing position and + * color starting with position 0 and ending with position 1. + * Intermediary positions may be used to specify other colours on the path. + */ + stops: GradientStop[]; +} + +export interface FillGradientPath { + type: 'gradient'; + gradient: 'path'; + + /** + * For 'path' gradient. Specifies the relative coordinates for the start of the path. + * 'left' and 'top' values range from 0 to 1 + */ + center: { left: number; top: number }; + + /** + * Specifies the gradient colour sequence. Is an array of objects containing position and + * color starting with position 0 and ending with position 1. + * Intermediary positions may be used to specify other colours on the path. + */ + stops: GradientStop[]; +} + +export type Fill = FillPattern | FillGradientAngle | FillGradientPath; + +export interface Font { + name?: string; + size?: number; + family?: number; + scheme?: 'minor' | 'major' | 'none'; + charset?: number; + color?: Color; + bold?: boolean; + italic?: boolean; + underline?: boolean | 'none' | 'single' | 'double' | 'singleAccounting' | 'doubleAccounting'; + strike?: boolean; + outline?: boolean; +} + +export type BorderStyle = + | 'thin' | 'dotted' | 'hair' | 'medium' | 'double' | 'thick' | 'dashDot' + | 'dashDotDot' | 'slantDashDot' | 'mediumDashed' | 'mediumDashDotDot' | 'mediumDashDot'; + +export interface Color { + /** + * Hex string for alpha-red-green-blue e.g. FF00FF00 + */ + argb?: string; + + /** + * Choose a theme by index + */ + theme?: number; +} + +export interface Border { + style?: BorderStyle; + color?: Color; +} + +export interface BorderDiagonal extends Border { + up?: boolean; + down?: boolean; +} + +export interface Borders { + top?: Border; + left?: Border; + bottom?: Border; + right?: Border; + diagonal?: BorderDiagonal; +} + +export interface Margins { + top?: number; + left?: number; + bottom?: number; + right?: number; + header?: number; + footer?: number; +} + +export const enum ReadingOrder { + LeftToRight = 1, + RightToLeft = 2, +} + +export interface Alignment { + horizontal?: 'left' | 'center' | 'right' | 'fill' | 'justify' | 'centerContinuous' | 'distributed'; + vertical?: 'top' | 'middle' | 'bottom' | 'distributed' | 'justify'; + wrapText?: boolean; + indent?: number; + readingOrder?: 'rtl' | 'ltr'; + textRotation?: number | 'vertical'; +} + +export interface Style { + numFmt?: string; + font?: Font; + alignment?: Alignment; + border?: Borders; + fill?: Fill; +} + +export type DataValidationOperator = + | 'between' | 'notBetween' | 'equal' | 'notEqual' | 'greaterThan' | 'lessThan' + | 'greaterThanOrEqual' | 'lessThanOrEqual'; + +export interface DataValidation { + type: 'list' | 'whole' | 'decimal' | 'date' | 'textLength' | 'custom'; + formulae: any[]; + allowBlank?: boolean; + operator?: DataValidationOperator; + error?: string; + errorTitle?: string; + errorStyle?: string; + prompt?: string; + promptTitle?: string; + showErrorMessage?: boolean; + showInputMessage?: boolean; +} + +export interface CellErrorValue { + error: '#N/A' | '#REF!' | '#NAME?' | '#DIV/0!' | '#NULL!' | '#VALUE!' | '#NUM!'; +} + +export interface RichText { + text: string; + font?: Font; +} + +export interface CellRichTextValue { + richText: RichText[]; +} + +export interface CellHyperlinkValue { + text: string; + hyperlink: string; +} + +export interface CellFormulaValue { + formula: string; + result: number | string | Date; +} + +export interface CellSharedFormulaValue { + sharedFormula: string; + readonly formula?: string; + result: number | string | Date; +} export const enum ValueType { Null = 0, @@ -23,170 +369,454 @@ export const enum FormulaType { Shared = 2 } -export const enum RelationshipType { - None = 0, - OfficeDocument = 1, - Worksheet = 2, - CalcChain = 3, - SharedStrings = 4, - Styles = 5, - Theme = 6, - Hyperlink = 7 -} +export type CellValue = + | null | number | string | boolean | Date + | CellErrorValue + | CellRichTextValue | CellHyperlinkValue + | CellFormulaValue | CellSharedFormulaValue; -export const enum DocumentType { - Xlsx = 1 -} - -export const enum ReadingOrder { - RightToLeft = 1, - LeftToRight = 2, -} - -export interface ErrorValue { - error: "#N/A" | "#REF!" | "#NAME?" | "#DIV/0!" | "#NULL!" | "#VALUE!" | "#NUM!"; -} - -export interface WorksheetView { - state?: "normal" | "split" | "frozen"; - showRuler?: boolean; - showRowColHeaders?: boolean; - showGridLines?: boolean; - zoomScale?: number; - zoomScaleNormal?: number; - style?: "pageBreakPreview" | "pageLayout"; -} - -export interface WorkbookView { - x?: number; - y?: number; - width?: number; - height?: number; - firstSheet?: number; - activeTab?: number; - visibility?: string; -} - -export interface Fill { - type: "pattern" | "gradient"; - pattern?: "none" | "solid"; - fgColor?: Color; - bgColor?: Color; -} - -export interface Font { - name: string; - size?: number; - family?: number; - schema?: "minor" | "major" | "none"; - charset?: number; - color?: Color; - bold?: boolean; - italic?: boolean; - underline?: true | false | "none" | "single" | "double" | "singleAccounting" | "doubleAccounting"; - strike?: boolean; - outline?: boolean; -} - -export type BorderStyle = - "thin" | "dotted" | "dashDot" | "hair" | "dashDotDot" | "slantDashDot" | "mediumDashed" | "mediumDashDotDot" | - "mediumDashDot" | "medium" | "double" | "thick"; - -export interface Color { +export interface Cell extends Style { /** - * Hex string for alpha-red-green-blue e.g. FF00FF00 + * Assign (or get) a name for a cell (will overwrite any other names that cell had) */ - argb: string; + name?: string; + + /** + * Assign (or get) an array of names for a cell (cells can have more than one name) + */ + names?: string[]; + + /** + * Cells can define what values are valid or not and provide + * prompting to the user to help guide them. + */ + dataValidation?: DataValidation; + + /** + * Value of the cell + */ + value: CellValue; + + /** + * convenience getter to access the formula + */ + readonly formula: string; + + /** + * convenience getter to access the formula result + */ + readonly result: number | string | Date; + + /** + * The type of the cell's value + */ + readonly type: ValueType; + + /** + * The type of the cell's formula + */ + readonly formulaType: FormulaType; + + /** + * The master cell when the current cell is a merge cell + */ + master?: Cell; + + /** + * The styles of the cell + */ + style: Style; + + /** + * Remove a name from a cell + */ + removeName(name: string): void; } -export interface Border { - style?: BorderStyle; - color?: Color; -} +export interface Row extends Style { + /** + * Set a specific row height + */ + height: number; -export interface Borders { - top?: Border; - left?: Border; - bottom?: Border; - right?: Border; -} + /** + * Make row hidden + */ + hidden: boolean; -export interface Alignment { - horizontal?: "left" | "center" | "right" | "fill" | "justify" | "centerContinuous" | "distributed"; - vertical?: "top" | "middle" | "bottom" | "distributed" | "justify"; - wrapText?: boolean; - indent?: number; - readingOrder?: "rtl" | "ltr"; - textrotation?: number | "vertical"; -} + /** + * Get a row as a sparse array + */ + values: any[] | any; -export interface Cell { - border?: Borders; - font?: Font; - alignment?: Alignment; - numFmt?: string; - value?: any; - fill?: Fill; -} + /** + * Set an outline level for rows + */ + outlineLevel?: number; -export interface Row { /** * The row number */ - number: number; - height: number; - hidden: boolean; - collapsed: boolean; - values: any[]; - outlineLevel?: number; + readonly number: number; + /** + * Indicate the collapsed state based on outlineLevel + */ + readonly collapsed: boolean; + + /** + * Number of non-empty cells + */ readonly cellCount: number; + + /** + * Number of cells including empty ones + */ readonly actualCellCount: number; - getCell(index: number): Cell; + /** + * Get cell by number, column letter or column key + */ + getCell(indexOrKey: number | string): Cell; + /** + * Iterate over all non-null cells in a row + */ eachCell(callback: (cell: Cell, colNumber: number) => void): void; - eachCell(opts: { includeEmpty: boolean}, callback: (cell: Cell, colNumber: number) => void): void; + + /** + * Iterate over all cells in a row (including empty cells) + */ + eachCell(opt: { includeEmpty: boolean }, callback: (cell: Cell, colNumber: number) => void): void; + + /** + * Cut one or more cells (cells to the right are shifted left) + * + * Note: this operation will not affect other rows + */ + splice(start: number, count: number, ...insert: any[]): void; + + /** + * Commit a completed row to stream + */ + commit(): void; } export interface Column { - width: number; + /** + * Can be a string to set one row high header or an array to set multi-row high header + */ + header?: string | string[]; + + /** + * The name of the properties associated with this column in each row + */ + key?: string; + + /** + * The width of the column + */ + width?: number; + + /** + * Set an outline level for columns + */ + outlineLevel?: number; + + /** + * Hides the column + */ + hidden?: boolean; + + /** + * Styles applied to the column + */ + style?: Style; +} + +export interface ColumnExtension extends Style { + /** + * indicate the collapsed state based on outlineLevel + */ + readonly collapsed: boolean; + + /** + * Iterate over all current cells in this column + */ + eachCell(callback: (cell: Cell, rowNumber: number) => void): void; + + /** + * Iterate over all current cells in this column including empty cells + */ + eachCell(opt: { includeEmpty: boolean }, callback: (cell: Cell, rowNumber: number) => void): void; +} + +export interface PageSetup { + /** + * Whitespace on the borders of the page. Units are inches. + */ + margins?: Margins; + + /** + * Orientation of the page - i.e. taller (`'portrait'`) or wider (`'landscape'`). + * + * `'portrait'` by default + */ + orientation?: 'portrait' | 'landscape'; + + /** + * Horizontal Dots per Inch. Default value is 4294967295 + */ + horizontalDpi?: number; + + /** + * Vertical Dots per Inch. Default value is 4294967295 + */ + verticalDpi?: number; + + /** + * Whether to use fitToWidth and fitToHeight or scale settings. + * + * Default is based on presence of these settings in the pageSetup object - if both are present, + * scale wins (i.e. default will be false) + */ + fitToPage?: boolean; + + /** + * How many pages wide the sheet should print on to. Active when fitToPage is true + * + * Default is 1 + */ + fitToWidth?: number; + + /** + * How many pages high the sheet should print on to. Active when fitToPage is true + * + * Default is 1 + */ + fitToHeight?: number; + + /** + * Percentage value to increase or reduce the size of the print. Active when fitToPage is false + * + * Default is 100 + */ + scale?: number; + + /** + * Which order to print the pages. + * + * Default is `downThenOver` + */ + pageOrder?: 'downThenOver' | 'overThenDown'; + + /** + * Print without colour + * + * false by default + */ + blackAndWhite?: boolean; + + /** + * Print with less quality (and ink) + * + * false by default + */ + draft?: boolean; + + /** + * Where to place comments + * + * Default is `None` + */ + cellComments?: 'atEnd' | 'asDisplayed' | 'None'; + + /** + * Where to show errors + * + * Default is `displayed` + */ + errors?: 'dash' | 'blank' | 'NA' | 'displayed'; + + /** + * What paper size to use (see below) + * + * | Name | Value | + * | ----------------------------- | --------- | + * | Letter | `undefined` | + * | Legal | `5` | + * | Executive | `7` | + * | A4 | `9` | + * | A5 | `11` | + * | B5 (JIS) | `13` | + * | Envelope #10 | `20` | + * | Envelope DL | `27` | + * | Envelope C5 | `28` | + * | Envelope B5 | `34` | + * | Envelope Monarch | `37` | + * | Double Japan Postcard Rotated | `82` | + * | 16K 197x273 mm | `119` | + */ + paperSize?: PaperSize; + + /** + * Whether to show the row numbers and column letters, `false` by default + */ + showRowColHeaders?: boolean; + + /** + * Whether to show grid lines, `false` by default + */ + showGridLines?: boolean; + + /** + * Which number to use for the first page + */ + firstPageNumber?: number; + + /** + * Whether to center the sheet data horizontally, `false` by default + */ + horizontalCentered?: boolean; + + /** + * Whether to center the sheet data vertically, `false` by default + */ + verticalCentered?: boolean; + + /** + * Set Print Area for a sheet, e.g. `'A1:G20'` + */ + printArea?: string; + + /** + * Repeat specific rows on every printed page, e.g. `'1:3'` + */ + printTitlesRow?: string; +} + +export type AutoFilter = string | { + from: string | { row: number; column: number }; + to: string | { row: number; column: number }; +}; + +export interface Image { + extension: 'jpeg' | 'png' | 'gif'; + filename?: string; + buffer?: Buffer; +} + +export interface ImageRange { + tl: { col: number; row: number }; + br: { col: number; row: number }; } export interface Worksheet { + /** + * Contains information related to how a worksheet is printed + */ + pageSetup: PageSetup; + + /** + * Worksheet Properties + */ + properties: WorksheetProperties; + + /** + * Open panes representing the sheet + */ + views: WorksheetView[]; + + /** + * Apply an auto filter to your worksheet. + */ + autoFilter?: AutoFilter; + + /** + * Add column headers and define column keys and widths. + * + * Note: these column structures are a workbook-building convenience only, + * apart from the column width, they will not be fully persisted. + */ + columns?: Column[]; + /** * The total row size of the document. Equal to the row number of the last row that has values. */ - rowCount: number; + readonly rowCount: number; + /** * A count of the number of rows that have values. If a mid-document row is empty, it will not be included in the count. */ - actualRowCount: number; + readonly actualRowCount: number; + /** * The total column size of the document. Equal to the maximum cell count from all of the rows */ - columnCount: number; + readonly columnCount: number; + /** * A count of the number of columns that have values. */ - actualColumnCount: number; + readonly actualColumnCount: number; /** - * Get or create a column + * Get the last editable row in a worksheet (or undefined if there are none) */ - getColumn(index: number): Column; + readonly lastRow: Row | undefined; /** - * Create a new row + * Access an individual columns by key, letter and 1-based column number */ - addRow(data: any[]): Row; + getColumn(indexOrKey: number | string): Column & ColumnExtension; + + /** + * Cut one or more columns (columns to the right are shifted left) + * and optionally insert more + * + * If column properties have been definde, they will be cut or moved accordingly + * + * Known Issue: If a splice causes any merged cells to move, the results may be unpredictable + * + * Also: If the worksheet has more rows than values in the colulmn inserts, + * the rows will still be shifted as if the values existed + */ + spliceColumns(start: number, count: number, ...insert: any[][]): void; + + /** + * Cut one or more rows (rows below are shifted up) + * and optionally insert more + * + * Known Issue: If a splice causes any merged cells to move, the results may be unpredictable + */ + spliceRows(start: number, count: number, ...insert: any[][]): void; + + /** + * Add a couple of Rows by key-value, after the last current row, using the column keys, + * or add a row by contiguous Array (assign to columns A, B & C) + */ + addRow(data: any[] | any): Row; + + /** + * Add multiple rows by providing an array of arrays or key-value pairs + */ + addRows(rows: any[]): void; /** * Get or create row by 0-based index */ getRow(index: number): Row; + + /** + * Iterate over all rows that have values in a worksheet + */ eachRow(callback: (row: Row, rowNumber: number) => void): void; + /** + * Iterate over all rows (including empty rows) in a worksheet + */ + eachRow(opt: { includeEmpty: boolean }, callback: (row: Row, rowNumber: number) => void): void; + /** * Get or create cell */ @@ -194,38 +824,222 @@ export interface Worksheet { /** * Merge cells, either: - * tlbr string - * tl string, br string - * t, l, b, r numbers + * + * tlbr string, e.g. `'A4:B5'` + * + * tl string, br string, e.g. `'G10', 'H11'` + * + * t, l, b, r numbers, e.g. `10,11,12,13` */ mergeCells(a: number | string, b?: number | string, c?: number, d?: number): void; + + /** + * unmerging the cells breaks the style links + */ + unMergeCells(cell: string): void; + + /** + * Using the image id from `Workbook.addImage`, set the background to the worksheet + */ + addBackgroundImage(imageId: string): void; + + /** + * Using the image id from `Workbook.addImage`, + * embed an image within the worksheet to cover a range + */ + addImage(imageId: string, range: string | ImageRange): void; + + /** + * Commit a completed worksheet to stream + */ + commit(): void; +} + +export interface WorksheetProperties { + /** + * Color of the tab + */ + tabColor?: Color; + + /** + * The worksheet column outline level (default: 0) + */ + outlineLevelCol?: number; + + /** + * The worksheet row outline level (default: 0) + */ + outlineLevelRow?: number; + + /** + * Default row height (default: 15) + */ + defaultRowHeight?: number; + + /** + * default: 55 + */ + dyDescent?: number; +} + +export interface AddWorksheetOptions { + properties?: WorksheetProperties; + pageSetup?: PageSetup; + views?: WorksheetView[]; +} + +export interface WorkbookProperties { + /** + * Set workbook dates to 1904 date system + */ + date1904: boolean; } export interface Xlsx { + /** + * read from a file + */ readFile(path: string): Promise; + + /** + * Create input stream for reading + */ + createInputStream(): Writable; + + /** + * write to a file + */ writeFile(path: string): Promise; + + /** + * write to a stream + */ + write(stream: Stream): Promise; } -export interface WorksheetProps { - showGridLines: boolean; +export interface CsvReadOptions { + dateFormats?: string[]; + map?(value: any, index: number): any; +} + +export interface CsvWriteOptions { + dateFormat?: string; +} + +export interface Csv { + /** + * read from a file + */ + readFile(path: string, options?: CsvReadOptions): Promise; + + /** + * read from a stream + */ + read(stream: Stream, options?: CsvReadOptions): Promise; + + /** + * Create input stream for reading + */ + createInputStream(): Writable; + + /** + * write to a file + */ + writeFile(path: string, options?: CsvWriteOptions): Promise; + + /** + * write to a stream + */ + write(stream: Stream, options?: CsvWriteOptions): Promise; } export class Workbook { - constructor(); - creator: string; lastModifiedBy: string; created: Date; modified: Date; lastPrinted: Date; - properties: { - date1904: boolean; - }; + properties: WorkbookProperties; + + /** + * xlsx file format operations + */ + readonly xlsx: Xlsx; + + /** + * csv file format operations + */ + readonly csv: Csv; + + /** + * The Workbook views controls how many separate windows Excel will open when viewing the workbook. + */ views: WorkbookView[]; - addWorksheet(name: string, opts?: { properties?: WorksheetProps, views?: WorksheetView[] }): Worksheet; + /** + * The list of worksheets added to this workbook + */ + worksheets: Worksheet[]; + /** + * Add a new worksheet and return a reference to it + */ + addWorksheet(name: string, options?: AddWorksheetOptions): Worksheet; + + /** + * fetch sheet by name or id + */ getWorksheet(indexOrName: number | string): Worksheet; - xlsx: Xlsx; + /** + * Iterate over all sheets. + * + * Note: `workbook.worksheets.forEach` will still work but this is better. + */ + eachSheet(callback: (worksheet: Worksheet, id: number) => void): void; + + /** + * Add Image to Workbook and return the id + */ + addImage(img: Image): string; + + /** + * Commit a completed workbook to stream and close the stream + */ + commit(): Promise; +} + +export namespace config { + function setValue(key: 'promise', promise: any): void; +} + +export namespace stream { + namespace xlsx { + interface WorkbookWriterOptions { + /** + * Specifies a writable stream to write the XLSX workbook to. + */ + stream?: Stream; + + /** + * If stream not specified, this field specifies the path to a file to write the XLSX workbook to. + */ + filename?: string; + + /** + * Specifies whether to use shared strings in the workbook. Default is false + */ + useSharedStrings?: boolean; + + /** + * Specifies whether to add style information to the workbook. + * Styles can add some performance overhead. Default is false + */ + useStyles?: boolean; + } + + class WorkbookWriter extends Workbook { + constructor(options: WorkbookWriterOptions); + } + } } diff --git a/types/execa/execa-tests.ts b/types/execa/execa-tests.ts index fd7428d1ae..abdbfd6dad 100644 --- a/types/execa/execa-tests.ts +++ b/types/execa/execa-tests.ts @@ -54,6 +54,15 @@ execa.shell('echo unicorns') execa('echo', ['unicorns']).stdout.pipe(process.stdout); execa('echo', ['unicorns']).stderr.pipe(process.stderr); +execa('forever', {extendEnv: false}).pid; +execa('forever', {argv0: 'hi'}).pid; +execa('forever', {localDir: '~'}).pid; +execa('forever', {reject: false}).pid; +execa('forever', {cleanup: false}).pid; +execa('forever', {stdin: 1}).pid; +execa('forever', {stdout: 'ignore'}).pid; +execa('forever', {stderr: undefined}).pid; + async () => { const { stdout } = await execa('noop', ['foo'], { stripEof: false }); assert(stdout === 'foo\n'); diff --git a/types/execa/index.d.ts b/types/execa/index.d.ts index df868e4d15..df2c0d9d83 100644 --- a/types/execa/index.d.ts +++ b/types/execa/index.d.ts @@ -1,21 +1,33 @@ -// Type definitions for execa 0.6 +// Type definitions for execa 0.7 // Project: https://github.com/sindresorhus/execa#readme // Definitions by: Douglas Duteil +// BendingBender // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped // TypeScript Version: 2.3 /// -import { ExecOptions, SpawnOptions, SpawnSyncOptions, SpawnSyncReturns, ChildProcess } from "child_process"; +import { ChildProcess, ExecOptions, SpawnOptions, SpawnSyncOptions } from "child_process"; import { Stream } from 'stream'; +type StdIOOption = 'pipe' | 'ipc' | 'ignore' | number | Stream | undefined | null; + interface ExecaOptions { input: string | Buffer | Stream; preferLocal: boolean; stripEof: boolean; + extendEnv: boolean; + argv0: string; + localDir: string; + reject: boolean; + cleanup: boolean; + stdin: StdIOOption; + stdout: StdIOOption; + stderr: StdIOOption; } type Options = SpawnOptions & ExecaOptions & ExecOptions; +type SyncOptions = SpawnSyncOptions & ExecaOptions & ExecOptions; interface ExecaReturns { cmd: string; @@ -42,10 +54,10 @@ declare namespace execa { function stdout(file: string, args?: string[], options?: Partial): Promise; function stderr(file: string, options?: Partial): Promise; function stderr(file: string, args?: string[], options?: Partial): Promise; - function shell(command: string, options?: SpawnOptions): ExecaChildProcess; - function sync(file: string, options?: SpawnSyncOptions): ExecaReturns; - function sync(file: string, args?: string[], options?: SpawnSyncOptions): ExecaReturns; - function shellSync(command: string, options?: SpawnOptions): ExecaReturns; + function shell(command: string, options?: Partial): ExecaChildProcess; + function sync(file: string, options?: Partial): ExecaReturns; + function sync(file: string, args?: string[], options?: Partial): ExecaReturns; + function shellSync(command: string, options?: Partial): ExecaReturns; } export = execa; diff --git a/types/expect/expect-tests.ts b/types/expect/expect-tests.ts index 6238a63c60..41bdbe5581 100644 --- a/types/expect/expect-tests.ts +++ b/types/expect/expect-tests.ts @@ -1,6 +1,6 @@ /// -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', () => { diff --git a/types/express-jwt/express-jwt-tests.ts b/types/express-jwt/express-jwt-tests.ts index 190c85ce4b..798818b728 100644 --- a/types/express-jwt/express-jwt-tests.ts +++ b/types/express-jwt/express-jwt-tests.ts @@ -17,4 +17,15 @@ var jwtCheck = jwt({ secret: 'shhhhhhared-secret' }); jwtCheck.unless = unless; -app.use(jwtCheck.unless({ path: '/api/login' })); \ No newline at end of file +app.use(jwtCheck.unless({ path: '/api/login' })); + +app.use(function (err: any, req: express.Request, res: express.Response, next: express.NextFunction) { + if (err) { + if (err instanceof jwt.UnauthorizedError) { + res.status(err.status); + res.end(); + } + } else { + next(err); + } +}); \ No newline at end of file diff --git a/types/express-jwt/index.d.ts b/types/express-jwt/index.d.ts index d75dfa9adf..ec7aeb64f7 100644 --- a/types/express-jwt/index.d.ts +++ b/types/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 , Kacper Polak +// Definitions by: Wonshik Kim , Kacper Polak , Sl1MBoy // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped import express = require('express'); @@ -36,6 +36,14 @@ declare namespace jwt { export interface RequestHandler extends express.RequestHandler { unless: typeof unless; } + + export class UnauthorizedError extends Error { + name: string; + message: string; + code: string; + status: number; + inner: Error + } } declare global { namespace Express { diff --git a/types/express-session/index.d.ts b/types/express-session/index.d.ts index 24c59db29d..60dedea20a 100644 --- a/types/express-session/index.d.ts +++ b/types/express-session/index.d.ts @@ -12,7 +12,7 @@ import node = require('events'); declare global { namespace Express { interface Request { - session: Session; + session?: Session; sessionID?: string; } diff --git a/types/falcor-express/index.d.ts b/types/falcor-express/index.d.ts index b149df75b9..c8a65e9f6c 100644 --- a/types/falcor-express/index.d.ts +++ b/types/falcor-express/index.d.ts @@ -7,6 +7,6 @@ -import {Request, Response, Handler} from 'express'; +import { Request, Response, Handler } from 'express'; import {DataSource} from 'falcor'; declare function dataSourceRoute(getDataSource: (req: Request, res: Response) => DataSource): Handler; diff --git a/types/falcor-http-datasource/falcor-http-datasource-tests.ts b/types/falcor-http-datasource/falcor-http-datasource-tests.ts index b341274a19..e014706df1 100644 --- a/types/falcor-http-datasource/falcor-http-datasource-tests.ts +++ b/types/falcor-http-datasource/falcor-http-datasource-tests.ts @@ -1,5 +1,5 @@ import HttpDataSource from 'falcor-http-datasource'; -import {Model} from 'falcor'; +import { Model } from 'falcor'; const model = new Model({ source: new HttpDataSource('/model.json') diff --git a/types/falcor-json-graph/falcor-json-graph-tests.ts b/types/falcor-json-graph/falcor-json-graph-tests.ts index 992ede0053..1b082c4720 100644 --- a/types/falcor-json-graph/falcor-json-graph-tests.ts +++ b/types/falcor-json-graph/falcor-json-graph-tests.ts @@ -1,6 +1,6 @@ -import {Key, KeySet, Path, PathSet, ref, atom, error, pathValue, pathInvalidation} from 'falcor-json-graph'; +import { Key, KeySet, Path, PathSet, ref, atom, error, pathValue, pathInvalidation } from 'falcor-json-graph'; const stringKey: Key = "productsById"; const numberKey: Key = 10; diff --git a/types/fast-diff/fast-diff-tests.ts b/types/fast-diff/fast-diff-tests.ts new file mode 100644 index 0000000000..3177bfa7fc --- /dev/null +++ b/types/fast-diff/fast-diff-tests.ts @@ -0,0 +1,16 @@ +import fastDiff = require('fast-diff'); + +let diffs: fastDiff.Diff[]; +diffs = fastDiff("hi there", "hi"); +diffs = fastDiff("hi there", "hi", 1); + +diffs.forEach((diff: fastDiff.Diff) => { + const operation: number = diff[0]; + const text: string = diff[1]; + + switch (diff[0]) { + case fastDiff.EQUAL: break; + case fastDiff.DELETE: break; + case fastDiff.INSERT: break; + } +}); diff --git a/types/fast-diff/index.d.ts b/types/fast-diff/index.d.ts new file mode 100644 index 0000000000..1f306a6e9d --- /dev/null +++ b/types/fast-diff/index.d.ts @@ -0,0 +1,16 @@ +// Type definitions for fast-diff 1.1 +// Project: https://github.com/jhchen/fast-diff#readme +// Definitions by: John Renner +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +declare function diff(text1: string, text2: string, cursorPos?: number): diff.Diff[]; + +declare namespace diff { + type Diff = [-1 | 0 | 1, string]; + + const DELETE: -1; + const INSERT: 1; + const EQUAL: 0; +} + +export = diff; diff --git a/types/fast-diff/tsconfig.json b/types/fast-diff/tsconfig.json new file mode 100644 index 0000000000..e89403e0ef --- /dev/null +++ b/types/fast-diff/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", + "fast-diff-tests.ts" + ] +} diff --git a/types/fast-diff/tslint.json b/types/fast-diff/tslint.json new file mode 100644 index 0000000000..3db14f85ea --- /dev/null +++ b/types/fast-diff/tslint.json @@ -0,0 +1 @@ +{ "extends": "dtslint/dt.json" } diff --git a/types/figures/figures-tests.ts b/types/figures/figures-tests.ts new file mode 100644 index 0000000000..f2c25bbe4b --- /dev/null +++ b/types/figures/figures-tests.ts @@ -0,0 +1,5 @@ +import figures = require('figures'); + +let str: string; +str = figures('✔︎ check'); +str = figures.tick; diff --git a/types/figures/index.d.ts b/types/figures/index.d.ts new file mode 100644 index 0000000000..2867326034 --- /dev/null +++ b/types/figures/index.d.ts @@ -0,0 +1,67 @@ +// Type definitions for figures 2.0 +// Project: https://github.com/sindresorhus/figures#readme +// Definitions by: BendingBender +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +export = figures; + +declare function figures(input: string): string; + +declare namespace figures { + const tick: string; + const cross: string; + const star: string; + const square: string; + const squareSmall: string; + const squareSmallFilled: string; + const play: string; + const circle: string; + const circleFilled: string; + const circleDotted: string; + const circleDouble: string; + const circleCircle: string; + const circleCross: string; + const circlePipe: string; + const circleQuestionMark: string; + const bullet: string; + const dot: string; + const line: string; + const ellipsis: string; + const pointer: string; + const pointerSmall: string; + const info: string; + const warning: string; + const hamburger: string; + const smiley: string; + const mustache: string; + const heart: string; + const arrowUp: string; + const arrowDown: string; + const arrowLeft: string; + const arrowRight: string; + const radioOn: string; + const radioOff: string; + const checkboxOn: string; + const checkboxOff: string; + const checkboxCircleOn: string; + const checkboxCircleOff: string; + const questionMarkPrefix: string; + const oneHalf: string; + const oneThird: string; + const oneQuarter: string; + const oneFifth: string; + const oneSixth: string; + const oneSeventh: string; + const oneEighth: string; + const oneNinth: string; + const oneTenth: string; + const twoThirds: string; + const twoFifths: string; + const threeQuarters: string; + const threeFifths: string; + const threeEighths: string; + const fourFifths: string; + const fiveSixths: string; + const fiveEighths: string; + const sevenEighth: string; +} diff --git a/types/figures/tsconfig.json b/types/figures/tsconfig.json new file mode 100644 index 0000000000..595779c25d --- /dev/null +++ b/types/figures/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", + "figures-tests.ts" + ] +} diff --git a/types/figures/tslint.json b/types/figures/tslint.json new file mode 100644 index 0000000000..3db14f85ea --- /dev/null +++ b/types/figures/tslint.json @@ -0,0 +1 @@ +{ "extends": "dtslint/dt.json" } diff --git a/types/file-saver/file-saver-tests.ts b/types/file-saver/file-saver-tests.ts index c76815a6fb..1cc06f58ba 100644 --- a/types/file-saver/file-saver-tests.ts +++ b/types/file-saver/file-saver-tests.ts @@ -1,6 +1,6 @@ -import {saveAs as importedSaveAs} from "file-saver"; +import { saveAs as importedSaveAs } from "file-saver"; function testImportedSaveAs() { var data: Blob = new Blob(["Hello, world!"], {type: "text/plain;charset=utf-8"}); var filename: string = 'hello world.txt'; diff --git a/types/file-type/file-type-tests.ts b/types/file-type/file-type-tests.ts index 1ce0bf6bdf..ecfd658a1a 100644 --- a/types/file-type/file-type-tests.ts +++ b/types/file-type/file-type-tests.ts @@ -1,5 +1,4 @@ -"use strict"; +import fileType = require("file-type"); -import fileType = require("file-type") - -fileType(new Buffer([0xFF, 0xD8, 0xFF])) +fileType(new Buffer([0xFF, 0xD8, 0xFF])); +fileType(new Uint8Array([0xFF, 0xD8, 0xFF])); diff --git a/types/file-type/index.d.ts b/types/file-type/index.d.ts index 3a88fe0a94..95217430eb 100644 --- a/types/file-type/index.d.ts +++ b/types/file-type/index.d.ts @@ -1,16 +1,17 @@ -// Type definitions for file-type +// Type definitions for file-type 5.2 // Project: https://github.com/sindresorhus/file-type // Definitions by: KIM Jaesuck a.k.a. gim tcaesvk -// Definitions: https://github.com/DefinitelyType/DefinitelyTyped +// BendingBender +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped /// export = FileType; -declare function FileType(buf: Buffer): FileType.FileTypeResult; +declare function FileType(buf: Buffer | Uint8Array): FileType.FileTypeResult; declare namespace FileType { - export interface FileTypeResult { + interface FileTypeResult { ext: string; mime: string; } diff --git a/types/file-type/tslint.json b/types/file-type/tslint.json new file mode 100644 index 0000000000..3db14f85ea --- /dev/null +++ b/types/file-type/tslint.json @@ -0,0 +1 @@ +{ "extends": "dtslint/dt.json" } diff --git a/types/filenamify/filenamify-tests.ts b/types/filenamify/filenamify-tests.ts new file mode 100644 index 0000000000..212ff424cf --- /dev/null +++ b/types/filenamify/filenamify-tests.ts @@ -0,0 +1,10 @@ +import * as filenamify from 'filenamify'; + +filenamify(''); +// => 'foo!bar' + +filenamify('foo:"bar"', {replacement: '🐴'}); +// => 'foo🐴bar' + +filenamify.path('/some/!path'); +// => '/some/path' diff --git a/types/filenamify/index.d.ts b/types/filenamify/index.d.ts new file mode 100644 index 0000000000..981b04443d --- /dev/null +++ b/types/filenamify/index.d.ts @@ -0,0 +1,15 @@ +// Type definitions for filenamify 2.0 +// Project: https://github.com/sindresorhus/filenamify +// Definitions by: Junyoung Choi +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +declare function filenamify(input: string, options?: filenamify.Options): string; + +declare namespace filenamify { + interface Options { + replacement: string; + } + function path(input: string, options?: filenamify.Options): string; +} + +export = filenamify; diff --git a/types/filenamify/tsconfig.json b/types/filenamify/tsconfig.json new file mode 100644 index 0000000000..aec1f33988 --- /dev/null +++ b/types/filenamify/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", + "filenamify-tests.ts" + ] +} diff --git a/types/filenamify/tslint.json b/types/filenamify/tslint.json new file mode 100644 index 0000000000..f93cf8562a --- /dev/null +++ b/types/filenamify/tslint.json @@ -0,0 +1,3 @@ +{ + "extends": "dtslint/dt.json" +} diff --git a/types/finalhandler/finalhandler-tests.ts b/types/finalhandler/finalhandler-tests.ts index af3550a4f4..81b9565404 100644 --- a/types/finalhandler/finalhandler-tests.ts +++ b/types/finalhandler/finalhandler-tests.ts @@ -1,5 +1,5 @@ -import {ServerRequest, ServerResponse} from "http"; +import { ServerRequest, ServerResponse } from "http"; import * as finalHandler from "finalhandler"; let req: ServerRequest; diff --git a/types/finalhandler/index.d.ts b/types/finalhandler/index.d.ts index a238c0d2a5..baad707772 100644 --- a/types/finalhandler/index.d.ts +++ b/types/finalhandler/index.d.ts @@ -5,7 +5,7 @@ /// -import {ServerRequest, ServerResponse} from "http"; +import { ServerRequest, ServerResponse } from "http"; declare function finalHandler(req: ServerRequest, res: ServerResponse, options?: finalHandler.Options): (err: any) => void; diff --git a/types/fixed-data-table/fixed-data-table-tests.tsx b/types/fixed-data-table/fixed-data-table-tests.tsx index 96c17a4a9a..cdbd46eb6c 100644 --- a/types/fixed-data-table/fixed-data-table-tests.tsx +++ b/types/fixed-data-table/fixed-data-table-tests.tsx @@ -1,5 +1,5 @@ import * as React from "react"; -import {Table, Cell, Column, CellProps} from "fixed-data-table"; +import { Table, Cell, Column, CellProps } from "fixed-data-table"; // create your Table class MyTable1 extends React.Component { diff --git a/types/flake-idgen/index.d.ts b/types/flake-idgen/index.d.ts index 39be5999b9..530b96b3ca 100644 --- a/types/flake-idgen/index.d.ts +++ b/types/flake-idgen/index.d.ts @@ -14,6 +14,8 @@ interface ConstructorOptions { seqMask?: number; } +declare namespace FlakeId {} + declare class FlakeId { constructor(options?: ConstructorOptions); next(callback?: (err: Error, id: Buffer) => void): Buffer; diff --git a/types/flat/flat-tests.ts b/types/flat/flat-tests.ts index 68699326c3..324ee3bb14 100644 --- a/types/flat/flat-tests.ts +++ b/types/flat/flat-tests.ts @@ -1,6 +1,6 @@ -import {flatten, unflatten} from "flat"; +import { flatten, unflatten } from "flat"; namespace TestFlatten { let options: { diff --git a/types/form-data/form-data-tests.ts b/types/form-data/form-data-tests.ts index 93457df3be..526fb5bce9 100644 --- a/types/form-data/form-data-tests.ts +++ b/types/form-data/form-data-tests.ts @@ -1,5 +1,3 @@ -/// - import FormData = require('form-data'); import fs = require('fs'); import http = require('http'); @@ -8,43 +6,45 @@ import fetch from 'node-fetch'; import * as ImportUsingES6Syntax from 'form-data'; -() => { - var form = new FormData(); +(() => { + const form = new FormData(); form.append('my_field', 'my value'); form.append('my_buffer', new Buffer(10)); form.append('my_file', fs.createReadStream('/foo/bar.jpg')); -} -() => { - var form = new FormData(); + const num: number = form.getLengthSync(); + const bool: boolean = form.hasKnownLength(); +})(); - http.request({ path: 'http://nodejs.org/images/logo.png' }, function (response) { +(() => { + const form = new FormData(); + + http.request({ path: 'http://nodejs.org/images/logo.png' }, response => { form.append('my_field', 'my value'); form.append('my_buffer', new Buffer(10)); form.append('my_logo', response); }); -} +})(); -() => { - var form = new FormData(); +(() => { + const form = new FormData(); form.append('my_field', 'my value'); form.append('my_buffer', new Buffer(10)); form.append('my_logo', request('http://nodejs.org/images/logo.png')); -} +})(); -() => { - var form = new FormData(); - form.submit('http://example.org/', function (err, res) { +(() => { + const form = new FormData(); + form.submit('http://example.org/', (err, res) => { // res – response object (http.IncomingMessage) // res.resume(); }); -} +})(); - -() => { - var form = new FormData(); - var request = http.request({ +(() => { + const form = new FormData(); + const request = http.request({ method: 'post', host: 'example.org', path: '/upload', @@ -53,89 +53,86 @@ import * as ImportUsingES6Syntax from 'form-data'; form.pipe(request); - request.on('response', function (res: any) { + request.on('response', res => { console.log(res.statusCode); }); -} +})(); - -() => { - var form = new FormData(); - form.submit('example.org/upload', function (err, res) { +(() => { + const form = new FormData(); + form.submit('example.org/upload', (err, res) => { + const r: http.IncomingMessage = res; console.log(res.statusCode); }); -} +})(); -() => { - var CRLF = '\r\n'; - var form = new FormData(); - var buffer = new Buffer(''); +(() => { + const CRLF = '\r\n'; + const form = new FormData(); + const buffer = new Buffer(''); - var options = { + const options = { header: CRLF + '--' + form.getBoundary() + CRLF + 'X-Custom-Header: 123' + CRLF + CRLF, knownLength: 1 }; form.append('my_buffer', buffer, options); - form.submit('http://example.com/', function (err, res) { + form.submit('http://example.com/', (err, res) => { if (err) throw err; console.log('Done'); }); -} +})(); -() => { - var form = new FormData(); +(() => { + const form = new FormData(); form.submit({ host: 'example.com', path: '/probably.php?extra=params', auth: 'username:password' - }, function (err, res) { + }, (err, res) => { console.log(res.statusCode); }); -} +})(); -() => { - var form = new FormData(); +(() => { + const form = new FormData(); form.submit({ host: 'example.com', path: '/surelynot.php', headers: { 'x-test-header': 'test-header-value' } - }, function (err, res) { + }, (err, res) => { console.log(res.statusCode); }); -} +})(); -() => { - var formData = { +(() => { + const formData = { my_field: 'my_value', my_file: fs.createReadStream(__dirname + '/unicycle.jpg'), }; - request.post({ url: 'http://service.com/upload', formData: formData }, function (err, httpResponse, body) { + request.post({ url: 'http://service.com/upload', formData }, (err, httpResponse, body) => { if (err) { return console.error('upload failed:', err); } console.log('Upload successful! Server responded with:', body); }); -} +})(); -() => { - var form = new FormData(); +(() => { + const form = new FormData(); form.append('a', 1); fetch('http://example.com', { method: 'POST', body: form }) - .then(function (res) { - return res.json(); - }).then(function (json) { + .then(res => res.json()) + .then(json => { console.log(json); }); -} +})(); -() => { - var form = new FormData(); - form.getLength((err: Error, length: number): void => { - // nothing - }); -} +(() => { + const form = new FormData(); + form.getLength((err: Error, length: number): void => {}); +})(); diff --git a/types/form-data/index.d.ts b/types/form-data/index.d.ts index e4bd6ca2e1..9b102b287f 100644 --- a/types/form-data/index.d.ts +++ b/types/form-data/index.d.ts @@ -1,26 +1,42 @@ -// Type definitions for form-data -// Project: https://github.com/felixge/node-form-data -// Definitions by: Carlos Ballesteros Velasco , Leon Yu +// Type definitions for form-data 2.2 +// Project: https://github.com/form-data/form-data +// Definitions by: Carlos Ballesteros Velasco +// Leon Yu +// BendingBender // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped // Imported from: https://github.com/soywiz/typescript-node-definitions/form-data.d.ts /// +import * as stream from 'stream'; +import * as http from 'http'; export = FormData; -import * as stream from "stream"; - declare class FormData extends stream.Readable { - append(key: string, value: any, options?: any): void; - getHeaders(): FormData.Dictionary; - submit(params: string | Object, callback: (error: any, response: any) => void): any; + append(key: string, value: any, options?: FormData.AppendOptions | string): void; + getHeaders(): FormData.Headers; + submit(params: string | FormData.SubmitOptions, callback?: (error: Error | undefined, response: http.IncomingMessage) => void): http.ClientRequest; getBoundary(): string; - getLength(callback: (err: Error, length: number) => void): void; + getLength(callback: (err: Error | undefined, length: number) => void): void; + getLengthSync(): number; + hasKnownLength(): boolean; } declare namespace FormData { - interface Dictionary { - [key: string]: T; + interface Headers { + [key: string]: any; + } + + interface AppendOptions { + header?: string | Headers; + knownLength?: number; + filename?: string; + filepath?: string; + contentType?: string; + } + + interface SubmitOptions extends http.RequestOptions { + protocol?: 'https:' | 'http:'; } } diff --git a/types/form-data/tslint.json b/types/form-data/tslint.json new file mode 100644 index 0000000000..3db14f85ea --- /dev/null +++ b/types/form-data/tslint.json @@ -0,0 +1 @@ +{ "extends": "dtslint/dt.json" } diff --git a/types/from2/from2-tests.ts b/types/from2/from2-tests.ts new file mode 100644 index 0000000000..8ad402c2ed --- /dev/null +++ b/types/from2/from2-tests.ts @@ -0,0 +1,75 @@ +import from = require('from2'); + +function fromString(str: string) { + return from((size, next) => { + if (str.length <= 0) { + return next(null, null); + } + + const chunk = str.slice(0, size); + str = str.slice(size); + + next(null, chunk); + }); +} + +fromString('hello world').pipe(process.stdout); + +let stream: NodeJS.ReadableStream; +stream = from((size, next) => next(null, 'foo')); +stream = from((size, next) => next(null, new Buffer(1))); +stream = from((size, next) => next(null, new Uint8Array(1))); +stream = from((size, next) => next(null, null)); +stream = from(['foo', new Buffer(1), new Uint8Array(1), null]); +// following should fail: +// stream = from((size, next) => next(null, {})); + +stream = from({objectMode: false}, (size, next) => next(null, 'foo')); +stream = from({objectMode: false}, (size, next) => next(null, new Buffer(1))); +stream = from({objectMode: false}, (size, next) => next(null, new Uint8Array(1))); +stream = from({objectMode: false}, (size, next) => next(null, null)); +stream = from({objectMode: false}, ['foo', new Buffer(1), new Uint8Array(1), null]); +// following should fail: +// stream = from({objectMode: false}, (size, next) => next(null, {})); + +stream = from({highWaterMark: 1}, (size, next) => next(null, 'foo')); +stream = from({highWaterMark: 1}, (size, next) => next(null, new Buffer(1))); +stream = from({highWaterMark: 1}, (size, next) => next(null, new Uint8Array(1))); +stream = from({highWaterMark: 1}, (size, next) => next(null, null)); +stream = from({highWaterMark: 1}, ['foo', new Buffer(1), new Uint8Array(1), null]); +// following should fail: +// stream = from({highWaterMark: 1}, (size, next) => next(null, {})); + +stream = from({objectMode: true}, (size, next) => next(null, {})); +stream = from({objectMode: true}, (size, next) => next(null, null)); +stream = from({objectMode: true}, [1, 'foo', {}, null]); + +stream = from.obj((size, next) => next(null, {})); +stream = from.obj((size, next) => next(null, null)); +stream = from.obj([1, 'foo', {}, null]); + +stream = from.obj({objectMode: true}, (size, next) => next(null, {})); +stream = from.obj({objectMode: true}, (size, next) => next(null, null)); +stream = from.obj({objectMode: true}, [1, 'foo', {}, null]); +// following should fail: +// stream = from.obj({objectMode: false}, [1, 'foo', {}, null]); +stream = from.obj({highWaterMark: 1}, (size, next) => next(null, {})); +stream = from.obj({highWaterMark: 1}, (size, next) => next(null, null)); +stream = from.obj({highWaterMark: 1}, [1, 'foo', {}, null]); + +let Ctor: from.From2Ctor; +Ctor = from.ctor({objectMode: false}); +Ctor = from.ctor(); +stream = new Ctor((size, next) => next(null, 'foo')); +stream = new Ctor((size, next) => next(null, new Buffer(1))); +stream = new Ctor((size, next) => next(null, new Uint8Array(1))); +stream = new Ctor((size, next) => next(null, null)); +stream = new Ctor(['foo', new Buffer(1), new Uint8Array(1), null]); +// following should fail: +// stream = new Ctor((size, next) => next(null, {})); + +let Ctor2: from.From2Ctor; +Ctor2 = from.ctor({objectMode: true}); +stream = new Ctor2((size, next) => next(null, {})); +stream = new Ctor2((size, next) => next(null, null)); +stream = new Ctor2([1, 'foo', {}, null]); diff --git a/types/from2/index.d.ts b/types/from2/index.d.ts new file mode 100644 index 0000000000..59872471b9 --- /dev/null +++ b/types/from2/index.d.ts @@ -0,0 +1,33 @@ +// Type definitions for from2 2.3 +// Project: https://github.com/hughsk/from2 +// Definitions by: BendingBender +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +/// +import * as stream from 'stream'; + +export = from2; + +declare function from2(read: from2.ReadInput): NodeJS.ReadableStream; +declare function from2(opts: from2.ObjectModeOptions, read: from2.ReadObjectInput): NodeJS.ReadableStream; +declare function from2(opts: from2.Options, read: from2.ReadInput): NodeJS.ReadableStream; + +declare namespace from2 { + function obj(read: ReadObjectInput): NodeJS.ReadableStream; + function obj(opts: { objectMode?: true } & stream.ReadableOptions, read: ReadObjectInput): NodeJS.ReadableStream; + + function ctor(opts?: Options): From2Ctor; + function ctor(opts: ObjectModeOptions): From2Ctor; + + type ObjectModeOptions = { objectMode: true } & stream.ReadableOptions; + type Options = { objectMode?: false } & stream.ReadableOptions; + + type From2Ctor = new(read: R) => NodeJS.ReadableStream; + + type ReadObjectInput = ReadCallback | any[]; + type ReadInput = ReadCallback | Chunk[]; + type ReadCallback = (size: number, next: N) => void; + type NextCallback = (err: any | undefined, chunk: Chunk) => void; + type NextObjectCallback = (err: any | undefined, chunk: any) => void; + type Chunk = string | Buffer | Uint8Array | null; +} diff --git a/types/from2/tsconfig.json b/types/from2/tsconfig.json new file mode 100644 index 0000000000..e632fe943f --- /dev/null +++ b/types/from2/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", + "from2-tests.ts" + ] +} diff --git a/types/from2/tslint.json b/types/from2/tslint.json new file mode 100644 index 0000000000..3db14f85ea --- /dev/null +++ b/types/from2/tslint.json @@ -0,0 +1 @@ +{ "extends": "dtslint/dt.json" } diff --git a/types/fs-extra-promise/fs-extra-promise-tests.ts b/types/fs-extra-promise/fs-extra-promise-tests.ts index c50115871b..30794946f3 100644 --- a/types/fs-extra-promise/fs-extra-promise-tests.ts +++ b/types/fs-extra-promise/fs-extra-promise-tests.ts @@ -15,6 +15,7 @@ let path: string; let data: any; let object: object; let buf: Buffer; +let strOrBuf: string | Buffer; let buffer: NodeBuffer; let modeNum: number; let modeStr: string; @@ -167,7 +168,7 @@ fs.readFile(filename, (err: Error, data: NodeBuffer) => { }); buffer = fs.readFileSync(filename); str = fs.readFileSync(filename, encoding); -buf = fs.readFileSync(filename, openOpts); +strOrBuf = fs.readFileSync(filename, openOpts); fs.writeFile(filename, data, errorCallback); fs.writeFile(filename, data, { encoding }, errorCallback); diff --git a/types/fs-extra/fs-extra-tests.ts b/types/fs-extra/fs-extra-tests.ts index 39f3a9d37a..903474e273 100644 --- a/types/fs-extra/fs-extra-tests.ts +++ b/types/fs-extra/fs-extra-tests.ts @@ -1,5 +1,5 @@ -import * as fs from 'fs-extra'; -import * as Path from 'path'; +import * as fs from "fs-extra"; +import * as Path from "path"; const len = 2; const src = ""; @@ -213,6 +213,16 @@ fs.lchmodSync(path, modeStr); fs.statSync(path); fs.lstatSync(path); +fs.read(0, new Buffer(""), 0, 0, null).then(x => { + const a = x.buffer; + const b = x.bytesRead; +}); + +fs.write(0, new Buffer(""), 0, 0, null).then(x => { + const a = x.buffer; + const b = x.bytesWritten; +}); + // $ExpectType Promise fs.writeFile("foo.txt", "i am foo", { encoding: "utf-8" }); diff --git a/types/fs-extra/index.d.ts b/types/fs-extra/index.d.ts index 49a056bce7..0231cac2d2 100644 --- a/types/fs-extra/index.d.ts +++ b/types/fs-extra/index.d.ts @@ -1,4 +1,4 @@ -// Type definitions for fs-extra 3.0 +// Type definitions for fs-extra 4.0 // Project: https://github.com/jprichardson/node-fs-extra // Definitions by: Alan Agius , // midknight41 , @@ -172,7 +172,7 @@ export function open(path: string | Buffer, flags: string | number, mode: number export function open(path: string | Buffer, flags: string | number, mode?: number): Promise; export function read(fd: number, buffer: Buffer, offset: number, length: number, position: number | null, callback: (err: NodeJS.ErrnoException, bytesRead: number, buffer: Buffer) => void): void; -export function read(fd: number, buffer: Buffer, offset: number, length: number, position: number | null): Promise<[number, Buffer]>; +export function read(fd: number, buffer: Buffer, offset: number, length: number, position: number | null): Promise; export function readFile(file: string | Buffer | number, callback: (err: NodeJS.ErrnoException, data: Buffer) => void): void; export function readFile(file: string | Buffer | number, encoding: string, callback: (err: NodeJS.ErrnoException, data: string) => void): void; @@ -233,8 +233,8 @@ export function write(fd: number, buffer: Buffer, offset: number, length: number export function write(fd: number, data: any, callback: (err: NodeJS.ErrnoException, written: number, str: string) => void): void; export function write(fd: number, data: any, offset: number, callback: (err: NodeJS.ErrnoException, written: number, str: string) => void): void; export function write(fd: number, data: any, offset: number, encoding: string, callback: (err: NodeJS.ErrnoException, written: number, str: string) => void): void; -export function write(fd: number, buffer: Buffer, offset: number, length: number, position?: number | null): Promise<[number, Buffer]>; -export function write(fd: number, data: any, offset: number, encoding?: string): Promise<[number, string]>; +export function write(fd: number, buffer: Buffer, offset: number, length: number, position?: number | null): Promise; +export function write(fd: number, data: any, offset: number, encoding?: string): Promise; export function writeFile(file: string | Buffer | number, data: any, callback: (err: NodeJS.ErrnoException) => void): void; export function writeFile(file: string | Buffer | number, data: any, options?: { encoding?: string; mode?: number; flag?: string; }): Promise; @@ -292,3 +292,13 @@ export interface WriteOptions { flag?: string; mode?: number; } + +export interface ReadResult { + bytesRead: number; + buffer: Buffer; +} + +export interface WriteResult { + bytesWritten: number; + buffer: Buffer; +} diff --git a/types/gapi.auth2/gapi.auth2-tests.ts b/types/gapi.auth2/gapi.auth2-tests.ts index 0766f3b914..75d35737df 100644 --- a/types/gapi.auth2/gapi.auth2-tests.ts +++ b/types/gapi.auth2/gapi.auth2-tests.ts @@ -1,7 +1,7 @@ /// function test_init() { - var auth = gapi.auth2.init({ + const auth: gapi.auth2.GoogleAuth = gapi.auth2.init({ client_id: 'my-id', cookie_policy: 'single_host_origin', scope: 'https://www.googleapis.com/auth/plus.login', @@ -14,9 +14,11 @@ function test_getAuthInstance() { client_id: 'my-id', cookie_policy: 'single_host_origin', scope: 'https://www.googleapis.com/auth/plus.login', - fetch_basic_profile: true + fetch_basic_profile: true, + ux_mode: "popup", + redirect_uri: "https://www.example.com" }); - var auth = gapi.auth2.getAuthInstance(); + const auth: gapi.auth2.GoogleAuth = gapi.auth2.getAuthInstance(); } function test_signIn() { @@ -27,7 +29,7 @@ function test_signIn() { } function test_signInOptionsBuild() { - var options = new gapi.auth2.SigninOptionsBuilder(); + const options = new gapi.auth2.SigninOptionsBuilder(); options.setAppPackageName('com.example.app'); options.setFetchBasicProfile(true); options.setPrompt('select_account'); @@ -36,24 +38,24 @@ function test_signInOptionsBuild() { } function test_getAuthResponse() { - var user = gapi.auth2.getAuthInstance().currentUser.get(); - var authResponse = user.getAuthResponse(); - var authResponseWithAuth = user.getAuthResponse(true); + const user: gapi.auth2.GoogleUser = gapi.auth2.getAuthInstance().currentUser.get(); + const authResponse: gapi.auth2.AuthResponse = user.getAuthResponse(); + const authResponseWithAuth: gapi.auth2.AuthResponse = user.getAuthResponse(true); } function test_reloadAuthResponse() { gapi.auth2.getAuthInstance().currentUser.get().reloadAuthResponse() .then(response => { - let token = response.access_token; - let expires_in = response.expires_in - }) + const token: string = response.access_token; + const expires_in: number = response.expires_in; + }); } function test_render() { - var success = (googleUser: gapi.auth2.GoogleUser): void => { + const success = (googleUser: gapi.auth2.GoogleUser): void => { console.log(googleUser); }; - var failure = (): void => { + const failure = (): void => { console.log('Failure callback'); }; @@ -71,7 +73,7 @@ function test_render() { /* Example taken from https://developers.google.com/identity/sign-in/web/ */ function onSignIn(googleUser: gapi.auth2.GoogleUser) { // Useful data for your client-side scripts: - var profile = googleUser.getBasicProfile(); + const profile = googleUser.getBasicProfile(); console.log("ID: " + profile.getId()); // Don't send this directly to your server! console.log('Full Name: ' + profile.getName()); console.log('Given Name: ' + profile.getGivenName()); @@ -80,42 +82,41 @@ function onSignIn(googleUser: gapi.auth2.GoogleUser) { console.log("Email: " + profile.getEmail()); // The ID token you need to pass to your backend: - var id_token = googleUser.getAuthResponse().id_token; + const id_token: string = googleUser.getAuthResponse().id_token; console.log("ID Token: " + id_token); -}; - +} /* Example taken from https://github.com/google/google-api-javascript-client/blob/master/samples/authSample.html */ // Enter an API key from the Google API Console: // https://console.developers.google.com/apis/credentials -var apiKey = 'YOUR_API_KEY'; +const apiKey = 'YOUR_API_KEY'; // Enter the API Discovery Docs that describes the APIs you want to // access. In this example, we are accessing the People API, so we load // Discovery Doc found here: https://developers.google.com/people/api/rest/ -var discoveryDocs = ["https://people.googleapis.com/$discovery/rest?version=v1"]; +const discoveryDocs = ["https://people.googleapis.com/$discovery/rest?version=v1"]; // Enter a client ID for a web application from the Google API Console: // https://console.developers.google.com/apis/credentials?project=_ // In your API Console project, add a JavaScript origin that corresponds // to the domain where you will be running the script. -var clientId = 'YOUR_WEB_CLIENT_ID.apps.googleusercontent.com'; +const clientId = 'YOUR_WEB_CLIENT_ID.apps.googleusercontent.com'; // Enter one or more authorization scopes. Refer to the documentation for // the API or https://developers.google.com/people/v1/how-tos/authorizing // for details. -var scopes = 'profile'; -var authorizeButton = document.getElementById('authorize-button'); -var signoutButton = document.getElementById('signout-button'); +const scopes = 'profile'; +const authorizeButton = document.getElementById('authorize-button'); +const signoutButton = document.getElementById('signout-button'); function handleClientLoad() { // Load the API client and auth2 library gapi.load('client:auth2', initClient); } function initClient() { gapi.client.init({ - apiKey: apiKey, - discoveryDocs: discoveryDocs, - clientId: clientId, + apiKey, + discoveryDocs, + clientId, scope: scopes - }).then(function () { + }).then(() => { // Listen for sign-in state changes. gapi.auth2.getAuthInstance().isSignedIn.listen(updateSigninStatus); // Handle the initial sign-in state. @@ -144,9 +145,9 @@ function handleSignoutClick(event: MouseEvent) { function makeApiCall() { gapi.client.people.people.get({ resourceName: 'people/me' - }).then(function (resp) { - var p = document.createElement('p'); - var name = resp.result.names[0].givenName; + }).then((resp) => { + const p = document.createElement('p'); + const name = resp.result.names[0].givenName; p.appendChild(document.createTextNode('Hello, ' + name + '!')); document.getElementById('content').appendChild(p); }); diff --git a/types/gapi.auth2/index.d.ts b/types/gapi.auth2/index.d.ts index 6e9e5c4199..b1e0e925d4 100644 --- a/types/gapi.auth2/index.d.ts +++ b/types/gapi.auth2/index.d.ts @@ -7,13 +7,12 @@ /// declare namespace gapi.auth2 { - /** * GoogleAuth is a singleton class that provides methods to allow the user to sign in with a Google account, * get the user's current sign-in status, get specific data from the user's Google profile, * request additional scopes, and sign out from the current account. */ - export class GoogleAuth { + class GoogleAuth { isSignedIn: IsSignedIn; currentUser: CurrentUser; @@ -22,15 +21,11 @@ declare namespace gapi.auth2 { * Calls the onInit function when the GoogleAuth object is fully initialized, or calls the onFailure function if * initialization fails. */ - then(onInit: () => any, onFailure?: (reason: string) => any): any; - - /** - * Signs in the user with the options specified to gapi.auth2.init(). - */ - signIn(): any; + then(onInit: (googleAuth: GoogleAuth) => any, onFailure?: (reason: string) => any): any; /** * Signs in the user using the specified options. + * If no option specified here, fallback to the options specified to gapi.auth2.init(). */ signIn(options?: SigninOptions | SigninOptionsBuilder): any; @@ -60,7 +55,7 @@ declare namespace gapi.auth2 { onsuccess: (googleUser: GoogleUser) => any, onfailure: (reason: string) => any): any; } - export interface IsSignedIn { + interface IsSignedIn { /** * Returns whether the current user is currently signed in. */ @@ -72,7 +67,7 @@ declare namespace gapi.auth2 { listen(listener: (signedIn: boolean) => any): void; } - export interface CurrentUser { + interface CurrentUser { /** * Returns a GoogleUser object that represents the current user. Note that in a newly-initialized * GoogleAuth instance, the current user has not been set. Use the currentUser.listen() method or the @@ -86,7 +81,7 @@ declare namespace gapi.auth2 { listen(listener: (user: GoogleUser) => any): void; } - export interface SigninOptions { + interface SigninOptions { /** * The package name of the Android app to install over the air. * See Android app installs from your web site: @@ -112,14 +107,14 @@ declare namespace gapi.auth2 { scope?: string; } - export class SigninOptionsBuilder { + class SigninOptionsBuilder { setAppPackageName(name: string): any; setFetchBasicProfile(fetch: boolean): any; setPrompt(prompt: string): any; setScope(scope: string): any; } - export interface BasicProfile { + interface BasicProfile { getId(): string; getName(): string; getGivenName(): string; @@ -128,7 +123,7 @@ declare namespace gapi.auth2 { getEmail(): string; } - export interface AuthResponse { + interface AuthResponse { access_token: string; id_token: string; login_hint: string; @@ -141,7 +136,7 @@ declare namespace gapi.auth2 { /** * A GoogleUser object represents one user account. */ - export interface GoogleUser { + interface GoogleUser { /** * Get the user's unique ID string. */ @@ -208,52 +203,62 @@ declare namespace gapi.auth2 { disconnect(): void; } + function init(params: { + /** + * The app's client ID, found and created in the Google Developers Console. + */ + client_id?: string; - export function init(params: { - /** - * The app's client ID, found and created in the Google Developers Console. - */ - client_id?: string; + /** + * The domains for which to create sign-in cookies. Either a URI, single_host_origin, or none. + * Defaults to single_host_origin if unspecified. + */ + cookie_policy?: string; - /** - * The domains for which to create sign-in cookies. Either a URI, single_host_origin, or none. - * Defaults to single_host_origin if unspecified. - */ - cookie_policy?: string; + /** + * The scopes to request, as a space-delimited string. Optional if fetch_basic_profile is not set to false. + */ + scope?: string; - /** - * The scopes to request, as a space-delimited string. Optional if fetch_basic_profile is not set to false. - */ - scope?: string; + /** + * Fetch users' basic profile information when they sign in. Adds 'profile' and 'email' to the requested scopes. True if unspecified. + */ + fetch_basic_profile?: boolean; - /** - * Fetch users' basic profile information when they sign in. Adds 'profile' and 'email' to the requested scopes. True if unspecified. - */ - fetch_basic_profile?: boolean; + /** + * The Google Apps domain to which users must belong to sign in. This is susceptible to modification by clients, + * so be sure to verify the hosted domain property of the returned user. Use GoogleUser.getHostedDomain() on the client, + * and the hd claim in the ID Token on the server to verify the domain is what you expected. + */ + hosted_domain?: string; - /** - * The Google Apps domain to which users must belong to sign in. This is susceptible to modification by clients, - * so be sure to verify the hosted domain property of the returned user. Use GoogleUser.getHostedDomain() on the client, - * and the hd claim in the ID Token on the server to verify the domain is what you expected. - */ - hosted_domain?: string; + /** + * Used only for OpenID 2.0 client migration. Set to the value of the realm that you are currently using for OpenID 2.0, + * as described in OpenID 2.0 (Migration). + */ + openid_realm?: string; - /** - * Used only for OpenID 2.0 client migration. Set to the value of the realm that you are currently using for OpenID 2.0, - * as described in OpenID 2.0 (Migration). - */ - openid_realm?: string; + /** + * The UX mode to use for the sign-in flow. + * By default, it will open the consent flow in a popup. + */ + ux_mode?: "popup" | "redirect"; + + /** + * If using ux_mode='redirect', this parameter allows you to override the default redirect_uri that will be used at the end of the consent flow. + * The default redirect_uri is the current URL stripped of query parameters and hash fragment. + */ + redirect_uri?: string; }): GoogleAuth; /** * Returns the GoogleAuth object. You must initialize the GoogleAuth object with gapi.auth2.init() before calling this method. */ - export function getAuthInstance(): GoogleAuth; + function getAuthInstance(): GoogleAuth; } declare namespace gapi.signin2 { - - export function render(id: any, options: { + function render(id: any, options: { /** * The auth scope or scopes to authorize. Auth scopes for individual APIs can be found in their documentation. */ @@ -280,15 +285,14 @@ declare namespace gapi.signin2 { theme?: string; /** - * The callback function to call when a user successfully signs in. - * This function must take one argument: an instance of gapi.auth2.GoogleUser (default: none). + * The callback function to call when a user successfully signs in (default: none). */ - onsuccess?: any; + onsuccess?(user: auth2.GoogleUser): void; /** - * The callback function to call when sign-in fails. This function takes no arguments (default: none). + * The callback function to call when sign-in fails (default: none). */ - onfailure?: any; + onfailure?(): void; /** * The package name of the Android app to install over the air. See diff --git a/types/gapi.auth2/tslint.json b/types/gapi.auth2/tslint.json new file mode 100644 index 0000000000..5cd702e55e --- /dev/null +++ b/types/gapi.auth2/tslint.json @@ -0,0 +1,8 @@ +{ + "extends": "dtslint/dt.json", + "rules": { + "indent": { + "options": [true, "spaces", 2] + } + } +} diff --git a/types/geokdbush/index.d.ts b/types/geokdbush/index.d.ts index 4ece8ff98d..117a1c10e9 100644 --- a/types/geokdbush/index.d.ts +++ b/types/geokdbush/index.d.ts @@ -3,7 +3,7 @@ // Definitions by: Denis Carriere // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -import {KDBush} from 'kdbush'; +import { KDBush } from 'kdbush'; export function around( index: KDBush, diff --git a/types/get-stream/index.d.ts b/types/get-stream/index.d.ts index 9dafe344ae..19c7c6067b 100644 --- a/types/get-stream/index.d.ts +++ b/types/get-stream/index.d.ts @@ -1,18 +1,19 @@ // Type definitions for get-stream 3.0 // Project: https://github.com/sindresorhus/get-stream#readme // Definitions by: Douglas Duteil +// BendingBender // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped /// -import {Stream} from 'stream'; +import { Stream } from 'stream'; interface Options { /** * Encoding of the incoming stream. * @default 'utf8' */ - encoding?: string; + encoding?: BufferEncoding | 'buffer'; /** * Maximum length of the returned string. If it exceeds this value before * the stream ends, the promise will be rejected. @@ -27,8 +28,8 @@ interface Options { * stream, indicating that there is no more data to be read. * The stream is switched to flowing mode. */ -declare function getStrem(stream: Stream, options?: Options): Promise; -declare namespace getStrem { +declare function getStream(stream: Stream, options?: Options): Promise; +declare namespace getStream { /** * Get the `stream` as an array of values. * @@ -58,4 +59,4 @@ declare namespace getStrem { function buffer(stream: Stream, options?: Options): Promise; } -export = getStrem; +export = getStream; diff --git a/types/gl-matrix/gl-matrix-tests.ts b/types/gl-matrix/gl-matrix-tests.ts index 6325ff5cd4..3642cca521 100644 --- a/types/gl-matrix/gl-matrix-tests.ts +++ b/types/gl-matrix/gl-matrix-tests.ts @@ -1,5 +1,5 @@ // common -import {vec2, mat2, mat3, mat4, vec3, vec4, mat2d, quat} from "gl-matrix"; +import { vec2, mat2, mat3, mat4, vec3, vec4, mat2d, quat } from "gl-matrix"; var outVal: number; var outBool: boolean; diff --git a/types/global-tunnel-ng/global-tunnel-ng-tests.ts b/types/global-tunnel-ng/global-tunnel-ng-tests.ts new file mode 100644 index 0000000000..b906e3b56c --- /dev/null +++ b/types/global-tunnel-ng/global-tunnel-ng-tests.ts @@ -0,0 +1,48 @@ +import * as globalTunnel from 'global-tunnel-ng'; + +globalTunnel.initialize({ + host: '10.0.0.10', + port: 8080, + proxyAuth: 'userId:password', // optional authentication + sockets: 50 // optional pool size for each http and https +}); + +globalTunnel.end(); + +globalTunnel.initialize({ + connect: 'neither', + host: '10.0.0.10', + port: 3128 +}); + +globalTunnel.initialize({ + connect: 'neither', + protocol: 'https:', + host: '10.0.0.10', + port: 3129 +}); + +globalTunnel.initialize({ + connect: 'both', + host: '10.0.0.10', + port: 3130 +}); + +globalTunnel.initialize({ + connect: 'both', + protocol: 'https:', + host: '10.0.0.10', + port: 3130, + proxyHttpsOptions: { + // use this config for app -> proxy + }, + originHttpsOptions: { + // use this config for proxy -> origin + } +}); + +globalTunnel.initialize(); + +const proxyUrl: string | null = globalTunnel.proxyUrl; +const proxyConfig: globalTunnel.Options | null = globalTunnel.proxyConfig; +const isProxying: boolean = globalTunnel.isProxying; diff --git a/types/global-tunnel-ng/index.d.ts b/types/global-tunnel-ng/index.d.ts new file mode 100644 index 0000000000..80f73f491f --- /dev/null +++ b/types/global-tunnel-ng/index.d.ts @@ -0,0 +1,23 @@ +// Type definitions for global-tunnel-ng 2.1 +// Project: https://github.com/salesforce/global-tunnel +// Definitions by: BendingBender +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +export function initialize(options?: Options | string): void; + +export function end(): void; + +export const proxyUrl: string | null; +export const proxyConfig: Options | null; +export const isProxying: boolean; + +export interface Options { + host: string; + port: number; + connect?: 'neither' | 'https' | 'both'; + protocol?: 'http:' | 'https:'; + proxyAuth?: string; + sockets?: number; + proxyHttpsOptions?: { [key: string]: any }; + originHttpsOptions?: { [key: string]: any }; +} diff --git a/types/global-tunnel-ng/tsconfig.json b/types/global-tunnel-ng/tsconfig.json new file mode 100644 index 0000000000..fa1974819d --- /dev/null +++ b/types/global-tunnel-ng/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", + "global-tunnel-ng-tests.ts" + ] +} diff --git a/types/global-tunnel-ng/tslint.json b/types/global-tunnel-ng/tslint.json new file mode 100644 index 0000000000..3db14f85ea --- /dev/null +++ b/types/global-tunnel-ng/tslint.json @@ -0,0 +1 @@ +{ "extends": "dtslint/dt.json" } diff --git a/types/gm/gm-tests.ts b/types/gm/gm-tests.ts index 50c124ffc5..2ac631ee55 100644 --- a/types/gm/gm-tests.ts +++ b/types/gm/gm-tests.ts @@ -1,70 +1,68 @@ import gm = require('gm'); import stream = require('stream'); -var src: string; -var matrix: string; -var enable: boolean; -var ltr: boolean; -var password: string; -var bits: number; -var intensity: number; -var r: number; -var g: number; -var b: number; -var opacity: number; -var x: number; -var y: number; -var radius: number; -var sigma: number; -var width: number; -var height: number; -var color: string; -var channel: string; -var type: string; -var factor: number; -var numColors: number; -var operator: string; -var multiplier: number; -var kernel: string; -var usePercent: boolean; -var time: number; -var server: string; -var method: string; -var percent: number; -var encoding: string; -var options: string; -var file: string; -var distance: number; -var geometry: string; -var direction: string; -var name: string; -var offset: number; -var blackPoint: number; -var gamma: number; -var whitePoint: number; -var limit: string; -var format: string; -var iterations: number; -var count: number; -var b: number; -var s: number; -var h: number; -var dest: string; -var images: string[]; -var angle: number; -var NxN: string; -var size: number; -var command: string; -var index: number; -var threshold: number; -var attribute: string; -var attrValue: string; -var format: string; -var font: string; -var quality: number; -var align: string; -var depth: number; -var readStream: stream.PassThrough; +let src: string; +let matrix: string; +let enable: boolean; +let ltr: boolean; +let password: string; +let bits: number; +let intensity: number; +let r: number; +let g: number; +let b: number; +let opacity: number; +let x: number; +let y: number; +let radius: number; +let sigma: number; +let width: number; +let height: number; +let color: string; +let channel: gm.ChannelType; +let type: string; +let factor: number; +let numColors: number; +let operator: string; +let multiplier: number; +let kernel: string; +let usePercent: boolean; +let time: number; +let server: string; +let method: string; +let percent: number; +let encoding: string; +let options: gm.ResizeOption; +let file: string; +let distance: number; +let geometry: string; +let direction: string; +let name: string; +let offset: number; +let blackPoint: number; +let gamma: number; +let whitePoint: number; +let limit: string; +let format: string; +let iterations: number; +let count: number; +let s: number; +let h: number; +let dest: string; +let images: string[]; +let angle: number; +let NxN: string; +let size: number; +let command: string; +let index: number; +let threshold: number; +let attribute: string; +let attrValue: string; +let font: string; +let quality: number; +let align: string; +let depth: number; +let readStream: stream.PassThrough; gm(src) .adjoin() @@ -288,20 +286,36 @@ gm(src) .windowGroup() .color((err, color) => { }) + .color({ bufferStream: true }, (err, color) => { + }) .depth((err, bitdepth) => { }) + .depth({ bufferStream: true }, (err, bitdepth) => { + }) .filesize((err, size) => { }) + .filesize({ bufferStream: true }, (err, size) => { + }) .format((err, format) => { }) + .format({ bufferStream: true }, (err, format) => { + }) .identify((err, info) => { }) + .identify({ bufferStream: true }, (err, info) => { + }) .res((err, resolution) => { }) + .res({ bufferStream: true }, (err, resolution) => { + }) .size((err, size) => { }) + .size({ bufferStream: true }, (err, size) => { + }) .orientation((err, orient) => { }) + .orientation({ bufferStream: true }, (err, orient) => { + }) .draw(options) .drawArc(x, y, x, y, radius, radius) .drawBezier(x, y, x, y) @@ -342,17 +356,16 @@ gm(src).toBuffer((err, buffer) => { gm(src).toBuffer(format, (err, buffer) => { }); -var imageMagick = gm.subClass({ imageMagick: true }); -var readStream = imageMagick(src) +let imageMagick = gm.subClass({ imageMagick: true }); +readStream = imageMagick(src) .adjoin() .stream(); -var passStream = imageMagick(readStream).stream(); +let passStream = imageMagick(readStream).stream(); -var buffers: Buffer[] = []; -var buffer: Buffer; +let buffers: Buffer[] = []; +let buffer: Buffer; passStream.on('data', (chunk) => buffers.push(chunk as Buffer)).on('close', () => { buffer = Buffer.concat(buffers); - var readstream = imageMagick(buffer).stream(); -}) - + let readstream = imageMagick(buffer).stream(); +}); diff --git a/types/gm/index.d.ts b/types/gm/index.d.ts index 8da081ffd5..2cba86936d 100644 --- a/types/gm/index.d.ts +++ b/types/gm/index.d.ts @@ -1,11 +1,10 @@ -// Type definitions for gm 1.17.0 +// Type definitions for gm 1.17 // Project: https://github.com/aheckmann/gm // Definitions by: Joel Spadin // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped /// - import stream = require('stream'); declare function m(image: string): m.State; @@ -14,49 +13,41 @@ declare function m(buffer: Buffer, image?: string): m.State; declare function m(width: number, height: number, color?: string): m.State; declare namespace m { - export interface ClassOptions { + interface ClassOptions { imageMagick?: boolean; nativeAutoOrient?: boolean; } - export interface CompareCallback { - (err: Error, isEqual: boolean, equality: number, raw: number): any; - } - - export interface GetterCallback { - (err: Error, value: T): any; - } - - export interface WriteCallback { - (err: Error, stdout: string, stderr: string, cmd: string): any; - } - - export interface ChannelInfo { + interface ChannelInfo { Red: T; Green: T; Blue: T; } - export interface CompareOptions { + interface CompareOptions { file?: string; highlightColor?: string; highlightStyle?: string; tolerance?: number; } - export interface ColorStatistics { + interface ColorStatistics { Minimum: string; Maximum: string; Mean: string; 'Standard Deviation': string; } - export interface Dimensions { + interface Dimensions { width: number; height: number; } - export interface ImageInfo { + interface GetterOptions { + bufferStream?: boolean; + } + + interface ImageInfo { 'Background Color': string; 'Border Color': string; 'Channel Depths': ChannelInfo; @@ -99,7 +90,7 @@ declare namespace m { Type: string; } - export interface State { + interface State { // Image Operations adjoin(): State; affine(matrix: string): State; @@ -255,19 +246,7 @@ declare namespace m { fuzz(distance: number, percent?: boolean): State; gamma(r: number, g: number, b: number): State; gaussian(radius: number, sigma?: number): State; - /** Width and height are specified in percents */ - geometry(width: number, height: number, option: '%'): State; - /** Specify maximum area in pixels */ - geometry(width: number, height: number, option: '@'): State; - /** Ignore aspect ratio */ - geometry(width: number, height: number, option: '!'): State; - /** Width and height are minimum values */ - geometry(width: number, height: number, option: '^'): State; - /** Change dimensions only if image is smaller than width or height */ - geometry(width: number, height: number, option: '<'): State; - /** Change dimensions only if image is larger than width or height */ - geometry(width: number, height: number, option: '>'): State; - geometry(width: number, height?: number, option?: string): State; + geometry(width: number, height?: number, option?: ResizeOption): State; geometry(geometry: string): State; greenPrimary(x: number, y: number): State; gravity(direction: 'NorthWest'): State; @@ -437,17 +416,7 @@ declare namespace m { process(command: string): State; profile(filename: string): State; progress(): State; - randomThreshold(channelType: 'All', LOWxHIGH: string): State; - randomThreshold(channelType: 'Intensity', LOWxHIGH: string): State; - randomThreshold(channelType: 'Red', LOWxHIGH: string): State; - randomThreshold(channelType: 'Green', LOWxHIGH: string): State; - randomThreshold(channelType: 'Blue', LOWxHIGH: string): State; - randomThreshold(channelType: 'Cyan', LOWxHIGH: string): State; - randomThreshold(channelType: 'Magenta', LOWxHIGH: string): State; - randomThreshold(channelType: 'Yellow', LOWxHIGH: string): State; - randomThreshold(channelType: 'Black', LOWxHIGH: string): State; - randomThreshold(channelType: 'Opacity', LOWxHIGH: string): State; - randomThreshold(channelType: string, LOWxHIGH: string): State; + randomThreshold(channelType: ChannelType, LOWxHIGH: string): State; quality(level: number): State; raise(width: number, height: number): State; recolor(matrix: string): State; @@ -462,19 +431,8 @@ declare namespace m { samplingFactor(horizontalFactor: number, verticalFactor: number): State; rawSize(width: number, height: number, offset?: number): State; resample(horizontal: number, vertical: number): State; - /** Width and height are specified in percents */ - resize(width: number, height: number, option: '%'): State; - /** Specify maximum area in pixels */ - resize(width: number, height: number, option: '@'): State; - /** Ignore aspect ratio */ - resize(width: number, height: number, option: '!'): State; - /** Width and height are minimum values */ - resize(width: number, height: number, option: '^'): State; - /** Change dimensions only if image is smaller than width or height */ - resize(width: number, height: number, option: '<'): State; - /** Change dimensions only if image is larger than width or height */ - resize(width: number, height: number, option: '>'): State; - resize(width: number, height?: number, option?: string): State; + resize(width: number, height: number, option: ResizeOption): State; + resize(width: number, height?: number, option?: ResizeOption): State; roll(horizontal: number, vertical: number): State; rotate(backgroundColor: string, degrees: number): State; scene(index: number): State; @@ -553,13 +511,21 @@ declare namespace m { // Getters color(callback: GetterCallback): State; + color(opts: GetterOptions, callback: GetterCallback): State; depth(callback: GetterCallback): State; + depth(opts: GetterOptions, callback: GetterCallback): State; filesize(callback: GetterCallback): State; + filesize(opts: GetterOptions, callback: GetterCallback): State; format(callback: GetterCallback): State; + format(opts: GetterOptions, callback: GetterCallback): State; identify(callback: GetterCallback): State; + identify(opts: GetterOptions, callback: GetterCallback): State; res(callback: GetterCallback): State; + res(opts: GetterOptions, callback: GetterCallback): State; size(callback: GetterCallback): State; + size(opts: GetterOptions, callback: GetterCallback): State; orientation(callback: GetterCallback): State; + orientation(opts: GetterOptions, callback: GetterCallback): State; // Drawing Operations draw(args: string): State; @@ -613,18 +579,42 @@ declare namespace m { write(filename: string, callback: WriteCallback): void; } - export interface SubClass { + interface SubClass { (image: string): State; (stream: NodeJS.ReadableStream, image?: string): State; (buffer: Buffer, image?: string): State; (width: number, height: number, color?: string): State; } - export function compare(filename1: string, filename2: string, callback: CompareCallback): void; - export function compare(filename1: string, filename2: string, tolerance: number, callback: CompareCallback): void; - export function compare(filename1: string, filename2: string, options: CompareOptions, callback: CompareCallback): void; + function compare(filename1: string, filename2: string, callback: CompareCallback): void; + function compare(filename1: string, filename2: string, tolerance: number, callback: CompareCallback): void; + function compare(filename1: string, filename2: string, options: CompareOptions, callback: CompareCallback): void; - export function subClass(options: ClassOptions): SubClass; + function subClass(options: ClassOptions): SubClass; + + type ChannelType = 'All' + | 'Intensity' + | 'Red' + | 'Green' + | 'Blue' + | 'Cyan' + | 'Magenta' + | 'Yellow' + | 'Black' + | 'Opacity'; + + type CompareCallback = (err: Error, isEqual: boolean, equality: number, raw: number) => any; + + type GetterCallback = (err: Error, value: T) => any; + + type ResizeOption = '%' /** Width and height are specified in percents */ + | '@' /** Specify maximum area in pixels */ + | '!' /** Ignore aspect ratio */ + | '^' /** Width and height are minimum values */ + | '<' /** Change dimensions only if image is smaller than width or height */ + | '>'; /** Change dimensions only if image is larger than width or height */ + + type WriteCallback = (err: Error, stdout: string, stderr: string, cmd: string) => any; } export = m; diff --git a/types/gm/tslint.json b/types/gm/tslint.json new file mode 100644 index 0000000000..7c456f533a --- /dev/null +++ b/types/gm/tslint.json @@ -0,0 +1,7 @@ +{ + "extends": "dtslint/dt.json", + "rules": { + // This package unifiable overloaded functions, lot of effort to fix + "unified-signatures": false + } +} diff --git a/types/google-libphonenumber/google-libphonenumber-tests.ts b/types/google-libphonenumber/google-libphonenumber-tests.ts index 9f6fd2e7e7..f9e7c4bf8e 100644 --- a/types/google-libphonenumber/google-libphonenumber-tests.ts +++ b/types/google-libphonenumber/google-libphonenumber-tests.ts @@ -1,6 +1,6 @@ import libphonenumber = require('google-libphonenumber'); -import {PhoneNumberFormat, PhoneNumberUtil, AsYouTypeFormatter} from 'google-libphonenumber'; +import { PhoneNumberFormat, PhoneNumberUtil, AsYouTypeFormatter } from 'google-libphonenumber'; () => { // Require `PhoneNumberFormat`. diff --git a/types/google.visualization/index.d.ts b/types/google.visualization/index.d.ts index 9e26c3bb2b..d5967384f1 100644 --- a/types/google.visualization/index.d.ts +++ b/types/google.visualization/index.d.ts @@ -1,6 +1,6 @@ // Type definitions for Google Visualisation Apis // Project: https://developers.google.com/chart/ -// Definitions by: Dan Ludwig , Gregory Moore , Dan Manastireanu , Michael Cheng +// Definitions by: Dan Ludwig , Gregory Moore , Dan Manastireanu , Michael Cheng , Ivan Bisultanov // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped declare namespace google { @@ -412,6 +412,8 @@ declare namespace google { export interface ChartArea { top?: any; left?: any; + right?: any; + bottom?: any; width?: any; height?: any; } diff --git a/types/googlemaps/index.d.ts b/types/googlemaps/index.d.ts index b36032d298..2fea0028b8 100644 --- a/types/googlemaps/index.d.ts +++ b/types/googlemaps/index.d.ts @@ -1163,7 +1163,7 @@ declare namespace google.maps { export interface GeocoderComponentRestrictions { administrativeArea?: string; - country?: string; + country?: string | string[]; locality?: string; postalCode?: string; route?: string; diff --git a/types/got/got-tests.ts b/types/got/got-tests.ts new file mode 100644 index 0000000000..29370358be --- /dev/null +++ b/types/got/got-tests.ts @@ -0,0 +1,152 @@ +import got = require('got'); +import cookie = require('cookie'); +import FormData = require('form-data'); +import * as fs from 'fs'; +import * as http from 'http'; + +let str: string; +let buf: Buffer; +let obj: object; + +got('todomvc.com') + .then(response => { + str = response.body; + }) + .catch((error: got.GotError) => { + console.log(error.response.body); + }); + +got('todomvc.com').cancel(); + +got('todomvc.com', {json: true}).then(response => obj = response.body); +got('todomvc.com', {json: true, body: {}}).then(response => obj = response.body); +got('todomvc.com', {json: true, body: [{}]}).then(response => obj = response.body); +got('todomvc.com', {json: true, form: true}).then(response => obj = response.body); +got('todomvc.com', {json: true, form: true, encoding: null}).then(response => obj = response.body); +got('todomvc.com', {json: true, form: true, encoding: null, hostname: 'todomvc'}).then(response => obj = response.body); + +got('todomvc.com', {form: true}).then(response => str = response.body); +got('todomvc.com', {form: true, body: {}}).then(response => str = response.body); +got('todomvc.com', {form: true, body: [{}]}).then(response => str = response.body); +got('todomvc.com', {form: true, body: [{}], encoding: null}).then(response => buf = response.body); +got('todomvc.com', {form: true, body: [{}], encoding: 'utf8'}).then(response => str = response.body); +got('todomvc.com', { + form: true, + body: [{}], + encoding: 'utf8', + hostname: 'todomvc' +}).then(response => str = response.body); +// following must lead to type checking error: got('todomvc.com', {form: true, body: ''}).then(response => str = response.body); + +got('todomvc.com', {encoding: null, hostname: 'todomvc'}).then(response => buf = response.body); +got('todomvc.com', {encoding: 'utf8', hostname: 'todomvc'}).then(response => str = response.body); + +got('todomvc.com', {hostname: 'todomvc'}).then(response => str = response.body); + +got.get('todomvc.com', {hostname: 'todomvc'}).then(response => str = response.body); +got.post('todomvc.com', {hostname: 'todomvc'}).then(response => str = response.body); +got.put('todomvc.com', {hostname: 'todomvc'}).then(response => str = response.body); +got.patch('todomvc.com', {hostname: 'todomvc'}).then(response => str = response.body); +got.head('todomvc.com', {hostname: 'todomvc'}).then(response => str = response.body); +got.delete('todomvc.com', {hostname: 'todomvc'}).then(response => str = response.body); + +got.stream('todomvc.com').pipe(fs.createWriteStream('index.html')); + +fs.createReadStream('index.html').pipe(got.stream.get('todomvc.com')); +fs.createReadStream('index.html').pipe(got.stream.post('todomvc.com')); +fs.createReadStream('index.html').pipe(got.stream.put('todomvc.com')); +fs.createReadStream('index.html').pipe(got.stream.patch('todomvc.com')); +fs.createReadStream('index.html').pipe(got.stream.head('todomvc.com')); +fs.createReadStream('index.html').pipe(got.stream.delete('todomvc.com')); + +let req: http.ClientRequest; +let res: http.IncomingMessage | undefined; +let opts: got.GotOptions; +let err: got.GotError; + +const stream = got.stream('todomvc.com'); +stream.addListener('request', (r) => req = r); +stream.addListener('response', (r) => res = r); +stream.addListener('redirect', (r, o) => { + res = r; + opts = o; +}); +stream.addListener('error', (e, b, r) => { + err = e; + res = r; +}); + +stream.on('request', (r) => req = r); +stream.on('response', (r) => res = r); +stream.on('redirect', (r, o) => { + res = r; + opts = o; +}); +stream.on('error', (e, b, r) => { + err = e; + res = r; +}); + +stream.once('request', (r) => req = r); +stream.once('response', (r) => res = r); +stream.once('redirect', (r, o) => { + res = r; + opts = o; +}); +stream.once('error', (e, b, r) => { + err = e; + res = r; +}); + +stream.prependListener('request', (r) => req = r); +stream.prependListener('response', (r) => res = r); +stream.prependListener('redirect', (r, o) => { + res = r; + opts = o; +}); +stream.prependListener('error', (e, b, r) => { + err = e; + res = r; +}); + +stream.prependOnceListener('request', (r) => req = r); +stream.prependOnceListener('response', (r) => res = r); +stream.prependOnceListener('redirect', (r, o) => { + res = r; + opts = o; +}); +stream.prependOnceListener('error', (e, b, r) => { + err = e; + res = r; +}); + +stream.removeListener('request', (r) => req = r); +stream.removeListener('response', (r) => res = r); +stream.removeListener('redirect', (r, o) => { + res = r; + opts = o; +}); +stream.removeListener('error', (e, b, r) => { + err = e; + res = r; +}); + +got('google.com', { + headers: { + cookie: cookie.serialize('foo', 'bar') + } +}); + +const form = new FormData(); + +form.append('my_file', fs.createReadStream('/foo/bar.jpg')); + +got.post('google.com', { + body: form +}); + +got('todomvc.com', { + headers: { + 'user-agent': `my-module/ (https://github.com/username/my-module)` + } +}); diff --git a/types/got/index.d.ts b/types/got/index.d.ts new file mode 100644 index 0000000000..fe498d5b34 --- /dev/null +++ b/types/got/index.d.ts @@ -0,0 +1,155 @@ +// Type definitions for got 7.1 +// Project: https://github.com/sindresorhus/got#readme +// Definitions by: BendingBender +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.2 + +/// + +import * as http from 'http'; +import * as nodeStream from 'stream'; + +export = got; + +declare const got: got.GotFn & + Record<'get' | 'post' | 'put' | 'patch' | 'head' | 'delete', got.GotFn> & + { + stream: got.GotStreamFn & Record<'get' | 'post' | 'put' | 'patch' | 'head' | 'delete', got.GotStreamFn> + }; + +declare namespace got { + // tslint:disable unified-signatures + interface GotFn { + (url: GotUrl): GotPromise; + (url: GotUrl, options: GotJSONOptions): GotPromise; + (url: GotUrl, options: GotFormOptions): GotPromise; + (url: GotUrl, options: GotFormOptions): GotPromise; + (url: GotUrl, options: GotBodyOptions): GotPromise; + (url: GotUrl, options: GotBodyOptions): GotPromise; + } + // tslint:disable unified-signatures + + type GotStreamFn = (url: GotUrl, options?: GotOptions) => GotEmitter & nodeStream.Duplex; + + type GotUrl = string | http.RequestOptions | URL; + + interface GotBodyOptions extends GotOptions { + body?: string | Buffer | nodeStream.Readable; + } + + interface GotJSONOptions extends GotOptions { + body?: object; + form?: boolean; + json: true; + } + + interface GotFormOptions extends GotOptions { + body?: {[key: string]: any}; + form: true; + json?: boolean; + } + + type GotOptions = http.RequestOptions & { + encoding?: E; + query?: string | object; + timeout?: number | TimeoutOptions; + retries?: number | RetryFunction; + followRedirect?: boolean; + decompress?: boolean; + useElectronNet?: boolean; + }; + + interface TimeoutOptions { + connect?: number; + socket?: number; + request?: number; + } + + type RetryFunction = (retry: number, error: any) => number; + + interface Response extends http.IncomingMessage { + body: B; + url: string; + requestUrl: string; + redirectUrls?: string[]; + } + + type GotPromise = Promise> & { cancel(): void }; + + interface GotEmitter { + addListener(event: 'request', listener: (req: http.ClientRequest) => void): this; + addListener(event: 'response', listener: (res: http.IncomingMessage) => void): this; + addListener(event: 'redirect', listener: (res: http.IncomingMessage, nextOptions: GotOptions) => void): this; + addListener(event: 'error', listener: (error: GotError, body?: any, res?: http.IncomingMessage) => void): this; + + on(event: 'request', listener: (req: http.ClientRequest) => void): this; + on(event: 'response', listener: (res: http.IncomingMessage) => void): this; + on(event: 'redirect', listener: (res: http.IncomingMessage, nextOptions: GotOptions) => void): this; + on(event: 'error', listener: (error: GotError, body?: any, res?: http.IncomingMessage) => void): this; + + once(event: 'request', listener: (req: http.ClientRequest) => void): this; + once(event: 'response', listener: (res: http.IncomingMessage) => void): this; + once(event: 'redirect', listener: (res: http.IncomingMessage, nextOptions: GotOptions) => void): this; + once(event: 'error', listener: (error: GotError, body?: any, res?: http.IncomingMessage) => void): this; + + prependListener(event: 'request', listener: (req: http.ClientRequest) => void): this; + prependListener(event: 'response', listener: (res: http.IncomingMessage) => void): this; + prependListener(event: 'redirect', listener: (res: http.IncomingMessage, nextOptions: GotOptions) => void): this; + prependListener(event: 'error', listener: (error: GotError, body?: any, res?: http.IncomingMessage) => void): this; + + prependOnceListener(event: 'request', listener: (req: http.ClientRequest) => void): this; + prependOnceListener(event: 'response', listener: (res: http.IncomingMessage) => void): this; + prependOnceListener(event: 'redirect', listener: (res: http.IncomingMessage, nextOptions: GotOptions) => void): this; + prependOnceListener(event: 'error', listener: (error: GotError, body?: any, res?: http.IncomingMessage) => void): this; + + removeListener(event: 'request', listener: (req: http.ClientRequest) => void): this; + removeListener(event: 'response', listener: (res: http.IncomingMessage) => void): this; + removeListener(event: 'redirect', listener: (res: http.IncomingMessage, nextOptions: GotOptions) => void): this; + removeListener(event: 'error', listener: (error: GotError, body?: any, res?: http.IncomingMessage) => void): this; + } + + type GotError = RequestError | ReadError | ParseError | HTTPError | MaxRedirectsError | UnsupportedProtocolError; + + interface RequestError extends StdError { + name: 'RequestError'; + } + + interface ReadError extends StdError { + name: 'ReadError'; + } + + interface ParseError extends StdError { + name: 'ParseError'; + statusCode: number; + statusMessage: string; + } + + interface HTTPError extends StdError { + name: 'HTTPError'; + statusCode: number; + statusMessage: string; + headers: http.IncomingHttpHeaders; + } + + interface MaxRedirectsError extends StdError { + name: 'MaxRedirectsError'; + statusCode: number; + statusMessage: string; + redirectUrls: string[]; + } + + interface UnsupportedProtocolError extends StdError { + name: 'UnsupportedProtocolError'; + } + + interface StdError extends Error { + code?: string; + host?: string; + hostname?: string; + method?: string; + path?: string; + protocol?: string; + url?: string; + response?: any; + } +} diff --git a/types/got/tsconfig.json b/types/got/tsconfig.json new file mode 100644 index 0000000000..be639b3c17 --- /dev/null +++ b/types/got/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", + "got-tests.ts" + ] +} diff --git a/types/got/tslint.json b/types/got/tslint.json new file mode 100644 index 0000000000..3db14f85ea --- /dev/null +++ b/types/got/tslint.json @@ -0,0 +1 @@ +{ "extends": "dtslint/dt.json" } diff --git a/types/graphql-date/graphql-date-tests.ts b/types/graphql-date/graphql-date-tests.ts index 07542c8c0d..14a6882646 100644 --- a/types/graphql-date/graphql-date-tests.ts +++ b/types/graphql-date/graphql-date-tests.ts @@ -1,4 +1,4 @@ -import {GraphQLObjectType} from 'graphql'; +import { GraphQLObjectType } from 'graphql'; import * as GraphQLDate from 'graphql-date'; const fooType = new GraphQLObjectType({ diff --git a/types/graphql-date/index.d.ts b/types/graphql-date/index.d.ts index 20cd74d61e..35ad44f7e1 100644 --- a/types/graphql-date/index.d.ts +++ b/types/graphql-date/index.d.ts @@ -3,7 +3,7 @@ // Definitions by: Eric Naeseth // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -import {GraphQLScalarType} from 'graphql'; +import { GraphQLScalarType } from 'graphql'; declare const date: GraphQLScalarType; diff --git a/types/graphql-type-json/graphql-type-json-tests.ts b/types/graphql-type-json/graphql-type-json-tests.ts index 3282681845..8d2435270e 100644 --- a/types/graphql-type-json/graphql-type-json-tests.ts +++ b/types/graphql-type-json/graphql-type-json-tests.ts @@ -1,4 +1,4 @@ -import {GraphQLObjectType, GraphQLInputObjectType} from "graphql"; +import { GraphQLObjectType, GraphQLInputObjectType } from "graphql"; import * as GraphQLJSON from "graphql-type-json"; const TestType = new GraphQLObjectType({ diff --git a/types/graphql-type-json/index.d.ts b/types/graphql-type-json/index.d.ts index 7d41b83013..c9549b946d 100644 --- a/types/graphql-type-json/index.d.ts +++ b/types/graphql-type-json/index.d.ts @@ -2,7 +2,7 @@ // Project: https://github.com/taion/graphql-type-json#readme // Definitions by: Pavel Ivanov // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -import {GraphQLScalarType} from "graphql"; +import { GraphQLScalarType } from "graphql"; declare const GraphQLJSON: GraphQLScalarType; export = GraphQLJSON; diff --git a/types/graphql/error/GraphQLError.d.ts b/types/graphql/error/GraphQLError.d.ts index 857f25b593..fbafcb1e30 100644 --- a/types/graphql/error/GraphQLError.d.ts +++ b/types/graphql/error/GraphQLError.d.ts @@ -9,7 +9,6 @@ import { Source } from '../language/source'; * GraphQL document and/or execution result that correspond to the Error. */ export class GraphQLError extends Error { - /** * A message describing the Error for debugging purposes. * @@ -40,7 +39,7 @@ export class GraphQLError extends Error { /** * An array of GraphQL AST Nodes corresponding to this error. */ - nodes?: Array | undefined; + nodes?: ASTNode[] | undefined; /** * The source GraphQL document corresponding to this error. @@ -51,7 +50,7 @@ export class GraphQLError extends Error { * An array of character offsets within the source GraphQL document * which correspond to this error. */ - positions?: Array | undefined; + positions?: number[] | undefined; /** * The original error thrown from a field resolver during execution. @@ -60,9 +59,9 @@ export class GraphQLError extends Error { constructor( message: string, - nodes?: Array, + nodes?: any[], source?: Source, - positions?: Array, + positions?: number[], path?: Array, originalError?: Error, ); diff --git a/types/graphql/error/formatError.d.ts b/types/graphql/error/formatError.d.ts index 5b974d5461..fbb31cdb23 100644 --- a/types/graphql/error/formatError.d.ts +++ b/types/graphql/error/formatError.d.ts @@ -6,13 +6,13 @@ import { GraphQLError } from './GraphQLError'; */ export function formatError(error: GraphQLError): GraphQLFormattedError; -export type GraphQLFormattedError = { - message: string, - locations?: Array, - path?: Array -}; +export interface GraphQLFormattedError { + message: string; + locations?: GraphQLErrorLocation[]; + path?: Array; +} -export type GraphQLErrorLocation = { - line: number, - column: number -}; +export interface GraphQLErrorLocation { + line: number; + column: number; +} diff --git a/types/graphql/error/index.d.ts b/types/graphql/error/index.d.ts index 50fe58c06a..cfb5b92740 100644 --- a/types/graphql/error/index.d.ts +++ b/types/graphql/error/index.d.ts @@ -1,4 +1,4 @@ export { GraphQLError } from './GraphQLError'; export { syntaxError } from './syntaxError'; export { locatedError } from './locatedError'; -export { formatError, GraphQLFormattedError, GraphQLErrorLocation } from './formatError'; \ No newline at end of file +export { formatError, GraphQLFormattedError, GraphQLErrorLocation } from './formatError'; diff --git a/types/graphql/error/locatedError.d.ts b/types/graphql/error/locatedError.d.ts index 8aca478f03..c827f8ede8 100644 --- a/types/graphql/error/locatedError.d.ts +++ b/types/graphql/error/locatedError.d.ts @@ -7,6 +7,6 @@ import { GraphQLError } from './GraphQLError'; */ export function locatedError( originalError: Error, - nodes: Array, + nodes: T[], path: Array ): GraphQLError; diff --git a/types/graphql/error/syntaxError.d.ts b/types/graphql/error/syntaxError.d.ts index d57b292211..80c4453e03 100644 --- a/types/graphql/error/syntaxError.d.ts +++ b/types/graphql/error/syntaxError.d.ts @@ -9,4 +9,4 @@ export function syntaxError( source: Source, position: number, description: string -): GraphQLError; \ No newline at end of file +): GraphQLError; diff --git a/types/graphql/execution/execute.d.ts b/types/graphql/execution/execute.d.ts index 48ee78840a..782310b6f4 100644 --- a/types/graphql/execution/execute.d.ts +++ b/types/graphql/execution/execute.d.ts @@ -22,7 +22,7 @@ export interface ExecutionContext { rootValue: any; operation: OperationDefinitionNode; variableValues: { [key: string]: any }; - errors: Array; + errors: GraphQLError[]; } /** @@ -32,7 +32,7 @@ export interface ExecutionContext { */ export interface ExecutionResult { data?: { [key: string]: any }; - errors?: Array; + errors?: GraphQLError[]; } /** diff --git a/types/graphql/execution/values.d.ts b/types/graphql/execution/values.d.ts index e6a0be63cc..3f6e909ed7 100644 --- a/types/graphql/execution/values.d.ts +++ b/types/graphql/execution/values.d.ts @@ -10,9 +10,9 @@ import { FieldNode, DirectiveNode, VariableDefinitionNode } from '../language/as */ export function getVariableValues( schema: GraphQLSchema, - varDefNodes: Array, + varDefNodes: VariableDefinitionNode[], inputs: { [key: string]: any } -): { [key: string]: any } +): { [key: string]: any }; /** * Prepares an object map of argument values given a list of argument diff --git a/types/graphql/graphql-tests.ts b/types/graphql/graphql-tests.ts index 58725259e7..7c0210249b 100644 --- a/types/graphql/graphql-tests.ts +++ b/types/graphql/graphql-tests.ts @@ -3,180 +3,180 @@ import * as graphql from 'graphql'; /////////////////////////// // graphql // /////////////////////////// -namespace graphql_tests { +function graphql_tests() { // TODO } /////////////////////////// // graphql/language // /////////////////////////// -namespace language_ast_tests { - // TODOS +function language_ast_tests() { + // TODO } -namespace language_index_tests { - // TODOS +function language_index_tests() { + // TODO } -namespace language_kinds_tests { - // TODOS +function language_kinds_tests() { + // TODO } -namespace language_lexer_tests { - // TODOS +function language_lexer_tests() { + // TODO } -namespace language_location_tests { - // TODOS +function language_location_tests() { + // TODO } -namespace language_parser_tests { - // TODOS +function language_parser_tests() { + // TODO } -namespace language_printer_tests { - // TODOS +function language_printer_tests() { + // TODO } -namespace language_source_tests { - // TODOS +function language_source_tests() { + // TODO } -namespace language_visitor_tests { - // TODOS +function language_visitor_tests() { + // TODO } /////////////////////////// // graphql/type // /////////////////////////// -namespace type_definition_tests { +function type_definition_tests() { // TODO } -namespace type_directives_tests { +function type_directives_tests() { // TODO } -namespace type_introspection_tests { +function type_introspection_tests() { // TODO } -namespace type_scalars_tests { +function type_scalars_tests() { // TODO } -namespace type_schema_tests { +function type_schema_tests() { // TODO } /////////////////////////// // graphql/validation // /////////////////////////// -namespace validation_specifiedRules_tests { - +function validation_specifiedRules_tests() { + // TODO } -namespace validation_validate_tests { - +function validation_validate_tests() { + // TODO } /////////////////////////// // graphql/execution // /////////////////////////// -namespace execution_execute_tests { +function execution_execute_tests() { // TODOS } -namespace execution_values_tests { +function execution_values_tests() { // TODOS } /////////////////////////// // graphql/error // /////////////////////////// -namespace error_GraphQLError { - +function error_GraphQLError() { + // TODOS } -namespace error_formatError { - +function error_formatError() { + // TODOS } -namespace error_locatedError { - +function error_locatedError() { + // TODOS } -namespace error_syntaxError { - +function error_syntaxError() { + // TODOS } /////////////////////////// // graphql/utilities // /////////////////////////// -namespace utilities_TypeInfo_tests { - //TODOS +function utilities_TypeInfo_tests() { + // TODOS } -namespace utilities_assertValidName_tests { - //TODOS +function utilities_assertValidName_tests() { + // TODOS } -namespace utilities_astFromValue_tests { - //TODOS +function utilities_astFromValue_tests() { + // TODOS } -namespace utilities_buildASTSchema_tests { - //TODOS +function utilities_buildASTSchema_tests() { + // TODOS } -namespace utilities_buildClientSchema_tests { - //TODOS +function utilities_buildClientSchema_tests() { + // TODOS } -namespace utilities_concatAST_tests { - //TODOS +function utilities_concatAST_tests() { + // TODOS } -namespace utilities_extendSchema_tests { - //TODOS +function utilities_extendSchema_tests() { + // TODOS } -namespace utilities_getOperationAST_tests { - //TODOS +function utilities_getOperationAST_tests() { + // TODOS } -namespace utilities_index_tests { - //TODOS +function utilities_index_tests() { + // TODOS } -namespace utilities_introspectionQuery_tests { - //TODOS +function utilities_introspectionQuery_tests() { + // TODOS } -namespace utilities_isValidJSValue_tests { - //TODOS +function utilities_isValidJSValue_tests() { + // TODOS } -namespace utilities_isValidLiteralValue_tests { - //TODOS +function utilities_isValidLiteralValue_tests() { + // TODOS } -namespace utilities_schemaPrinter_tests { - //TODOS +function utilities_schemaPrinter_tests() { + // TODOS } -namespace utilities_separateOperations_tests { - //TODOS +function utilities_separateOperations_tests() { + // TODOS } -namespace utilities_typeComparators_tests { - //TODOS +function utilities_typeComparators_tests() { + // TODOS } -namespace utilities_typeFromAST_tests { - //TODOS +function utilities_typeFromAST_tests() { + // TODOS } -namespace utilities_valueFromAST_tests { - //TODOS +function utilities_valueFromAST_tests() { + // TODOS } diff --git a/types/graphql/index.d.ts b/types/graphql/index.d.ts index fbd724ff4a..d4cf14b42f 100644 --- a/types/graphql/index.d.ts +++ b/types/graphql/index.d.ts @@ -1,6 +1,10 @@ // Type definitions for graphql 0.10 // Project: https://www.npmjs.com/package/graphql -// Definitions by: TonyYang , Caleb Meredith , Dominic Watson , Firede , Kepennar +// Definitions by: TonyYang +// Caleb Meredith +// Dominic Watson +// Firede +// Kepennar // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped // TypeScript Version: 2.3 @@ -9,12 +13,9 @@ export { graphql } from './graphql'; -/// - // Create and operate on GraphQL type definitions and schema. export * from './type'; - // Parse and operate on GraphQL language source files. export * from './language'; @@ -28,7 +29,6 @@ export { ExecutionResult, } from './execution'; - // Validate GraphQL queries. export { validate, @@ -36,7 +36,6 @@ export { specifiedRules, } from './validation'; - // Create and format GraphQL errors. export { GraphQLError, @@ -45,7 +44,6 @@ export { GraphQLErrorLocation, } from './error'; - // Utilities for operating on GraphQL type schema and parsed sources. export { // The GraphQL query recommended for a full schema introspection. diff --git a/types/graphql/language/ast.d.ts b/types/graphql/language/ast.d.ts index d0f25b65d0..f4bc343ed2 100644 --- a/types/graphql/language/ast.d.ts +++ b/types/graphql/language/ast.d.ts @@ -4,8 +4,7 @@ import { Source } from './source'; * Contains a range of UTF-8 character offsets and token references that * identify the region of the source from which the AST derived. */ -export type Location = { - +export interface Location { /** * The character offset at which this Node begins. */ @@ -30,37 +29,37 @@ export type Location = { * The Source document the AST represents. */ source: Source; -}; +} /** * Represents a range of characters represented by a lexical token * within a Source. */ -export type Token = { - +export interface Token { /** * The kind of Token. */ - kind: '' - | '' - | '!' - | '$' - | '(' - | ')' - | '...' - | ':' - | '=' - | '@' - | '[' - | ']' - | '{' - | '|' - | '}' - | 'Name' - | 'Int' - | 'Float' - | 'String' - | 'Comment'; + kind: + | '' + | '' + | '!' + | '$' + | '(' + | ')' + | '...' + | ':' + | '=' + | '@' + | '[' + | ']' + | '{' + | '|' + | '}' + | 'Name' + | 'Int' + | 'Float' + | 'String' + | 'Comment'; /** * The character offset at which this Node begins. @@ -94,12 +93,13 @@ export type Token = { */ prev?: Token; next?: Token; -}; +} /** * The list of all possible AST node types. */ -export type ASTNode = NameNode +export type ASTNode = + | NameNode | DocumentNode | OperationDefinitionNode | VariableDefinitionNode @@ -139,7 +139,7 @@ export type ASTNode = NameNode // Name -export type NameNode = { +export interface NameNode { kind: 'Name'; loc?: Location; value: string; @@ -147,30 +147,31 @@ export type NameNode = { // Document -export type DocumentNode = { +export interface DocumentNode { kind: 'Document'; loc?: Location; - definitions: Array; + definitions: DefinitionNode[]; } -export type DefinitionNode = OperationDefinitionNode +export type DefinitionNode = + | OperationDefinitionNode | FragmentDefinitionNode - | TypeSystemDefinitionNode // experimental non-spec addition. + | TypeSystemDefinitionNode; // experimental non-spec addition. -export type OperationDefinitionNode = { +export interface OperationDefinitionNode { kind: 'OperationDefinition'; loc?: Location; operation: OperationTypeNode; name?: NameNode; - variableDefinitions?: Array; - directives?: Array; + variableDefinitions?: VariableDefinitionNode[]; + directives?: DirectiveNode[]; selectionSet: SelectionSetNode; } // Note: subscription is an experimental non-spec addition. export type OperationTypeNode = 'query' | 'mutation' | 'subscription'; -export type VariableDefinitionNode = { +export interface VariableDefinitionNode { kind: 'VariableDefinition'; loc?: Location; variable: VariableNode; @@ -178,70 +179,70 @@ export type VariableDefinitionNode = { defaultValue?: ValueNode; } -export type VariableNode = { +export interface VariableNode { kind: 'Variable'; loc?: Location; name: NameNode; } -export type SelectionSetNode = { +export interface SelectionSetNode { kind: 'SelectionSet'; loc?: Location; - selections: Array; + selections: SelectionNode[]; } -export type SelectionNode = FieldNode +export type SelectionNode = + | FieldNode | FragmentSpreadNode - | InlineFragmentNode + | InlineFragmentNode; -export type FieldNode = { +export interface FieldNode { kind: 'Field'; loc?: Location; alias?: NameNode; name: NameNode; - arguments?: Array; - directives?: Array; + arguments?: ArgumentNode[]; + directives?: DirectiveNode[]; selectionSet?: SelectionSetNode; } -export type ArgumentNode = { +export interface ArgumentNode { kind: 'Argument'; loc?: Location; name: NameNode; value: ValueNode; } - // Fragments -export type FragmentSpreadNode = { +export interface FragmentSpreadNode { kind: 'FragmentSpread'; loc?: Location; name: NameNode; - directives?: Array; + directives?: DirectiveNode[]; } -export type InlineFragmentNode = { +export interface InlineFragmentNode { kind: 'InlineFragment'; loc?: Location; typeCondition?: NamedTypeNode; - directives?: Array; + directives?: DirectiveNode[]; selectionSet: SelectionSetNode; } -export type FragmentDefinitionNode = { +export interface FragmentDefinitionNode { kind: 'FragmentDefinition'; loc?: Location; name: NameNode; typeCondition: NamedTypeNode; - directives?: Array; + directives?: DirectiveNode[]; selectionSet: SelectionSetNode; } - // Values -export type ValueNode = VariableNode +export type ValueNode = + | VariableNode | IntValueNode | FloatValueNode | StringValueNode @@ -249,92 +250,91 @@ export type ValueNode = VariableNode | NullValueNode | EnumValueNode | ListValueNode - | ObjectValueNode + | ObjectValueNode; -export type IntValueNode = { +export interface IntValueNode { kind: 'IntValue'; loc?: Location; value: string; } -export type FloatValueNode = { +export interface FloatValueNode { kind: 'FloatValue'; loc?: Location; value: string; } -export type StringValueNode = { +export interface StringValueNode { kind: 'StringValue'; loc?: Location; value: string; } -export type BooleanValueNode = { +export interface BooleanValueNode { kind: 'BooleanValue'; loc?: Location; value: boolean; } -export type NullValueNode = { +export interface NullValueNode { kind: 'NullValue'; loc?: Location; } -export type EnumValueNode = { +export interface EnumValueNode { kind: 'EnumValue'; loc?: Location; value: string; } -export type ListValueNode = { +export interface ListValueNode { kind: 'ListValue'; loc?: Location; - values: Array; + values: ValueNode[]; } -export type ObjectValueNode = { +export interface ObjectValueNode { kind: 'ObjectValue'; loc?: Location; - fields: Array; + fields: ObjectFieldNode[]; } -export type ObjectFieldNode = { +export interface ObjectFieldNode { kind: 'ObjectField'; loc?: Location; name: NameNode; value: ValueNode; } - // Directives -export type DirectiveNode = { +export interface DirectiveNode { kind: 'Directive'; loc?: Location; name: NameNode; - arguments?: Array; + arguments?: ArgumentNode[]; } - // Type Reference -export type TypeNode = NamedTypeNode +export type TypeNode = + | NamedTypeNode | ListTypeNode - | NonNullTypeNode + | NonNullTypeNode; -export type NamedTypeNode = { +export interface NamedTypeNode { kind: 'NamedType'; loc?: Location; name: NameNode; -}; +} -export type ListTypeNode = { +export interface ListTypeNode { kind: 'ListType'; loc?: Location; type: TypeNode; } -export type NonNullTypeNode = { +export interface NonNullTypeNode { kind: 'NonNullType'; loc?: Location; type: NamedTypeNode | ListTypeNode; @@ -342,115 +342,117 @@ export type NonNullTypeNode = { // Type System Definition -export type TypeSystemDefinitionNode = SchemaDefinitionNode +export type TypeSystemDefinitionNode = + | SchemaDefinitionNode | TypeDefinitionNode | TypeExtensionDefinitionNode - | DirectiveDefinitionNode + | DirectiveDefinitionNode; -export type SchemaDefinitionNode = { +export interface SchemaDefinitionNode { kind: 'SchemaDefinition'; loc?: Location; - directives: Array; - operationTypes: Array; + directives: DirectiveNode[]; + operationTypes: OperationTypeDefinitionNode[]; } -export type OperationTypeDefinitionNode = { +export interface OperationTypeDefinitionNode { kind: 'OperationTypeDefinition'; loc?: Location; operation: OperationTypeNode; type: NamedTypeNode; } -export type TypeDefinitionNode = ScalarTypeDefinitionNode +export type TypeDefinitionNode = + | ScalarTypeDefinitionNode | ObjectTypeDefinitionNode | InterfaceTypeDefinitionNode | UnionTypeDefinitionNode | EnumTypeDefinitionNode - | InputObjectTypeDefinitionNode + | InputObjectTypeDefinitionNode; -export type ScalarTypeDefinitionNode = { +export interface ScalarTypeDefinitionNode { kind: 'ScalarTypeDefinition'; loc?: Location; name: NameNode; - directives?: Array; + directives?: DirectiveNode[]; } -export type ObjectTypeDefinitionNode = { +export interface ObjectTypeDefinitionNode { kind: 'ObjectTypeDefinition'; loc?: Location; name: NameNode; - interfaces?: Array; - directives?: Array; - fields: Array; + interfaces?: NamedTypeNode[]; + directives?: DirectiveNode[]; + fields: FieldDefinitionNode[]; } -export type FieldDefinitionNode = { +export interface FieldDefinitionNode { kind: 'FieldDefinition'; loc?: Location; name: NameNode; - arguments: Array; + arguments: InputValueDefinitionNode[]; type: TypeNode; - directives?: Array; + directives?: DirectiveNode[]; } -export type InputValueDefinitionNode = { +export interface InputValueDefinitionNode { kind: 'InputValueDefinition'; loc?: Location; name: NameNode; type: TypeNode; defaultValue?: ValueNode; - directives?: Array; + directives?: DirectiveNode[]; } -export type InterfaceTypeDefinitionNode = { +export interface InterfaceTypeDefinitionNode { kind: 'InterfaceTypeDefinition'; loc?: Location; name: NameNode; - directives?: Array; - fields: Array; + directives?: DirectiveNode[]; + fields: FieldDefinitionNode[]; } -export type UnionTypeDefinitionNode = { +export interface UnionTypeDefinitionNode { kind: 'UnionTypeDefinition'; loc?: Location; name: NameNode; - directives?: Array; - types: Array; + directives?: DirectiveNode[]; + types: NamedTypeNode[]; } -export type EnumTypeDefinitionNode = { +export interface EnumTypeDefinitionNode { kind: 'EnumTypeDefinition'; loc?: Location; name: NameNode; - directives?: Array; - values: Array; + directives?: DirectiveNode[]; + values: EnumValueDefinitionNode[]; } -export type EnumValueDefinitionNode = { +export interface EnumValueDefinitionNode { kind: 'EnumValueDefinition'; loc?: Location; name: NameNode; - directives?: Array; + directives?: DirectiveNode[]; } -export type InputObjectTypeDefinitionNode = { +export interface InputObjectTypeDefinitionNode { kind: 'InputObjectTypeDefinition'; loc?: Location; name: NameNode; - directives?: Array; - fields: Array; + directives?: DirectiveNode[]; + fields: InputValueDefinitionNode[]; } -export type TypeExtensionDefinitionNode = { +export interface TypeExtensionDefinitionNode { kind: 'TypeExtensionDefinition'; loc?: Location; definition: ObjectTypeDefinitionNode; } -export type DirectiveDefinitionNode = { +export interface DirectiveDefinitionNode { kind: 'DirectiveDefinition'; loc?: Location; name: NameNode; - arguments?: Array; - locations: Array; + arguments?: InputValueDefinitionNode[]; + locations: NameNode[]; } diff --git a/types/graphql/language/kinds.d.ts b/types/graphql/language/kinds.d.ts index 3b595beb65..626d350818 100644 --- a/types/graphql/language/kinds.d.ts +++ b/types/graphql/language/kinds.d.ts @@ -63,4 +63,4 @@ export const TYPE_EXTENSION_DEFINITION: 'TypeExtensionDefinition'; // Directive Definitions -export const DIRECTIVE_DEFINITION: 'DirectiveDefinition'; \ No newline at end of file +export const DIRECTIVE_DEFINITION: 'DirectiveDefinition'; diff --git a/types/graphql/language/lexer.d.ts b/types/graphql/language/lexer.d.ts index 5175b5b1e6..4a55f03dc2 100644 --- a/types/graphql/language/lexer.d.ts +++ b/types/graphql/language/lexer.d.ts @@ -18,7 +18,7 @@ export function createLexer( /** * The return type of createLexer. */ -export type Lexer = { +export interface Lexer { source: Source; options: TOptions; @@ -46,7 +46,7 @@ export type Lexer = { * Advances the token stream to the next non-ignored token. */ advance(): Token; -}; +} /** * An exported enum describing the different kinds of tokens that the diff --git a/types/graphql/language/location.d.ts b/types/graphql/language/location.d.ts index 8c638a3a96..4d7a13e314 100644 --- a/types/graphql/language/location.d.ts +++ b/types/graphql/language/location.d.ts @@ -1,6 +1,5 @@ import { Source } from "./source"; - export interface SourceLocation { line: number; column: number; diff --git a/types/graphql/language/parser.d.ts b/types/graphql/language/parser.d.ts index 1458d6736d..5aa195ddd4 100644 --- a/types/graphql/language/parser.d.ts +++ b/types/graphql/language/parser.d.ts @@ -5,14 +5,14 @@ import { Lexer } from "./lexer"; /** * Configuration options to control parser behavior */ -export type ParseOptions = { +export interface ParseOptions { /** * By default, the parser creates AST nodes that know the location * in the source that they correspond to. This configuration flag * disables that behavior for performance or testing. */ - noLocation?: boolean -}; + noLocation?: boolean; +} /** * Given a GraphQL source, parses it into a Document. diff --git a/types/graphql/language/visitor.d.ts b/types/graphql/language/visitor.d.ts index d4c528501e..024b292ed6 100644 --- a/types/graphql/language/visitor.d.ts +++ b/types/graphql/language/visitor.d.ts @@ -38,7 +38,7 @@ export const QueryDocumentKeys: { EnumValueDefinition: string[]; InputObjectTypeDefinition: string[]; TypeExtensionDefinition: string[]; -} +}; export const BREAK: any; diff --git a/types/graphql/tslint.json b/types/graphql/tslint.json new file mode 100644 index 0000000000..2750cc0197 --- /dev/null +++ b/types/graphql/tslint.json @@ -0,0 +1 @@ +{ "extends": "dtslint/dt.json" } \ No newline at end of file diff --git a/types/graphql/type/definition.d.ts b/types/graphql/type/definition.d.ts index eb64172f40..5b0a2e9181 100644 --- a/types/graphql/type/definition.d.ts +++ b/types/graphql/type/definition.d.ts @@ -10,14 +10,14 @@ import { GraphQLSchema } from './schema'; * These are all of the possible kinds of types. */ export type GraphQLType = - GraphQLScalarType | - GraphQLObjectType | - GraphQLInterfaceType | - GraphQLUnionType | - GraphQLEnumType | - GraphQLInputObjectType | - GraphQLList | - GraphQLNonNull; + | GraphQLScalarType + | GraphQLObjectType + | GraphQLInterfaceType + | GraphQLUnionType + | GraphQLEnumType + | GraphQLInputObjectType + | GraphQLList + | GraphQLNonNull; export function isType(type: any): type is GraphQLType; @@ -27,16 +27,15 @@ export function assertType(type: any): GraphQLType; * These types may be used as input types for arguments and directives. */ export type GraphQLInputType = - GraphQLScalarType | - GraphQLEnumType | - GraphQLInputObjectType | - GraphQLList | - GraphQLNonNull< - GraphQLScalarType | - GraphQLEnumType | - GraphQLInputObjectType | - GraphQLList - >; + | GraphQLScalarType + | GraphQLEnumType + | GraphQLInputObjectType + | GraphQLList + | GraphQLNonNull< + | GraphQLScalarType + | GraphQLEnumType + | GraphQLInputObjectType + | GraphQLList>; export function isInputType(type: GraphQLType): type is GraphQLInputType; @@ -46,20 +45,19 @@ export function assertInputType(type: GraphQLType): GraphQLInputType; * These types may be used as output types as the result of fields. */ export type GraphQLOutputType = - GraphQLScalarType | - GraphQLObjectType | - GraphQLInterfaceType | - GraphQLUnionType | - GraphQLEnumType | - GraphQLList | - GraphQLNonNull< - GraphQLScalarType | - GraphQLObjectType | - GraphQLInterfaceType | - GraphQLUnionType | - GraphQLEnumType | - GraphQLList - >; + | GraphQLScalarType + | GraphQLObjectType + | GraphQLInterfaceType + | GraphQLUnionType + | GraphQLEnumType + | GraphQLList + | GraphQLNonNull< + | GraphQLScalarType + | GraphQLObjectType + | GraphQLInterfaceType + | GraphQLUnionType + | GraphQLEnumType + | GraphQLList>; export function isOutputType(type: GraphQLType): type is GraphQLOutputType; @@ -69,8 +67,8 @@ export function assertOutputType(type: GraphQLType): GraphQLOutputType; * These types may describe types which may be leaf values. */ export type GraphQLLeafType = - GraphQLScalarType | - GraphQLEnumType; + | GraphQLScalarType + | GraphQLEnumType; export function isLeafType(type: GraphQLType): type is GraphQLLeafType; @@ -80,9 +78,9 @@ export function assertLeafType(type: GraphQLType): GraphQLLeafType; * These types may describe the parent context of a selection set. */ export type GraphQLCompositeType = - GraphQLObjectType | - GraphQLInterfaceType | - GraphQLUnionType; + | GraphQLObjectType + | GraphQLInterfaceType + | GraphQLUnionType; export function isCompositeType(type: GraphQLType): type is GraphQLCompositeType; @@ -92,8 +90,8 @@ export function assertCompositeType(type: GraphQLType): GraphQLCompositeType; * These types may describe the parent context of a selection set. */ export type GraphQLAbstractType = - GraphQLInterfaceType | - GraphQLUnionType; + | GraphQLInterfaceType + | GraphQLUnionType; export function isAbstractType(type: GraphQLType): type is GraphQLAbstractType; @@ -103,13 +101,13 @@ export function assertAbstractType(type: GraphQLType): GraphQLAbstractType; * These types can all accept null as a value. */ export type GraphQLNullableType = - GraphQLScalarType | - GraphQLObjectType | - GraphQLInterfaceType | - GraphQLUnionType | - GraphQLEnumType | - GraphQLInputObjectType | - GraphQLList; + | GraphQLScalarType + | GraphQLObjectType + | GraphQLInterfaceType + | GraphQLUnionType + | GraphQLEnumType + | GraphQLInputObjectType + | GraphQLList; export function getNullableType( type: T @@ -119,12 +117,12 @@ export function getNullableType( * These named types do not include modifiers like List or NonNull. */ export type GraphQLNamedType = - GraphQLScalarType | - GraphQLObjectType | - GraphQLInterfaceType | - GraphQLUnionType | - GraphQLEnumType | - GraphQLInputObjectType; + | GraphQLScalarType + | GraphQLObjectType + | GraphQLInterfaceType + | GraphQLUnionType + | GraphQLEnumType + | GraphQLInputObjectType; export function isNamedType(type: GraphQLType): boolean; @@ -175,9 +173,9 @@ export class GraphQLScalarType { export interface GraphQLScalarTypeConfig { name: string; description?: string; - serialize: (value: any) => TExternal | null | undefined; - parseValue?: (value: any) => TInternal | null | undefined; - parseLiteral?: (valueNode: ValueNode) => TInternal | null | undefined; + serialize(value: any): TExternal | null | undefined; + parseValue?(value: any): TInternal | null | undefined; + parseLiteral?(valueNode: ValueNode): TInternal | null | undefined; } /** @@ -224,17 +222,16 @@ export class GraphQLObjectType { constructor(config: GraphQLObjectTypeConfig); getFields(): GraphQLFieldMap; - getInterfaces(): Array; + getInterfaces(): GraphQLInterfaceType[]; toString(): string; } - export interface GraphQLObjectTypeConfig { name: string; - interfaces?: Thunk>; + interfaces?: Thunk; fields: Thunk>; isTypeOf?: GraphQLIsTypeOfFn; - description?: string + description?: string; } export type GraphQLTypeResolver = ( @@ -258,7 +255,7 @@ export type GraphQLFieldResolver = ( export interface GraphQLResolveInfo { fieldName: string; - fieldNodes: Array; + fieldNodes: FieldNode[]; returnType: GraphQLOutputType; parentType: GraphQLCompositeType; path: ResponsePath; @@ -297,7 +294,7 @@ export interface GraphQLField { name: string; description: string; type: GraphQLOutputType; - args: Array; + args: GraphQLArgument[]; resolve?: GraphQLFieldResolver; isDeprecated?: boolean; deprecationReason?: string; @@ -345,15 +342,15 @@ export class GraphQLInterfaceType { } export interface GraphQLInterfaceTypeConfig { - name: string, - fields: Thunk>, + name: string; + fields: Thunk>; /** * Optionally provide a custom type resolver function. If one is not provided, * the default implementation will call `isTypeOf` on each implementing * Object type. */ - resolveType?: GraphQLTypeResolver, - description?: string + resolveType?: GraphQLTypeResolver; + description?: string; } /** @@ -386,14 +383,14 @@ export class GraphQLUnionType { constructor(config: GraphQLUnionTypeConfig); - getTypes(): Array; + getTypes(): GraphQLObjectType[]; toString(): string; } export interface GraphQLUnionTypeConfig { - name: string, - types: Thunk>, + name: string; + types: Thunk; /** * Optionally provide a custom type resolver function. If one is not provided, * the default implementation will call `isTypeOf` on each implementing @@ -429,7 +426,7 @@ export class GraphQLEnumType { description: string; constructor(config: GraphQLEnumTypeConfig); - getValues(): Array; + getValues(): GraphQLEnumValue[]; getValue(name: string): GraphQLEnumValue; serialize(value: any): string; parseValue(value: any): any; diff --git a/types/graphql/type/directives.d.ts b/types/graphql/type/directives.d.ts index 5e470ddfca..aed6234ef5 100644 --- a/types/graphql/type/directives.d.ts +++ b/types/graphql/type/directives.d.ts @@ -3,7 +3,6 @@ import { GraphQLArgument } from './definition'; - export const DirectiveLocation: { // Operations QUERY: 'QUERY', @@ -27,7 +26,7 @@ export const DirectiveLocation: { INPUT_FIELD_DEFINITION: 'INPUT_FIELD_DEFINITION', }; -export type DirectiveLocationEnum = any //$Keys +export type DirectiveLocationEnum = keyof typeof DirectiveLocation; /** * Directives are used by the GraphQL runtime as a way of modifying execution @@ -36,8 +35,8 @@ export type DirectiveLocationEnum = any //$Keys export class GraphQLDirective { name: string; description: string; - locations: Array; - args: Array; + locations: DirectiveLocationEnum[]; + args: GraphQLArgument[]; constructor(config: GraphQLDirectiveConfig); } @@ -45,7 +44,7 @@ export class GraphQLDirective { export interface GraphQLDirectiveConfig { name: string; description?: string; - locations: Array; + locations: DirectiveLocationEnum[]; args?: GraphQLFieldConfigArgumentMap; } @@ -72,4 +71,4 @@ export const GraphQLDeprecatedDirective: GraphQLDirective; /** * The full list of specified directives. */ -export const specifiedDirectives: Array; +export const specifiedDirectives: GraphQLDirective[]; diff --git a/types/graphql/type/introspection.d.ts b/types/graphql/type/introspection.d.ts index 0227328b1d..989e34a882 100644 --- a/types/graphql/type/introspection.d.ts +++ b/types/graphql/type/introspection.d.ts @@ -10,7 +10,6 @@ import { } from './definition'; import { GraphQLField } from './definition'; - export const __Schema: GraphQLObjectType; export const __Directive: GraphQLObjectType; export const __DirectiveLocation: GraphQLEnumType; @@ -28,7 +27,7 @@ export const TypeKind: { INPUT_OBJECT: 'INPUT_OBJECT', LIST: 'LIST', NON_NULL: 'NON_NULL', -} +}; export const __TypeKind: GraphQLEnumType; diff --git a/types/graphql/type/scalars.d.ts b/types/graphql/type/scalars.d.ts index 6c01256643..31a33aafad 100644 --- a/types/graphql/type/scalars.d.ts +++ b/types/graphql/type/scalars.d.ts @@ -1,6 +1,5 @@ import { GraphQLScalarType } from './definition'; - export const GraphQLInt: GraphQLScalarType; export const GraphQLFloat: GraphQLScalarType; export const GraphQLString: GraphQLScalarType; diff --git a/types/graphql/type/schema.d.ts b/types/graphql/type/schema.d.ts index 01bd3b1ca5..2d0c5c7f3d 100644 --- a/types/graphql/type/schema.d.ts +++ b/types/graphql/type/schema.d.ts @@ -10,7 +10,6 @@ import { GraphQLDirective, } from './directives'; - /** * Schema Definition * @@ -53,14 +52,14 @@ export class GraphQLSchema { getSubscriptionType(): GraphQLObjectType|null|undefined; getTypeMap(): { [typeName: string]: GraphQLNamedType }; getType(name: string): GraphQLType; - getPossibleTypes(abstractType: GraphQLAbstractType): Array; + getPossibleTypes(abstractType: GraphQLAbstractType): GraphQLObjectType[]; isPossibleType( abstractType: GraphQLAbstractType, possibleType: GraphQLObjectType ): boolean; - getDirectives(): Array; + getDirectives(): GraphQLDirective[]; getDirective(name: string): GraphQLDirective; } @@ -68,6 +67,6 @@ export interface GraphQLSchemaConfig { query: GraphQLObjectType; mutation?: GraphQLObjectType; subscription?: GraphQLObjectType; - types?: Array; - directives?: Array; + types?: GraphQLNamedType[]; + directives?: GraphQLDirective[]; } diff --git a/types/graphql/utilities/TypeInfo.d.ts b/types/graphql/utilities/TypeInfo.d.ts index b4fa855569..98a53d37ef 100644 --- a/types/graphql/utilities/TypeInfo.d.ts +++ b/types/graphql/utilities/TypeInfo.d.ts @@ -36,10 +36,8 @@ export class TypeInfo { leave(node: ASTNode): any; } -export interface getFieldDef { - ( - schema: GraphQLSchema, - parentType: GraphQLType, - fieldNode: FieldNode - ): GraphQLField -} +export type getFieldDef = ( + schema: GraphQLSchema, + parentType: GraphQLType, + fieldNode: FieldNode, +) => GraphQLField; diff --git a/types/graphql/utilities/assertValidName.d.ts b/types/graphql/utilities/assertValidName.d.ts index 6104a26063..5ca2310a26 100644 --- a/types/graphql/utilities/assertValidName.d.ts +++ b/types/graphql/utilities/assertValidName.d.ts @@ -1,2 +1,2 @@ // Helper to assert that provided names are valid. -export function assertValidName(name: string): void; \ No newline at end of file +export function assertValidName(name: string): void; diff --git a/types/graphql/utilities/astFromValue.d.ts b/types/graphql/utilities/astFromValue.d.ts index 3d8ecdd0ec..44745c5e6c 100644 --- a/types/graphql/utilities/astFromValue.d.ts +++ b/types/graphql/utilities/astFromValue.d.ts @@ -1,12 +1,15 @@ import { ValueNode, - //IntValueNode, - //FloatValueNode, - //StringValueNode, - //BooleanValueNode, - //EnumValueNode, - //ListValueNode, - //ObjectValueNode, + /* + TODO: + IntValueNode, + FloatValueNode, + StringValueNode, + BooleanValueNode, + EnumValueNode, + ListValueNode, + ObjectValueNode, + */ } from '../language/ast'; import { GraphQLInputType } from '../type/definition'; @@ -30,4 +33,4 @@ import { GraphQLInputType } from '../type/definition'; export function astFromValue( value: any, type: GraphQLInputType -): ValueNode // Warning: there is a code in bottom: throw new TypeError +): ValueNode; // Warning: there is a code in bottom: throw new TypeError diff --git a/types/graphql/utilities/buildASTSchema.d.ts b/types/graphql/utilities/buildASTSchema.d.ts index 94f4e2a47a..b20c8fc856 100644 --- a/types/graphql/utilities/buildASTSchema.d.ts +++ b/types/graphql/utilities/buildASTSchema.d.ts @@ -2,7 +2,6 @@ import { DocumentNode, Location } from '../language/ast'; import { Source } from '../language/source'; import { GraphQLSchema } from '../type/schema'; - /** * This takes the ast of a schema document produced by the parse function in * src/language/parser.js. @@ -24,5 +23,5 @@ export function getDescription(node: { loc?: Location }): string; /** * A helper function to build a GraphQLSchema directly from a source * document. -*/ + */ export function buildSchema(source: string | Source): GraphQLSchema; diff --git a/types/graphql/utilities/buildClientSchema.d.ts b/types/graphql/utilities/buildClientSchema.d.ts index 391e651f52..166ec43cf7 100644 --- a/types/graphql/utilities/buildClientSchema.d.ts +++ b/types/graphql/utilities/buildClientSchema.d.ts @@ -1,7 +1,6 @@ import { IntrospectionQuery } from './introspectionQuery'; import { GraphQLSchema } from '../type/schema'; - /** * Build a GraphQLSchema for use by client tools. * diff --git a/types/graphql/utilities/concatAST.d.ts b/types/graphql/utilities/concatAST.d.ts index 1f6fcb985f..405ac69936 100644 --- a/types/graphql/utilities/concatAST.d.ts +++ b/types/graphql/utilities/concatAST.d.ts @@ -1,9 +1,8 @@ import { DocumentNode } from '../language/ast'; - /** * Provided a collection of ASTs, presumably each from different files, * concatenate the ASTs together into batched AST, useful for validating many * GraphQL source files which together represent one conceptual application. */ -export function concatAST(asts: Array): DocumentNode; +export function concatAST(asts: DocumentNode[]): DocumentNode; diff --git a/types/graphql/utilities/extendSchema.d.ts b/types/graphql/utilities/extendSchema.d.ts index 60b91e70b2..f7d00b2fee 100644 --- a/types/graphql/utilities/extendSchema.d.ts +++ b/types/graphql/utilities/extendSchema.d.ts @@ -1,7 +1,6 @@ import { DocumentNode } from '../language/ast'; import { GraphQLSchema } from '../type/schema'; - /** * Produces a new schema given an existing schema and a document which may * contain GraphQL type extensions and definitions. The original schema will diff --git a/types/graphql/utilities/findBreakingChanges.d.ts b/types/graphql/utilities/findBreakingChanges.d.ts index 94a74ced90..78d5a5a95b 100644 --- a/types/graphql/utilities/findBreakingChanges.d.ts +++ b/types/graphql/utilities/findBreakingChanges.d.ts @@ -10,7 +10,6 @@ import { } from '../type/definition'; import { GraphQLSchema } from '../type/schema'; - export const BreakingChangeType: { FIELD_CHANGED_KIND: 'FIELD_CHANGED_KIND', FIELD_REMOVED: 'FIELD_REMOVED', @@ -20,17 +19,18 @@ export const BreakingChangeType: { VALUE_REMOVED_FROM_ENUM: 'VALUE_REMOVED_FROM_ENUM', }; -export type BreakingChangeKey = 'FIELD_CHANGED_KIND' +export type BreakingChangeKey = + | 'FIELD_CHANGED_KIND' | 'FIELD_REMOVED' | 'TYPE_CHANGED_KIND' | 'TYPE_REMOVED' | 'TYPE_REMOVED_FROM_UNION' | 'VALUE_REMOVED_FROM_ENUM'; -export type BreakingChange = { +export interface BreakingChange { type: BreakingChangeKey; description: string; -}; +} /** * Given two schemas, returns an Array containing descriptions of all the types @@ -39,7 +39,7 @@ export type BreakingChange = { export function findBreakingChanges( oldSchema: GraphQLSchema, newSchema: GraphQLSchema -): Array +): BreakingChange[]; /** * Given two schemas, returns an Array containing descriptions of any breaking @@ -48,7 +48,7 @@ export function findBreakingChanges( export function findRemovedTypes( oldSchema: GraphQLSchema, newSchema: GraphQLSchema -): Array +): BreakingChange[]; /** * Given two schemas, returns an Array containing descriptions of any breaking @@ -57,7 +57,7 @@ export function findRemovedTypes( export function findTypesThatChangedKind( oldSchema: GraphQLSchema, newSchema: GraphQLSchema -): Array +): BreakingChange[]; /** * Given two schemas, returns an Array containing descriptions of any breaking @@ -67,7 +67,7 @@ export function findTypesThatChangedKind( export function findFieldsThatChangedType( oldSchema: GraphQLSchema, newSchema: GraphQLSchema -): Array; +): BreakingChange[]; /** * Given two schemas, returns an Array containing descriptions of any breaking @@ -76,7 +76,7 @@ export function findFieldsThatChangedType( export function findTypesRemovedFromUnions( oldSchema: GraphQLSchema, newSchema: GraphQLSchema -): Array; +): BreakingChange[]; /** * Given two schemas, returns an Array containing descriptions of any breaking @@ -85,4 +85,4 @@ export function findTypesRemovedFromUnions( export function findValuesRemovedFromEnums( oldSchema: GraphQLSchema, newSchema: GraphQLSchema -): Array; +): BreakingChange[]; diff --git a/types/graphql/utilities/findDeprecatedUsages.d.ts b/types/graphql/utilities/findDeprecatedUsages.d.ts index 58e9ae1685..8f6ff48239 100644 --- a/types/graphql/utilities/findDeprecatedUsages.d.ts +++ b/types/graphql/utilities/findDeprecatedUsages.d.ts @@ -10,4 +10,4 @@ import { GraphQLError } from '../error/GraphQLError'; export function findDeprecatedUsages( schema: GraphQLSchema, ast: DocumentNode -): Array +): GraphQLError[]; diff --git a/types/graphql/utilities/introspectionQuery.d.ts b/types/graphql/utilities/introspectionQuery.d.ts index cb9f0267b6..a89c5c1fec 100644 --- a/types/graphql/utilities/introspectionQuery.d.ts +++ b/types/graphql/utilities/introspectionQuery.d.ts @@ -95,26 +95,25 @@ fragment TypeRef on __Type { */ export const introspectionQuery: string; - export interface IntrospectionQuery { - __schema: IntrospectionSchema + __schema: IntrospectionSchema; } export interface IntrospectionSchema { queryType: IntrospectionNamedTypeRef; mutationType?: IntrospectionNamedTypeRef; subscriptionType?: IntrospectionNamedTypeRef; - types: Array; - directives: Array; + types: IntrospectionType[]; + directives: IntrospectionDirective[]; } export type IntrospectionType = - IntrospectionScalarType | - IntrospectionObjectType | - IntrospectionInterfaceType | - IntrospectionUnionType | - IntrospectionEnumType | - IntrospectionInputObjectType; + | IntrospectionScalarType + | IntrospectionObjectType + | IntrospectionInterfaceType + | IntrospectionUnionType + | IntrospectionEnumType + | IntrospectionInputObjectType; export interface IntrospectionScalarType { kind: 'SCALAR'; @@ -126,43 +125,43 @@ export interface IntrospectionObjectType { kind: 'OBJECT'; name: string; description?: string; - fields: Array; - interfaces: Array; + fields: IntrospectionField[]; + interfaces: IntrospectionNamedTypeRef[]; } export interface IntrospectionInterfaceType { kind: 'INTERFACE'; name: string; description?: string; - fields: Array; - possibleTypes: Array; + fields: IntrospectionField[]; + possibleTypes: IntrospectionNamedTypeRef[]; } export interface IntrospectionUnionType { kind: 'UNION'; name: string; description?: string; - possibleTypes: Array; + possibleTypes: IntrospectionNamedTypeRef[]; } export interface IntrospectionEnumType { kind: 'ENUM'; name: string; description?: string; - enumValues: Array; + enumValues: IntrospectionEnumValue[]; } export interface IntrospectionInputObjectType { kind: 'INPUT_OBJECT'; name: string; description?: string; - inputFields: Array; + inputFields: IntrospectionInputValue[]; } export type IntrospectionTypeRef = - IntrospectionNamedTypeRef | - IntrospectionListTypeRef | - IntrospectionNonNullTypeRef + | IntrospectionNamedTypeRef + | IntrospectionListTypeRef + | IntrospectionNonNullTypeRef; export interface IntrospectionNamedTypeRef { kind: string; @@ -182,7 +181,7 @@ export interface IntrospectionNonNullTypeRef { export interface IntrospectionField { name: string; description?: string; - args: Array; + args: IntrospectionInputValue[]; type: IntrospectionTypeRef; isDeprecated: boolean; deprecationReason?: string; @@ -205,6 +204,6 @@ export interface IntrospectionEnumValue { export interface IntrospectionDirective { name: string; description?: string; - locations: Array; - args: Array; + locations: DirectiveLocationEnum[]; + args: IntrospectionInputValue[]; } diff --git a/types/graphql/utilities/isValidJSValue.d.ts b/types/graphql/utilities/isValidJSValue.d.ts index a06706ec2c..cd11014579 100644 --- a/types/graphql/utilities/isValidJSValue.d.ts +++ b/types/graphql/utilities/isValidJSValue.d.ts @@ -8,4 +8,4 @@ import { GraphQLInputType } from '../type/definition'; export function isValidJSValue( value: any, type: GraphQLInputType -): Array +): string[]; diff --git a/types/graphql/utilities/isValidLiteralValue.d.ts b/types/graphql/utilities/isValidLiteralValue.d.ts index 71f7471a70..697c8eb97e 100644 --- a/types/graphql/utilities/isValidLiteralValue.d.ts +++ b/types/graphql/utilities/isValidLiteralValue.d.ts @@ -11,4 +11,4 @@ import { GraphQLInputType } from '../type/definition'; export function isValidLiteralValue( type: GraphQLInputType, valueNode: ValueNode -): Array +): string[]; diff --git a/types/graphql/utilities/separateOperations.d.ts b/types/graphql/utilities/separateOperations.d.ts index b5d9e7439a..4b4106df53 100644 --- a/types/graphql/utilities/separateOperations.d.ts +++ b/types/graphql/utilities/separateOperations.d.ts @@ -5,4 +5,4 @@ import { export function separateOperations( documentAST: DocumentNode -): { [operationName: string]: DocumentNode } +): { [operationName: string]: DocumentNode }; diff --git a/types/graphql/utilities/typeComparators.d.ts b/types/graphql/utilities/typeComparators.d.ts index f9442914d3..16e6acd680 100644 --- a/types/graphql/utilities/typeComparators.d.ts +++ b/types/graphql/utilities/typeComparators.d.ts @@ -7,7 +7,6 @@ import { GraphQLSchema } from '../type/schema'; - /** * Provided two types, return true if the types are equal (invariant). */ diff --git a/types/graphql/utilities/typeFromAST.d.ts b/types/graphql/utilities/typeFromAST.d.ts index ce1c8b061f..c3cacf90df 100644 --- a/types/graphql/utilities/typeFromAST.d.ts +++ b/types/graphql/utilities/typeFromAST.d.ts @@ -5,4 +5,4 @@ import { GraphQLSchema } from '../type/schema'; export function typeFromAST( schema: GraphQLSchema, typeNode: TypeNode -): GraphQLType +): GraphQLType; diff --git a/types/graphql/utilities/valueFromAST.d.ts b/types/graphql/utilities/valueFromAST.d.ts index a292e079ab..24dd435448 100644 --- a/types/graphql/utilities/valueFromAST.d.ts +++ b/types/graphql/utilities/valueFromAST.d.ts @@ -6,7 +6,6 @@ import { ObjectValueNode } from '../language/ast'; - export function valueFromAST( valueNode: ValueNode, type: GraphQLInputType, diff --git a/types/graphql/validation/validate.d.ts b/types/graphql/validation/validate.d.ts index 9f4a9afdad..a4b628777e 100644 --- a/types/graphql/validation/validate.d.ts +++ b/types/graphql/validation/validate.d.ts @@ -19,9 +19,6 @@ import { GraphQLDirective } from '../type/directives'; import { TypeInfo } from '../utilities/TypeInfo'; import { specifiedRules } from './specifiedRules'; - -//type ValidationRule = (context: ValidationContext) => any; - /** * Implements the "Validation" section of the spec. * @@ -38,8 +35,8 @@ import { specifiedRules } from './specifiedRules'; export function validate( schema: GraphQLSchema, ast: DocumentNode, - rules?: Array -): Array; + rules?: any[] +): GraphQLError[]; /** * This uses a specialized visitor which runs multiple visitors in parallel, @@ -51,13 +48,13 @@ export function visitUsingRules( schema: GraphQLSchema, typeInfo: TypeInfo, documentAST: DocumentNode, - rules: Array -): Array; + rules: any[] +): GraphQLError[]; export type NodeWithSelectionSet = OperationDefinitionNode | FragmentDefinitionNode; export interface VariableUsage { - node: VariableNode, - type: GraphQLInputType + node: VariableNode; + type: GraphQLInputType; } /** @@ -69,7 +66,7 @@ export class ValidationContext { constructor(schema: GraphQLSchema, ast: DocumentNode, typeInfo: TypeInfo); reportError(error: GraphQLError): void; - getErrors(): Array; + getErrors(): GraphQLError[]; getSchema(): GraphQLSchema; @@ -77,17 +74,17 @@ export class ValidationContext { getFragment(name: string): FragmentDefinitionNode; - getFragmentSpreads(node: SelectionSetNode): Array; + getFragmentSpreads(node: SelectionSetNode): FragmentSpreadNode[]; getRecursivelyReferencedFragments( operation: OperationDefinitionNode - ): Array; + ): FragmentDefinitionNode[]; - getVariableUsages(node: NodeWithSelectionSet): Array; + getVariableUsages(node: NodeWithSelectionSet): VariableUsage[]; getRecursiveVariableUsages( operation: OperationDefinitionNode - ): Array; + ): VariableUsage[]; getType(): GraphQLOutputType; @@ -100,4 +97,4 @@ export class ValidationContext { getDirective(): GraphQLDirective; getArgument(): GraphQLArgument; -} \ No newline at end of file +} diff --git a/types/gridstack/gridstack-tests.ts b/types/gridstack/gridstack-tests.ts index 0ef4a7691b..2cf6079b53 100644 --- a/types/gridstack/gridstack-tests.ts +++ b/types/gridstack/gridstack-tests.ts @@ -19,8 +19,10 @@ if (gridstack !== gsFromElement) throw Error('These should match!'); gridstack.addWidget("test", 1, 2, 3, 4, true); gridstack.addWidget(document.createElement('div'), 1, 2, 3, 4, true); gridstack.addWidget($(document.createElement('div')), 1, 2, 3, 4, true); +gridstack.makeWidget($(document.createElement('div'))); gridstack.batchUpdate(); gridstack.cellHeight();; gridstack.cellHeight(2); gridstack.cellWidth(); gridstack.getCellFromPixel({ left:20, top: 20 }); +gridstack.removeAll(false); \ No newline at end of file diff --git a/types/gridstack/index.d.ts b/types/gridstack/index.d.ts index 2406f5e08b..fa0c99463c 100644 --- a/types/gridstack/index.d.ts +++ b/types/gridstack/index.d.ts @@ -1,11 +1,11 @@ // Type definitions for Gridstack // Project: http://troolee.github.io/gridstack.js/ -// Definitions by: Pascal Senn , Ricky Blankenaufulland +// Definitions by: Pascal Senn , Ricky Blankenaufulland , Sl1MBoy // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped // TypeScript Version: 2.3 interface JQuery { - gridstack (options: IGridstackOptions): JQuery; + gridstack(options: IGridstackOptions): JQuery; data(key: "gridstack"): GridStack; } @@ -26,28 +26,29 @@ interface GridStack { /** * Initializes batch updates. You will see no changes until commit method is called. */ - batchUpdate():void + batchUpdate(): void /** * Gets current cell height. */ - cellHeight():number + cellHeight(): number /** * Update current cell height. This method rebuilds an internal CSS style sheet. Note: You can expect performance issues if call this method too often. * @param {number} val the cell height */ - cellHeight(val:number):void + cellHeight(val: number): void /** * Gets current cell width. */ - cellWidth():number + cellWidth(): number /** * Finishes batch updates. Updates DOM nodes. You must call it after batchUpdate. */ - commit():void + commit(): void /** * Destroys a grid instance. + * @param {boolean} detachGrid if false nodes and grid will not be removed from the DOM (Optional. Default true). */ - destroy(): void + destroy(detachGrid?: boolean): void /* * Disables widgets moving/resizing. */ @@ -56,12 +57,27 @@ interface GridStack { * Enables widgets moving/resizing. */ enable(): void - /* + /** + * Enables/disables widget moving. + * This is a shortcut for: + * grid.movable(this.container.children('.' + this.opts.itemClass), doEnable); + * @param {boolean} doEnable + * @param {boolean} includeNewWidgets will force new widgets to be draggable + */ + enableMove(doEnable: boolean, includeNewWidgets: boolean): void + /** + * Enables/disables widget resizing. + * @param {boolean} doEnable + * @param {boolean} includeNewWidgets will force new widgets to be resizable + */ + enableResize(doEnable: boolean, includeNewWidgets: boolean): void + /** * Get the position of the cell under a pixel on screen. * @param {MousePosition} position the position of the pixel to resolve in absolute coordinates, as an object with top and leftproperties + * @param {boolean} useOffset if true, value will be based on offset vs position (Optional. Default false). Useful when grid is within position: relative element. */ - getCellFromPixel(position: MousePosition): CellPosition, - /* + getCellFromPixel(position: MousePosition, useOffset?: boolean): CellPosition, + /** * Checks if specified area is empty. * @param {number} x the position x. * @param {number} y the position y. @@ -69,29 +85,49 @@ interface GridStack { * @param {number} height the height of to check */ isAreaEmpty(x: number, y: number, width: number, height: number): void - /* + /** * Locks/unlocks widget. * @param {HTMLElement} el widget to modify. * @param {boolean} val if true widget will be locked. */ locked(el: HTMLElement, val: boolean): void - /* + /** + * If you add elements to your gridstack container by hand, you have to tell gridstack afterwards to make them widgets. + * + * If you want gridstack to add the elements for you, use addWidget instead. Makes the given element a widget and returns it. + * + * @param {string | HTMLElement | JQuery} el widget to add + */ + makeWidget(el: string | HTMLElement | JQuery): JQuery + /** + * Set the maxWidth for a widget. + * @param {HTMLElement} el widget to modify. + * @param {number} val A numeric value of the number of columns + */ + maxWidth(el: HTMLElement, val: number): void + /** * Set the minWidth for a widget. * @param {HTMLElement} el widget to modify. * @param {number} val A numeric value of the number of columns */ minWidth(el: HTMLElement, val: number): void - /* + /** + * Set the maxHeight for a widget. + * @param {HTMLElement} el widget to modify. + * @param {number} val A numeric value of the number of rows + */ + maxHeight(el: HTMLElement, val: number): void + /** * Set the minHeight for a widget. * @param {HTMLElement} el widget to modify. * @param {number} val A numeric value of the number of rows */ minHeight(el: HTMLElement, val: number): void - /* - * Enables/Disables moving. - * @param {HTMLElement} el widget to modify. - * @param {number} val if true widget will be draggable. - */ + /** + * Enables/Disables moving. + * @param {HTMLElement} el widget to modify. + * @param {number} val if true widget will be draggable. + */ movable(el: HTMLElement, val: boolean): void /** * Changes widget position @@ -109,8 +145,9 @@ interface GridStack { removeWidget(el: HTMLElement, detachNode?: boolean): void /** * Removes all widgets from the grid. + * @param {boolean} detachNode if false DOM node won't be removed from the tree (Optional. Default true). */ - removeAll(): void + removeAll(detachNode?: boolean): void /** * Changes widget size * @param {HTMLElement} el widget to modify @@ -124,6 +161,19 @@ interface GridStack { * @param {boolean} val if true widget will be resizable. */ resizable(el: HTMLElement, val: boolean): void + /** + * Toggle the grid animation state. Toggles the grid-stack-animate class. + * @param {boolean} doAnimate if true the grid will animate. + */ + setAnimation(doAnimate: boolean): void + /** + * (Experimental) Modify number of columns in the grid. + * Will attempt to update existing widgets to conform to new number of columns. + * Requires gridstack-extra.css or gridstack-extra.min.css. + * @param {number} gridWidth Integer between 1 and 12. + * @param {boolean} doNotPropagate if true existing widgets will not be updated. + */ + setGridWidth(gridWidth: number, doNotPropagate: boolean): void /** * Toggle the grid static state. Also toggle the grid-stack-static class. * @param {boolean} staticValue if true the grid become static. @@ -138,6 +188,12 @@ interface GridStack { * @param {number} height new dimensions height. If value is null or undefined it will be ignored. */ update(el: HTMLElement, x: number, y: number, width: number, height: number): void + /** + * Sets the vertial margin + * @param {number} value new vertical margin value. + * @param {boolean} noUpdate if true, styles will not be updated. + */ + verticalMargin(value: number, noUpdate: boolean): void /** * Returns true if the height of the grid will be less the vertical constraint. Always returns true if grid doesn't have height constraint. * @param {number} x new position x. If value is null or undefined it will be ignored. @@ -146,8 +202,9 @@ interface GridStack { * @param {number} height new dimensions height. If value is null or undefined it will be ignored. * @param {boolean} autoPosition if true then x, y parameters will be ignored and widget will be places on the first available position */ - willItFit(x: number, y: number, width: number, height: number, autoPosition:boolean):boolean + willItFit(x: number, y: number, width: number, height: number, autoPosition: boolean): boolean + } /** @@ -155,14 +212,14 @@ interface GridStack { */ interface MousePosition { top: number, - left:number, + left: number, } /** * Defines the position of a cell inside the grid */ interface CellPosition { x: number, - y:number + y: number } declare namespace GridStackUI { interface Utils { @@ -172,7 +229,7 @@ declare namespace GridStackUI { *@param dir 1 for asc, -1 for desc (optional) *@param width width of the grid. If undefined the width will be calculated automatically (optional). **/ - sort(nodes: HTMLElement[], dir: number, width: number): void + sort(nodes: HTMLElement[], dir?: number, width?: number): void } } /** @@ -180,6 +237,10 @@ declare namespace GridStackUI { * Defines the options for a Gridstack */ interface IGridstackOptions { + /** + * if true of jquery selector the grid will accept widgets dragged from other grids or from outside (default: false) + */ + acceptWidgets?: boolean; /** * if true the resizing handles are shown even if the user is not hovering over the widget (default: false) */ @@ -196,6 +257,19 @@ interface IGridstackOptions { * one cell height (default: 60) */ cellHeight?: number; + /** + * class that implement drag'n'drop functionallity for gridstack. + * If false grid will be static. (default: null - first available plugin will be used) + */ + ddPlugin?: any; + /** + * disallows dragging of widgets (default: false). + */ + disableDrag?: boolean; + /** + * disallows resizing of widgets (default: false). + */ + disableResize?: boolean; /** * allows to override jQuery UI draggable options. (default: { handle: '.grid-stack-item-content', scroll: true, appendTo: 'body' }) */ @@ -204,6 +278,10 @@ interface IGridstackOptions { * draggable handle selector (default: '.grid-stack-item-content') */ handle?: string; + /** + * draggable handle class (e.g. 'grid-stack-item-content'). If set handle is ignored (default: null) + */ + handleClass?: string; /** * maximum rows amount.Default is 0 which means no maximum rows */ @@ -220,14 +298,38 @@ interface IGridstackOptions { * minimal width.If window width is less, grid will be shown in one - column mode (default: 768) */ minWidth?: number; + /** + * disables the onColumnMode when the window width is less than minWidth (default: 'false') + */ + disableOneColumnMode?: boolean; + /** + * class set on grid when in one column mode (default: 'grid-stack-one-column-mode') + */ + oneColumnModeClass?: string; /** * class for placeholder (default: 'grid-stack-placeholder') */ placeholderClass?: string; + /** + * placeholder default content (default: '') + */ + placeholderText?: string; /** * allows to override jQuery UI resizable options. (default: { autoHide: true, handles: 'se' }) */ resizable?: {}; + /** + * if true widgets could be removed by dragging outside of the grid. It could also be a jQuery selector string, + */ + removable?: boolean; + /** + * time in milliseconds before widget is being removed while dragging outside of the grid. (default: 2000) + */ + removeTimeout?: number; + /** + * if true turns grid to RTL. Possible values are true, false, 'auto' (default: 'auto') + */ + rtl?: boolean | 'auto'; /** * makes grid static (default false).If true widgets are not movable/ resizable.You don't even need jQueryUI draggable/resizable. A CSS class grid-stack-static is also added to the container. */ @@ -240,4 +342,4 @@ interface IGridstackOptions { * amount of columns (default: 12) */ width?: number; -} +} \ No newline at end of file diff --git a/types/gulp-watch/index.d.ts b/types/gulp-watch/index.d.ts index f9855f09a6..8b96e78c97 100644 --- a/types/gulp-watch/index.d.ts +++ b/types/gulp-watch/index.d.ts @@ -5,7 +5,7 @@ /// -import {SrcOptions} from "vinyl-fs"; +import { SrcOptions } from "vinyl-fs"; interface IOptions extends SrcOptions { ignoreInitial?: boolean; diff --git a/types/handlebars/index.d.ts b/types/handlebars/index.d.ts index 56c341aa47..006ef242c3 100644 --- a/types/handlebars/index.d.ts +++ b/types/handlebars/index.d.ts @@ -308,3 +308,7 @@ declare namespace hbs { declare module "handlebars" { export = Handlebars; } + +declare module "handlebars/handlebars.runtime" { + export = Handlebars; +} diff --git a/types/handsontable/index.d.ts b/types/handsontable/index.d.ts index 165d872e8f..6d86a085f1 100644 --- a/types/handsontable/index.d.ts +++ b/types/handsontable/index.d.ts @@ -1,6 +1,8 @@ // Type definitions for Handsontable 0.31 // Project: https://handsontable.com/ -// Definitions by: Handsoncode sp. z o.o. , Ryan Riley +// Definitions by: Handsoncode sp. z o.o. +// Ryan Riley +// Andrew Stegmaier // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped\ declare namespace __Handsontable { @@ -401,8 +403,100 @@ declare namespace Handsontable { } interface Hooks { + /** + * Adds a listener (globally or locally) to a specified hook name. + * + * @param key Hook name. + * @param callback Callback function or an array of functions. + * @param context (optional) The context for the hook callback to be added - a Handsontable instance or leave empty. + */ + add(key: string, callback: ((...params: any[]) => any | void) | Array<(...params: any[]) => any | void>, context?: Handsontable): Object; + + /** + * Returns a new object with empty handlers related to every registered hook name. + */ + createEmptyBucket(): Object; + + /** + * Deregisters a hook name (removes it from the list of known hook names). + * + * @param key Hook name. + */ + deregister(key: string): void; + + /** + * Destroy all listeners connected to the context. If no context is provided, the global listeners will be destroyed. + * + * @param context (optional) A Handsontable instance. + */ + destroy(context?: Handsontable): void; + + /** + * Get hook bucket based on the context of the object or if argument is undefined, get the global hook bucket. + * + * @param context (optional) A Handsontable instance. + */ + getBucket(context?: Handsontable): Object; + + /** + * Returns an array of registered hooks. + */ + getRegistered(): string[]; + + /** + * Checks whether there are any registered listeners for the provided hook name. + * + * @param key Hook name. + * @param context (optional) A Handsontable instance. + */ + has(key: string, context?: Handsontable): boolean; + + /** + * Returns a boolean depending on if a hook by such name has been registered. + * + * @param key Hook name. + */ + isRegistered(key: string): boolean; + + /** + * Adds a listener to a specified hook. After the hook runs this listener will be automatically removed from the bucket. + * + * @param key Hook/Event name. + * @param callback Callback function. + * @param context (optional) A Handsontable instance. + */ + once(key: string, callback: ((...params: any[]) => any | void) | Array<(...params: any[]) => any | void>, context?: Handsontable): void; + + /** + * Registers a hook name (adds it to the list of the known hook names). Used by plugins. + * + * @param key The hook name. + */ register(key: string): void; - run(instace: Core, hookName: string, key?: any, value?: any): any; + + /** + * Removes a listener from a hook with a given name. + * + * @param key Hook/Event name. + * @param callback Callback function. + * @param context (optional) A Handsontable instance. + */ + remove(key: string, callback: (...params: any[]) => any | void, context?: Handsontable): boolean; + + /** + * Runs all local and global callbacks assigned to the hook identified by the key parameter. + * It returns either a return value from the last called callback or the first parameter (p1) passed to the run function. + * + * @param context Handsontable instance. + * @param key Hook/Event name. + * @param p1 (optional) Parameter to be passed as an argument to the callback function. + * @param p2 (optional) Parameter to be passed as an argument to the callback function. + * @param p3 (optional) Parameter to be passed as an argument to the callback function. + * @param p4 (optional) Parameter to be passed as an argument to the callback function. + * @param p5 (optional) Parameter to be passed as an argument to the callback function. + * @param p6 (optional) Parameter to be passed as an argument to the callback function. + */ + run(context: Handsontable, key: string, p1?: any, p2?: any, p3?: any, p4?: any, p5?: any, p6?: any): any; } interface Dom { diff --git a/types/handsontable/test/global.ts b/types/handsontable/test/global.ts index 331f62759d..3760fb1f95 100644 --- a/types/handsontable/test/global.ts +++ b/types/handsontable/test/global.ts @@ -293,7 +293,32 @@ function test_HandsontableMethods() { Handsontable.renderers.TextRenderer(hot, new HTMLTableDataCellElement(), 0, 0, "prop", 1.235, {}); Handsontable.Dom.addEvent(new HTMLElement(), "eventName", () => { return; }); Handsontable.Dom.empty(new HTMLElement()); -} + + let bucket: {}; + let registeredHooks: string[]; + let hasHook: boolean; + let isRegistered: boolean; + bucket = Handsontable.hooks.add('beforeInit', () => { return; }); + bucket = Handsontable.hooks.add('beforeInit', () => { return; }, hot); + Handsontable.hooks.createEmptyBucket(); + Handsontable.hooks.deregister('myHook'); + Handsontable.hooks.destroy(); + Handsontable.hooks.destroy(hot); + bucket = Handsontable.hooks.getBucket(); + bucket = Handsontable.hooks.getBucket(hot); + registeredHooks = Handsontable.hooks.getRegistered(); + hasHook = Handsontable.hooks.has("myHook"); + hasHook = Handsontable.hooks.has("myHook", hot); + isRegistered = Handsontable.hooks.isRegistered("myHook"); + Handsontable.hooks.once('beforeInit', () => { return; }); + Handsontable.hooks.once('beforeInit', [() => { return; }, () => { return; }]); + Handsontable.hooks.once('beforeInit', () => { return; }, hot); + Handsontable.hooks.register('myHook'); + Handsontable.hooks.remove('beforeInit', () => { return; }); + Handsontable.hooks.remove('beforeInit', () => { return; }, hot); + Handsontable.hooks.run(hot, 'beforeInit'); + Handsontable.hooks.run(hot, 'beforeInit', 'param1', 'param2', 'param3', 'param4', 'param5', 'param6'); + } class MyCustomHotPlugin extends Handsontable.plugins.BasePlugin { isEnabled(): boolean { diff --git a/types/handsontable/test/module.ts b/types/handsontable/test/module.ts index a67ab6942d..0bdffed3f5 100644 --- a/types/handsontable/test/module.ts +++ b/types/handsontable/test/module.ts @@ -295,6 +295,31 @@ function test_HandsontableMethods() { Handsontable.renderers.TextRenderer(hot, new HTMLTableDataCellElement(), 0, 0, "prop", 1.235, {}); Handsontable.Dom.addEvent(new HTMLElement(), "eventName", () => { return; }); Handsontable.Dom.empty(new HTMLElement()); + + let bucket: {}; + let registeredHooks: string[]; + let hasHook: boolean; + let isRegistered: boolean; + bucket = Handsontable.hooks.add('beforeInit', () => { return; }); + bucket = Handsontable.hooks.add('beforeInit', () => { return; }, hot); + Handsontable.hooks.createEmptyBucket(); + Handsontable.hooks.deregister('myHook'); + Handsontable.hooks.destroy(); + Handsontable.hooks.destroy(hot); + bucket = Handsontable.hooks.getBucket(); + bucket = Handsontable.hooks.getBucket(hot); + registeredHooks = Handsontable.hooks.getRegistered(); + hasHook = Handsontable.hooks.has("myHook"); + hasHook = Handsontable.hooks.has("myHook", hot); + isRegistered = Handsontable.hooks.isRegistered("myHook"); + Handsontable.hooks.once('beforeInit', () => { return; }); + Handsontable.hooks.once('beforeInit', [() => { return; }, () => { return; }]); + Handsontable.hooks.once('beforeInit', () => { return; }, hot); + Handsontable.hooks.register('myHook'); + Handsontable.hooks.remove('beforeInit', () => { return; }); + Handsontable.hooks.remove('beforeInit', () => { return; }, hot); + Handsontable.hooks.run(hot, 'beforeInit'); + Handsontable.hooks.run(hot, 'beforeInit', 'param1', 'param2', 'param3', 'param4', 'param5', 'param6'); } class MyCustomHotPlugin extends Handsontable.plugins.BasePlugin { diff --git a/types/hapi-auth-jwt2/index.d.ts b/types/hapi-auth-jwt2/index.d.ts index 2e5826e044..0109bfb33d 100644 --- a/types/hapi-auth-jwt2/index.d.ts +++ b/types/hapi-auth-jwt2/index.d.ts @@ -2,7 +2,7 @@ // Project: http://github.com/dwyl/hapi-auth-jwt2 // Definitions by: Warren Seymour // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -import {Request, Response, PluginFunction} from 'hapi'; +import { Request, Response, PluginFunction } from 'hapi'; declare namespace hapiAuthJwt2 { /** diff --git a/types/hapi/index.d.ts b/types/hapi/index.d.ts index 91432e1d1f..87d7b94e35 100644 --- a/types/hapi/index.d.ts +++ b/types/hapi/index.d.ts @@ -42,7 +42,7 @@ import { type JoiValidationObject = JoiSchema | JoiSchemaMap | (JoiSchema | JoiSchemaMap)[]; import * as Catbox from 'catbox'; -import {MimosOptions} from 'mimos'; +import { MimosOptions } from 'mimos'; import Podium = require('podium'); import * as Shot from 'shot'; @@ -571,10 +571,10 @@ export interface ServerEventCriteria { * Related to [See docs](https://hapijs.com/api/16.1.1#servermethodname-method-options) */ export interface ServerMethod { - /** Not possible to improve this typing due to this unresolvable issue: https://github.com/Microsoft/TypeScript/issues/15190 */ - (...args: (any | ServerMethodNext)[]): void; /** the method must return a value (result, Error, or a promise) or throw an Error. */ (...args: any[]): any | Error | Promise; + /** Not possible to improve this typing due to this unresolvable issue: https://github.com/Microsoft/TypeScript/issues/15190 */ + (...args: (any | ServerMethodNext)[]): void; /** When configured with caching enabled, server.methods[name].cache will be an object see ServerMethodNameCacheObject */ cache?: ServerMethodNameCacheObject; } diff --git a/types/hapi/test/server/method.ts b/types/hapi/test/server/method.ts index a67022d250..e1cc2ce487 100644 --- a/types/hapi/test/server/method.ts +++ b/types/hapi/test/server/method.ts @@ -76,3 +76,21 @@ var config = { }; server.method(config); server.method([config]); + +// https://github.com/DefinitelyTyped/DefinitelyTyped/issues/18283 + +const syncX1 = function (arg1: string) { + return Promise.resolve("some value" + arg1); +} +type SyncX1 = typeof syncX1; + +const asyncX1 = function (callback: Hapi.ServerMethodNext) { + callback(null, "result"); +} +type AsyncX1 = typeof asyncX1; + +server.method("MethodSyncX1", syncX1); +server.method("MethodAsyncX1", asyncX1); +(server.methods.MethodSyncX1 as SyncX1)("argument1") as Promise; +const cb: Hapi.ServerMethodNext = (err, result, ttl) => {} +(server.methods.MethodAsyncX1 as AsyncX1)(cb) as void; diff --git a/types/hasha/hasha-tests.ts b/types/hasha/hasha-tests.ts new file mode 100644 index 0000000000..d0054de81a --- /dev/null +++ b/types/hasha/hasha-tests.ts @@ -0,0 +1,19 @@ +import hasha = require('hasha'); + +let str: string | null; +let buf: Buffer | null; + +str = hasha('unicorn'); +str = hasha('unicorn', {algorithm: 'md5'}); +str = hasha('unicorn', {algorithm: 'md5', encoding: 'latin1'}); +buf = hasha('unicorn', {algorithm: 'md5', encoding: 'buffer'}); + +process.stdin.pipe(hasha.stream()).pipe(process.stdout); + +hasha.fromStream(process.stdin).then(hash => str = hash); +hasha.fromStream(process.stdin, {encoding: 'hex'}).then(hash => str = hash); +hasha.fromStream(process.stdin, {encoding: 'buffer'}).then(hash => buf = hash); + +hasha.fromFile('unicorn.png').then(hash => str = hash); +hasha.fromFile('unicorn.png', {encoding: 'base64'}).then(hash => str = hash); +hasha.fromFile('unicorn.png', {encoding: 'buffer'}).then(hash => buf = hash); diff --git a/types/hasha/index.d.ts b/types/hasha/index.d.ts new file mode 100644 index 0000000000..a158af88a3 --- /dev/null +++ b/types/hasha/index.d.ts @@ -0,0 +1,38 @@ +// Type definitions for hasha 3.0 +// Project: https://github.com/sindresorhus/hasha +// Definitions by: BendingBender +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +/// +import * as crypto from "crypto"; + +export = hasha; + +declare function hasha(input: hasha.HashaInput): string; +declare function hasha(input: hasha.HashaInput, options: hasha.HashaOptions): string; +declare function hasha(input: hasha.HashaInput, options: hasha.HashaOptions): Buffer; + +declare namespace hasha { + type HashaInput = string | string[] | Buffer | Buffer[]; + type ToStringEncoding = 'hex' | 'base64' | 'latin1' | 'binary' | undefined; + type HashaEncoding = ToStringEncoding | 'buffer'; + + interface HashaOptions { + encoding?: E; + algorithm?: string; + } + + function stream(options?: HashaOptions): crypto.Hash; + + function fromStream(stream: NodeJS.ReadableStream): Promise; + function fromStream(stream: NodeJS.ReadableStream, options?: HashaOptions): Promise; + function fromStream(stream: NodeJS.ReadableStream, options?: HashaOptions): Promise; + + function fromFile(filePath: string): Promise; + function fromFile(filePath: string, options: HashaOptions): Promise; + function fromFile(filePath: string, options: HashaOptions): Promise; + + function fromFileSync(filePath: string): string; + function fromFileSync(filePath: string, options: HashaOptions): string; + function fromFileSync(filePath: string, options: HashaOptions): Buffer; +} diff --git a/types/hasha/tsconfig.json b/types/hasha/tsconfig.json new file mode 100644 index 0000000000..3aeb5973e8 --- /dev/null +++ b/types/hasha/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", + "hasha-tests.ts" + ] +} diff --git a/types/hasha/tslint.json b/types/hasha/tslint.json new file mode 100644 index 0000000000..3db14f85ea --- /dev/null +++ b/types/hasha/tslint.json @@ -0,0 +1 @@ +{ "extends": "dtslint/dt.json" } diff --git a/types/highcharts/index.d.ts b/types/highcharts/index.d.ts index 4a252c899f..914fb83f96 100644 --- a/types/highcharts/index.d.ts +++ b/types/highcharts/index.d.ts @@ -6694,6 +6694,8 @@ declare namespace Highcharts { getOptions(): Options; map(array: any[], fn: Function): any[]; + + wrap(prototype: any, type: string, cb: (proceed: Function, ...args: any[]) => void): void; } /** diff --git a/types/i18next-express-middleware/index.d.ts b/types/i18next-express-middleware/index.d.ts index 6676c5c9fa..f9877b2659 100644 --- a/types/i18next-express-middleware/index.d.ts +++ b/types/i18next-express-middleware/index.d.ts @@ -2,6 +2,7 @@ // Project: http://i18next.com/ // Definitions by: Cyril Schumacher // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.3 declare namespace I18next { interface I18nextOptions extends i18nextExpressMiddleware.I18nextOptions { } @@ -94,8 +95,8 @@ declare module "i18next-express-middleware" { init(services: any, options?: Object, allOptions?: Object): void; } - export function getResourcesHandler(i18next: i18next.I18n, options: Object): express.Handler; - export function handle(i18next: i18next.I18n, options?: Object): express.Handler; + export function getResourcesHandler(i18next: i18next.i18n, options: Object): express.Handler; + export function handle(i18next: i18next.i18n, options?: Object): express.Handler; /** * @summary Gets handler for missing key. @@ -103,5 +104,5 @@ declare module "i18next-express-middleware" { * @param {Object} options The options. * @return {express.Handler} The express handler. */ - export function missingKeyHandler(i18next: i18next.I18n, options: Object): express.Handler; + export function missingKeyHandler(i18next: i18next.i18n, options: Object): express.Handler; } diff --git a/types/i18next-express-middleware/tsconfig.json b/types/i18next-express-middleware/tsconfig.json index a194e6465c..6f42d82105 100644 --- a/types/i18next-express-middleware/tsconfig.json +++ b/types/i18next-express-middleware/tsconfig.json @@ -11,11 +11,6 @@ "typeRoots": [ "../" ], - "paths": { - "i18next": [ - "i18next/v2" - ] - }, "types": [], "noEmit": true, "forceConsistentCasingInFileNames": true diff --git a/types/iconv/iconv-tests.ts b/types/iconv/iconv-tests.ts index 396c207279..d3d9bff917 100644 --- a/types/iconv/iconv-tests.ts +++ b/types/iconv/iconv-tests.ts @@ -1,5 +1,5 @@ import Iconv = require("iconv"); -import {Writable} from "stream"; +import { Writable } from "stream"; const iconv: Iconv.Iconv = new Iconv("utf-8", "cp932"); const iconvFromFunction: Iconv.Iconv = Iconv("utf-8", "cp932"); diff --git a/types/imap-simple/imap-simple-tests.ts b/types/imap-simple/imap-simple-tests.ts index 39236023d5..9161ebb832 100644 --- a/types/imap-simple/imap-simple-tests.ts +++ b/types/imap-simple/imap-simple-tests.ts @@ -81,3 +81,21 @@ imaps.connect(config).then(function (connection) { // { filename: "pay-stub.pdf", data: Buffer() } ] }); }); + +imaps.connect({ + imap: config.imap, + onmail: function (numNewMail) { + //... + }, + onexpunge: function (seqno) { + //... + }, + onupdate: function (seqno, info) { + //... + } +}).then(function (connection) { + connection.on("error", err => { + console.error("imap socket error", err); + }) +}); + diff --git a/types/imap-simple/index.d.ts b/types/imap-simple/index.d.ts index 765c8a5f0a..9f851ae21b 100644 --- a/types/imap-simple/index.d.ts +++ b/types/imap-simple/index.d.ts @@ -1,8 +1,10 @@ -// Type definitions for imap-simple v1.6.3 +// Type definitions for imap-simple v3.1.0 // Project: https://github.com/chadxz/imap-simple // Definitions by: Jeffery Grajkowski // Definitions: https://github.com/psnider/DefinitelyTyped/imap-simple +/// + import Imap = require("imap"); export interface ImapSimpleOptions { @@ -11,6 +13,15 @@ export interface ImapSimpleOptions { /** Time in milliseconds to wait before giving up on a connection attempt. (Deprecated: please use options.imap.authTimeout instead) */ connectTimeout?: number; + + /** Server event emitted when new mail arrives in the currently open mailbox. */ + onmail?: (numNewMail: number) => void; + + /** Server event emitted when a message was expunged externally. seqno is the sequence number (instead of the unique UID) of the message that was expunged. If you are caching sequence numbers, all sequence numbers higher than this value MUST be decremented by 1 in order to stay synchronized with the server and to keep correct continuity. */ + onexpunge?: (seqno: number) => void; + + /** Server event emitted when message metadata (e.g. flags) changes externally. */ + onupdate?: (seqno: number, info: any) => void; } export interface MessageBodyPart extends Imap.ImapMessageBodyInfo { @@ -21,9 +32,10 @@ export interface MessageBodyPart extends Imap.ImapMessageBodyInfo { export interface Message { attributes: Imap.ImapMessageAttributes; parts: MessageBodyPart[]; + seqno: number; } -export class ImapSimple { +export class ImapSimple extends NodeJS.EventEmitter { constructor(imap: Imap); /** Open a mailbox, calling the provided callback with signature (err, boxName), or resolves the returned promise with boxName. */ @@ -48,6 +60,14 @@ export class ImapSimple { /** Moves the specified message(s) in the currently open mailbox to another mailbox. source corresponds to a node-imap MessageSource which specifies the messages to be moved. When completed, either calls the provided callback with signature (err), or resolves the returned promise. */ moveMessage(source: string | string[], boxName: string, callback: (err: Error) => void): void; moveMessage(source: string | string[], boxName: string): Promise; + + /** Adds the provided flag(s) to the specified message(s). uid is the uid of the message you want to add the flag to or an array of uids. flag is either a string or array of strings indicating the flags to add. */ + addFlags(source: string | string[], flag: string | string[], callback: (err: Error) => void): void; + addFlags(source: string | string[], flag: string | string[]): Promise; + + /** Removes the provided flag(s) from the specified message(s). uid is the uid of the message you want to remove the flag from or an array of uids. flag is either a string or array of strings indicating the flags to remove. */ + delFlags(source: string | string[], flag: string | string[], callback: (err: Error) => void): void; + delFlags(source: string | string[], flag: string | string[]): Promise; } export namespace errors { @@ -58,7 +78,6 @@ export namespace errors { } } - /** Main entry point. Connect to an Imap server. */ export function connect(options: ImapSimpleOptions, callback: (err: Error, connection: ImapSimple) => void): void; export function connect(options: ImapSimpleOptions): Promise; diff --git a/types/inherits/index.d.ts b/types/inherits/index.d.ts index 0c8b2f0f8c..4ae7eef4c5 100644 --- a/types/inherits/index.d.ts +++ b/types/inherits/index.d.ts @@ -6,5 +6,5 @@ /// -import {inherits} from "util"; +import { inherits } from "util"; export = inherits; diff --git a/types/inline-style-prefixer/index.d.ts b/types/inline-style-prefixer/index.d.ts new file mode 100644 index 0000000000..f5b496f25a --- /dev/null +++ b/types/inline-style-prefixer/index.d.ts @@ -0,0 +1,26 @@ +// Type definitions for inline-style-prefixer 3.0 +// Project: https://github.com/rofrischmann/inline-style-prefixer +// Definitions by: Andrej Hazucha +// dpetrezselyova +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +export = InlineStylePrefixer; + +interface Configuration { + userAgent?: string; + keepUnprefixed?: boolean; +} + +declare class InlineStylePrefixer { + constructor(cfg?: Configuration); + + prefix(style: CSSStyleDeclaration): CSSStyleDeclaration; + + // support for React.CSSProperties + prefix(style: T): T; + + static prefixAll(style: CSSStyleDeclaration): CSSStyleDeclaration; + + // support for React.CSSProperties + static prefixAll(style: T): T; +} diff --git a/types/inline-style-prefixer/inline-style-prefixer-tests.ts b/types/inline-style-prefixer/inline-style-prefixer-tests.ts new file mode 100644 index 0000000000..7592cdc252 --- /dev/null +++ b/types/inline-style-prefixer/inline-style-prefixer-tests.ts @@ -0,0 +1,8 @@ +import Prefixer = require('inline-style-prefixer'); + +const prefixer = new Prefixer(); + +const prefixed = prefixer.prefix({ + fontSize: '16', + flexDirection: 'column' +} as CSSStyleDeclaration); diff --git a/types/inline-style-prefixer/tsconfig.json b/types/inline-style-prefixer/tsconfig.json new file mode 100644 index 0000000000..a0651edee4 --- /dev/null +++ b/types/inline-style-prefixer/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", + "inline-style-prefixer-tests.ts" + ] +} diff --git a/types/inline-style-prefixer/tslint.json b/types/inline-style-prefixer/tslint.json new file mode 100644 index 0000000000..3db14f85ea --- /dev/null +++ b/types/inline-style-prefixer/tslint.json @@ -0,0 +1 @@ +{ "extends": "dtslint/dt.json" } diff --git a/types/into-stream/index.d.ts b/types/into-stream/index.d.ts new file mode 100644 index 0000000000..f682ff10a7 --- /dev/null +++ b/types/into-stream/index.d.ts @@ -0,0 +1,17 @@ +// Type definitions for into-stream 3.1 +// Project: https://github.com/sindresorhus/into-stream +// Definitions by: BendingBender +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.3 + +/// + +export = intoStream; + +declare function intoStream(input: intoStream.Input | Promise): NodeJS.ReadableStream; + +declare namespace intoStream { + function obj(input: object | Iterable | Promise>): NodeJS.ReadableStream; + + type Input = Buffer | string | Iterable; +} diff --git a/types/into-stream/into-stream-tests.ts b/types/into-stream/into-stream-tests.ts new file mode 100644 index 0000000000..e1f3a9a7b0 --- /dev/null +++ b/types/into-stream/into-stream-tests.ts @@ -0,0 +1,27 @@ +import intoStream = require('into-stream'); + +function iterableFrom(arr: any[]) { + return { + *[Symbol.iterator]() { + let i = 0; + while (i < arr.length) { + yield arr[i++]; + } + } + }; +} + +intoStream('unicorn').pipe(process.stdout); +intoStream('unicorn'.split('')).pipe(process.stdout); +intoStream(iterableFrom('unicorn'.split(''))).pipe(process.stdout); +intoStream(new Buffer('unicorn')).pipe(process.stdout); +intoStream(Promise.resolve('unicorn')).pipe(process.stdout); + +const f = {foo: true}; +const f2 = [{foo: true}, {bar: true}]; +intoStream.obj(f).pipe(process.stdout); +intoStream.obj(f2).pipe(process.stdout); +intoStream.obj(iterableFrom(f2)).pipe(process.stdout); +intoStream.obj(Promise.resolve(f)).pipe(process.stdout); +intoStream.obj(Promise.resolve(f2)).pipe(process.stdout); +intoStream.obj(Promise.resolve(iterableFrom(f2))).pipe(process.stdout); diff --git a/types/into-stream/tsconfig.json b/types/into-stream/tsconfig.json new file mode 100644 index 0000000000..c48cf3e387 --- /dev/null +++ b/types/into-stream/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", + "into-stream-tests.ts" + ] +} diff --git a/types/into-stream/tslint.json b/types/into-stream/tslint.json new file mode 100644 index 0000000000..3db14f85ea --- /dev/null +++ b/types/into-stream/tslint.json @@ -0,0 +1 @@ +{ "extends": "dtslint/dt.json" } diff --git a/types/is-ip/index.d.ts b/types/is-ip/index.d.ts new file mode 100644 index 0000000000..930cb8951d --- /dev/null +++ b/types/is-ip/index.d.ts @@ -0,0 +1,35 @@ +// Type definitions for is-ip 2.0 +// Project: https://github.com/sindresorhus/is-ip#readme +// Definitions by: coderslagoon +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +/** + * Check if input is IPv4 or IPv6. + * + * @param {input} input + * + * @returns {boolean} + */ +declare function isIp(input: string): boolean; + +declare namespace isIp { + /** + * Check if input is IPv4. + * + * @param {input} input + * + * @returns {boolean} + */ + function v4(input: string): boolean; + + /** + * Check if input is IPv6. + * + * @param {input} input + * + * @returns {boolean} + */ + function v6(input: string): boolean; +} + +export = isIp; diff --git a/types/is-ip/is-ip-tests.ts b/types/is-ip/is-ip-tests.ts new file mode 100644 index 0000000000..d062f6dde9 --- /dev/null +++ b/types/is-ip/is-ip-tests.ts @@ -0,0 +1,28 @@ +import * as isIp from "is-ip"; + +isIp("nope"); +// => false + +isIp("127.0.0.1"); +// => true + +isIp("0.0.0.0"); +// => true + +isIp("127.0.0.256"); +// => false + +isIp.v4("127.0.0.1"); +// => true + +isIp.v4("1:2:3:4:5:6:7:8"); +// => false + +isIp.v6("1:2:3:4:5:6:7:8"); +// => true + +isIp.v6("::"); +// => true + +isIp.v6("127.0.0.1"); +// => false diff --git a/types/is-ip/tsconfig.json b/types/is-ip/tsconfig.json new file mode 100644 index 0000000000..be6e5c55e0 --- /dev/null +++ b/types/is-ip/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", + "is-ip-tests.ts" + ] +} diff --git a/types/is-ip/tslint.json b/types/is-ip/tslint.json new file mode 100644 index 0000000000..3db14f85ea --- /dev/null +++ b/types/is-ip/tslint.json @@ -0,0 +1 @@ +{ "extends": "dtslint/dt.json" } diff --git a/types/is-stream/index.d.ts b/types/is-stream/index.d.ts new file mode 100644 index 0000000000..0c24d084d9 --- /dev/null +++ b/types/is-stream/index.d.ts @@ -0,0 +1,18 @@ +// Type definitions for is-stream 1.1 +// Project: https://github.com/sindresorhus/is-stream#readme +// Definitions by: BendingBender +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +/// +import * as stream from "stream"; + +export = isStream; + +declare function isStream(maybeStream: any): maybeStream is stream.Stream; + +declare namespace isStream { + function writable(maybeWritable: any): maybeWritable is stream.Writable; + function readable(maybeReadable: any): maybeReadable is stream.Readable; + function duplex(maybeDuplex: any): maybeDuplex is stream.Duplex; + function transform(maybeTransform: any): maybeTransform is stream.Transform; +} diff --git a/types/is-stream/is-stream-tests.ts b/types/is-stream/is-stream-tests.ts new file mode 100644 index 0000000000..9d9eb315b4 --- /dev/null +++ b/types/is-stream/is-stream-tests.ts @@ -0,0 +1,24 @@ +import isStream = require('is-stream'); +import * as stream from 'stream'; + +const anyStream: any = new stream.Stream(); + +if (isStream(anyStream)) { + const justStream: stream.Stream = anyStream; +} + +if (isStream.writable(anyStream)) { + const writableStream: stream.Writable = anyStream; +} + +if (isStream.readable(anyStream)) { + const readableStream: stream.Readable = anyStream; +} + +if (isStream.duplex(anyStream)) { + const duplexStream: stream.Duplex = anyStream; +} + +if (isStream.transform(anyStream)) { + const transformStream: stream.Transform = anyStream; +} diff --git a/types/is-stream/tsconfig.json b/types/is-stream/tsconfig.json new file mode 100644 index 0000000000..926737569f --- /dev/null +++ b/types/is-stream/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", + "is-stream-tests.ts" + ] +} diff --git a/types/is-stream/tslint.json b/types/is-stream/tslint.json new file mode 100644 index 0000000000..3db14f85ea --- /dev/null +++ b/types/is-stream/tslint.json @@ -0,0 +1 @@ +{ "extends": "dtslint/dt.json" } diff --git a/types/is-svg/index.d.ts b/types/is-svg/index.d.ts new file mode 100644 index 0000000000..21e85cd2e2 --- /dev/null +++ b/types/is-svg/index.d.ts @@ -0,0 +1,8 @@ +// Type definitions for is-svg 2.1 +// Project: https://github.com/sindresorhus/is-svg#readme +// Definitions by: BendingBender +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +export = isSvg; + +declare function isSvg(input: string): boolean; diff --git a/types/is-svg/is-svg-tests.ts b/types/is-svg/is-svg-tests.ts new file mode 100644 index 0000000000..d556a944f9 --- /dev/null +++ b/types/is-svg/is-svg-tests.ts @@ -0,0 +1,3 @@ +import isSvg = require('is-svg'); + +const result: boolean = isSvg(''); diff --git a/types/is-svg/tsconfig.json b/types/is-svg/tsconfig.json new file mode 100644 index 0000000000..9776ba1c77 --- /dev/null +++ b/types/is-svg/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", + "is-svg-tests.ts" + ] +} diff --git a/types/is-svg/tslint.json b/types/is-svg/tslint.json new file mode 100644 index 0000000000..3db14f85ea --- /dev/null +++ b/types/is-svg/tslint.json @@ -0,0 +1 @@ +{ "extends": "dtslint/dt.json" } diff --git a/types/japanese-holidays/japanese-holidays-tests.ts b/types/japanese-holidays/japanese-holidays-tests.ts index 32f760360e..a3f77b2dc4 100644 --- a/types/japanese-holidays/japanese-holidays-tests.ts +++ b/types/japanese-holidays/japanese-holidays-tests.ts @@ -1,4 +1,4 @@ -import {isHoliday, isHolidayAt, getHolidaysOf} from 'japanese-holidays'; +import { isHoliday, isHolidayAt, getHolidaysOf } from 'japanese-holidays'; const date = new Date(2017, 0, 9); const h: string | undefined = isHoliday(date); diff --git a/types/jasmine-enzyme/index.d.ts b/types/jasmine-enzyme/index.d.ts new file mode 100644 index 0000000000..df8d9aaf16 --- /dev/null +++ b/types/jasmine-enzyme/index.d.ts @@ -0,0 +1,30 @@ +// Type definitions for jasmine-enzyme 3.6 +// Project: https://github.com/blainekasten/enzyme-matchers/blob/master/packages/jasmine-enzyme/README.md +// Definitions by: Umar Bolatov +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.4 + +/// +/// + +declare namespace jasmine { + interface Matchers { + toBeChecked(): boolean; + toBeDisabled(): boolean; + toBeEmpty(): boolean; + toBePresent(): boolean; + toContainReact(reactInstance: JSX.Element): boolean; + toHaveClassName(className: string): boolean; + toHaveHTML(html: string): boolean; + toHaveProp(propKey: string, propValue?: any): boolean; + toHaveRef(refName: string): string; + toHaveState(stateKey: string, stateValue?: any): boolean; + toHaveStyle(styleKey: string, styleValue?: any): boolean; + toHaveTagName(tagName: string): boolean; + toHaveText(text?: string): boolean; + toIncludeText(text: string): boolean; + toHaveValue(value: any): boolean; + toMatchElement(reactInstance: JSX.Element): boolean; + toMatchSelector(selector: string): boolean; + } +} diff --git a/types/jasmine-enzyme/jasmine-enzyme-tests.tsx b/types/jasmine-enzyme/jasmine-enzyme-tests.tsx new file mode 100644 index 0000000000..53ee972ed3 --- /dev/null +++ b/types/jasmine-enzyme/jasmine-enzyme-tests.tsx @@ -0,0 +1,462 @@ +import * as React from "react"; +import { mount, render } from "enzyme"; + +describe('toBeChecked', () => { + function Fixture() { + return ( +
+ + + +
+ ); + } + const wrapper = mount(); + + describe('matches', () => { + it('should pass', () => { + expect(wrapper.find('#checked')).toBeChecked(); + }); + }); + + describe('.not matches', () => { + it('should pass', () => { + expect(wrapper.find('#not')).not.toBeChecked(); + }); + }); +}); + +describe('toBeDisabled', () => { + function Fixture() { + return ( +
+ + +
+ ); + } + const wrapper = mount(); + + describe('matches', () => { + it('should pass', () => { + expect(wrapper.find('#disabled')).toBeDisabled(); + }); + }); + + describe('.not matches', () => { + it('should pass', () => { + expect(wrapper.find('#not')).not.toBeDisabled(); + }); + }); +}); + +describe('toBeEmpty', () => { + function Fixture() { + return ( +
+ + +
+ ); + } + const wrapper = mount(); + + describe('matches', () => { + it('should pass', () => { + expect(wrapper.find('ul')).toBeEmpty(); + }); + }); + + describe('.not matches', () => { + it('should pass', () => { + expect(wrapper.find('span')).not.toBeEmpty(); + }); + }); +}); + +describe('toBePresent', () => { + function Fixture() { + return ( +
+ + +
+ ); + } + const wrapper = mount(); + + describe('matches', () => { + it('should pass', () => { + expect(wrapper.find('span')).toBePresent(); + }); + }); + + describe('.not matches', () => { + it('should pass', () => { + expect(wrapper.find('ul')).not.toBePresent(); + }); + }); +}); + +describe('toContainReact', () => { + class User extends React.Component<{ index: number }> { + render() { + return ( + User {this.props.index} + ); + } + } + + class Fixture extends React.Component { + render() { + return ( +
+
    +
  • +
  • +
+
+ ); + } + } + const wrapper = mount(); + + describe('matches', () => { + it('should pass', () => { + expect(wrapper).toContainReact(); + }); + }); + + describe('.not matches', () => { + it('should pass', () => { + expect(wrapper).not.toContainReact(); + }); + }); +}); + +describe('toHaveClassName', () => { + function Fixture() { + return ( +
+ + +
+ ); + } + const wrapper = mount(); + + describe('matches', () => { + it('should pass', () => { + expect(wrapper.find('.foo')).toHaveClassName('foo'); + expect(wrapper.find('.bar')).toHaveClassName('bar baz'); + expect(wrapper.find('.bar')).toHaveClassName('baz'); + }); + }); + + describe('.not matches', () => { + it('should pass', () => { + expect(wrapper.find('.foo')).not.toHaveClassName('baz'); + }); + }); +}); + +describe('toHaveHTML', () => { + function Fixture() { + return ( +
+ Test +
+ ); + } + const wrapper = mount(); + + describe('matches', () => { + it('should pass', () => { + expect(wrapper.find('#child')).toHaveHTML( + 'Test' + ); + }); + }); + + describe('.not matches', () => { + it('should pass', () => { + expect(wrapper.find('#child')).toHaveHTML( + '
Test' + ); + }); + }); +}); + +describe('toHaveProp', () => { + function User(props: { foo: string, bar: number[] }) { + return ( +
+ ); + } + + function Fixture() { + return ( +
+ +
+ ); + } + + const wrapper = mount(); + + describe('matches', () => { + it('should have prop "foo"', () => { + expect(wrapper.find(User)).toHaveProp('foo'); + expect(wrapper.find(User)).toHaveProp('foo', 'baz'); + }); + + it('should have prop "bar"', () => { + expect(wrapper.find(User)).toHaveProp('bar'); + expect(wrapper.find(User)).toHaveProp('bar', [1, 2, 3]); + }); + }); + + describe('.not matches', () => { + it('should not have prop "baz"', () => { + expect(wrapper.find(User)).not.toHaveProp('baz'); + }); + }); +}); + +describe('toHaveRef', () => { + class Fixture extends React.Component { + render() { + return ( +
+ +
+ ); + } + } + const wrapper = mount(); + + describe('matches', () => { + it('should pass', () => { + expect(wrapper).toHaveRef('child'); + }); + }); + + describe('.not matches', () => { + it('should pass', () => { + expect(wrapper).not.toHaveRef('foo'); + }); + }); +}); + +describe('toHaveState', () => { + class Fixture extends React.Component { + constructor() { + super(); + this.state = { + foo: false, + }; + } + + render() { + return ( +
+ ); + } + } + + const wrapper = mount(); + + describe('matches', () => { + it('should pass', () => { + expect(wrapper).toHaveState('foo'); + expect(wrapper).toHaveState('foo', false); + }); + }); + + describe('.not matches', () => { + it('should pass', () => { + expect(wrapper).not.toHaveState('bar'); + }); + }); +}); + +describe('toHaveStyle', () => { + function Fixture() { + const style1 = { height: '100%' }; + const style2 = { flex: 8 }; + + return ( +
+ + +
+ ); + } + const wrapper = mount(); + + describe('matches', () => { + it('should pass', () => { + expect(wrapper.find('#style1')).toHaveStyle('height', '100%'); + expect(wrapper.find('#style2')).toHaveStyle('flex', 8); + }); + }); + + describe('.not matches', () => { + it('should pass', () => { + expect(wrapper).not.toHaveStyle('width'); + expect(wrapper).not.toHaveStyle('height', '50%'); + }); + }); +}); + +describe('toHaveTagName', () => { + function Fixture() { + return ( +
+ +
+ ); + } + const wrapper = mount(); + + describe('matches', () => { + it('should pass', () => { + expect(wrapper.find('#span')).toHaveTagName('span'); + }); + }); + + describe('.not matches', () => { + it('should pass', () => { + expect(wrapper.find('#span')).not.toHaveTagName('div'); + }); + }); +}); + +describe('toHaveText', () => { + function Fixture() { + return ( +
+

Text

+

+
+ ); + } + const wrapper = mount(); + + describe('matches', () => { + it('should pass', () => { + expect(wrapper.find('#full')).toHaveText('Text'); + expect(wrapper.find('#full')).toHaveText(); + }); + }); + + describe('.not matches', () => { + it('should pass', () => { + expect(wrapper.find('#full')).not.toHaveText('Wrong'); + expect(wrapper.find('#empty')).not.toHaveText(); + }); + }); +}); + +describe('toIncludeText', () => { + function Fixture() { + return ( +
+

Some important text

+
+ ); + } + const wrapper = mount(); + + describe('matches', () => { + it('should pass', () => { + expect(wrapper.find('#full')).toIncludeText('important'); + }); + }); + + describe('.not matches', () => { + it('should pass', () => { + expect(wrapper.find('#full')).not.toIncludeText('Wrong'); + }); + }); +}); + +describe('toHaveValue', () => { + function Fixture() { + return ( +
+ + {}} /> +
+ ); + } + const wrapper = mount(); + + describe('matches', () => { + it('should pass', () => { + expect(wrapper.find('input').at(0)).toHaveValue('test'); + expect(wrapper.find('input').at(1)).toHaveValue('bar'); + }); + }); + + describe('.not matches', () => { + it('should pass', () => { + expect(wrapper.find('input').at(0)).not.toHaveValue('bar'); + expect(wrapper.find('input').at(1)).not.toHaveValue('test'); + }); + }); +}); + +describe('toMatchElement', () => { + function Fixture() { + return ( +
+ +
+ ); + } + const wrapper = mount(); + + describe('matches', () => { + it('should pass', () => { + expect(wrapper).toMatchElement(); + expect(wrapper.find('span')).toMatchElement( + + ); + }); + }); + + describe('.not matches', () => { + it('should pass', () => { + expect(wrapper).not.toMatchElement(
); + }); + }); +}); + +describe('toMatchSelector', () => { + function Fixture() { + return ( +
+ +
+ ); + } + const wrapper = mount(); + + describe('matches', () => { + it('should pass', () => { + expect(wrapper.find('span')).toMatchSelector('span'); + expect(wrapper.find('span')).toMatchSelector('#foo'); + expect(wrapper.find('span')).toMatchSelector('.bar'); + }); + }); + + describe('.not matches', () => { + it('should pass', () => { + expect(wrapper.find('span')).not.toMatchSelector('div'); + }); + }); +}); diff --git a/types/jasmine-enzyme/tsconfig.json b/types/jasmine-enzyme/tsconfig.json new file mode 100644 index 0000000000..d153f4bc10 --- /dev/null +++ b/types/jasmine-enzyme/tsconfig.json @@ -0,0 +1,24 @@ +{ + "compilerOptions": { + "jsx": "react", + "module": "commonjs", + "lib": [ + "es6", + "dom" + ], + "noImplicitAny": true, + "noImplicitThis": true, + "strictNullChecks": false, + "baseUrl": "../", + "typeRoots": [ + "../" + ], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true + }, + "files": [ + "index.d.ts", + "jasmine-enzyme-tests.tsx" + ] +} \ No newline at end of file diff --git a/types/jasmine-enzyme/tslint.json b/types/jasmine-enzyme/tslint.json new file mode 100644 index 0000000000..3db14f85ea --- /dev/null +++ b/types/jasmine-enzyme/tslint.json @@ -0,0 +1 @@ +{ "extends": "dtslint/dt.json" } diff --git a/types/jdenticon/jdenticon-tests.ts b/types/jdenticon/jdenticon-tests.ts index b26a01696b..aaa5abc531 100644 --- a/types/jdenticon/jdenticon-tests.ts +++ b/types/jdenticon/jdenticon-tests.ts @@ -1,4 +1,4 @@ -import {jdenticon} from "jdenticon"; +import { jdenticon } from "jdenticon"; function testJdenticon() { if (typeof jdenticon.version !== 'string') { diff --git a/types/jest/index.d.ts b/types/jest/index.d.ts index 633af80085..267f1d4a1a 100644 --- a/types/jest/index.d.ts +++ b/types/jest/index.d.ts @@ -729,7 +729,7 @@ declare namespace jest { type TestResultsProcessor = (testResult: AggregatedResult) => AggregatedResult; type HasteResolver = any; // import HasteResolver from 'jest-resolve'; - type ModuleMocker = any; // import {ModuleMocker} from 'jest-mock'; + type ModuleMocker = any; // import { ModuleMocker } from 'jest-mock'; type ModuleMap = any; // import {ModuleMap} from 'jest-haste-map'; type HasteFS = any; // import {FS as HasteFS} from 'jest-haste-map'; type Runtime = any; // import Runtime from 'jest-runtime'; diff --git a/types/jpm/jpm-tests.ts b/types/jpm/jpm-tests.ts index 526bbe6063..34523f1a14 100644 --- a/types/jpm/jpm-tests.ts +++ b/types/jpm/jpm-tests.ts @@ -100,7 +100,7 @@ console.log(urls.toFilename(urls.URL("http://example.com"))); console.log(urls.DataURL("file:///my/path/file.txt").mimeType); import * as windows from "sdk/windows"; -import {stringify} from "sdk/querystring"; +import { stringify } from "sdk/querystring"; for (let window of windows.browserWindows) { console.info(window.title); } diff --git a/types/jquery-editable-select/index.d.ts b/types/jquery-editable-select/index.d.ts new file mode 100644 index 0000000000..43ae7065ae --- /dev/null +++ b/types/jquery-editable-select/index.d.ts @@ -0,0 +1,71 @@ +// Type definitions for jquery-editable-select 2.2 +// Project: https://github.com/indrimuska/jquery-editable-select +// Definitions by: Vincent Biret +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.3 + +/// + +declare namespace JQueryEditableSelect { + interface EditableSelectOptions { + /** + * Filter (or not) items in list while typing. + */ + filter?: boolean; + /** + * Easing used for showing and hiding the dropdown list. + */ + effects?: 'default' | 'slide' | 'fade'; + /** + * Duration of the easings (in milliseconds). + */ + duration?: number | 'fast' | 'slow'; + /** + * Where to append the dropdown list in the DOM. + */ + appendTo?: string | JQuery; + /** + * How dropdown list is triggered. + */ + trigger?: 'focus'| 'manual'; + } +} + +interface JQuery { + /** + * Transforms the -
; - } -} - -class SelectWithStringValueTest extends React.Component> { - - render() { - 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 = { - name: "test-select-with-string-value", - value: "bar", - options: options, - onChange: onChange - }; - - return
- ; + } + + render() { + return ; + } + } + }); +}); diff --git a/types/react-select/tslint.json b/types/react-select/tslint.json new file mode 100644 index 0000000000..3db14f85ea --- /dev/null +++ b/types/react-select/tslint.json @@ -0,0 +1 @@ +{ "extends": "dtslint/dt.json" } diff --git a/types/react-sortable-tree/index.d.ts b/types/react-sortable-tree/index.d.ts index a7805cd90e..a6a04f4968 100644 --- a/types/react-sortable-tree/index.d.ts +++ b/types/react-sortable-tree/index.d.ts @@ -15,7 +15,7 @@ export interface TreeItem { title?: string; subtitle?: string; expanded?: boolean; - children: TreeItem[]; + children?: TreeItem[]; [x: string]: any; } diff --git a/types/react-sortable-tree/react-sortable-tree-tests.tsx b/types/react-sortable-tree/react-sortable-tree-tests.tsx index 8b89db5196..1a5e2dfcd0 100644 --- a/types/react-sortable-tree/react-sortable-tree-tests.tsx +++ b/types/react-sortable-tree/react-sortable-tree-tests.tsx @@ -21,7 +21,7 @@ class Test extends React.Component { { title: "Title", subtitle: "Subtitle", children: [ {title: "Child 1", subtitle: "Subtitle", children: []}, - {title: "Child 2", subtitle: "Subtitle", children: []} + {title: "Child 2", subtitle: "Subtitle"} ] } ]; diff --git a/types/react-sortable-tree/tsconfig.json b/types/react-sortable-tree/tsconfig.json index f82f976d38..df74da5295 100644 --- a/types/react-sortable-tree/tsconfig.json +++ b/types/react-sortable-tree/tsconfig.json @@ -2,7 +2,8 @@ "compilerOptions": { "module": "commonjs", "lib": [ - "es6" + "es6", + "dom" ], "noImplicitAny": true, "noImplicitThis": true, diff --git a/types/react-sticky/react-sticky-tests.tsx b/types/react-sticky/react-sticky-tests.tsx index 6eb9d0e0d0..f7cc460611 100644 --- a/types/react-sticky/react-sticky-tests.tsx +++ b/types/react-sticky/react-sticky-tests.tsx @@ -1,4 +1,4 @@ -import {Sticky, StickyContainer} from "react-sticky"; +import { Sticky, StickyContainer } from "react-sticky"; import * as React from "react"; const StickyAllOptions: JSX.Element = diff --git a/types/react-tag-input/index.d.ts b/types/react-tag-input/index.d.ts index 1ab94f7f89..942902973c 100644 --- a/types/react-tag-input/index.d.ts +++ b/types/react-tag-input/index.d.ts @@ -33,5 +33,6 @@ export interface ReactTagsProps { } export class WithContext extends React.Component { } +export class WithOutContext extends React.Component { } export default WithContext; diff --git a/types/react-tagcloud/react-tagcloud-tests.tsx b/types/react-tagcloud/react-tagcloud-tests.tsx index efdbfab378..4d4382db6d 100644 --- a/types/react-tagcloud/react-tagcloud-tests.tsx +++ b/types/react-tagcloud/react-tagcloud-tests.tsx @@ -1,7 +1,7 @@ // simple cloud import * as React from "react"; import * as ReactDOM from "react-dom"; -import {TagCloud, DefaultRenderer} from "react-tagcloud"; +import { TagCloud, DefaultRenderer } from "react-tagcloud"; let data = [ { value: "jQuery", count: 25 }, { value: "MongoDB", count: 18 }, diff --git a/types/react-virtualized/dist/es/ArrowKeyStepper.d.ts b/types/react-virtualized/dist/es/ArrowKeyStepper.d.ts index e42ff353f2..6bc853361b 100644 --- a/types/react-virtualized/dist/es/ArrowKeyStepper.d.ts +++ b/types/react-virtualized/dist/es/ArrowKeyStepper.d.ts @@ -21,6 +21,14 @@ export type ArrowKeyStepperProps = { columnCount: number; rowCount: number; mode?: 'edges' | 'cells'; + /** + * PLEASE NOTE + * The [key: string]: any; line is here on purpose + * This is due to the need of force re-render of PureComponent + * Check the following link if you want to know more + * https://github.com/bvaughn/react-virtualized#pass-thru-props + */ + [key: string]: any; } export type ScrollIndexes = { scrollToRow: number, diff --git a/types/react-virtualized/dist/es/AutoSizer.d.ts b/types/react-virtualized/dist/es/AutoSizer.d.ts index 1da48c8120..35a9081095 100644 --- a/types/react-virtualized/dist/es/AutoSizer.d.ts +++ b/types/react-virtualized/dist/es/AutoSizer.d.ts @@ -20,6 +20,14 @@ export type AutoSizerProps = { * ({ height, width }) => PropTypes.element */ children?: (props: Dimensions) => React.ReactNode + /** + * PLEASE NOTE + * The [key: string]: any; line is here on purpose + * This is due to the need of force re-render of PureComponent + * Check the following link if you want to know more + * https://github.com/bvaughn/react-virtualized#pass-thru-props + */ + [key: string]: any; }; /** * Decorator component that automatically adjusts the width and height of a single child. diff --git a/types/react-virtualized/dist/es/CellMeasurer.d.ts b/types/react-virtualized/dist/es/CellMeasurer.d.ts index 0621d5579a..46c033ba49 100644 --- a/types/react-virtualized/dist/es/CellMeasurer.d.ts +++ b/types/react-virtualized/dist/es/CellMeasurer.d.ts @@ -53,6 +53,14 @@ export type CellMeasurerProps = { parent?: React.ReactType; rowIndex?: number; style?: React.CSSProperties; + /** + * PLEASE NOTE + * The [key: string]: any; line is here on purpose + * This is due to the need of force re-render of PureComponent + * Check the following link if you want to know more + * https://github.com/bvaughn/react-virtualized#pass-thru-props + */ + [key: string]: any; } /** * Wraps a cell and measures its rendered content. diff --git a/types/react-virtualized/dist/es/Collection.d.ts b/types/react-virtualized/dist/es/Collection.d.ts index 9a6730b76e..e3b378eacb 100644 --- a/types/react-virtualized/dist/es/Collection.d.ts +++ b/types/react-virtualized/dist/es/Collection.d.ts @@ -106,6 +106,14 @@ export type CollectionProps = { * (vs virtualized) columns. */ width: number; + /** + * PLEASE NOTE + * The [key: string]: any; line is here on purpose + * This is due to the need of force re-render of PureComponent + * Check the following link if you want to know more + * https://github.com/bvaughn/react-virtualized#pass-thru-props + */ + [key: string]: any; }; /** diff --git a/types/react-virtualized/dist/es/ColumnSizer.d.ts b/types/react-virtualized/dist/es/ColumnSizer.d.ts index 512e8db4a1..c3779c493c 100644 --- a/types/react-virtualized/dist/es/ColumnSizer.d.ts +++ b/types/react-virtualized/dist/es/ColumnSizer.d.ts @@ -26,6 +26,14 @@ export type ColumnSizerProps = { columnCount?: number; /** Width of Grid or Table child */ width: number; + /** + * PLEASE NOTE + * The [key: string]: any; line is here on purpose + * This is due to the need of force re-render of PureComponent + * Check the following link if you want to know more + * https://github.com/bvaughn/react-virtualized#pass-thru-props + */ + [key: string]: any; } /** * High-order component that auto-calculates column-widths for `Grid` cells. diff --git a/types/react-virtualized/dist/es/Grid.d.ts b/types/react-virtualized/dist/es/Grid.d.ts index 66801c4592..cc4cbaa9ac 100644 --- a/types/react-virtualized/dist/es/Grid.d.ts +++ b/types/react-virtualized/dist/es/Grid.d.ts @@ -280,6 +280,14 @@ export type GridCoreProps = { * Width of Grid; this property determines the number of visible (vs virtualized) columns. */ width: number; + /** + * PLEASE NOTE + * The [key: string]: any; line is here on purpose + * This is due to the need of force re-render of PureComponent + * Check the following link if you want to know more + * https://github.com/bvaughn/react-virtualized#pass-thru-props + */ + [key: string]: any; } export type GridProps = GridCoreProps & { diff --git a/types/react-virtualized/dist/es/InfiniteLoader.d.ts b/types/react-virtualized/dist/es/InfiniteLoader.d.ts index 1062caeb35..746ddc71f0 100644 --- a/types/react-virtualized/dist/es/InfiniteLoader.d.ts +++ b/types/react-virtualized/dist/es/InfiniteLoader.d.ts @@ -44,6 +44,14 @@ export type InfiniteLoaderProps = { * This value defaults to 15. */ threshold?: number; + /** + * PLEASE NOTE + * The [key: string]: any; line is here on purpose + * This is due to the need of force re-render of PureComponent + * Check the following link if you want to know more + * https://github.com/bvaughn/react-virtualized#pass-thru-props + */ + [key: string]: any; }; /** diff --git a/types/react-virtualized/dist/es/Masonry.d.ts b/types/react-virtualized/dist/es/Masonry.d.ts index 25b790ced6..4c67835722 100644 --- a/types/react-virtualized/dist/es/Masonry.d.ts +++ b/types/react-virtualized/dist/es/Masonry.d.ts @@ -46,7 +46,15 @@ export type MasonryProps = { scrollTop?: number, style?: React.CSSProperties, tabIndex?: number, - width: number + width: number, + /** + * PLEASE NOTE + * The [key: string]: any; line is here on purpose + * This is due to the need of force re-render of PureComponent + * Check the following link if you want to know more + * https://github.com/bvaughn/react-virtualized#pass-thru-props + */ + [key: string]: any; } export type MasonryState = { diff --git a/types/react-virtualized/dist/es/ScrollSync.d.ts b/types/react-virtualized/dist/es/ScrollSync.d.ts index 2d49bee5d0..00137bf635 100644 --- a/types/react-virtualized/dist/es/ScrollSync.d.ts +++ b/types/react-virtualized/dist/es/ScrollSync.d.ts @@ -26,6 +26,14 @@ export type ScrollSyncProps = { * ({ onScroll, scrollLeft, scrollTop }) => PropTypes.element */ children?: (props: ScrollSyncChildProps) => React.ReactNode + /** + * PLEASE NOTE + * The [key: string]: any; line is here on purpose + * This is due to the need of force re-render of PureComponent + * Check the following link if you want to know more + * https://github.com/bvaughn/react-virtualized#pass-thru-props + */ + [key: string]: any; }; export type ScrollSyncState = { diff --git a/types/react-virtualized/dist/es/WindowScroller.d.ts b/types/react-virtualized/dist/es/WindowScroller.d.ts index 16be9f8e1a..5ee54eb178 100644 --- a/types/react-virtualized/dist/es/WindowScroller.d.ts +++ b/types/react-virtualized/dist/es/WindowScroller.d.ts @@ -19,6 +19,14 @@ export type WindowScrollerProps = { onScroll?: (params: { scrollTop: number }) => void; /** Element to attach scroll event listeners. Defaults to window. */ scrollElement?: HTMLElement; + /** + * PLEASE NOTE + * The [key: string]: any; line is here on purpose + * This is due to the need of force re-render of PureComponent + * Check the following link if you want to know more + * https://github.com/bvaughn/react-virtualized#pass-thru-props + */ + [key: string]: any; } export type WindowScrollerState = { height: number, diff --git a/types/react-virtualized/index.d.ts b/types/react-virtualized/index.d.ts index 598d65302c..8bd32e7b26 100644 --- a/types/react-virtualized/index.d.ts +++ b/types/react-virtualized/index.d.ts @@ -2,6 +2,7 @@ // Project: https://github.com/bvaughn/react-virtualized // Definitions by: Kalle Ott // John Gunther +// Konstantin Nesterov // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped // TypeScript Version: 2.3 diff --git a/types/react-virtualized/react-virtualized-tests.tsx b/types/react-virtualized/react-virtualized-tests.tsx index 3f6a6d8a35..e0bd1d50ed 100644 --- a/types/react-virtualized/react-virtualized-tests.tsx +++ b/types/react-virtualized/react-virtualized-tests.tsx @@ -1656,7 +1656,7 @@ export class TableExample extends PureComponent<{}, any> { } } -import {TableCellProps} from "react-virtualized" +import { TableCellProps } from "react-virtualized" export class DynamicHeightTableColumnExample extends PureComponent { state; diff --git a/types/react-widgets/lib/Calendar.d.ts b/types/react-widgets/lib/Calendar.d.ts index 1f68410dd9..d9d0a6d540 100644 --- a/types/react-widgets/lib/Calendar.d.ts +++ b/types/react-widgets/lib/Calendar.d.ts @@ -1,5 +1,5 @@ import * as React from 'react'; -import {ReactWidgetsCommonProps} from './CommonProps'; +import { ReactWidgetsCommonProps } from './CommonProps'; interface CalendarProps extends ReactWidgetsCommonProps{ /** diff --git a/types/react-widgets/lib/Combobox.d.ts b/types/react-widgets/lib/Combobox.d.ts index 473919f31d..a3b6aadb94 100644 --- a/types/react-widgets/lib/Combobox.d.ts +++ b/types/react-widgets/lib/Combobox.d.ts @@ -1,5 +1,5 @@ import * as React from 'react'; -import {ReactWidgetsCommonDropdownProps} from './CommonProps'; +import { ReactWidgetsCommonDropdownProps } from './CommonProps'; interface ComboBoxMessages { /** diff --git a/types/react-widgets/lib/DateTimePicker.d.ts b/types/react-widgets/lib/DateTimePicker.d.ts index 87f95a15e9..2f2f520cf2 100644 --- a/types/react-widgets/lib/DateTimePicker.d.ts +++ b/types/react-widgets/lib/DateTimePicker.d.ts @@ -1,5 +1,5 @@ import * as React from 'react'; -import {ReactWidgetsCommonDropdownProps} from './CommonProps'; +import { ReactWidgetsCommonDropdownProps } from './CommonProps'; interface DateTimePickerProps extends ReactWidgetsCommonDropdownProps { /** diff --git a/types/react-widgets/lib/DropdownList.d.ts b/types/react-widgets/lib/DropdownList.d.ts index b0aebc1de8..06ae39619b 100644 --- a/types/react-widgets/lib/DropdownList.d.ts +++ b/types/react-widgets/lib/DropdownList.d.ts @@ -1,5 +1,5 @@ import * as React from 'react'; -import {ReactWidgetsCommonDropdownProps} from './CommonProps'; +import { ReactWidgetsCommonDropdownProps } from './CommonProps'; interface DropdownListProps extends ReactWidgetsCommonDropdownProps { /** diff --git a/types/react-widgets/lib/Multiselect.d.ts b/types/react-widgets/lib/Multiselect.d.ts index 0b528dd14c..8f3b5591f2 100644 --- a/types/react-widgets/lib/Multiselect.d.ts +++ b/types/react-widgets/lib/Multiselect.d.ts @@ -1,5 +1,5 @@ import * as React from 'react'; -import {ReactWidgetsCommonDropdownProps} from './CommonProps'; +import { ReactWidgetsCommonDropdownProps } from './CommonProps'; interface MultiselectProps extends ReactWidgetsCommonDropdownProps { /** diff --git a/types/react-widgets/lib/NumberPicker.d.ts b/types/react-widgets/lib/NumberPicker.d.ts index 59f46ee3c1..0feaee5bf1 100644 --- a/types/react-widgets/lib/NumberPicker.d.ts +++ b/types/react-widgets/lib/NumberPicker.d.ts @@ -1,5 +1,5 @@ import * as React from 'react'; -import {ReactWidgetsCommonProps} from './CommonProps'; +import { ReactWidgetsCommonProps } from './CommonProps'; interface NumberPickerProps extends ReactWidgetsCommonProps{ /** diff --git a/types/react-widgets/lib/SelectList.d.ts b/types/react-widgets/lib/SelectList.d.ts index ca925898c6..a70f4c4de8 100644 --- a/types/react-widgets/lib/SelectList.d.ts +++ b/types/react-widgets/lib/SelectList.d.ts @@ -1,5 +1,5 @@ import * as React from 'react'; -import {ReactWidgetsCommonProps} from './CommonProps'; +import { ReactWidgetsCommonProps } from './CommonProps'; interface SelectListProps extends ReactWidgetsCommonProps{ /** diff --git a/types/react/README.md b/types/react/README.md deleted file mode 100644 index 594b16d48f..0000000000 --- a/types/react/README.md +++ /dev/null @@ -1,60 +0,0 @@ -## Known Problems & Workarounds - -### **The type of `cloneElement` is incorrect.** -`cloneElement(element, props)` should should accept a `props` object with a subset of the properties on `element.props`. 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 -declare function cloneElement

( - element: ReactElement

, - props?: Q & Attributes, - ...children: ReactNode[]): ReactElement

; -``` -However, type inference for `Q` defaults to `{}` when [intersected with another type](https://github.com/Microsoft/TypeScript/pull/5738#issuecomment-181904905). And since any object is assignable to `{}`, we would lose the type safety of the `P extends Q` constraint. Therefore, the type of `props` is left as `Q`, which should work for most cases. If you need to call `cloneElement` with `key` or `ref`, you'll need a type cast: -```ts -interface ButtonProps { - label: string, - isDisabled?: boolean; -} -var element: React.CElement; - -React.cloneElement(element, { label: "label" }); - -// cloning with optional props requires a cast -React.cloneElement(element, <{ isDisabled?: boolean }>{ isDisabled: true }); - -// cloning with key or ref requires a cast -React.cloneElement(element, >{ ref: button => button.reset() }); -React.cloneElement(element, <{ isDisabled?: boolean } & React.Attributes>{ - key: "disabledButton", - isDisabled: true -}); -``` - -### **`React.Component` subclass members aren't contextually typed.** -This problem manifests itself in two ways. It should be fixed in [TypeScript 2.0](https://github.com/Microsoft/TypeScript/pull/6118). - - - You might expect `componentDidUpdate(prevProps, prevState)` to have `prevProps` and `prevState` contextually typed as `P` and `S` respectively, but currently that is not the case. You must explicitly type-annotate both arguments. - - - You may get a cryptic error message when either `React.createElement` or `React.createFactory` doesn't recognize the `type` argument that you passed in as a valid `React.Component` subclass, because you overrode one of the static or instance members with a type that's not compatible with the superclass property's type. For example, with the following code: - ```ts - import * as React from "react"; - - class MyComponent extends React.Component { - static contextTypes = { - someValue: React.PropTypes.string - }; - } - - React.createFactory(MyComponent); - ``` - you might get this error: - ``` - error TS2345: Argument of type 'typeof MyComponent' is not assignable to parameter of type 'string | ComponentClass | StatelessComponent' - Type 'typeof ModernComponent' is not assignable to type 'StatelessComponent'. - Types of property 'contextTypes' are incompatible. - Type '{ someValue: Requireable; }' is not assignable to type 'ValidationMap'. - Index signature is missing in type '{ someValue: Requireable; }'. - ``` - The work around is to add an explicit type annotation: - ```ts - static contextTypes: React.ValidationMap = ... - ``` diff --git a/types/react/index.d.ts b/types/react/index.d.ts index 3849e98d7f..6b5b163048 100644 --- a/types/react/index.d.ts +++ b/types/react/index.d.ts @@ -1,4 +1,4 @@ -// Type definitions for React 15.0 +// Type definitions for React 16.0 // Project: http://facebook.github.io/react/ // Definitions by: Asana // AssureSign @@ -12,9 +12,41 @@ // Tanguy Krotoff // Dovydas Navickas // Stéphane Goetz +// Rich Seviora // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped // TypeScript Version: 2.3 +/* +Known Problems & Workarounds +1. The type of cloneElement is incorrect. +cloneElement(element, props) should accept props object with a subset of properties on element.props. +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: +declare function cloneElement

( + element: ReactElement

, + props?: Q & Attributes, + ...children: ReactNode[]): ReactElement

; +However, type inference for Q defaults to {} when intersected with another type. +(https://github.com/Microsoft/TypeScript/pull/5738#issuecomment-181904905) +And since any object is assignable to {}, we would lose the type safety of the P extends Q constraint. +Therefore, the type of props is left as Q, which should work for most cases. +If you need to call cloneElement with key or ref, you'll need a type cast: +interface ButtonProps { + label: string, + isDisabled?: boolean; +} +var element: React.CElement; +React.cloneElement(element, { label: "label" }); +// cloning with optional props requires a cast +React.cloneElement(element, <{ isDisabled?: boolean }>{ isDisabled: true }); +// cloning with key or ref requires a cast +React.cloneElement(element, >{ ref: button => button.reset() }); +React.cloneElement(element, <{ isDisabled?: boolean } & React.Attributes>{ + key: "disabledButton", + isDisabled: true +}); +*/ + type NativeAnimationEvent = AnimationEvent; type NativeClipboardEvent = ClipboardEvent; type NativeCompositionEvent = CompositionEvent; @@ -321,6 +353,11 @@ declare namespace React { componentWillUpdate?(nextProps: Readonly

, nextState: Readonly, nextContext: any): void; componentDidUpdate?(prevProps: Readonly

, prevState: Readonly, prevContext: any): void; componentWillUnmount?(): void; + /** + * Catches exceptions generated in descendant components. Unhandled exceptions will cause + * the entire component tree to unmount. + */ + componentDidCatch?(error: Error, errorInfo: ErrorInfo): void; } interface Mixin extends ComponentLifecycle { @@ -2815,8 +2852,10 @@ declare namespace React { } interface TextareaHTMLAttributes extends HTMLAttributes { + autoComplete?: string; autoFocus?: boolean; cols?: number; + dirName?: string; disabled?: boolean; form?: string; maxLength?: number; @@ -3352,6 +3391,16 @@ declare namespace React { item(index: number): Touch; identifiedTouch(identifier: number): Touch; } + + // + // Error Interfaces + // ---------------------------------------------------------------------- + interface ErrorInfo { + /** + * Captures which component contained the exception, and it's ancestors. + */ + componentStack: string; + } } declare global { diff --git a/types/react/v15/index.d.ts b/types/react/v15/index.d.ts new file mode 100644 index 0000000000..5082c5a1d6 --- /dev/null +++ b/types/react/v15/index.d.ts @@ -0,0 +1,3587 @@ +// Type definitions for React 15.6 +// Project: http://facebook.github.io/react/ +// Definitions by: Asana +// AssureSign +// Microsoft +// John Reilly +// Benoit Benezech +// Patricio Zavolinsky +// Digiguru +// Eric Anderson +// Albert Kurniawan +// Tanguy Krotoff +// Dovydas Navickas +// Stéphane Goetz +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.3 + +/* +Known Problems & Workarounds + +1. The type of cloneElement is incorrect. +cloneElement(element, props) should accept props object with a subset of properties on element.props. +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: + +declare function cloneElement

( + element: ReactElement

, + props?: Q & Attributes, + ...children: ReactNode[]): ReactElement

; + +However, type inference for Q defaults to {} when intersected with another type. +(https://github.com/Microsoft/TypeScript/pull/5738#issuecomment-181904905) +And since any object is assignable to {}, we would lose the type safety of the P extends Q constraint. +Therefore, the type of props is left as Q, which should work for most cases. +If you need to call cloneElement with key or ref, you'll need a type cast: + +interface ButtonProps { + label: string, + isDisabled?: boolean; +} +var element: React.CElement; + +React.cloneElement(element, { label: "label" }); + +// cloning with optional props requires a cast +React.cloneElement(element, <{ isDisabled?: boolean }>{ isDisabled: true }); + +// cloning with key or ref requires a cast +React.cloneElement(element, >{ ref: button => button.reset() }); +React.cloneElement(element, <{ isDisabled?: boolean } & React.Attributes>{ + key: "disabledButton", + isDisabled: true +}); +*/ + +type NativeAnimationEvent = AnimationEvent; +type NativeClipboardEvent = ClipboardEvent; +type NativeCompositionEvent = CompositionEvent; +type NativeDragEvent = DragEvent; +type NativeFocusEvent = FocusEvent; +type NativeKeyboardEvent = KeyboardEvent; +type NativeMouseEvent = MouseEvent; +type NativeTouchEvent = TouchEvent; +type NativeTransitionEvent = TransitionEvent; +type NativeUIEvent = UIEvent; +type NativeWheelEvent = WheelEvent; + +// tslint:disable-next-line:export-just-namespace +export = React; +export as namespace React; + +declare namespace React { + // + // React Elements + // ---------------------------------------------------------------------- + + type ReactType = string | ComponentType; + type ComponentType

= ComponentClass

| StatelessComponent

; + + type Key = string | number; + type Ref = string | ((instance: T | null) => any); + + // tslint:disable-next-line:interface-over-type-literal + type ComponentState = {}; + + interface Attributes { + key?: Key; + } + interface ClassAttributes extends Attributes { + ref?: Ref; + } + + interface ReactElement

{ + type: string | ComponentClass

| SFC

; + props: P; + key: Key | null; + } + + interface SFCElement

extends ReactElement

{ + type: SFC

; + } + + type CElement> = ComponentElement; + interface ComponentElement> extends ReactElement

{ + type: ComponentClass

; + ref?: Ref; + } + + type ClassicElement

= CElement>; + + // string fallback for custom web-components + interface DOMElement

| SVGAttributes, T extends Element> extends ReactElement

{ + type: string; + ref: Ref; + } + + // ReactHTML for ReactHTMLElement + // tslint:disable-next-line:no-empty-interface + interface ReactHTMLElement extends DetailedReactHTMLElement, T> { } + + interface DetailedReactHTMLElement

, T extends HTMLElement> extends DOMElement { + type: keyof ReactHTML; + } + + // ReactSVG for ReactSVGElement + interface ReactSVGElement extends DOMElement, SVGElement> { + type: keyof ReactSVG; + } + + // + // Factories + // ---------------------------------------------------------------------- + + type Factory

= (props?: Attributes & P, ...children: ReactNode[]) => ReactElement

; + + type SFCFactory

= (props?: Attributes & P, ...children: ReactNode[]) => SFCElement

; + + type ComponentFactory> = + (props?: ClassAttributes & P, ...children: ReactNode[]) => CElement; + + type CFactory> = ComponentFactory; + type ClassicFactory

= CFactory>; + + type DOMFactory

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

, T extends HTMLElement> extends DOMFactory { + (props?: ClassAttributes & P | null, ...children: ReactNode[]): DetailedReactHTMLElement; + } + + interface SVGFactory extends DOMFactory, SVGElement> { + (props?: ClassAttributes & SVGAttributes | null, ...children: ReactNode[]): ReactSVGElement; + } + + // + // React Nodes + // http://facebook.github.io/react/docs/glossary.html + // ---------------------------------------------------------------------- + + type ReactText = string | number; + type ReactChild = ReactElement | ReactText; + + // Should be Array but type aliases cannot be recursive + type ReactFragment = {} | Array; + type ReactNode = ReactChild | ReactFragment | boolean | null | undefined; + + // + // Top Level API + // ---------------------------------------------------------------------- + + function createClass(spec: ComponentSpec): ClassicComponentClass

; + + // DOM Elements + function createFactory( + type: keyof ReactHTML): HTMLFactory; + function createFactory( + type: keyof ReactSVG): SVGFactory; + function createFactory

, T extends Element>( + type: string): DOMFactory; + + // Custom components + function createFactory

(type: SFC

): SFCFactory

; + function createFactory

( + type: ClassType, ClassicComponentClass

>): CFactory>; + function createFactory, C extends ComponentClass

>( + type: ClassType): CFactory; + function createFactory

(type: ComponentClass

): Factory

; + + // DOM Elements + function createElement

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

, T extends SVGElement>( + type: keyof ReactSVG, + props?: ClassAttributes & P, + ...children: ReactNode[]): ReactSVGElement; + function createElement

, T extends Element>( + type: string, + props?: ClassAttributes & P, + ...children: ReactNode[]): DOMElement; + + // Custom components + function createElement

( + type: SFC

, + props?: Attributes & P, + ...children: ReactNode[]): SFCElement

; + function createElement

( + type: ClassType, ClassicComponentClass

>, + props?: ClassAttributes> & P, + ...children: ReactNode[]): CElement>; + function createElement, C extends ComponentClass

>( + type: ClassType, + props?: ClassAttributes & P, + ...children: ReactNode[]): CElement; + function createElement

( + type: ComponentClass

, + props?: Attributes & P, + ...children: ReactNode[]): ReactElement

; + + // DOM Elements + // ReactHTMLElement + function cloneElement

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

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

, T extends SVGElement>( + element: ReactSVGElement, + props?: P, + ...children: ReactNode[]): ReactSVGElement; + // DOM Element (has to be the last, because type checking stops at first overload that fits) + function cloneElement

, T extends Element>( + element: DOMElement, + props?: DOMAttributes & P, + ...children: ReactNode[]): DOMElement; + + // Custom components + function cloneElement

( + element: SFCElement

, + props?: Q, // should be Q & Attributes, but then Q is inferred as {} + ...children: ReactNode[]): SFCElement

; + function cloneElement

>( + element: CElement, + props?: Q, // should be Q & ClassAttributes + ...children: ReactNode[]): CElement; + function cloneElement

( + element: ReactElement

, + props?: Q, // should be Q & Attributes + ...children: ReactNode[]): ReactElement

; + + function isValidElement

(object: {}): object is ReactElement

; + + const DOM: ReactDOM; + const PropTypes: ReactPropTypes; + const Children: ReactChildren; + const version: string; + + // + // Component API + // ---------------------------------------------------------------------- + + type ReactInstance = Component | Element; + + // Base component for plain JS classes + // tslint:disable-next-line:no-empty-interface + interface Component

extends ComponentLifecycle { } + class Component { + constructor(props?: P, context?: any); + + // Disabling unified-signatures to have separate overloads. It's easier to understand this way. + // tslint:disable:unified-signatures + setState(f: (prevState: S, props: P) => Pick, callback?: () => any): void; + setState(state: Pick, callback?: () => any): void; + // tslint:enable:unified-signatures + + forceUpdate(callBack?: () => any): void; + render(): JSX.Element | null | false; + + // React.Props is now deprecated, which means that the `children` + // property is not available on `P` by default, even though you can + // 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: Readonly<{ children?: ReactNode }> & Readonly

; + state: Readonly; + context: any; + refs: { + [key: string]: ReactInstance + }; + } + + class PureComponent

extends Component { } + + interface ClassicComponent

extends Component { + replaceState(nextState: S, callback?: () => any): void; + isMounted(): boolean; + getInitialState?(): S; + } + + interface ChildContextProvider { + getChildContext(): CC; + } + + // + // Class Interfaces + // ---------------------------------------------------------------------- + + type SFC

= StatelessComponent

; + interface StatelessComponent

{ + (props: P & { children?: ReactNode }, context?: any): ReactElement | null; + propTypes?: ValidationMap

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

; + displayName?: string; + } + + interface ComponentClass

{ + new (props?: P, context?: any): Component; + propTypes?: ValidationMap

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

; + displayName?: string; + } + + interface ClassicComponentClass

extends ComponentClass

{ + new (props?: P, context?: any): ClassicComponent; + getDefaultProps?(): P; + } + + /** + * We use an intersection type to infer multiple type parameters from + * a single argument, which is useful for many top-level API defs. + * See https://github.com/Microsoft/TypeScript/issues/7234 for more info. + */ + type ClassType, C extends ComponentClass

> = + C & + (new (props?: P, context?: any) => T) & + (new (props?: P, context?: any) => { props: P }); + + // + // Component Specs and Lifecycle + // ---------------------------------------------------------------------- + + interface ComponentLifecycle { + componentWillMount?(): void; + componentDidMount?(): void; + componentWillReceiveProps?(nextProps: Readonly

, nextContext: any): void; + shouldComponentUpdate?(nextProps: Readonly

, nextState: Readonly, nextContext: any): boolean; + componentWillUpdate?(nextProps: Readonly

, nextState: Readonly, nextContext: any): void; + componentDidUpdate?(prevProps: Readonly

, prevState: Readonly, prevContext: any): void; + componentWillUnmount?(): void; + } + + interface Mixin extends ComponentLifecycle { + mixins?: Array>; + statics?: { + [key: string]: any; + }; + + displayName?: string; + propTypes?: ValidationMap; + contextTypes?: ValidationMap; + childContextTypes?: ValidationMap; + + getDefaultProps?(): P; + getInitialState?(): S; + } + + interface ComponentSpec extends Mixin { + render(): ReactElement | null; + + [propertyName: string]: any; + } + + // + // Event System + // ---------------------------------------------------------------------- + + interface SyntheticEvent { + bubbles: boolean; + currentTarget: EventTarget & T; + cancelable: boolean; + defaultPrevented: boolean; + eventPhase: number; + isTrusted: boolean; + nativeEvent: Event; + preventDefault(): void; + isDefaultPrevented(): boolean; + stopPropagation(): void; + isPropagationStopped(): boolean; + persist(): void; + // If you thought this should be `EventTarget & T`, see https://github.com/DefinitelyTyped/DefinitelyTyped/pull/12239 + target: EventTarget; + timeStamp: number; + type: string; + } + + interface ClipboardEvent extends SyntheticEvent { + clipboardData: DataTransfer; + nativeEvent: NativeClipboardEvent; + } + + interface CompositionEvent extends SyntheticEvent { + data: string; + nativeEvent: NativeCompositionEvent; + } + + interface DragEvent extends MouseEvent { + dataTransfer: DataTransfer; + nativeEvent: NativeDragEvent; + } + + interface FocusEvent extends SyntheticEvent { + nativeEvent: NativeFocusEvent; + relatedTarget: EventTarget; + } + + // tslint:disable-next-line:no-empty-interface + interface FormEvent extends SyntheticEvent { + } + + interface InvalidEvent extends SyntheticEvent { + target: EventTarget & T; + } + + interface ChangeEvent extends SyntheticEvent { + target: EventTarget & T; + } + + interface KeyboardEvent extends SyntheticEvent { + altKey: boolean; + charCode: number; + ctrlKey: boolean; + getModifierState(key: string): boolean; + key: string; + keyCode: number; + locale: string; + location: number; + metaKey: boolean; + nativeEvent: NativeKeyboardEvent; + repeat: boolean; + shiftKey: boolean; + which: number; + } + + interface MouseEvent extends SyntheticEvent { + altKey: boolean; + button: number; + buttons: number; + clientX: number; + clientY: number; + ctrlKey: boolean; + getModifierState(key: string): boolean; + metaKey: boolean; + nativeEvent: NativeMouseEvent; + pageX: number; + pageY: number; + relatedTarget: EventTarget; + screenX: number; + screenY: number; + shiftKey: boolean; + } + + interface TouchEvent extends SyntheticEvent { + altKey: boolean; + changedTouches: TouchList; + ctrlKey: boolean; + getModifierState(key: string): boolean; + metaKey: boolean; + nativeEvent: NativeTouchEvent; + shiftKey: boolean; + targetTouches: TouchList; + touches: TouchList; + } + + interface UIEvent extends SyntheticEvent { + detail: number; + nativeEvent: NativeUIEvent; + view: AbstractView; + } + + interface WheelEvent extends MouseEvent { + deltaMode: number; + deltaX: number; + deltaY: number; + deltaZ: number; + nativeEvent: NativeWheelEvent; + } + + interface AnimationEvent extends SyntheticEvent { + animationName: string; + elapsedTime: number; + nativeEvent: NativeAnimationEvent; + pseudoElement: string; + } + + interface TransitionEvent extends SyntheticEvent { + elapsedTime: number; + nativeEvent: NativeTransitionEvent; + propertyName: string; + pseudoElement: string; + } + + // + // Event Handler Types + // ---------------------------------------------------------------------- + + type EventHandler> = (event: E) => void; + + type ReactEventHandler = EventHandler>; + + type ClipboardEventHandler = EventHandler>; + type CompositionEventHandler = EventHandler>; + type DragEventHandler = EventHandler>; + type FocusEventHandler = EventHandler>; + type FormEventHandler = EventHandler>; + type ChangeEventHandler = EventHandler>; + type KeyboardEventHandler = EventHandler>; + type MouseEventHandler = EventHandler>; + type TouchEventHandler = EventHandler>; + type UIEventHandler = EventHandler>; + type WheelEventHandler = EventHandler>; + type AnimationEventHandler = EventHandler>; + type TransitionEventHandler = EventHandler>; + + // + // Props / DOM Attributes + // ---------------------------------------------------------------------- + + /** + * @deprecated. This was used to allow clients to pass `ref` and `key` + * to `createElement`, which is no longer necessary due to intersection + * types. If you need to declare a props object before passing it to + * `createElement` or a factory, use `ClassAttributes`: + * + * ```ts + * var b: Button | null; + * var props: ButtonProps & ClassAttributes - -

- - ); + ) } -// Decorate with reduxForm(). It will read the initialValues prop provided by connect() -const DecoratedInitializeFromStateFormFunction = reduxForm({ - form: 'initializeFromState' // a unique identifier for this form -})(InitializeFromStateFormFunction) - -// You have to connect() to any reducers that you wish to connect to yourself -const ConnectedDecoratedInitializeFromStateFormFunction = connect( - state => ({ - initialValues: state.account.data // pull initial values from account reducer - }), -)(DecoratedInitializeFromStateFormFunction); - -// React ComponentClass instead of StatelessComponent - -class InitializeFromStateFormClass extends React.Component> { - render() { - return InitializeFromStateFormFunction(this.props); +// Specifying form data type is not required here, but is recommended to avoid confusion +const testFormWithValidationDecorator = reduxForm({ + form: "testWithValidation", + validate: (values, props) => { + return { + foo: "Bad foo" + } } -} - -// Decorate with reduxForm(). It will read the initialValues prop provided by connect() -const DecoratedInitializeFromStateFormClass = reduxForm({ - form: 'initializeFromState' // a unique identifier for this form -})(InitializeFromStateFormClass); - -// You have to connect() to any reducers that you wish to connect to yourself -const mapStateToProps = (state: any) => ({ - initialValues: { firstName: state.account.data.firstName } // pull initial values from account reducer -} as {initialValues?: Partial}); -const ConnectedDecoratedInitializeFromStateFormClass = connect(mapStateToProps)(DecoratedInitializeFromStateFormClass); - -class ImmutableCustomField extends Component { - render() { - const F = ImmutableField as new () => GenericField; - return ; - } -} - -@immutableReduxForm({ - form: 'myForm' }) -class MyImmutableForm extends Component { - render() { - return ( -
- - -
- ); + +// Specifying form data type is not required here, but is recommended to avoid confusion +const testFormWithInitialValuesDecorator = reduxForm({ + form: "testWithValidation", + initialValues: { + foo: "A Foo is here" } -} +}) + +// Specifying form data type *is* required here, because type inference will guess the type of +// the form data type parameter to be {foo: string}. The result of validate does not contain "foo" +const testFormWithInitialValuesAndValidationDecorator = reduxForm({ + form: "testWithValidation", + initialValues: { + foo: "A Foo is here" + }, + validate: (values, props) => { + return { + bar: "Bad foo" + } + } +}) + +type TestProps = {} & InjectedFormProps; +const Test = reduxForm({ + form : "test" +})( + class Test extends Component { + + handleSubmitForm = (values: Partial, dispatch: Dispatch, props: TestProps) => {}; + + handleSubmitFormAny = (event: any) => {}; + + render() { + const { handleSubmit } = this.props; + + return ( +
+
+ + + + + + + + + + + + + + + + null } + /> + + null } + foo="bar" + /> + + + + + + +
+ ) + } + } +); reducer({}, { - type: 'ACTION' + type: "ACTION" }); reducer.plugin({ - myform: (state: any, action: FormAction) => { - if (action.type === actionTypes.CHANGE && action.meta.form === 'securitySettings') { + myForm: (state: any, action: FormAction) => { + if (action.type === actionTypes.CHANGE && action.meta.form === "securitySettings") { return { ...state, values: { diff --git a/types/redux-form/tsconfig.json b/types/redux-form/tsconfig.json index 625f4b9492..eea8fb4b64 100644 --- a/types/redux-form/tsconfig.json +++ b/types/redux-form/tsconfig.json @@ -22,6 +22,19 @@ "files": [ "index.d.ts", "redux-form-tests.tsx", - "immutable/index.d.ts" + "immutable/index.d.ts", + "lib/actions.d.ts", + "lib/actionTypes.d.ts", + "lib/Field.d.ts", + "lib/Fields.d.ts", + "lib/FieldArray.d.ts", + "lib/Form.d.ts", + "lib/FormSection.d.ts", + "lib/formValues.d.ts", + "lib/formValueSelector.d.ts", + "lib/reducer.d.ts", + "lib/reduxForm.d.ts", + "lib/selectors.d.ts", + "lib/SubmissionError.d.ts" ] } diff --git a/types/redux-form/v4/redux-form-tests.tsx b/types/redux-form/v4/redux-form-tests.tsx index 2c962460fa..424c87c609 100644 --- a/types/redux-form/v4/redux-form-tests.tsx +++ b/types/redux-form/v4/redux-form-tests.tsx @@ -1,6 +1,6 @@ import * as React from 'react'; -import {Component, PropTypes} from 'react'; +import { Component, PropTypes } from 'react'; import {createStore, combineReducers} from 'redux'; import {reduxForm, reducer as reduxFormReducer, ReduxFormProps} from 'redux-form'; diff --git a/types/redux-form/v6/index.d.ts b/types/redux-form/v6/index.d.ts new file mode 100644 index 0000000000..8a51117530 --- /dev/null +++ b/types/redux-form/v6/index.d.ts @@ -0,0 +1,46 @@ +// Type definitions for redux-form 6.6 +// Project: https://github.com/erikras/redux-form +// Definitions by: Carson Full , Daniel Lytkin , Karol Janyst , Luka Zakrajsek +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.3 + +import { + ComponentClass, + StatelessComponent, + ReactElement +} from "react"; + +export type FieldValue = any; + +export type FieldType = "Field" | "FieldArray"; + +export interface DataShape { + [fieldName: string]: FieldValue +} + +export type FormErrors = { + [P in keyof FormData]?: ReactElement | string | { _error?: string }; +}; + +export type FormWarnings = { + [P in keyof FormData]?: ReactElement | string | { _warning?: string }; +}; + +/** + * A component class or stateless function component. + * Workaround for: ComponentClass

| SFC

which does + * not resolve due to a bug in TypeScript. + * https://github.com/Microsoft/TypeScript/pull/8674 + */ +export type ComponentConstructor

= ComponentClass

| StatelessComponent

; + +export * from "./lib/reduxForm"; +export * from "./lib/Field"; +export * from "./lib/Fields"; +export * from "./lib/FieldArray"; +export * from "./lib/Form"; +export * from "./lib/FormSection"; +export * from "./lib/actions"; +export * from "./lib/actionTypes"; +export * from "./lib/reducer"; +export * from "./lib/selectors"; diff --git a/types/redux-form/v6/lib/Field.d.ts b/types/redux-form/v6/lib/Field.d.ts new file mode 100644 index 0000000000..ecef15b4c7 --- /dev/null +++ b/types/redux-form/v6/lib/Field.d.ts @@ -0,0 +1,333 @@ +import { + Component, + ReactElement, + ChangeEvent, + DragEvent, + FocusEvent +} from "react"; +import { Dispatch } from "redux"; +import { ComponentConstructor, DataShape, FieldValue } from "../index"; + +/** + * These are the props to give to `Field`. + * Any others will be passed through to your component. + */ +interface BaseFieldProps { + /** + * A string path, in dot-and-bracket notation, corresponding to a value + * in the form values. It may be as simple as 'firstName' or as complicated + * as contact.billing.address[2].phones[1].areaCode. + * + * Required but made optional so interface can be used on decorated components. + */ + name?: string; + + /** + * A Component, stateless function, or string corresponding to a default + * JSX element. + * + * Required but made optional so interface can be used on decorated components. + */ + component?: ComponentConstructor | "input" | "select" | "textarea", + + /** + * Formats the value from the Redux store to be displayed in the field input. + * Common use cases are to format Numbers into currencies or Dates into a + * localized date format. + */ + format?: Formatter | null; + + /** + * A function to convert whatever value the user has entered into the value that you + * want stored in the Redux store for the field. + * + * For instance, if you want the value to be in all uppercase, you would pass + * value => value.toUpperCase() + */ + normalize?: Normalizer; + + /** + * Don't use. + */ + props?: any; + + /** + * Parses the value given from the field input component to the type that you want + * stored in the Redux store. Common use cases are to parse currencies into Numbers into + * currencies or localized date formats into Dates. + */ + parse?: Parser; + + /** + * Allows you to to provide a field-level validation rule. The function will be given the + * current value of the field and all the other form values. If the field is valid, it + * should return `undefined`, if the field is invalid, it should return an error + * (usually, but not necessarily, a `String`). + */ + validate?: Validator | Validator[]; + + /** + * Allows you to to provide a field-level warning rule. The function will be given the + * current value of the field and all the other form values. If the field needs a warning, + * it should return the warning (usually, but not necessarily, a `String`). If the field + * does not need a warning, it should return `undefined`. + */ + warn?: Validator | Validator[]; + + /** + * If true, the rendered component will be available with the + * getRenderedComponent() method. Defaults to false. Cannot be used if your + * component is a stateless function component. + */ + withRef?: boolean; +} + +/** + * @param value The value entered by the user. + * @param previousValue The previous value for the field. + * @param allValues All the values in the entire form with the new value. + * This will be an Immutable Map if you are using Immutable JS. + * @param previousAllValues All the values in the entire form before the current change. + * This will be an Immutable Map if you are using Immutable JS. + */ +export type Normalizer = (value: FieldValue, previousValue?: FieldValue, allValues?: any, previousAllValues?: any) => FieldValue; + +export type Formatter = (value: FieldValue, name: string) => FieldValue; + +export type Parser = (value: FieldValue, name: string) => FieldValue; + +export type Validator = (value: FieldValue, allValues?: any, props?: any) => any; + +/** + * Declare Field as this interface to specify the generic. + */ +export interface GenericField extends Component { + /** + * true if the current value is different from the initialized value, + * false otherwise. + */ + dirty: boolean; + + /** + * The name prop that you passed in. + */ + name: string; + + /** + * true if the current value is the same as the initialized value, + * false otherwise. + */ + pristine: boolean; + + /** + * The current value of the field. + */ + value: FieldValue; + + /** + * Returns the instance of the rendered component. For this to work, you must + * provide a withRef prop, and your component must not be a stateless function + * component. + */ + getRenderedComponent(): Component & FieldCustomProps>; +} + +/** + * The Field Instance API. + */ +export class Field extends Component implements GenericField { + /** + * true if the current value is different from the initialized value, + * false otherwise. + */ + dirty: boolean; + + /** + * The name prop that you passed in. + */ + name: string; + + /** + * true if the current value is the same as the initialized value, + * false otherwise. + */ + pristine: boolean; + + /** + * The current value of the field. + */ + value: FieldValue; + + /** + * Returns the instance of the rendered component. For this to work, you must + * provide a withRef prop, and your component must not be a stateless function + * component. + */ + getRenderedComponent(): Component; +} + +/** + * These are props that `Field` will pass to your wrapped component (not including custom props). + */ +interface WrappedFieldProps { + /** + * An object containing all the props that you will normally want to pass to + * your input component. + */ + input?: WrappedFieldInputProps; + + /** + * An object containing all the metadata props. + */ + meta: WrappedFieldMetaProps; +} + +/** + * These props are meant to be destructured into your component. + */ +interface EventOrValueHandler { + (event: Event): void; + (value: FieldValue, newValue: FieldValue, previousValue: FieldValue): void; +} + +interface WrappedFieldInputProps { + /** + * An alias for value only when value is a boolean. Provided for + * convenience of destructuring the whole field object into the props of a + * form element. + */ + checked?: boolean; + + /** + * The name prop passed in. + */ + name: string; + + /** + * A function to call when the form field loses focus. + */ + onBlur: EventOrValueHandler>; + + /** + * A function to call when the form field is changed. + */ + onChange: EventOrValueHandler>; + + /** + * A function to call when the form field receives a 'dragStart' event. + * Saves the field value in the event for giving the field it is dropped + * into. + */ + onDragStart: EventOrValueHandler>; + + /** + * A function to call when the form field receives a drop event. + */ + onDrop: EventOrValueHandler>; + + /** + * A function to call when the form field receives focus. + */ + onFocus: EventOrValueHandler>; + + /** + * The value of this form field. It will be a boolean for checkboxes, and + * a string for all other input types. If there is no value in the Redux + * state for this field, it will default to ''. This is to + * ensure that the input is controlled. + */ + value: FieldValue; +} + +/** + * These props are metadata about the state of this field that redux-form is tracking for you. + */ +interface WrappedFieldMetaProps { + + /** + * true if this field currently has focus. It will only work if you are + * passing onFocus to your input element. + */ + active?: boolean; + + /** + * true if this field has been set with the AUTOFILL action and has not since been changed + * with a CHANGE action. This is useful to render the field in a way that the user can tell + * that the value was autofilled for them. + */ + autofilled: boolean; + + /** + * true if the form is currently running asynchronous validation because this + * field was blurred. + */ + asyncValidating: boolean; + + /** + * true if the field value has changed from its initialized value. + * Opposite of pristine. + */ + dirty: boolean; + + /** + * The Redux dispatch function. + */ + dispatch: Dispatch; + + /** + * The error for this field if its value is not passing validation. Both + * synchronous, asynchronous, and submit validation errors will be reported here. + */ + error?: any; + + /** + * The name of the form. Could be useful if you want to manually dispatch actions. + */ + form?: string; + + /** + * true if the field value fails validation (has a validation error). + * Opposite of valid. + */ + invalid: boolean; + + /** + * true if the field value is the same as its initialized value. Opposite + * of dirty. + */ + pristine: boolean; + + /** + * true if the field is currently being submitted + */ + submitting?: boolean; + + /** + * true if the form had onSubmit called and failed to submit for any reason. + * A subsequent successful submit will set it back to false. + */ + submitFailed?: boolean; + + /** + * true if the field has been touched. By default this will be set when + * the field is blurred. + */ + touched: boolean; + + /** + * true if the field value passes validation (has no validation errors). + * Opposite of invalid. + */ + valid: boolean; + + /** + * true if this field has ever had focus. It will only work if you are + * passing onFocus to your input element. + */ + visited?: boolean; + + /** + * The warning for this field if its value is not passing warning validation. + */ + warning?: any; +} diff --git a/types/redux-form/v6/lib/FieldArray.d.ts b/types/redux-form/v6/lib/FieldArray.d.ts new file mode 100644 index 0000000000..9629eecb27 --- /dev/null +++ b/types/redux-form/v6/lib/FieldArray.d.ts @@ -0,0 +1,217 @@ +import { Component } from "react"; +import { ComponentConstructor, Validator } from "../index"; + +/** + * These are the props to give to `FieldArray`. + * Any others will be passed through to your component. + */ +interface BaseFieldArrayProps { + /** + * A string path, in dot-and-bracket notation, corresponding to a value + * in the form values. It may be as simple as 'firstName' or as complicated + * as contact.billing.address[2].phones[1].areaCode. + * + * Required but made optional so interface can be used on decorated components. + */ + name?: string; + + /** + * A Component or stateless function to render the field array. + * + * Required but made optional so interface can be used on decorated components. + */ + component?: ComponentConstructor, + + /** + * Allows you to to provide a field-level validation rule. The function will be given the + * current value of the field and all the other form values. If the field is valid, it + * should return `undefined`, if the field is invalid, it should return an error + * (usually, but not necessarily, a `String`). + */ + validate?: Validator | Validator[]; + + /** + * Allows you to to provide a field-level warning rule. The function will be given the + * current value of the field and all the other form values. If the field needs a warning, + * it should return the warning (usually, but not necessarily, a `String`). If the field + * does not need a warning, it should return `undefined`. + */ + warn?: Validator | Validator[]; + + /** + * If true, the rendered component will be available with the + * getRenderedComponent() method. Defaults to false. Cannot be used if your + * component is a stateless function component. + */ + withRef?: boolean; + + props?: any; +} + +/** + * Declare FieldArray as this interface to specify the generics. + */ +export interface GenericFieldArray extends Component { + + /** + * The name prop that you passed in. + */ + name: string; + + /** + * true if this field passes validation, false otherwise. + */ + valid: boolean; + + /** + * Returns the instance of the rendered component. For this to work, you must + * provide a withRef prop, and your component must not be a stateless function + * component. + */ + getRenderedComponent(): Component & FieldCustomProps>; +} + +/** + * The FieldArray Instance API. + */ +export class FieldArray extends Component implements GenericFieldArray { + + /** + * The name prop that you passed in. + */ + name: string; + + /** + * true if this field passes validation, false otherwise. + */ + valid: boolean; + + /** + * Returns the instance of the rendered component. For this to work, you must + * provide a withRef prop, and your component must not be a stateless function + * component. + */ + getRenderedComponent(): Component; +} + +/** + * These are props that `FieldArray` will pass to your wrapped component. + */ +interface WrappedFieldArrayProps { + fields: FieldsProps; + meta: FieldArrayMetaProps; +} + +interface FieldsProps { + /** + * A method to iterate over each value of the array. + */ + forEach(callback: (name: string, index: number, fields: FieldsProps) => void): void; + + /** + * A method to get a single value from the array value. + */ + get(index: number): T; + + /** + * A method to get all the values in the array. + */ + getAll(): T[]; + + /** + * A function to insert a new value into the array at any arbitrary index. + */ + insert(index: number, value: T): void; + + /** + * The current length of the array. + */ + length: number; + + /** + * A method to iterate over each value of the array. Returns an array of the + * results of each call to the callback. + */ + map(callback: (name: string, index: number, fields: FieldsProps) => any): any; + + /** + * Removes an item from the end of the array. Returns the item removed. + */ + pop(): T; + + /** + * Adds a value to the end of the array. + */ + push(value: T): void; + + /** + * Removes an item from the array at an arbitrary index. + */ + remove(index: number): void; + + /** + * Removes an item from beginning of the array. Returns the item removed. + */ + shift(): T; + + /** + * Swaps two items in the array at the given indexes. + */ + swap(indexA: number, indexB: number): void; + + /** + * Adds an item to the beginning of the array. + */ + unshift(value: T): void; +} + +interface FieldArrayMetaProps { + /** + * true if the any of the fields in the field array have changed from their + * initialized value. Opposite of pristine. + */ + dirty: boolean; + + /** + * The error for this field array if its value is not passing validation. Both + * synchronous, asynchronous, and submit validation errors will be reported here. + * Array-specific errors should be returned from the validation function as an + * _error key on the array. + */ + error?: string; + + /** + * Name of your form provided to `reduxForm()` as the `form` config property. + */ + form: string; + + /** + * true if the field array value fails validation (has a validation error). + * Opposite of valid. + */ + invalid: boolean; + + /** + * true if the all of the fields in the field array are the same as their + * initialized value. Opposite of dirty. + */ + pristine: boolean; + + /** + * true if any of the fields have been touched. + */ + touched: boolean; + + /** + * true if the field value passes validation (has no validation errors). + * Opposite of invalid. + */ + valid: boolean; + + /** + * The warning for this field array if its values are not passing warning validation. + * Array-specific errors should be returned from the validation function as an + * `_warning` key on the array. + */ + warning?: string; +} diff --git a/types/redux-form/v6/lib/Fields.d.ts b/types/redux-form/v6/lib/Fields.d.ts new file mode 100644 index 0000000000..b2c210ba8c --- /dev/null +++ b/types/redux-form/v6/lib/Fields.d.ts @@ -0,0 +1,116 @@ +import { Component } from "react"; +import { ComponentConstructor, Formatter, Parser, FieldValue, WrappedFieldProps } from "../index"; + +/** + * These are the props to give to `Field`. + * Any others will be passed through to your component. + */ +interface BaseFieldsProps { + /** + * An array of strings (or the pseudo-array fields provided by FieldArray), + * in dot-and-bracket notation, corresponding to form values. + * They may be as simple as 'firstName' or as complicated as + * 'contact.billing.address[2].phones[1].areaCode'. + */ + names: string[]; + + /** + * A Component or stateless function that will be given all the props necessary + * to render the field inputs. + */ + component?: ComponentConstructor; + + /** + * Formats the value from the Redux store to be displayed in the field input. + * Common use cases are to format Numbers into currencies or Dates into a localized date format. + * + * format is called with the field value and name as arguments and should return the new formatted + * value to be displayed in the field input. + * + * To respect React 15 input behavior there is defaultFormat = value => value == null ? '' : value + * internally used. To disable that you can pass null as format prop. + */ + format?: Formatter | null; + + /** + * Don't use. + */ + props?: any; + + /** + * Parses the value given from the field input component to the type that you want stored in the Redux store. + * Common use cases are to parse currencies into Numbers into currencies or localized date formats into Dates. + * + * parse is called with the field value and name as arguments and should return the new parsed value to be + * stored in the Redux store. + */ + parse?: Parser; + + /** + * If true, the rendered component will be available with the getRenderedComponent() method. + * Defaults to false. Cannot be used if your component is a stateless function component. + */ + withRef?: boolean; +} + +/** + * Declare Fields as this interface to specify the generics. + */ +export interface GenericFields extends Component { + /** + * true if the current value of any of the fields is different from the initialized value, false otherwise. + */ + dirty: boolean; + + /** + * The names prop that you passed in. + */ + names: string[]; + + /** + * true if the all of the current values are the same as the initialized values, false otherwise. + */ + pristine: boolean; + + /** + * The current values of the fields. If they are nested, the values will duplicate the structure. + * For example, if your names are [ 'name.first', 'name.last', 'email' ], the values will be + * { name: { first: 'John', last: 'Smith' }, email: 'john@email.com' } + */ + values: { [name: string]: FieldValue }; + + getRenderedComponent(): Component; +} + +/** + * The Fields Instance API. + */ +export class Fields extends Component implements GenericFields { + /** + * true if the current value of any of the fields is different from the initialized value, false otherwise. + */ + dirty: boolean; + + /** + * The names prop that you passed in. + */ + names: string[]; + + /** + * true if the all of the current values are the same as the initialized values, false otherwise. + */ + pristine: boolean; + + /** + * The current values of the fields. If they are nested, the values will duplicate the structure. + * For example, if your names are [ 'name.first', 'name.last', 'email' ], the values will be + * { name: { first: 'John', last: 'Smith' }, email: 'john@email.com' } + */ + values: { [name: string]: FieldValue }; + + getRenderedComponent(): Component; +} + +interface WrappedFieldsProps { + [name: string]: WrappedFieldsProps & WrappedFieldProps +} diff --git a/types/redux-form/v6/lib/Form.d.ts b/types/redux-form/v6/lib/Form.d.ts new file mode 100644 index 0000000000..9339348393 --- /dev/null +++ b/types/redux-form/v6/lib/Form.d.ts @@ -0,0 +1,22 @@ +import { Component, HTMLProps, FormEvent } from "react"; +import { Dispatch } from "redux"; +import { SubmitHandler, FormProps, FormErrors } from "../index" + +interface FormSubmitHandler { + (values: any, dispatch?: Dispatch, props?: FormProps & { [prop: string]: any }): void | FormErrors | Promise; + //(e: FormEvent): void; +} + +export interface FormComponentProps extends HTMLProps { + /** + * The function to call when form submission is triggered. + */ + onSubmit: FormSubmitHandler; +} + +/** + * The Form component is a simple wrapper for the React

component that + * allows the surrounding redux-form-decorated component to trigger its + * onSubmit function. + */ +export class Form extends Component {} diff --git a/types/redux-form/v6/lib/FormSection.d.ts b/types/redux-form/v6/lib/FormSection.d.ts new file mode 100644 index 0000000000..9be46ebf80 --- /dev/null +++ b/types/redux-form/v6/lib/FormSection.d.ts @@ -0,0 +1,15 @@ +import { Component } from "react"; + +interface FormSectionProps { + /** + * The name all child fields should be prefixed with. + */ + name: string; +} + +/** + * The FormSection component makes it easy to split forms into smaller components that are resuable across + * multiple forms. It does this by prefixing the name of Field, Fields and FieldArray children, at any depth, + * with the value specified in the name prop. + */ +export class FormSection extends Component {} diff --git a/types/redux-form/v6/lib/actionTypes.d.ts b/types/redux-form/v6/lib/actionTypes.d.ts new file mode 100644 index 0000000000..ce1ba5d208 --- /dev/null +++ b/types/redux-form/v6/lib/actionTypes.d.ts @@ -0,0 +1,37 @@ +export interface ActionTypes { + ARRAY_INSERT: string; + ARRAY_MOVE: string; + ARRAY_POP: string; + ARRAY_PUSH: string; + ARRAY_REMOVE: string; + ARRAY_REMOVE_ALL: string; + ARRAY_SHIFT: string; + ARRAY_SPLICE: string; + ARRAY_UNSHIFT: string; + ARRAY_SWAP: string; + AUTOFILL: string; + BLUR: string; + CHANGE: string; + CLEAR_SUBMIT: string; + CLEAR_SUBMIT_ERRORS: string; + CLEAR_ASYNC_ERROR: string; + DESTROY: string; + FOCUS: string; + INITIALIZE: string; + REGISTER_FIELD: string; + RESET: string; + SET_SUBMIT_FAILED: string; + SET_SUBMIT_SUCCEEDED: string; + START_ASYNC_VALIDATION: string; + START_SUBMIT: string; + STOP_ASYNC_VALIDATION: string; + STOP_SUBMIT: string; + SUBMIT: string; + TOUCH: string; + UNREGISTER_FIELD: string; + UNTOUCH: string; + UPDATE_SYNC_ERRORS: string; + UPDATE_SYNC_WARNINGS: string; +} + +export const actionTypes: ActionTypes; diff --git a/types/redux-form/v6/lib/actions.d.ts b/types/redux-form/v6/lib/actions.d.ts new file mode 100644 index 0000000000..b126549f68 --- /dev/null +++ b/types/redux-form/v6/lib/actions.d.ts @@ -0,0 +1,160 @@ +import { Action } from "redux"; +import { FormErrors, FormWarnings, FieldType } from "../index"; + +export interface FormAction extends Action { + meta: { + form: string; + }; +} + +/** + * Inserts an item into a field array at the specified index + */ +export function arrayInsert(form: string, field: string, index: number, value: any): FormAction; + +/** + * Moves an item from one index in the array to another. In effect, it performs a remove and an + * insert, so the item already at the `to` position will be bumped to a higher index, not overwritten. + */ +export function arrayMove(form: string, field: string, from: number, to: number): FormAction; + +/** + * Removes an item from the end of a field array + */ +export function arrayPop(form: string, field: string): FormAction; + +/** + * Appends an item to the end of a field array + */ +export function arrayPush(form: string, field: string, value: any): FormAction; + +/** + * Removes an item at the specified index from a field array + */ +export function arrayRemove(form: string, field: string, index: number): FormAction; + +/** + * Removes all items from a field array + */ +export function arrayRemoveAll(form: string, field: string): FormAction; + +/** + * Removes an item from the beginning of a field array + */ +export function arrayShift(form: string, field: string): FormAction; + +/** + * ADVANCED USAGE - Inserts and/or removes items from a field array. Works similarly to Array.splice. + */ +export function arraySplice(form: string, field: string, index: number, removeNum: number, value: any): FormAction; + +/** + * Swaps two items at the specified indexes in a field array + */ +export function arraySwap(form: string, field: string, indexA: number, indexB: number): FormAction; + +/** + * Inserts an item at the beginning of a field array + */ +export function arrayUnshift(form: string, field: string, value: any): FormAction; + +/** + * Saves the value to the field and sets its `autofilled` property to `true`. + */ +export function autofill(form: string, field: string, value: any): FormAction; + +/** + * Saves the value to the field + */ +export function blur(form: string, field: string, value: any): FormAction; + +/** + * Saves the value to the field + */ +export function change(form: string, field: string, value: any): FormAction; + +/** + * Destroys the form, removing all it's state + */ +export function destroy(...form: string[]): FormAction; + +/** + * Marks the given field as active and visited + */ +export function focus(form: string, field: string): FormAction; + +/** + * Sets the initial values in the form with which future data values will be compared to calculate dirty and pristine. + * The data parameter may contain deep nested array and object values that match the shape of your form fields. + * If the keepDirty parameter is true, the values of the currently dirty fields will be retained to avoid overwriting + * user edits. + */ +interface InitializeOptions { + keepDirty : boolean; + keepSubmitSucceeded: boolean; +} + +export function initialize(form: string, data: any, keepDirty?: boolean | InitializeOptions, options?: InitializeOptions): FormAction; + +/** + * Registers a field with the form. + */ +export function registerField(form: string, name: string, type: FieldType): FormAction; + +/** + * Resets the values in the form back to the values past in with the most recent initialize action. + */ +export function reset(form: string): FormAction; + +/** + * Flips the asyncValidating flag true + */ +export function startAsyncValidation(form: string): FormAction; + +/** + * Flips the asyncValidating flag false and populates asyncError for each field. + */ +export function stopAsyncValidation(form: string, errors?: any): FormAction; + +export function setSubmitFailed(form: string, ...fields: string[]): FormAction; + +export function setSubmitSucceeded(form: string, ...fields: string[]): FormAction; + +/** + * Flips the submitting flag true. + */ +export function startSubmit(form: string): FormAction; + +/** + * Flips the submitting flag false and populates submitError for each field. + */ +export function stopSubmit(form: string, errors?: any): FormAction; + +/** + * Flips the asyncValidating flag false and populates asyncError for each field. + */ +export function stopAsyncValidation(form: string, errors?: any): FormAction; + +/** + * Triggers a submission of the specified form. + */ +export function submit(form: string): FormAction; + +/** + * Marks all the fields passed in as touched. + */ +export function touch(form: string, ...fields: string[]): FormAction; + +/** + * Unregisters a field with the form. + */ +export function unregisterField(form: string, name: string): FormAction; + +/** + * Resets the 'touched' flag for all the fields passed in. + */ +export function untouch(form: string, ...fields: string[]): FormAction; + +export function updateSyncErrors(from: string, syncErrors: FormErrors, error: any): FormAction; + +export function updateSyncWarnings(form: string, syncWarnings: FormWarnings, warning: any): FormAction; diff --git a/types/redux-form/v6/lib/reducer.d.ts b/types/redux-form/v6/lib/reducer.d.ts new file mode 100644 index 0000000000..f1dc6315bf --- /dev/null +++ b/types/redux-form/v6/lib/reducer.d.ts @@ -0,0 +1,49 @@ +import { Action, Reducer } from "redux"; +import { FieldType } from "../index"; + +export interface FormReducer extends Reducer { + /** + * Returns a form reducer that will also pass each action through + * additional reducers specified. The parameter should be an object mapping + * from formName to a (state, action) => nextState reducer. The state + * passed to each reducer will only be the slice that pertains to that + * form. + */ + plugin(reducers: FormReducerMapObject): Reducer; +} + +export const reducer: FormReducer; + +export interface FormReducerMapObject { + [formName: string]: Reducer; +} + +/** + * Store state + */ + +export interface FormStateMap { + [formName: string]: FormState; +} + +export interface FormState { + registeredFields: RegisteredFieldState[]; + fields?: {[name: string]: FieldState}; + values?: { [fieldName: string]: string }; + active?: string; + anyTouched?: boolean; + submitting?: boolean; + submitErrors?: { [fieldName: string]: string }; + submitFailed?: boolean; +} + +export interface RegisteredFieldState { + name: string; + type: FieldType; +} + +export interface FieldState { + active?: boolean; + touched?: boolean; + visited?: boolean; +} diff --git a/types/redux-form/v6/lib/reduxForm.d.ts b/types/redux-form/v6/lib/reduxForm.d.ts new file mode 100644 index 0000000000..f1eac8d928 --- /dev/null +++ b/types/redux-form/v6/lib/reduxForm.d.ts @@ -0,0 +1,571 @@ +import { + Component, + ComponentClass, + ReactElement, + SyntheticEvent, + ReactEventHandler, + StatelessComponent +} from "react"; +import { Dispatch } from "redux"; +import { DataShape, FieldValue, FormErrors, FormWarnings, RegisteredFieldState, ComponentConstructor } from "../index"; + +export function reduxForm( + config: Config +): FormDecorator; + +export function reduxForm( + config: Config +): FormDecorator; + +export function reduxForm( + config: Config +): FormDecorator; + +/** + * This is not entirely correct but Typescript expect input and output for decorators to be the same type. + * Because of that, React HoCs can't be fully defined. https://www.typescriptlang.org/docs/handbook/decorators.html + */ +export interface FormDecorator { + >>(component: T): T; +} + +export interface Config { + /** + * the name of your form and the key to where your form's state will be + * mounted under the redux-form reducer + */ + form?: string; + + /** + * field names for which onBlur should trigger a call to the asyncValidate + * function. Defaults to []. + * + * See Asynchronous Blur Validation Example for more details. + */ + asyncBlurFields?: string[]; + + /** + * a function that takes all the form values, the dispatch function, and + * the props given to your component, and returns a Promise that will + * resolve if the validation is passed, or will reject with an object of + * validation errors in the form { field1: , field2: }. + * + * See Asynchronous Blur Validation Example for more details. + */ + asyncValidate?(values: FormData, dispatch: Dispatch, props: P, blurredField: string): Promise; + + /** + * Whether or not to automatically destroy your form's state in the Redux + * store when your component is unmounted. Defaults to true. + */ + destroyOnUnmount?: boolean; + + /** + * Reinitialize the form every time the initialValues prop changes. + * Defaults to false. + */ + enableReinitialize?: boolean; + + /** + * Whether or not to force unregistration of fields -- use in conjunction + * with destroyOnUnmount. Useful for wizard-type forms where you want to destroy + * fields as they unmount, but not the form's state. Defaults to false, as forms + * are normally unregistered on unmount. + */ + forceUnregisterOnUnmount?: boolean; + + /** + * A function that takes the entire Redux state and returns the state slice + * which corresponds to where the redux-form reducer was mounted. This + * functionality is rarely needed, and defaults to assuming that the reducer + * is mounted under the "form" key. + */ + getFormState?(state: S): any; + + /** + * When set to true and enableReinitialize is also set, the form will retain the value of dirty fields when + * reinitializing. When this option is not set (the default), reinitializing the form replaces all field values. + * This option is useful in situations where the form has live updates or continues to be editable after + * form submission; it prevents reinitialization from overwriting user changes. Defaults to false. + */ + keepDirtyOnReinitialize?: boolean; + + /** + * The values with which to initialize your form in componentWillMount(). + * Particularly useful when Editing Multiple Records, but can also be used + * with single-record forms. The values should be in the form + * { field1: 'value1', field2: 'value2' }. + */ + initialValues?: Partial; + + /** + * A callback function that will be called with all the form values any time + * any of the form values change. + */ + onChange?: (values: any) => void; + + /** + * The function to call with the form data when the handleSubmit() is fired + * from within the form component. If you do not specify it as a prop here, + * you must pass it as a parameter to handleSubmit() inside your form + * component. + */ + onSubmit?: SubmitHandler; + + /** + * A callback function that will be called when a submission fails for whatever reason. + * + * @param errors The errors that caused the submission to fail. + * @param dispatch The Redux `dispatch` function. + * @param submitError The error object that caused the submission to fail. If `errors` is set this will be most + * likely a `SubmissionError`, otherwise it can be any error or null. + * @param props The props passed into your decorated component. + */ + onSubmitFail?(errors: FormErrors, dispatch: Dispatch, submitError: any, props: P): void; + + /** + * A callback function that will be called when a submission succeeds. + * + * @param result Any result that onSubmit has returned + * @param dispatch The Redux dispatch function + * @param props The props passed into your decorated component + */ + onSubmitSuccess?(result: any, dispatch: Dispatch, props: P): void; + + /** + * If specified, all the props normally passed into your decorated + * component directly will be passed under the key specified. Useful if + * using other decorator libraries on the same component to avoid prop + * namespace collisions. + */ + propNamespace?: string; + + /** + * If true, implements `shouldComponentUpdate` and shallowly compares _only_ + * the Redux-connected props that are needed to manage the form state. This + * prevents unnecessary updates, but assumes the component is a "pure" + * component and does not rely on any input or state other than its props and + * the selected Redux store's state. Defaults to true. + */ + pure?: boolean; + + /** + * An optional function you may provide to have full control over when sync validation happens. + */ + shouldValidate?(params: ValidateCallback): boolean; + + /** + * An optional function you may provide to have full control over when async + * validation happens. + */ + shouldAsyncValidate?(params: AsyncValidateCallback): boolean; + + /** + * marks fields as touched when the blur action is fired. Defaults to true. + */ + touchOnBlur?: boolean; + + /** + * marks fields as touched when the change action is fired. Defaults to + * false. + */ + touchOnChange?: boolean; + + /** + * Do not remove submit errors when the change action is fired. Defaults to false. + */ + persistentSubmitErrors?: boolean; + + /** + * a synchronous validation function that takes the form values and props + * passed into your component. If validation passes, it should return {}. + * If validation fails, it should return the validation errors in the form + * { field1: , field2: }. + * Defaults to (values, props) => ({}). + */ + validate?(values: FormData, props: FormProps & P): FormErrors; + + /** + * A synchronous warning function that takes the form values and props passed into your component. + * Warnings work the same as validations, but do not mark a form as invalid. If the warning check passes, + * it should return {}. If the check fails, it should return the warnings in the form + * { field1: , field2: }. Defaults to (values, props) => ({}). + */ + warn?(values: FormData, props: FormProps & P): FormWarnings; +} + +/** + * If your onSubmit function returns a promise, the submitting property will be set to true + * until the promise has been resolved or rejected. If it is rejected with a redux-form + * SubmissionError containing errors in the form { field1: 'error', field2: 'error' } then + * the submission errors will be added to each field (to the error prop) just like async + * validation errors are. If there is an error that is not specific to any field, but applicable + * to the entire form, you may pass that as if it were the error for a field called _error, + * and it will be given as the error prop. + */ +export interface SubmitHandler { + (values: FormData, dispatch: Dispatch, props: FormProps & P): void | FormErrors | Promise; +} + +interface ValidateCallback { + /** + * The values. + */ + values: FormData; + + /** + * The next props. + */ + nextProps: any; + + /** + * The current props. + */ + props: any; + + /** + * true if the form is being initially rendered. + */ + initialRender: boolean; + + /** + * The structure object being used internally for values. You may wish to use 'deepEqual' from the structure. + */ + structure: any; +} + +interface AsyncValidateCallback { + /** + * Any existing asynchronous validation errors + */ + asyncErrors?: FormErrors; + + /** + * true if the form has ever been initialized with initial values + */ + initialized: boolean; + + /** + * The reason to possibly run async validation. It will either be: 'blur' or + * 'submit', depending on whether an async blur field had triggered the async + * validation or if submitting the form has triggered it, respectively. + */ + trigger: "blur" | "submit"; + + /** + * The name of the field that has triggered the async validation. May be undefined. + */ + blurredField?: string; + + /** + * true if the form is pristine, false if it is dirty + */ + pristine: boolean; + + /** + * true if synchronous validation is passing, false if it is failing. + */ + syncValidationPasses: boolean; +} + +/** + * A throwable error that is used to return submit validation errors from onSubmit. + * The purpose being to distinguish promise rejection because of validation errors + * from promise rejection because of AJAX I/O problems or other server errors. + */ +export class SubmissionError extends Error { + errors: FormErrors; + + constructor(errors?: FormErrors); +} + +/** + * The following are methods or properties that you can access on an instance + * of your decorated form component (outermost component named "ReduxForm"). + */ +export interface FormComponent extends ComponentClass

{ + /** + * true if the form data has changed from its initialized values. Opposite + * of pristine. + */ + dirty: boolean; + + /** + * true if the form has validation errors. Opposite of valid. + */ + invalid: boolean; + + /** + * true if the form data is the same as its initialized values. Opposite + * of dirty. + */ + pristine: boolean; + + /** + * An array of objects with fields `name` and `type` for each field + * representing all the fields in the form. Mainly useful for testing. + */ + registeredFields: RegisteredFieldState[]; + + /** + * Resets all the values in the form to the initialized state, making it + * pristine again. + */ + reset(): void; + + /** + * Submits the form. Returns a promise that will be resolved when the form + * is submitted successfully, or rejected if the submission fails. + */ + submit(): Promise; + + /** + * true if the form passes validation (has no validation errors). Opposite + * of invalid. + */ + valid: boolean; + + /** + * The current values of all the fields in the form. + */ + values: FormData; + + /** + * A reference to the instance of the component you decorated with reduxForm(). + * Mainly useful for testing. + */ + wrappedInstance: ReactElement

> +} + +/** + * These are the props that will be passed to your form component. + * Your form component's props can extend this interface if you want + * to use strict checks. + */ +export interface StrictFormProps { + /** + * true if any of the fields have been marked as touched, false otherwise. + */ + anyTouched: boolean; + + /** + * A set of pre-bound action creators for you to operate on array fields in your form. + */ + array: { + /** + * Inserts a value into the given array field in your form. + */ + insert(field: string, index: number, value: FieldValue): void; + + /** + * Moves a value at the given from index to the given to index in + * the given array field in your form. + */ + move(field: string, from: number, to: number): void; + + /** + * Pops a value off of the end of a given array field in your form. + */ + pop(field: string): void; + + /** + * Pushes the given value onto the end of the given array field in your form. + */ + push(field: string, value: FieldValue): void; + + /** + * Removes a value at the given index from the given array field in your form. + */ + remove(field: string, index: number): void; + + /** + * Removes all the values from the given array field in your form. + */ + removeAll(field: string): void; + + /** + * Shifts a value out of the beginning of the given array in your form. + */ + shift(field: string): void; + + /** + * Performs an Array.splice operation on the given array in your form. + */ + splice(field: string, index: number, removeNum: number, value: FieldValue): void; + + /** + * Swaps two values at the given indexes of the given array field in your form. + */ + swap(field: string, indexA: number, indexB: number): void; + + /** + * Unshifts the given value into the beginning of the given array field in your form. + */ + unshift(field: string, value: FieldValue): void; + } + + /** + * A function that may be called to initiate asynchronous validation if + * asynchronous validation is enabled. + */ + asyncValidate: () => void; + + /** + * This value will be either: + * - false - No asynchronous validation is currently happening + * - true - Asynchronous validation is currently running in preparation to submit a form + * - a string - The name of the field that just blurred to trigger asynchronous validation + */ + asyncValidating: string | boolean; + + /** + * Sets the value and marks the field as autofilled in the Redux Store. This is useful when a field + * needs to be set programmatically, but in a way that lets the user know (via a styling change using + * the autofilled prop in Field) that it has been autofilled for them programmatically. + */ + autofill(field: string, value: FieldValue): void; + + /** + * Marks a field as blurred in the Redux store. + */ + blur(field: string, value: FieldValue): void; + + /** + * Changes the value of a field in the Redux store. + */ + change(field: string, value: FieldValue): void; + + /** + * Clear async error of a field in the Redux store. + */ + clearAsyncError(field: string): void; + + /** + * Destroys the form state in the Redux store. By default, this will be + * called for you in componentWillUnmount(). + */ + destroy(): void; + + /** + * true if the form data has changed from its initialized values. Opposite + * of pristine. + */ + dirty: boolean; + + /** + * A generic error for the entire form given by the _error key in the + * result from the synchronous validation function, the asynchronous + * validation, or the rejected promise from onSubmit. + */ + error: string; + + /** + * The form name that you gave to the reduxForm() decorator or the prop you + * passed in to your decorated form component. + */ + form: string; + + /** + * A function meant to be passed to or to + * + +

+ + ); +} + +// Decorate with reduxForm(). It will read the initialValues prop provided by connect() +const DecoratedInitializeFromStateFormFunction = reduxForm({ + form: 'initializeFromState' // a unique identifier for this form +})(InitializeFromStateFormFunction) + +// You have to connect() to any reducers that you wish to connect to yourself +const ConnectedDecoratedInitializeFromStateFormFunction = connect( + state => ({ + initialValues: state.account.data // pull initial values from account reducer + }), +)(DecoratedInitializeFromStateFormFunction); + +// React ComponentClass instead of StatelessComponent + +class InitializeFromStateFormClass extends React.Component> { + render() { + return InitializeFromStateFormFunction(this.props); + } +} + +// Decorate with reduxForm(). It will read the initialValues prop provided by connect() +const DecoratedInitializeFromStateFormClass = reduxForm({ + form: 'initializeFromState' // a unique identifier for this form +})(InitializeFromStateFormClass); + +// You have to connect() to any reducers that you wish to connect to yourself +const mapStateToProps = (state: any) => ({ + initialValues: { firstName: state.account.data.firstName } // pull initial values from account reducer +} as {initialValues?: Partial}); +const ConnectedDecoratedInitializeFromStateFormClass = connect(mapStateToProps)(DecoratedInitializeFromStateFormClass); + +reducer({}, { + type: 'ACTION' +}); + +reducer.plugin({ + myform: (state: any, action: FormAction) => { + if (action.type === actionTypes.CHANGE && action.meta.form === 'securitySettings') { + return { + ...state, + values: { + ...state.values, + downloadLinkAutoPassword: true, + }, + }; + } else { + return state; + } + } +}); diff --git a/types/redux-form/v6/tsconfig.json b/types/redux-form/v6/tsconfig.json new file mode 100644 index 0000000000..1903e7055b --- /dev/null +++ b/types/redux-form/v6/tsconfig.json @@ -0,0 +1,30 @@ +{ + "compilerOptions": { + "module": "commonjs", + "lib": [ + "es6", + "dom" + ], + "experimentalDecorators": true, + "noImplicitAny": true, + "noImplicitReturns": true, + "noImplicitThis": true, + "strictNullChecks": true, + "jsx": "react", + "baseUrl": "../../", + "typeRoots": [ + "../../" + ], + "types": [], + "paths": { + "redux-form": ["redux-form/v6"], + "redux-form/*": ["redux-form/v6/*"] + }, + "noEmit": true, + "forceConsistentCasingInFileNames": true + }, + "files": [ + "index.d.ts", + "redux-form-tests.tsx" + ] +} diff --git a/types/redux-logger/redux-logger-tests.ts b/types/redux-logger/redux-logger-tests.ts index db0131b95e..3ede2b8806 100644 --- a/types/redux-logger/redux-logger-tests.ts +++ b/types/redux-logger/redux-logger-tests.ts @@ -1,5 +1,5 @@ -import {createLogger} from 'redux-logger'; +import { createLogger } from 'redux-logger'; import logger from 'redux-logger'; import { applyMiddleware, createStore } from 'redux'; diff --git a/types/redux-promise/redux-promise-tests.ts b/types/redux-promise/redux-promise-tests.ts index 39f3c9fe84..1305cd6833 100644 --- a/types/redux-promise/redux-promise-tests.ts +++ b/types/redux-promise/redux-promise-tests.ts @@ -1,4 +1,4 @@ -import {createAction} from 'redux-actions'; +import { createAction } from 'redux-actions'; import { createStore, applyMiddleware, PromiseAction } from 'redux'; import promise = require('redux-promise'); diff --git a/types/requirejs/index.d.ts b/types/requirejs/index.d.ts index b2d5879e85..f44c203e5c 100644 --- a/types/requirejs/index.d.ts +++ b/types/requirejs/index.d.ts @@ -81,17 +81,23 @@ interface RequireShim { interface RequireConfig { - // The root path to use for all module lookups. + /** + * The root path to use for all module lookups. + */ baseUrl?: string; - // Path mappings for module names not found directly under - // baseUrl. + /** + * Path mappings for module names not found directly under + * baseUrl. + */ paths?: { [key: string]: any; }; - // Dictionary of Shim's. - // does not cover case of key->string[] - shim?: { [key: string]: RequireShim; }; + /** + * Dictionary of Shim's. + * Can be of type RequireShim or string[] of dependencies + */ + shim?: { [key: string]: RequireShim | string[]; }; /** * For the given module prefix, instead of loading the diff --git a/types/restangular/index.d.ts b/types/restangular/index.d.ts index 5d871cdd67..c5ad7da7e3 100644 --- a/types/restangular/index.d.ts +++ b/types/restangular/index.d.ts @@ -7,7 +7,7 @@ /// // Support AMD require (copying angular.d.ts approach) -// allows for import {IRequestConfig} from 'restangular' ES6 approach +// allows for import { IRequestConfig } from 'restangular' ES6 approach import * as angular from 'angular'; export = restangular; export as namespace Restangular; @@ -121,7 +121,7 @@ declare namespace restangular { getList(subElement?: any, queryParams?: any, headers?: any): ICollectionPromise; getList(subElement?: any, queryParams?: any, headers?: any): ICollectionPromise; put(queryParams?: any, headers?: any): IPromise; - post(subElement: any, elementToPost: any, queryParams?: any, headers?: any): IPromise; + post(subElement: any, elementToPost?: any, queryParams?: any, headers?: any): IPromise; post(subElement: any, elementToPost: T, queryParams?: any, headers?: any): IPromise; remove(queryParams?: any, headers?: any): IPromise; head(queryParams?: any, headers?: any): IPromise; diff --git a/types/restify-plugins/index.d.ts b/types/restify-plugins/index.d.ts index d461358bdc..c0d8114d92 100644 --- a/types/restify-plugins/index.d.ts +++ b/types/restify-plugins/index.d.ts @@ -3,7 +3,7 @@ // Definitions by: Костя Третяк // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -import {RequestHandler, Server, Request, Response, Route} from 'restify'; +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: diff --git a/types/rheostat/rheostat-tests.tsx b/types/rheostat/rheostat-tests.tsx index 1116861943..263e287f6f 100644 --- a/types/rheostat/rheostat-tests.tsx +++ b/types/rheostat/rheostat-tests.tsx @@ -1,5 +1,5 @@ import * as React from 'react'; -import Rheostat, {Orientation, Algorithm, PublicState} from 'rheostat'; +import Rheostat, { Orientation, Algorithm, PublicState } from 'rheostat'; type Element = React.ReactElement; diff --git a/types/riot/index.d.ts b/types/riot/index.d.ts index 3c76a0b1d0..079132db72 100644 --- a/types/riot/index.d.ts +++ b/types/riot/index.d.ts @@ -1,426 +1,727 @@ -// Type definitions for riot v2.6.0 +// Type definitions for riot 3.6 // Project: https://github.com/riot/riot // Definitions by: Boriss Nazarovs // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.3 -declare namespace riot { +/** + * Current version number as a string + */ +export const version: string; + +/** + * Riot settings + */ +export interface Settings { /** - * Current version number as string + * Setting used to customize the start and end tokens of the expression + * @default { } */ - const version: string; + brackets: string; + /** + * If set to false, riot will not create lighter tag instances for anonymous tags + * @default true + */ + skipAnonymousTags: boolean; + /** + * If set to false, DOM event handlers will not trigger update events + * @default true + */ + autoUpdate: boolean; + /** + * `riot.renderAsync` timeout in ms + * @default 1000 + */ + asyncRenderTimeout: number; +} + +export const settings: Settings; + +export interface TemplateError extends Error { + riotData: { + _riot_id: number; + tagName: string; + }; +} + +/** + * Riot template engine + */ +export interface Tmpl { + (expression: string, data?: any): any; + + version: string; /** - * Riot settings + * Utility hook function to catch all the errors swallowed by the riot template engine */ - interface Settings { - /** - * Setting used to customize the start and end tokens of the expression - */ - brackets: string; - } + errorHandler(error: TemplateError): void; +} - const settings: Settings; +/** + * Object that is used to inject and manage the css of every tag instance + */ +export interface StyleManager { + styleNode: HTMLStyleElement; - interface TemplateError extends Error { - riotData: { - tagName: string; - } - } + /** + * Save a tag style to be later injected into DOM + * @param {string} css - css string + * @param {string} name - if it's passed the css will be mapped to a tagname + */ + add(css: string, name?: string): void; - interface Util { - tmpl: { - errorHandler(error: TemplateError): void; - } - } + /** + * Inject all previously saved tag styles into DOM + */ + inject(): void; +} - const util: Util; +export interface DOMUtil { + /** + * Select multiple nodes in the DOM + * @param selector - DOM selector + * @param ctx - DOM node where the targets of our search will is located + * @returns DOM nodes found + */ + $$(selector: string, ctx?: Element): Element[]; + + /** + * Select a single node in the DOM + * @param selector - unique dom selector + * @param ctx - DOM node where the target of search will is located + * @returns DOM node found + */ + $(selector: string, ctx?: Element): Element | null; + + /** + * Create a document fragment + * @returns Document fragment + */ + createFrag(): DocumentFragment; + + /** + * Create a document text node + * @returns Text node + */ + createDOMPlaceholder(): Text; + + /** + * Check if a DOM node is an svg element + * @param element - node to check + * @returns { boolean } True if element is an svg element + */ + isSvg(element: Element): element is SVGElement; + + /** + * Create a generic DOM node + * @param name - name of the DOM node + * @returns Created element + */ + mkEl(name: string): Element; + + /** + * Set the inner html of any DOM node SVGs included + * @param container - DOM node where html should be injected + * @param html - html to inject + */ + setInnerHTML(container: Element, html: string): void; + + /** + * Toggle the visibility of a DOM node + * @param element - DOM node to update visibility for + * @param show - If true element is shown + */ + toggleVisibility(element: Element, show?: boolean): void; + + /** + * Remove any DOM attribute from a node + * @param element - DOM node to update + * @param name - name of the attribute + */ + remAttr(element: Element, name: string): void; + + /** + * Get the value of any DOM attribute on a node + * @param element - DOM node + * @param name - name of the attribute + * @returns Attribute value + */ + getAttr(element: Element, name: string): string | null; + + /** + * Set any DOM attribute + * @param element - DOM node we want to update + * @param name - name of the property we want to set + * @param value - value of the property we want to set + */ + setAttr(element: Element, name: string, value: string): void; + + /** + * Convert a style object to a string + * @param style - style object to parse + * @returns Resulting css string + */ + styleObjectToString(style: any): string; + + /** + * Insert tag safely + * @param root - children container + * @param curr - node to insert + * @param next - node that should precede inserted node + */ + safeInsert(root: Node, curr: Node, next: Node): void; + + /** + * Run callback function for each attribute in html string + * @param html - html string we want to parse + * @param fn - callback function to apply on found attributes + */ + walkAttrs(html: string, fn: (attrName: string, attrValue: string) => void): void; + + /** + * Walk down recursively through all child nodes starting with provided dom node + * @param node - starting node where we will start the recursion + * @param fn - callback to transform the child node just found + * @param context - fn can optionally return an object, which is passed to children + */ + walkNodes(node: Node, fn: (node: Node, context: any) => any, context: any): void; +} + +export interface CheckUtil { + /** + * Check if provided value is name of boolean attribute + * @param value - name to check + * @returns True if value is name of boolean attribute + */ + isBoolAttr(value: string): boolean; + + /** + * Check if provided value is a function + * @param value - reference to check + * @returns True if provided value is a function + */ + isFunction(value: any): boolean; + + /** + * Check if provided value is an object (null excluded) + * @param value - reference to check + * @returns True if provided value is an object + */ + isObject(value: any): boolean; + + /** + * Check if provided value is undefined + * @param value - reference to check + * @returns True if provided value is undefined + */ + isUndefined(value: any): boolean; + + /** + * Check if provided value is a string + * @param value - reference to check + * @returns True if provided value is a string + */ + isString(value: any): value is string; + + /** + * Check if provided value is empty. Different from falsy, because 0 or false are not considered to be blank + * @param value - value to check + * @returns True if provided value is undefined, null or empty string + */ + isBlank(value: any): boolean; + + /** + * Check if provided value is an array + * @param value - reference to check + * @returns True if provided value is an array + */ + isArray(value: any): boolean; + + /** + * Check whether object's property could be overridden + * @param obj - source object + * @param key - object property + * @returns True if value for specified key can be overridden + */ + isWritable(obj: any, key: string): boolean; + + /** + * Check if provided string is a reserved name for Riot tag instances + * @param value - name to check + * @returns True if provided string is a reserved name + */ + isReservedName(value: string): boolean; +} + +export interface MiscUtil { + /** + * Specialized function for looping over array-like collections + * @param list - collection of items + * @param fn - callback applied to each item + */ + each(list: any, fn: (item: any, index: number) => void): void; + + /** + * Check whether an array contains an item + * @param arr - target array + * @param item - item to test + * @returns True if array contains item + */ + contains(arr: any[], item: any): boolean; + + /** + * Convert a string containing dashes to camel case + * @param str - input string + * @returns my-string -> myString + */ + toCamel(str: string): string; + + /** + * Check if string starts with specified value + * @param str - source string + * @param value - test string + * @returns True if string starts with provided value + */ + startsWith(str: string, value: string): boolean; + + /** + * Helper function to set an immutable property + * @param el - object where the new property will be set + * @param key - object key where the new property will be stored + * @param value - value of the new property + * @param options - set the property overriding the default options + * @returns The initial object + */ + defineProperty(el: any, key: string, value: any, options: any): any; + + /** + * Extend any object with other properties + * @param args - objects to merge + * @returns The resulting extended object + */ + extend(...args: any[]): any; +} + +export interface TagsUtil { + /** + * Detect the tag implementation by a DOM node + * @param element - DOM node we need to parse to get its tag implementation + * @returns Object containing the implementation of a custom tag (template and boot function) + */ + getTag(element: Element): any; + + /** + * Inherit properties from a target tag instance + * @param target - tag where we will inherit properties + * @param propsInSyncWithParent - array of properties to sync with the target + */ + inheritFrom(this: TagInstance, target: TagInstance, propsInSyncWithParent: string[]): void; + + /** + * Move the position of a custom tag in its parent tag + * @param tagName - key where the tag was stored + * @param newPos - index where the new tag will be stored + */ + moveChildTag(this: TagInstance, tagName: string, newPos: number): void; + + /** + * Create a new child tag including it correctly into its parent + * @param child - child tag implementation + * @param opts - tag options containing the DOM node where the tag will be mounted + * @param innerHTML - inner html of the child node + * @param parent - instance of the parent tag including the child custom tag + * @returns Instance of the new child tag just created + */ + initChildTag(child: any, opts: any, innerHTML: string, parent: TagInstance): TagInstance; + + /** + * Loop backward all the parents tree to detect the first custom parent tag + * @param tag - a tag instance + * @returns Instance of the first custom parent tag found + */ + getImmediateCustomParentTag(tag: TagInstance): TagInstance; + + /** + * Trigger the unmount method on all the expressions + * @param expressions - DOM expressions + */ + unmountAll(expressions: any[]): void; + + /** + * Get the tag name of any DOM node + * @param dom - DOM node we want to parse + * @param skipDataIs - hack to ignore the data-is attribute when attaching to parent + * @returns Name to identify this dom node in riot + */ + getTagName(dom: Element, skipDataIs: boolean): string; + + /** + * With this function we avoid that the internal Tag methods get overridden + * @param data - options we want to use to extend the tag instance + * @returns Clean object without containing the riot internal reserved words + */ + cleanUpData(data: any): any; + + /** + * Set the property of an object for a given key. If something already + * exists there, then it becomes an array containing both the old and new value. + * @param obj - object on which to set the property + * @param key - property name + * @param value - the value of the property to be set + * @param ensureArray - ensure that the property remains an array + * @param index - add the new item in a certain array position + */ + arrayishAdd(obj: any, key: string, value: any, ensureArray?: boolean, index?: number): void; + + /** + * Removes an item from an object at a given key. If the key points to an array, + * then the item is just removed from the array. + * @param obj - object on which to remove the property + * @param key - property name + * @param value - the value of the property to be removed + * @param ensureArray - ensure that the property remains an array + */ + arrayishRemove(obj: any, key: string, value: any, ensureArray?: boolean): void; + + /** + * Mount a tag creating new Tag instance + * @param root - dom node where the tag will be mounted + * @param tagName - name of the riot tag we want to mount + * @param opts - options to pass to the Tag instance + * @param ctx - optional context that will be used to extend an existing class ( used in riot.Tag ) + * @returns Created tag instance + */ + mountTo(root: Element, tagName: string, opts?: TagOpts, ctx?: any): TagInstance; + + /** + * Makes a tag virtual and replaces a reference in the dom + * @param tag - tag to make virtual + * @param ref - dom reference location + */ + makeReplaceVirtual(tag: TagInstance, ref: Node): void; + + /** + * Adds the elements for a virtual tag + * @param src - the node that will do the inserting or appending + * @param target - only if inserting, insert before this tag's first child + */ + makeVirtual(this: TagInstance, src: Node, target?: TagInstance): void; + + /** + * Move virtual tag and all child nodes + * @param src - the node that will do the inserting + * @param target - insert before this tag's first child + */ + moveVirtual(this: TagInstance, src: Node, target: TagInstance): void; + + /** + * Get selectors for tags + * @param tags - tag names to select + * @returns Selector + */ + selectTags(tags: string[]): string; +} + +export interface Util { + /** + * Reference to the internal riot template engine + */ + tmpl: Tmpl; /** * Internal riot tags cache */ - const vdom: Tag[]; - - interface Observable { - /** - * Register callback for specified events. - * Callback is executed each time event is triggered - * @param events Space separated list of events or wildcard '*' that matches all events - * @param callback Callback function - */ - on?(events: string, callback: Function): Observable; - - /** - * Register callback for specified events. - * Callback is executed at most once. - * @param events Space separated list of events. - * @param callback Callback function - */ - one?(events: string, callback: Function): Observable; - - /** - * Remove all registered callbacks for specified events - * @param events Space separated list of events or wildcard '*' that matches all events - */ - off?(events: string): Observable; - - /** - * Remove specified callback for specified events - * @param events Space separated list of events or wildcard '*' that matches all events - * @param callback Callback function to remove - */ - off?(events: string, callback: Function): Observable; - - /** - * Execute all callback functions registered for specified list of events - * @param events Space separated list of events - * @param args Arguments provided to callbacks - */ - trigger?(events: string, ...args: any[]): Observable; - } + vdom: TagInstance[]; /** - * Riot Router + * Object used to append and create custom tags css */ - interface Route { - /** - * Register callback that is executed when the URL changes - * @param callback Callback function - */ - (callback: (...args: any[]) => void): void; - - /** - * Register callback that is executed when the URL changes and new URL matches specified filter - * @param filter URL filter - * @param callback Callback function - */ - (filter: string, callback: (...any: string[]) => void): void; - - /** - * Change the browser URL and notify all the listeners registered with `Route(callback)` - * @param to New URL - * @param title Document title for new URL - * @param shouldReplace Should new url replace the current history - */ - (to: string, title?: string, shouldReplace?: boolean): void; - - /** - * Return a new routing context - */ - create(): Route; - - /** - * Start listening for url changes - * @param autoExec Should router exec routing on the current url - */ - start(autoExec?: boolean): void; - - /** - * Stop all the routings. - * Removes the listeners and clears the callbacks. - */ - stop(): void; - - /** - * Study the current browser path “in place” and emit routing without waiting for it to change. - */ - exec(): void; - - /** - * @deprecated - */ - exec(callback: Function): void; - - /** - * Extract query from the url - */ - query(): { [key: string]: string }; - - /** - * Change the base path - * @param base Base path - */ - base(base: string): void; - - /** - * Change the default parsers to the custom ones. - * @param parser Replacement parser for default parser - * @param secondParser Replacement parser for handling url filters - */ - parser(parser: (path: string) => any[], secondParser?: (path: string, filter: string) => any[]): void; - } + styleManager: StyleManager; /** - * Adds Observer support for the given object or - * if the argument is empty a new observable instance is created and returned. - * @param el Object to become observable + * Series of utility functions to query and update DOM nodes */ - function observable(el?: any): Observable; - - const route: Route; + dom: DOMUtil; /** - * Mount custom tags with specified tag name. Returns an array of mounted tag instances. - * @param selector Tag selector. - * It can be tag name, css selector or special '*' selector that matches all tags on the page. - * @param opts Optional object passed for the tags to consume. + * Series of helper functions needed for type checking */ - function mount(selector: string, opts?: any): Tag[]; + check: CheckUtil; /** - * Mount a custom tag on DOM nodes matching provided selector. Returns an array of mounted tag instances. - * @param selector CSS selector - * @param tagName Custom tag name - * @param opts Optional object passed for the tag to consume. + * Generic helper functions */ - function mount(selector: string, tagName: string, opts?: any): Tag[]; + misc: MiscUtil; /** - * Mount a custom tag on a given DOM node. Returns an array of mounted tag instances. - * @param domNode DOM node - * @param tagName Tag name - * @param opts Optional object passed for the tag to consume. + * Methods for managing all the riot tags instances */ - function mount(domNode: Node, tagName: string, opts?: any): Tag[]; - - /** - * Render a tag to html. This method is only available on server-side. - * @param tagName Custom tag name - * @param opts Optional object passed for the tag to consume. - */ - function render(tagName: string, opts?: any): string; - - /** - * Update all the mounted tags and their expressions on the page. - * Returns an array of tag instances that are mounted on the page. - */ - function update(): Tag[]; - - /** - * Register a global mixin and automatically add it to all tag instances. - * @param mixinObject Mixin object - */ - function mixin(mixinObject: TagMixin): void; - - /** - * Register a shared mixin, globally available to be used in any tag using `TagInstance.mixin(mixinName)` - * @param mixinName Name of the mixin - * @param mixinObject Mixin object - * @param isGlobal Is global mixin? - */ - function mixin(mixinName: string, mixinObject: TagMixin, isGlobal?: boolean): void; - - /** - * Create a new custom tag “manually” without the compiler. Returns name of the tag. - * @param tagName The tag name - * @param html The layout with expressions - * @param css The style of the tag - * @param attrs String of attributes for the tag - * @param constructor The initialization function being called before - * the tag expressions are calculated and before the tag is mounted - */ - function tag(tagName: string, html: string, css?: string, attrs?: string, constructor?: (opts: any) => void): string; - - - interface TagImplementation { - /** - * Tag template - */ - tmpl: string; - /** - * The callback function called on the mount event - * @param opts Tag options object - */ - fn?(opts: any): void; - /** - * Root tag html attributes as object (key => value) - */ - attrs?: { - [key: string]: any; - } - } - - interface TagConfiguration { - /** - * DOM node where you will mount the tag template - */ - root: Node; - /** - * Tag options - */ - opts?: any; - /** - * Is it used in as loop tag - */ - isLoop?: boolean; - /** - * Is already registered using `riot.tag` - */ - hasImpl?: boolean; - /** - * Loop item in the loop assigned to this instance - */ - item?: any; - } - - interface TagInterface extends Observable { - /** - * options object - */ - opts?: any; - /** - * the parent tag if any - */ - parent?: Tag; - /** - * root DOM node - */ - root?: Node; - /** - * nested custom tags - */ - tags?: { - [key: string]: Tag | Tag[]; - }; - - /** - * Updates all the expressions on the current tag instance as well as on all the children. - * @param data Context data - */ - update?(data?: any): void; - - /** - * Extend tag with functionality available on shared mixin registered with `riot.mixin(mixinName, mixinObject)` - * @param mixinName Name of shared mixin - */ - mixin?(mixinName: string): void; - - /** - * Extend tag functionality with functionality available on provided mixin object. - * @param mixinObject Mixin object - */ - mixin?(mixinObject: TagMixin): void; - - /** - * Mount the tag - */ - mount?(): void; - - /** - * Detach the tag and its children from the page. - * @param keepTheParent If `true` unmounting tag doesn't remove the parent tag - */ - unmount?(keepTheParent?: boolean): void; - } - - - class Tag implements TagInterface { - /** - * Tag constructor - * @param impl Tag implementation - * @param conf Tag configuration - * @param innerHTML HTML that can be used replacing a nested `yield` tag in its template - */ - constructor(impl: TagImplementation, conf: TagConfiguration, innerHTML?: string); - - /** - * options object - */ - opts: any; - /** - * the parent tag if any - */ - parent: Tag; - /** - * root DOM node - */ - root: Node; - /** - * nested custom tags - */ - tags: { - [key: string]: Tag | Tag[]; - }; - - /** - * Updates all the expressions on the current tag instance as well as on all the children. - * @param data Context data - */ - update(data?: any): void; - - /** - * Extend tag with functionality available on shared mixin registered with `riot.mixin(mixinName, mixinObject)` - * @param mixinName Name of shared mixin - */ - mixin(mixinName: string): void; - - /** - * Extend tag functionality with functionality available on provided mixin object. - * @param mixinObject Mixin object - */ - mixin(mixinObject: TagMixin): void; - - /** - * Mount the tag - */ - mount(): void; - - /** - * Detach the tag and its children from the page. - * @param keepTheParent If `true` unmounting tag doesn't remove the parent tag - */ - unmount(keepTheParent?: boolean): void; - - // Observable methods - on(events: string, callback: Function): this; - one(events: string, callback: Function): this; - off(events: string): this; - off(events: string, callback: Function): this; - trigger(events: string, ...args: any[]): this; - } - - /** - * Mixin object for extending tag functionality. - * When it gets mixed in it has access to all tag properties. - * It should not override any built in tag properties - */ - interface TagMixin extends TagInterface { - /** - * Special method which can initialize - * the mixin when it's loaded to the tag and is not - * accessible from the tag its mixed in - */ - init?(): void; - } - - /** - * Compile all tags defined with