diff --git a/.github/CODEOWNERS b/.github/CODEOWNERS index 930f751c85..f5f20b233d 100644 --- a/.github/CODEOWNERS +++ b/.github/CODEOWNERS @@ -3683,7 +3683,7 @@ /types/react-json/ @spielc /types/react-json-pretty/ @LKay /types/react-json-tree/ @gnestor -/types/react-jsonschema-form/ @iamdanfox @sirreal @iplus26 @KurtPreston @phbou72 @LucianBuzzo +/types/react-jsonschema-form/ @iamdanfox @iplus26 @KurtPreston @phbou72 @LucianBuzzo /types/react-lazyload/ @m0a /types/react-lazylog/ @benjaminRomano /types/react-leaflet/ @danzel @davschne @yuit diff --git a/types/ckeditor/index.d.ts b/types/ckeditor/index.d.ts index fb7fe92088..6815d3aa98 100644 --- a/types/ckeditor/index.d.ts +++ b/types/ckeditor/index.d.ts @@ -8,7 +8,7 @@ // See https://github.com/DefinitelyTyped/DefinitelyTyped/issues/1827 for more informations. interface Window { - CKEDITOR_BASEPATH: string; + CKEDITOR_BASEPATH?: string; } declare namespace CKEDITOR { @@ -2530,7 +2530,7 @@ declare namespace CKEDITOR { accessKeyUp(dialog: dialog, key: string): void; disable(): void; enable(): void; - focus(): ui.dialog.uiElement; + focus(): ui.dialog.uiElement | undefined; getDialog(): dialog; getElement(): dom.element; getInputElement(): dom.element; @@ -2541,7 +2541,7 @@ declare namespace CKEDITOR { isVisible(): boolean; registerEvents(definition: CKEDITOR.dialog.definition.uiElement): ui.dialog.uiElement; selectParentTab(): ui.dialog.uiElement; - setValue(value: any, noChangeEvent: boolean): ui.dialog.uiElement; + setValue(value: any, noChangeEvent: boolean): ui.dialog.uiElement | undefined; } class vbox extends hbox { diff --git a/types/cli-interact/cli-interact-tests.ts b/types/cli-interact/cli-interact-tests.ts new file mode 100644 index 0000000000..89e55ee46f --- /dev/null +++ b/types/cli-interact/cli-interact-tests.ts @@ -0,0 +1,22 @@ +import * as cliInteract from 'cli-interact'; + +cliInteract.getChar('Tell me one of', 'abcdef'); +cliInteract.getChoiceByChar('frequency', ['daily', 'weekly', 'monthly']); +cliInteract.getChoiceByChar('frequency', ['daily', 'weekly', 'monthly'], true); +cliInteract.getChoice('frequency', ['daily', 'weekly', 'monthly']); +cliInteract.getChoice('frequency', ['daily', 'weekly', 'monthly'], { + returnNumeric: true, +}); +cliInteract.getIPversion(true); +cliInteract.getNumber('Case 1: You MAY give me a number: ', {allowNoAnswer: true}); +cliInteract.getNumber('Case 2: You MUST give me a number: '); +cliInteract.getNumber('Case 3: You MUST give me an integer: ', true); +cliInteract.getNumber('Case 4: You MAY give me an answer. If you do, it MUST be an integer', { + allowNoAnswer: true, + requireInteger: true, +}); +cliInteract.getYesNo('Is it true', true); +cliInteract.getYesNo('Is it true'); +cliInteract.question('Tell me what do you want: ', { + charlist: 'yn' +}); diff --git a/types/cli-interact/index.d.ts b/types/cli-interact/index.d.ts new file mode 100644 index 0000000000..eb05aa682e --- /dev/null +++ b/types/cli-interact/index.d.ts @@ -0,0 +1,27 @@ +// Type definitions for cli-interact 0.1 +// Project: https://github.com/zhami/cli-interact +// Definitions by: Florian Keller +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +import { BasicOptions } from 'readline-sync'; + +export interface ChoiceOptions { + allowNoAnswer?: boolean; + returnNumeric?: boolean; +} + +export interface NumberOptions { + allowNoAnswer?: boolean; + requireInteger?: boolean; +} + +export function getChar(promptText: string, allowedCharsAsString: string, flagAllowNoAnswer?: boolean): string; +export function getChoice(title: string, choices: string[], opts: ChoiceOptions & {returnNumeric: true}): number; +export function getChoice(title: string, choices: string[], opts?: ChoiceOptions): string; +export function getChoiceByChar(title: string, choices: string[], flagAllowNoAnswer?: boolean): string; +export function getInteger(promptText: string): number; +export function getIPversion(flagAllowNoAnswer?: boolean): string; +export function getNumber(promptText: string, opts?: boolean | NumberOptions): number; +export function getYesNo(title: string, flagAllowNoAnswer: true): boolean | undefined; +export function getYesNo(title: string, flagAllowNoAnswer?: false): boolean; +export function question(prompt: string, options?: BasicOptions): string; diff --git a/types/cli-interact/tsconfig.json b/types/cli-interact/tsconfig.json new file mode 100644 index 0000000000..76750910d6 --- /dev/null +++ b/types/cli-interact/tsconfig.json @@ -0,0 +1,23 @@ +{ + "compilerOptions": { + "module": "commonjs", + "lib": [ + "es6" + ], + "noImplicitAny": true, + "noImplicitThis": true, + "strictNullChecks": true, + "strictFunctionTypes": true, + "baseUrl": "../", + "typeRoots": [ + "../" + ], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true + }, + "files": [ + "index.d.ts", + "cli-interact-tests.ts" + ] +} diff --git a/types/cli-interact/tslint.json b/types/cli-interact/tslint.json new file mode 100644 index 0000000000..3db14f85ea --- /dev/null +++ b/types/cli-interact/tslint.json @@ -0,0 +1 @@ +{ "extends": "dtslint/dt.json" } diff --git a/types/cometd/cometd-tests.ts b/types/cometd/cometd-tests.ts new file mode 100644 index 0000000000..ada9412c04 --- /dev/null +++ b/types/cometd/cometd-tests.ts @@ -0,0 +1,241 @@ +import { CometD, Listener, Message } from "cometd"; + +const cometd = new CometD(); + +// Configuring +// =========== + +cometd.configure("http://localhost:8080/cometd"); + +cometd.configure({ + url: "http://localhost:8080/cometd" +}); + +cometd.registerExtension("ack", { incoming: () => {}, outgoing: () => {} }); + +cometd.unregisterTransport("websocket"); + +// Handshaking +// =========== + +cometd.handshake(handshakeReply => { + if (handshakeReply.successful) { + // Successfully connected to the server. + } +}); + +const additionalInfoHandshake = { + "com.acme.credentials": { + user: "cometd", + token: "xyzsecretabc" + } +}; +cometd.handshake(additionalInfoHandshake, handshakeReply => { + if (handshakeReply.successful) { + // Successfully connected to the server. + } +}); + +cometd.init("http://host1:8080/cometd"); + +// Subscribing and Unsubscribing +// ============================= + +cometd.subscribe( + "/foo", + message => {}, + subscribeReply => { + if (subscribeReply.successful) { + // The server successfully subscribed this client to the "/foo" channel. + } + } +); + +const additionalInfoSubscribe = { + "com.acme.priority": 10 +}; +cometd.subscribe("/foo", message => {}, additionalInfoSubscribe, subscribeReply => { + if (subscribeReply.successful) { + // The server successfully subscribed this client to the "/foo" channel. + } +}); + +const subscription1 = cometd.addListener("/meta/connect", () => {}); +const subscription2 = cometd.subscribe("/foo/bar/", () => {}); + +cometd.unsubscribe(subscription2); +cometd.removeListener(subscription1); + +const subscription3 = cometd.subscribe("/foo/bar/", () => {}); + +const additionalInfoUnsubscribe = { + "com.acme.discard": true +}; +cometd.unsubscribe(subscription3, additionalInfoUnsubscribe, unsubscribeReply => { + // Your logic here. +}); + +// Subscribers versus Listeners +// ============================ + +let _reportListener: Listener | undefined; + +cometd.addListener("/meta/handshake", message => { + // Only subscribe if the handshake is successful + if (message.successful) { + // Batch all subscriptions together + cometd.batch(() => { + // Correct to subscribe to broadcast channels + cometd.subscribe("/members", m => {}); + + // Correct to subscribe to service channels + cometd.subscribe("/service/status", m => {}); + + // Messy to add listeners after removal, prefer using cometd.subscribe(...) + if (_reportListener) { + cometd.removeListener(_reportListener); + _reportListener = cometd.addListener("/service/report", m => {}); + } + + // Wrong to add listeners without removal + cometd.addListener("/service/notification", m => {}); + }); + } +}); + +// Dynamic Resubscription +// ====================== + +let _subscription: Listener | undefined; + +class Controller { + dynamicSubscribe = () => { + _subscription = cometd.subscribe("/dynamic", this.onEvent); + } + + onEvent = (message: Message) => { + if (message.successful) { + // Your logic here. + } + } + + dynamicUnsubscribe = () => { + if (_subscription) { + cometd.unsubscribe(_subscription); + _subscription = undefined; + } + } +} + +cometd.addListener("/meta/handshake", message => { + if (message.successful) { + cometd.batch(() => { + // Static subscription, no need to remember the subscription handle + cometd.subscribe("/static", () => {}); + + // Dynamic re-subscription + if (_subscription) { + _subscription = cometd.resubscribe(_subscription); + } + }); + } +}); + +// Listeners and Subscribers Exception Handling +// ============================================ + +cometd.onListenerException = function(exception, subscriptionHandle, isListener, message) { + // Uh-oh, something went wrong, disable this listener/subscriber + // Object "this" points to the CometD object + if (isListener) { + this.removeListener(subscriptionHandle); + } else { + this.unsubscribe(subscriptionHandle); + } +}; + +// Meta Channel List +// ================= + +let _connected = false; + +cometd.addListener("/meta/connect", message => { + if (cometd.isDisconnected()) { + return; + } + + const wasConnected = _connected; + _connected = message.successful; + if (!wasConnected && _connected) { + // Reconnected + } else if (wasConnected && !_connected) { + // Disconnected + } +}); + +cometd.addListener("/meta/disconnect", message => { + if (message.successful) { + _connected = false; + } +}); + +// Publishing +// ========== + +cometd.publish("/mychannel", { mydata: { foo: "bar" } }); + +cometd.publish("/mychannel", { mydata: { foo: "bar" } }, publishAck => { + if (publishAck.successful) { + // The message reached the server + } +}); + +// Publishing Binary Data +// ====================== + +// Create an ArrayBuffer. +const buffer = new ArrayBuffer(4); + +// Fill it with the bytes. +const view = new DataView(buffer); +view.setUint8(0, 0xca); +view.setUint8(1, 0xfe); +view.setUint8(2, 0xba); +view.setUint8(3, 0xbe); + +// Send it. +cometd.publishBinary("/binary", view, true, { prolog: "java" }); + +// Disconnecting +// ============= + +cometd.disconnect(disconnectReply => { + if (disconnectReply.successful) { + // Server truly received the disconnect request + } +}); + +const additionalInfoDisconnect = { + "com.acme.reset": false +}; +cometd.disconnect(additionalInfoDisconnect, disconnectReply => { + if (disconnectReply.successful) { + // Server truly received the disconnect request + } +}); + +// Message Batching +// ================ + +cometd.batch(() => { + cometd.publish("/channel1", { product: "foo" }); + cometd.publish("/channel2", { notificationType: "all" }); + cometd.publish("/channel3", { update: false }); +}); + +// Alternatively, but not recommended: +cometd.startBatch(); +cometd.publish("/channel1", { product: "foo" }); +cometd.publish("/channel2", { notificationType: "all" }); +cometd.publish("/channel3", { update: false }); +cometd.endBatch(); diff --git a/types/cometd/index.d.ts b/types/cometd/index.d.ts index cc97b304fe..32e4f962bb 100644 --- a/types/cometd/index.d.ts +++ b/types/cometd/index.d.ts @@ -1,55 +1,467 @@ -// Type definitions for CometD 2.5.1 +// Type definitions for CometD 4.0 // Project: http://cometd.org -// Definitions by: Derek Cicerone +// Definitions by: Derek Cicerone , Daniel Perez Alvarez // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.3 -declare namespace CometD { - - interface ConfigurationOptions { - url: string; - logLevel?: string; - maxConnections?: number; - backoffIncrement?: number; - maxBackoff?: number; - reverseIncomingExtensions?: boolean; - maxNetworkDelay?: number; - requestHeaders?: any; - appendMessageTypeToURL?: boolean; - autoBatch?: boolean; - } - +export interface Configuration { + /** + * The URL of the Bayeux server this client will connect to. + */ + url: string; + /** + * The log level. Possible values are: "warn", "info", "debug". Output to `window.console` if + * available. + */ + logLevel?: string; + /** + * The maximum number of connections used to connect to the Bayeux server. Change this value + * only if you know exactly the client’s connection limit and what "request queued behind long + * poll" means. + */ + maxConnections?: number; + /** + * The number of milliseconds that the backoff time increments every time a connection with the + * Bayeux server fails. CometD attempts to reconnect after the backoff time elapses. + */ + backoffIncrement?: number; + /** + * The maximum number of milliseconds of the backoff time after which the backoff time is not + * incremented further. + */ + maxBackoff?: number; + /** + * The maximum number of milliseconds to wait before considering a request to the Bayeux server + * failed. + */ + maxNetworkDelay?: number; + /** + * An object containing the request headers to be sent for every Bayeux request (for example, + * `{"My-Custom-Header": "MyValue"}`). + */ + requestHeaders?: object; + /** + * Determines whether or not the Bayeux message type (handshake, connect, disconnect) is + * appended to the URL of the Bayeux server (see above). + */ + appendMessageTypeToURL?: boolean; + /** + * Determines whether multiple publishes that get queued are sent as a batch on the first + * occasion, without requiring explicit batching. + */ + autoBatch?: boolean; + /** + * The maximum number of milliseconds to wait for a WebSocket connection to be opened. It does + * not apply to HTTP connections. A timeout value of 0 means to wait forever. + */ + connectTimeout?: number; + /** + * Only applies to the websocket transport. Determines whether to stick using the websocket + * transport when a websocket transport failure has been detected after the websocket transport + * was able to successfully connect to the server. + */ + stickyReconnect?: boolean; + /** + * The max length of the URI for a request made with the callback-polling transport. Microsoft + * Internet Explorer 7 and 8 are known to limit the URI length, so single large messages sent by + * CometD may fail to remain within the max URI length when encoded in JSON. + */ + maxURILength?: number; } -interface CometD { - - websocketEnabled?: boolean; +export interface Message { + successful: boolean; + data: any; +} - onListenerException: (exception: any, subscriptionHandle: any, isListener: boolean, message: string) => void; +export type Listener = (message: Message) => void; - init(options: CometD.ConfigurationOptions): void; +export interface Extension { + incoming?: Listener; + outgoing?: Listener; +} - configure(config: CometD.ConfigurationOptions): void; - - subscribe(channel: string, listener: (message: any) => void): void; +export class CometD { + constructor(options?: Configuration); - addListener(channel: string, listener: (message: any) => void): void; - removeListener(listener: (message: any) => void): void; + /** + * Registers the given transport under the given transport type. + * + * The optional index parameter specifies the priority at which the transport is registered + * (where `0` is the max priority). + * + * If a transport with the same type is already registered, this function does nothing and + * returns `false`. + * + * @param type the transport type + * @param transport the transport object + * @param index the index at which this transport is to be registered + * @return true if the transport has been registered, false otherwise + */ + registerTransport(type: string, transport: object, index?: number): boolean; + /** + * Unregisters the transport with the given transport type. + * + * @param type the transport type to unregister + * @return the transport that has been unregistered, or null if no transport was previously + * registered under the given transport type + */ + unregisterTransport(type: string): void; + + /** + * Unregisters all transports. + */ + unregisterTransports(): void; + + /** + * Configures and establishes the Bayeux communication with the Bayeux server via a handshake + * and a subsequent connect. + * + * @param configuration the configuration object + * @param handshakeProps an object to be merged with the handshake message + */ + init(configuration: string | Configuration, handshakeProps?: object): void; + + /** + * Configures the initial Bayeux communication with the Bayeux server. + * + * @param configuration the URL of the Bayeux server, or a configuration object that must + * contain a mandatory field `url` + */ + configure(config: string | Configuration): void; + + /** + * Establishes the Bayeux communication with the Bayeux server via a handshake and a subsequent + * connect. + * + * @param handshakeCallback a function to be invoked when the handshake is acknowledged + */ + handshake(handshakeCallback: Listener): void; + + /** + * Establishes the Bayeux communication with the Bayeux server via a handshake and a subsequent + * connect. + * + * @param handshakeProps an object to be merged with the handshake message + * @param handshakeCallback a function to be invoked when the handshake is acknowledged + */ + handshake(handshakeProps: object, handshakeCallback: Listener): void; + + /** + * Disconnects from the Bayeux server. + * + * @param disconnectCallback a function to be invoked when the disconnect is acknowledged + */ + disconnect(disconnectCallback: Listener): void; + + /** + * Disconnects from the Bayeux server. + * + * @param disconnectProps an object to be merged with the disconnect message + * @param disconnectCallback a function to be invoked when the disconnect is acknowledged + */ + disconnect(disconnectProps: object, disconnectCallback: Listener): void; + + /** + * Marks the start of a batch of application messages to be sent to the server in a single + * request, obtaining a single response containing (possibly) many application reply messages. + * + * Messages are held in a queue and not sent until `endBatch` is called. If `startBatch` is + * called multiple times, then an equal number of `endBatch` calls must be made to close and + * send the batch of messages. + */ + startBatch(): void; + + /** + * Marks the end of a batch of application messages to be sent to the server in a single + * request. + */ + endBatch(): void; + + /** + * Executes the given callback in the given scope, surrounded by a `startBatch` and `endBatch` + * calls. + * + * @param callback the callback to be executed within `startBatch` and `endBatch` calls + */ + batch(callback: () => void): void; + + /** + * Adds a listener for Bayeux messages, performing the given callback in the given scope when a + * message for the given channel arrives. + * + * - Must be used to listen to meta channel messages. + * - May be used to listen to service channel messages. + * - Should not be used to listen broadcast channel messages (use `subscribe` instead). + * - Does not involve any communication with the Bayeux server, and as such can be called before + * calling `handshake`. + * - Is synchronous: when it returns, you are guaranteed that the listener has been added. + * + * @param channel the channel the listener is interested to + * @param callback the callback to call when a message is sent to the channel + * @returns the subscription handle to be passed to `removeListener` + */ + addListener(channel: string, callback: Listener): Listener; + + /** + * Removes the subscription obtained with a call to `addListener`. + * + * @param subscription the subscription to unsubscribe. + */ + removeListener(subscription: Listener): void; + + /** + * Removes all listeners registered with `addListener` or `subscribe`. + */ clearListeners(): void; + /** + * Subscribes to the given channel, performing the given callback in the given scope when a + * message for the channel arrives. + * + * - Must not be used to listen to meta channels messages (if attempted, the server returns an + * error). + * - May be used to listen to service channel messages. + * - Should be used to listen to broadcast channel messages. + * - Involves a communication with the Bayeux server and as such cannot be called before calling + * `handshake`. + * - Is asynchronous: it returns immediately, well before the Bayeux server has received the + * subscription request. + * + * @param channel the channel to subscribe to + * @param callback the callback to call when a message is sent to the channel + * @param subscribeCallback a function to be invoked when the subscription is acknowledged + * @return the subscription handle to be passed to `unsubscribe` + */ + subscribe(channel: string, callback: Listener, subscribeCallback?: Listener): Listener; + + /** + * Subscribes to the given channel, performing the given callback in the given scope when a + * message for the channel arrives. + * + * - Must not be used to listen to meta channels messages (if attempted, the server returns an + * error). + * - May be used to listen to service channel messages. + * - Should be used to listen to broadcast channel messages. + * - Involves a communication with the Bayeux server and as such cannot be called before calling + * `handshake`. + * - Is asynchronous: it returns immediately, well before the Bayeux server has received the + * subscription request. + * + * @param channel the channel to subscribe to + * @param callback the callback to call when a message is sent to the channel + * @param subscribeProps an object to be merged with the subscribe message + * @param subscribeCallback a function to be invoked when the subscription is acknowledged + * @return the subscription handle to be passed to `unsubscribe` + */ + subscribe(channel: string, callback: Listener, subscribeProps: object, subscribeCallback?: Listener): Listener; + + /** + * Unsubscribes the subscription obtained with a call to `subscribe`. + * + * @param subscription the subscription to unsubscribe. + * @param unsubscribeCallback a function to be invoked when the unsubscription is acknowledged + */ + unsubscribe(subscription: Listener, unsubscribeCallback?: Listener): void; + + /** + * Unsubscribes the subscription obtained with a call to `subscribe`. + * + * @param subscription the subscription to unsubscribe. + * @param unsubscribeProps an object to be merged with the unsubscribe message + * @param unsubscribeCallback a function to be invoked when the unsubscription is acknowledged + */ + unsubscribe(subscription: Listener, unsubscribeProps: object, unsubscribeCallback?: Listener): void; + + /** + * Resubscribes as necessary in case of a re-handshake. + */ + resubscribe(subscription: Listener, subscribeProps?: object): Listener; + + /** + * Removes all subscriptions added via `subscribe`, but does not remove the listeners added via + * `addListener`. + */ clearSubscriptions(): void; - handshake(handshake_params: any): void; + /** + * Publishes a message on the given channel, containing the given content. + * + * @param channel the channel to publish the message to + * @param content the content of the message + * @param publishCallback a function to be invoked when the publish is acknowledged by the + * server + */ + publish(channel: string, content: object, publishCallback?: Listener): void; - publish(channel: string, message: any): void; + /** + * Publishes a message on the given channel, containing the given content. + * + * @param channel the channel to publish the message to + * @param content the content of the message + * @param publishProps an object to be merged with the publish message + * @param publishCallback a function to be invoked when the publish is acknowledged by the + * server + */ + publish(channel: string, content: object, publishProps: object, publishCallback?: Listener): void; + /** + * Publishes a message with binary data on the given channel. + * + * The binary data chunk may be an `ArrayBuffer`, a `DataView`, a `TypedArray` (such as + * `Uint8Array`) or a plain integer array. + * + * The meta data object may contain additional application data such as a file name, a mime + * type, etc. + * + * @param channel the channel to publish the message to + * @param data the binary data to publish + * @param last whether the binary data chunk is the last + * @param meta an object containing meta data associated to the binary chunk + * @param callback a function to be invoked when the publish is acknowledged by the server + */ + publishBinary( + channel: string, + data: ArrayBuffer | DataView | Uint8Array | Uint16Array | Uint32Array, + last: boolean, + meta?: object, + callback?: Listener + ): void; - disconnect(): void; + /** + * Returns a string representing the status of the Bayeux communication with the Bayeux server. + * + * @return the status of the Bayeux communication + */ + getStatus(): string; -} + /** + * Returns whether this instance has been disconnected. + * + * @return whether this instance has been disconnected. + */ + isDisconnected(): boolean; + /** + * Sets the backoff period used to increase the backoff time when retrying an unsuccessful or + * failed message. + * + * Default value is 1 second, which means if there is a persistent failure the retries will + * happen after 1 second, then after 2 seconds, then after 3 seconds, etc. So for example with + * 15 seconds of elapsed time, there will be 5 retries (at 1, 3, 6, 10 and 15 seconds elapsed). + * + * @param period the backoff period to set + */ + setBackoffIncrement(period: number): void; + /** + * Returns the backoff period used to increase the backoff time when retrying an unsuccessful or + * failed message. + * + * @returns the backoff increment + */ + getBackoffIncrement(): void; -interface JQueryStatic { - cometd: CometD; + /** + * Returns the backoff period to wait before retrying an unsuccessful or failed message. + * + * @returns the backoff period + */ + getBackoffPeriod(): void; + + /** + * Increases the backoff period up to the maximum value configured. + * + * @returns the backoff period after increment + */ + increaseBackoffPeriod(): number; + + /** + * Resets the backoff period to zero. + */ + resetBackoffPeriod(): void; + + /** + * Sets the log level for console logging. + * + * @param level the log level string + */ + setLogLevel(level: "error" | "warn" | "info" | "debug"): void; + + /** + * Registers an extension whose callbacks are called for every incoming message (that comes from + * the server to this client implementation) and for every outgoing message (that originates + * from this client implementation for the server). + * + * The format of the extension object is the following: + * + * { + * incoming: (message) => { ... }, + * outgoing: (message) => { ... } + * } + * + * Both properties are optional, but if they are present they will be called respectively for + * each incoming message and for each outgoing message. + * + * @param name the name of the extension + * @param extension the extension to register + * @return true if the extension was registered, false otherwise + */ + registerExtension(name: string, extension: Extension): boolean; + + /** + * Unregister an extension previously registered with `registerExtension`. + * + * @param name the name of the extension to unregister. + * @return true if the extension was unregistered, false otherwise + */ + unregisterExtension(name: string): boolean; + + /** + * Find the extension registered with the given name. + * + * @param name the name of the extension to find + * @return the extension found or null if no extension with the given name has been registered + */ + getExtension(name: string): Extension; + + /** + * Returns the name assigned to this CometD object, or the string 'default' if no name has been + * explicitly passed as parameter to the constructor. + * + * @return the name assigned to this CometD object, or `'default'` + */ + getName(): string; + + /** + * Returns the client ID assigned by the Bayeux server during handshake. + * + * @return the client ID assigned by the Bayeux server + */ + getClientId(): string; + + /** + * Returns the URL of the Bayeux server. + * + * @return the URL of the Bayeux server + */ + getURL(): string; + + /** + * Returns the configuration for this CometD object. + * + * @return the configuration for this CometD object + */ + getConfiguration(): Configuration; + + /** + * Handler invoked every time a listener or subscriber throws an exception. + * + * @param exception the exception thrown + * @param subscriptionHandle the listener or subscription that threw the exception + * @param isListener whether it was a listener + * @param message the message received from the Bayeux server + */ + onListenerException: (exception: any, subscriptionHandle: Listener, isListener: boolean, message: string) => void; } diff --git a/types/cometd/tsconfig.json b/types/cometd/tsconfig.json index 02963e3afd..6533a1a225 100644 --- a/types/cometd/tsconfig.json +++ b/types/cometd/tsconfig.json @@ -6,7 +6,7 @@ ], "noImplicitAny": true, "noImplicitThis": true, - "strictNullChecks": false, + "strictNullChecks": true, "strictFunctionTypes": true, "baseUrl": "../", "typeRoots": [ @@ -17,6 +17,7 @@ "forceConsistentCasingInFileNames": true }, "files": [ - "index.d.ts" + "index.d.ts", + "cometd-tests.ts" ] } \ No newline at end of file diff --git a/types/cometd/tslint.json b/types/cometd/tslint.json index a41bf5d19a..f93cf8562a 100644 --- a/types/cometd/tslint.json +++ b/types/cometd/tslint.json @@ -1,79 +1,3 @@ { - "extends": "dtslint/dt.json", - "rules": { - "adjacent-overload-signatures": false, - "array-type": false, - "arrow-return-shorthand": false, - "ban-types": false, - "callable-types": false, - "comment-format": false, - "dt-header": false, - "eofline": false, - "export-just-namespace": false, - "import-spacing": false, - "interface-name": false, - "interface-over-type-literal": false, - "jsdoc-format": false, - "max-line-length": false, - "member-access": false, - "new-parens": false, - "no-any-union": false, - "no-boolean-literal-compare": false, - "no-conditional-assignment": false, - "no-consecutive-blank-lines": false, - "no-construct": false, - "no-declare-current-package": false, - "no-duplicate-imports": false, - "no-duplicate-variable": false, - "no-empty-interface": false, - "no-for-in-array": false, - "no-inferrable-types": false, - "no-internal-module": false, - "no-irregular-whitespace": false, - "no-mergeable-namespace": false, - "no-misused-new": false, - "no-namespace": false, - "no-object-literal-type-assertion": false, - "no-padding": false, - "no-redundant-jsdoc": false, - "no-redundant-jsdoc-2": false, - "no-redundant-undefined": false, - "no-reference-import": false, - "no-relative-import-in-test": false, - "no-self-import": false, - "no-single-declare-module": false, - "no-string-throw": false, - "no-unnecessary-callback-wrapper": false, - "no-unnecessary-class": false, - "no-unnecessary-generics": false, - "no-unnecessary-qualifier": false, - "no-unnecessary-type-assertion": false, - "no-useless-files": false, - "no-var-keyword": false, - "no-var-requires": false, - "no-void-expression": false, - "no-trailing-whitespace": false, - "object-literal-key-quotes": false, - "object-literal-shorthand": false, - "one-line": false, - "one-variable-per-declaration": false, - "only-arrow-functions": false, - "prefer-conditional-expression": false, - "prefer-const": false, - "prefer-declare-function": false, - "prefer-for-of": false, - "prefer-method-signature": false, - "prefer-template": false, - "radix": false, - "semicolon": false, - "space-before-function-paren": false, - "space-within-parens": false, - "strict-export-declare-modifiers": false, - "trim-file": false, - "triple-equals": false, - "typedef-whitespace": false, - "unified-signatures": false, - "void-return": false, - "whitespace": false - } + "extends": "dtslint/dt.json" } diff --git a/types/complex/complex-tests.ts b/types/complex/complex-tests.ts index 23074d104d..8268f0c135 100644 --- a/types/complex/complex-tests.ts +++ b/types/complex/complex-tests.ts @@ -1,42 +1,44 @@ import Complex from 'complex'; -var z: Complex = new Complex(2, 3); -var z: Complex = Complex.from(2, 3); -var z: Complex = Complex.from(2, 4); -var z: Complex = Complex.from(5); -var z: Complex = Complex.from('2+5i'); -var z: Complex = Complex.fromPolar(3, Math.PI); -var z: Complex = Complex.i; -var z: Complex = Complex.one; -var z: Complex = z.fromRect(2, 3); -var z: Complex = z.fromPolar(3, Math.PI); -var z: Complex = z.toPrecision(3); -var z: Complex = z.toFixed(3); -var z: Complex = z.finalize(); -var x: number = z.magnitude(); -var x: number = z.abs(); -var x: number = z.angle(); -var x: number = z.arg(); -var x: number = z.phase(); -var z: Complex = z.conjugate(); -var z: Complex = z.negate(); -var z: Complex = z.multiply(z); -var z: Complex = z.mult(3); -var z: Complex = z.divide(z); -var z: Complex = z.div(3); -var z: Complex = z.add(z); -var z: Complex = z.subtract(z); -var z: Complex = z.sub(3); -var z: Complex = z.pow(z); -var z: Complex = z.sqrt(); -var z: Complex = z.log(2); -var z: Complex = z.exp(); -var z: Complex = z.sin(); -var z: Complex = z.cos(); -var z: Complex = z.tan(); -var z: Complex = z.sinh(); -var z: Complex = z.cosh(); -var z: Complex = z.tanh(); -var z: Complex = z.clone(); -var s: string = z.toString(); -var b: boolean = z.equals(z); +let z: Complex = new Complex(2, 3); +z = Complex.from(2, 3); +z = Complex.from(2, 4); +z = Complex.from(5); +z = Complex.from('2+5i'); +z = Complex.fromPolar(3, Math.PI); +z = Complex.i; +z = Complex.one; +z = z.fromRect(2, 3); +z = z.fromPolar(3, Math.PI); +z = z.toPrecision(3); +z = z.toFixed(3); +z = z.finalize(); +let x: number = z.magnitude(); +x = z.abs(); +x = z.angle(); +x = z.arg(); +x = z.phase(); +z = z.conjugate(); +z = z.negate(); +z = z.multiply(z); +z = z.mult(3); +z = z.divide(z); +z = z.div(3); +z = z.add(z); +z = z.subtract(z); +z = z.sub(3); +z = z.pow(z); +z = z.sqrt(); +z = z.log(2); +z = z.exp(); +z = z.sin(); +z = z.cos(); +z = z.tan(); +z = z.sinh(); +z = z.cosh(); +z = z.tanh(); +z = z.clone(); +const s: string = z.toString(); +const b: boolean = z.equals(z); +const n: number = z.real; +const i: number = z.im; diff --git a/types/complex/index.d.ts b/types/complex/index.d.ts index 90ad161ffc..3f44ba8e1e 100644 --- a/types/complex/index.d.ts +++ b/types/complex/index.d.ts @@ -1,6 +1,7 @@ -// Type definitions for Complex 3.0.1 +// Type definitions for Complex 3.0 // Project: https://github.com/arian/Complex // Definitions by: Aya Morisawa +// Paul Vasich // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped export default class Complex { @@ -46,6 +47,16 @@ export default class Complex { */ static one: Complex; + /** + * The Complex number's real component + */ + real: number; + + /** + * The Complex number's imaginary component + */ + im: number; + /** * Set the real and imaginary properties a and b from a + bi. * @param real The real part of the number @@ -61,19 +72,25 @@ export default class Complex { fromPolar(r: number, phi: number): Complex; /** - * Set the precision of the numbers. Similar to Number.prototype.toPrecision. Useful before printing the number with the toString method. + * Set the precision of the numbers. Similar to Number.prototype.toPrecision. + * Useful before printing the number with the toString method. * @param k An integer specifying the number of significant digits */ toPrecision(k: number): Complex; /** - * Format a number using fixed-point notation. Similar to Number.prototype.toFixed. Useful before printing the number with the toString method. - * @param k The number of digits to appear after the decimal point; this may be a value between 0 and 20, inclusive, and implementations may optionally support a larger range of values. If this argument is omitted, it is treated as 0. + * Format a number using fixed-point notation. Similar to Number.prototype.toFixed. + * Useful before printing the number with the toString method. + * @param k The number of digits to appear after the decimal point [0 - 20]. + * Implementations may optionally support a larger range of values. + * If this argument is omitted, it is treated as 0. */ toFixed(k: number): Complex; /** - * Finalize the instance. The number will not change and any other method call will return a new instance. Very useful when a complex instance should stay constant. For example the Complex.i variable is a finalized instance. + * Finalize the instance. The number will not change and any other method call will return a new instance. + * Very useful when a complex instance should stay constant. + * For example the Complex.i variable is a finalized instance. */ finalize(): Complex; @@ -167,7 +184,8 @@ export default class Complex { /** * Return the natural logarithm (base E) - * @param k The actual answer has a multiplicity (ln(z) = ln|z| + arg(z)) where arg(z) can return the same for different angles (every 2*pi), with this argument you can define which answer is required + * @param k The actual answer has a multiplicity (ln(z) = ln|z| + arg(z)) where arg(z) can return the same for + * different angles (every 2*pi), with this argument you can define which answer is required */ log(k?: number): Complex; @@ -194,17 +212,17 @@ export default class Complex { /** * Calculate the hyperbolic sine of the complex number */ - sinh(): Complex + sinh(): Complex; /** * Calculate the hyperbolic cosine of the complex number */ - cosh(): Complex + cosh(): Complex; /** * Calculate the hyperbolic tangent of the complex number */ - tanh(): Complex + tanh(): Complex; /** * Return a new Complex instance with the same real and imaginary properties diff --git a/types/complex/tsconfig.json b/types/complex/tsconfig.json index b8a54e716a..0869ead6e6 100644 --- a/types/complex/tsconfig.json +++ b/types/complex/tsconfig.json @@ -6,7 +6,7 @@ ], "noImplicitAny": true, "noImplicitThis": true, - "strictNullChecks": false, + "strictNullChecks": true, "strictFunctionTypes": true, "baseUrl": "../", "typeRoots": [ @@ -20,4 +20,4 @@ "index.d.ts", "complex-tests.ts" ] -} \ No newline at end of file +} diff --git a/types/complex/tslint.json b/types/complex/tslint.json index a41bf5d19a..3db14f85ea 100644 --- a/types/complex/tslint.json +++ b/types/complex/tslint.json @@ -1,79 +1 @@ -{ - "extends": "dtslint/dt.json", - "rules": { - "adjacent-overload-signatures": false, - "array-type": false, - "arrow-return-shorthand": false, - "ban-types": false, - "callable-types": false, - "comment-format": false, - "dt-header": false, - "eofline": false, - "export-just-namespace": false, - "import-spacing": false, - "interface-name": false, - "interface-over-type-literal": false, - "jsdoc-format": false, - "max-line-length": false, - "member-access": false, - "new-parens": false, - "no-any-union": false, - "no-boolean-literal-compare": false, - "no-conditional-assignment": false, - "no-consecutive-blank-lines": false, - "no-construct": false, - "no-declare-current-package": false, - "no-duplicate-imports": false, - "no-duplicate-variable": false, - "no-empty-interface": false, - "no-for-in-array": false, - "no-inferrable-types": false, - "no-internal-module": false, - "no-irregular-whitespace": false, - "no-mergeable-namespace": false, - "no-misused-new": false, - "no-namespace": false, - "no-object-literal-type-assertion": false, - "no-padding": false, - "no-redundant-jsdoc": false, - "no-redundant-jsdoc-2": false, - "no-redundant-undefined": false, - "no-reference-import": false, - "no-relative-import-in-test": false, - "no-self-import": false, - "no-single-declare-module": false, - "no-string-throw": false, - "no-unnecessary-callback-wrapper": false, - "no-unnecessary-class": false, - "no-unnecessary-generics": false, - "no-unnecessary-qualifier": false, - "no-unnecessary-type-assertion": false, - "no-useless-files": false, - "no-var-keyword": false, - "no-var-requires": false, - "no-void-expression": false, - "no-trailing-whitespace": false, - "object-literal-key-quotes": false, - "object-literal-shorthand": false, - "one-line": false, - "one-variable-per-declaration": false, - "only-arrow-functions": false, - "prefer-conditional-expression": false, - "prefer-const": false, - "prefer-declare-function": false, - "prefer-for-of": false, - "prefer-method-signature": false, - "prefer-template": false, - "radix": false, - "semicolon": false, - "space-before-function-paren": false, - "space-within-parens": false, - "strict-export-declare-modifiers": false, - "trim-file": false, - "triple-equals": false, - "typedef-whitespace": false, - "unified-signatures": false, - "void-return": false, - "whitespace": false - } -} +{ "extends": "dtslint/dt.json" } diff --git a/types/digibyte/digibyte-tests.ts b/types/digibyte/digibyte-tests.ts new file mode 100644 index 0000000000..5785b8ebda --- /dev/null +++ b/types/digibyte/digibyte-tests.ts @@ -0,0 +1,43 @@ +import * as digibyte from 'digibyte'; + +const transaction = new digibyte.Transaction({}); + +const output: digibyte.Transaction.Output = transaction.outputs[0]; +const input: digibyte.Transaction.Input = transaction.inputs[0]; + +const privateKey: digibyte.PrivateKey = new digibyte.PrivateKey('privateKey'); +const publicKey: digibyte.PublicKey = privateKey.publicKey; +const publicKeyAsString: string = publicKey.toString(); + +const signature = digibyte.crypto.ECDSA.sign(Buffer.from('sign this message', 'hex'), new digibyte.PrivateKey('privateKey')); + +digibyte.crypto.ECDSA.verify( + Buffer.from('buffer', 'hex'), + digibyte.crypto.Signature.fromString('signature'), + new digibyte.PublicKey('publicKey') +); + +const utxo: digibyte.Transaction.UnspentOutput[] = [new digibyte.Transaction.UnspentOutput({})]; + +new digibyte.Block(Buffer.from('123', 'hex')); + +const tx = new digibyte.Transaction() + .from(utxo) + .change('digibyteAddress') + .addData(Buffer.from('')) + .sign('digibyteAddressPrivateKey') + .enableRBF(); + +tx.verify(); + +new digibyte.Unit(2, 'DGB').toSatoshis(); + +digibyte.Unit.fromMilis(1000).toDGB(); + +const paymentInfo = { + address: 'DFVsFBiKuaL5HM9NWZgdHTQecLNit6tX5Y', + amount: digibyte.Unit.fromDGB(1000).toSatoshis(), +}; + +const uri = new digibyte.URI(paymentInfo).toString(); +uri.toString(); diff --git a/types/digibyte/index.d.ts b/types/digibyte/index.d.ts new file mode 100644 index 0000000000..e53638a98e --- /dev/null +++ b/types/digibyte/index.d.ts @@ -0,0 +1,311 @@ +// Type definitions for digibyte 0.14 +// Project: https://github.com/digibyte/digibyte-lib +// Definitions by: Lautaro Dragan +// Adam Wolfe +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +// TypeScript Version: 2.2 + +/// + +export namespace crypto { + class BN { } + + namespace ECDSA { + function sign(message: Buffer, key: PrivateKey): Signature; + function verify(hashbuf: Buffer, sig: Signature, pubkey: PublicKey, endian?: 'little'): boolean; + } + + namespace Hash { + function sha1(buffer: Buffer): Buffer; + function sha256(buffer: Buffer): Buffer; + function sha256sha256(buffer: Buffer): Buffer; + function sha256ripemd160(buffer: Buffer): Buffer; + function sha512(buffer: Buffer): Buffer; + function ripemd160(buffer: Buffer): Buffer; + + function sha256hmac(data: Buffer, key: Buffer): Buffer; + function sha512hmac(data: Buffer, key: Buffer): Buffer; + } + + namespace Random { + function getRandomBuffer(size: number): Buffer; + } + + namespace Point {} + + class Signature { + static fromDER(sig: Buffer): Signature; + static fromString(data: string): Signature; + SIGHASH_ALL: number; + toString(): string; + } +} + +export namespace Transaction { + class UnspentOutput { + static fromObject(o: object): UnspentOutput; + + readonly address: Address; + readonly txId: string; + readonly outputIndex: number; + readonly script: Script; + readonly satoshis: number; + + constructor(data: object); + + inspect(): string; + toObject(): this; + toString(): string; + } + + class Output { + readonly script: Script; + readonly satoshis: number; + + constructor(data: object); + + setScript(script: Script | string | Buffer): this; + inspect(): string; + toObject(): object; + } + + class Input { + readonly prevTxId: Buffer; + readonly outputIndex: number; + readonly sequenceNumber: number; + readonly script: Script; + readonly output?: Output; + } +} + +export class Transaction { + inputs: Transaction.Input[]; + outputs: Transaction.Output[]; + readonly id: string; + readonly hash: string; + nid: string; + + constructor(serialized?: any); + + from(utxos: Transaction.UnspentOutput[]): this; + to(address: Address[] | Address | string, amount: number): this; + change(address: Address | string): this; + fee(amount: number): this; + feePerKb(amount: number): this; + sign(privateKey: PrivateKey | string): this; + applySignature(sig: crypto.Signature): this; + addInput(input: Transaction.Input): this; + addOutput(output: Transaction.Output): this; + addData(value: Buffer): this; + lockUntilDate(time: Date | number): this; + lockUntilBlockHeight(height: number): this; + + hasWitnesses(): boolean; + getFee(): number; + getChangeOutput(): Transaction.Output | null; + getLockTime(): Date | number; + + verify(): string | boolean; + isCoinbase(): boolean; + + enableRBF(): this; + isRBF(): boolean; + + inspect(): string; + serialize(): string; +} + +export class Block { + hash: string; + height: number; + transactions: Transaction[]; + header: { + time: number; + prevHash: string; + }; + + constructor(data: Buffer | object); +} + +export class PrivateKey { + readonly publicKey: PublicKey; + readonly network: Networks.Network; + + toAddress(): Address; + toPublicKey(): PublicKey; + toString(): string; + toObject(): object; + toJSON(): object; + toWIF(): string; + + constructor(key?: string, network?: Networks.Network); +} + +export class PublicKey { + constructor(source: string); + + static fromPrivateKey(privateKey: PrivateKey): PublicKey; + + toBuffer(): Buffer; + toDER(): Buffer; +} + +export class HDPrivateKey { + readonly hdPublicKey: HDPublicKey; + + constructor(data?: string | Buffer | object); + + derive(arg: string | number, hardened?: boolean): HDPrivateKey; + deriveChild(arg: string | number, hardened?: boolean): HDPrivateKey; + deriveNonCompliantChild(arg: string | number, hardened?: boolean): HDPrivateKey; + + toString(): string; + toObject(): object; + toJSON(): object; +} + +export class HDPublicKey { + readonly xpubkey: Buffer; + readonly network: Networks.Network; + readonly depth: number; + readonly publicKey: PublicKey; + readonly fingerPrint: Buffer; + + constructor(arg: string | Buffer | object); + + derive(arg: string | number, hardened?: boolean): HDPublicKey; + deriveChild(arg: string | number, hardened?: boolean): HDPublicKey; + + toString(): string; +} + +export namespace Script { + const types: { + DATA_OUT: string; + }; + function buildMultisigOut(publicKeys: PublicKey[], threshold: number, opts: object): Script; + function buildWitnessMultisigOutFromScript(script: Script): Script; + function buildMultisigIn(pubkeys: PublicKey[], threshold: number, signatures: Buffer[], opts: object): Script; + function buildP2SHMultisigIn(pubkeys: PublicKey[], threshold: number, signatures: Buffer[], opts: object): Script; + function buildPublicKeyHashOut(address: Address): Script; + function buildPublicKeyOut(pubkey: PublicKey): Script; + function buildDataOut(data: string | Buffer, encoding?: string): Script; + function buildScriptHashOut(script: Script): Script; + function buildPublicKeyIn(signature: crypto.Signature | Buffer, sigtype: number): Script; + function buildPublicKeyHashIn(publicKey: PublicKey, signature: crypto.Signature | Buffer, sigtype: number): Script; + + function fromAddress(address: string | Address): Script; + + function empty(): Script; +} + +export class Script { + constructor(data: string | object); + + set(obj: object): this; + + toBuffer(): Buffer; + toASM(): string; + toString(): string; + toHex(): string; + + isPublicKeyHashOut(): boolean; + isPublicKeyHashIn(): boolean; + + getPublicKey(): Buffer; + getPublicKeyHash(): Buffer; + + isPublicKeyOut(): boolean; + isPublicKeyIn(): boolean; + + isScriptHashOut(): boolean; + isWitnessScriptHashOut(): boolean; + isWitnessPublicKeyHashOut(): boolean; + isWitnessProgram(): boolean; + isScriptHashIn(): boolean; + isMultisigOut(): boolean; + isMultisigIn(): boolean; + isDataOut(): boolean; + + getData(): Buffer; + isPushOnly(): boolean; + + classify(): string; + classifyInput(): string; + classifyOutput(): string; + + isStandard(): boolean; + + prepend(obj: any): this; + add(obj: any): this; + + hasCodeseparators(): boolean; + removeCodeseparators(): this; + + equals(script: Script): boolean; + + getAddressInfo(): Address | boolean; + findAndDelete(script: Script): this; + checkMinimalPush(i: number): boolean; + getSignatureOperationsCount(accurate: boolean): number; + + toAddress(): Address; +} + +export interface Util { + readonly buffer: { + reverse(a: any): any; + }; +} + +export namespace Networks { + interface Network { + readonly name: string; + readonly alias: string; + } + + const livenet: Network; + const mainnet: Network; + const testnet: Network; + + function add(data: any): Network; + function remove(network: Network): void; + function get(args: string | number | Network, keys: string | string[]): Network; +} + +export class Address { + readonly hashBuffer: Buffer; + readonly network: Networks.Network; + readonly type: string; + + constructor(data: Buffer | Uint8Array | string | object, network?: Networks.Network, type?: string); +} + +export class Unit { + static fromDGB(amount: number): Unit; + static fromMilis(amount: number): Unit; + static fromBits(amount: number): Unit; + static fromSatoshis(amount: number): Unit; + static fromFiat(amount: number, exchangeRate: number): Unit; + + constructor(amount: number, unitPreference: string); + + toDGB(): number; + toMilis(): number; + toBits(): number; + toSatoshis(): number; +} + +export class URI { + static fromString(str: string): URI; + static fromObject(json: object): URI; + static isValid(data: boolean): URI; + static fromSatoshis(amount: number): URI; + + constructor(data: string | object); + + toString(): string; + toObject(): any; + parse(): any; +} diff --git a/types/digibyte/tsconfig.json b/types/digibyte/tsconfig.json new file mode 100644 index 0000000000..f384af2359 --- /dev/null +++ b/types/digibyte/tsconfig.json @@ -0,0 +1,24 @@ +{ + "compilerOptions": { + "module": "commonjs", + "lib": [ + "es6" + ], + "target": "es6", + "noImplicitAny": true, + "noImplicitThis": true, + "strictNullChecks": true, + "strictFunctionTypes": true, + "baseUrl": "../", + "typeRoots": [ + "../" + ], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true + }, + "files": [ + "index.d.ts", + "digibyte-tests.ts" + ] +} \ No newline at end of file diff --git a/types/digibyte/tslint.json b/types/digibyte/tslint.json new file mode 100644 index 0000000000..dae7fb7540 --- /dev/null +++ b/types/digibyte/tslint.json @@ -0,0 +1,4 @@ +{ + "extends": "dtslint/dt.json", + "rules": {} +} \ No newline at end of file diff --git a/types/ember/index.d.ts b/types/ember/index.d.ts index 594e2e2fcc..4e7ec4f74f 100755 --- a/types/ember/index.d.ts +++ b/types/ember/index.d.ts @@ -13,7 +13,6 @@ // TypeScript Version: 2.8 /// -/// /// /// /// @@ -30,609 +29,530 @@ /// /// -declare module 'ember' { - import { - Objectify, Fix, UnwrapComputedPropertySetters, - UnwrapComputedPropertySetter, - UnwrapComputedPropertyGetters, - UnwrapComputedPropertyGetter, - EmberClassArguments, EmberClassConstructor, EmberInstanceArguments, - ComputedPropertyCallback, - ObserverMethod - } from '@ember/object/-private/types'; - import * as HandlebarsNamespace from 'handlebars'; - // Capitalization is intentional: this makes it much easier to re-export RSVP on - // the Ember namespace. - import Rsvp from 'rsvp'; - import { TemplateFactory } from 'htmlbars-inline-precompile'; +import { + Objectify, Fix, UnwrapComputedPropertySetters, + UnwrapComputedPropertySetter, + UnwrapComputedPropertyGetters, + UnwrapComputedPropertyGetter, + EmberClassArguments, EmberClassConstructor, EmberInstanceArguments, + ComputedPropertyCallback, + ObserverMethod +} from '@ember/object/-private/types'; +import * as HandlebarsNamespace from 'handlebars'; +// Capitalization is intentional: this makes it much easier to re-export RSVP on +// the Ember namespace. +import Rsvp from 'rsvp'; +import { TemplateFactory } from 'htmlbars-inline-precompile'; - import { Registry as ServiceRegistry } from '@ember/service'; - import { Registry as ControllerRegistry } from '@ember/controller'; - import * as EmberStringNs from '@ember/string'; - // tslint:disable-next-line:no-duplicate-imports - import * as EmberServiceNs from '@ember/service'; - import * as EmberPolyfillsNs from '@ember/polyfills'; - import * as EmberUtilsNs from '@ember/utils'; - import * as EmberRunloopNs from '@ember/runloop'; - import * as EmberObjectNs from '@ember/object'; - import * as EmberObjectObserversNs from '@ember/object/observers'; - import * as EmberObjectMixinNs from '@ember/object/mixin'; - import * as EmberObjectProxyNs from '@ember/object/proxy'; - import * as EmberObjectPromiseProxyNs from '@ember/object/promise-proxy-mixin'; - import * as EmberObjectInternalsNs from '@ember/object/internals'; - import * as EmberObjectComputedNs from '@ember/object/computed'; - import * as EmberObjectEventedNs from '@ember/object/evented'; - import * as EmberObjectEventsNs from '@ember/object/events'; - // @ember/debug - import * as EmberDebugNs from '@ember/debug'; - import _ContainerDebugAdapter from '@ember/debug/container-debug-adapter'; - import EmberDataAdapter from '@ember/debug/data-adapter'; - // @ember/engine - import * as EmberEngineNs from '@ember/engine'; - import * as EmberEngineInstanceNs from '@ember/engine/instance'; - import _ContainerProxyMixin from '@ember/engine/-private/container-proxy-mixin'; - import _RegistryProxyMixin from '@ember/engine/-private/registry-proxy-mixin'; - import EmberCoreObject from '@ember/object/core'; - import * as EmberApplicationNs from '@ember/application'; - import * as EmberApplicationInstanceNs from '@ember/application/instance'; - import * as EmberApplicationDeprecateNs from '@ember/application/deprecations'; - import * as EmberTestNs from '@ember/test'; - // tslint:disable-next-line:no-duplicate-imports - import * as EmberControllerNs from '@ember/controller'; - // tslint:disable-next-line:no-duplicate-imports - import EmberMixin from '@ember/object/mixin'; - import EmberObservable from '@ember/object/observable'; - // @ember/array - import * as EmberArrayNs from '@ember/array'; - import EmberMutableArray from '@ember/array/mutable'; - import EmberNativeArray from '@ember/array/-private/native-array'; - import EmberArrayProxy from '@ember/array/proxy'; - import EmberEnumerable from '@ember/array/-private/enumerable'; - import EmberMutableEnumerable from '@ember/array/-private/mutable-enumerable'; - import EmberArrayProtoExtensions from '@ember/array/types/prototype-extensions'; - // @ember/run - import { RunMethod } from '@ember/runloop/-private/types'; - // @ember/error - import EmberError from '@ember/error'; +import { Registry as ServiceRegistry } from '@ember/service'; +import { Registry as ControllerRegistry } from '@ember/controller'; +import * as EmberStringNs from '@ember/string'; +// tslint:disable-next-line:no-duplicate-imports +import * as EmberServiceNs from '@ember/service'; +import * as EmberPolyfillsNs from '@ember/polyfills'; +import * as EmberUtilsNs from '@ember/utils'; +import * as EmberRunloopNs from '@ember/runloop'; +import * as EmberObjectNs from '@ember/object'; +import * as EmberObjectObserversNs from '@ember/object/observers'; +import * as EmberObjectMixinNs from '@ember/object/mixin'; +import * as EmberObjectProxyNs from '@ember/object/proxy'; +import * as EmberObjectPromiseProxyNs from '@ember/object/promise-proxy-mixin'; +import * as EmberObjectInternalsNs from '@ember/object/internals'; +import * as EmberObjectComputedNs from '@ember/object/computed'; +import * as EmberObjectEventedNs from '@ember/object/evented'; +import * as EmberObjectEventsNs from '@ember/object/events'; +// @ember/debug +import * as EmberDebugNs from '@ember/debug'; +import _ContainerDebugAdapter from '@ember/debug/container-debug-adapter'; +import EmberDataAdapter from '@ember/debug/data-adapter'; +// @ember/engine +import * as EmberEngineNs from '@ember/engine'; +import * as EmberEngineInstanceNs from '@ember/engine/instance'; +import _ContainerProxyMixin from '@ember/engine/-private/container-proxy-mixin'; +import _RegistryProxyMixin from '@ember/engine/-private/registry-proxy-mixin'; +import EmberCoreObject from '@ember/object/core'; +import * as EmberApplicationNs from '@ember/application'; +import * as EmberApplicationInstanceNs from '@ember/application/instance'; +import * as EmberApplicationDeprecateNs from '@ember/application/deprecations'; +import * as EmberTestNs from '@ember/test'; +// tslint:disable-next-line:no-duplicate-imports +import * as EmberControllerNs from '@ember/controller'; +// tslint:disable-next-line:no-duplicate-imports +import EmberMixin from '@ember/object/mixin'; +import EmberObservable from '@ember/object/observable'; +// @ember/array +import * as EmberArrayNs from '@ember/array'; +import EmberMutableArray from '@ember/array/mutable'; +import EmberNativeArray from '@ember/array/-private/native-array'; +import EmberArrayProxy from '@ember/array/proxy'; +import EmberEnumerable from '@ember/array/-private/enumerable'; +import EmberMutableEnumerable from '@ember/array/-private/mutable-enumerable'; +import EmberArrayProtoExtensions from '@ember/array/types/prototype-extensions'; +// @ember/run +import { RunMethod } from '@ember/runloop/-private/types'; +// @ember/error +import EmberError from '@ember/error'; - type EmberArray = EmberArrayNs.default; - import EmberActionHandler from '@ember/object/-private/action-handler'; - import EmberComponent from '@ember/component'; - import EmberTextArea from '@ember/component/text-area'; - import EmberTextField from '@ember/component/text-field'; - import EmberCheckbox from '@ember/component/checkbox'; - import EmberHelper from '@ember/component/helper'; - // @ember/routing - import EmberRoutingRouter from '@ember/routing/router'; - import EmberRoutingRoute from '@ember/routing/route'; - import EmberRoutingTransition from '@ember/routing/-private/transition'; - import EmberRoutingRouterService from '@ember/routing/router-service'; - import EmberRoutingHashLocation from '@ember/routing/hash-location'; - import EmberRoutingAutoLocation from '@ember/routing/auto-location'; - import EmberRoutingHistoryLocation from '@ember/routing/history-location'; - import EmberRoutingNoneLocation from '@ember/routing/none-location'; - import EmberRoutingLinkComponent from '@ember/routing/link-component'; - // @ember/application - import EmberDefaultResolver from '@ember/application/-private/default-resolver'; - import EmberEventDispatcher from '@ember/application/-private/event-dispatcher'; - import EmberRegistry from '@ember/application/-private/registry'; - import EmberResolver from '@ember/application/resolver'; - // @ember/test - import EmberTestAdapter from '@ember/test/adapter'; +type EmberArray = EmberArrayNs.default; +import EmberActionHandler from '@ember/object/-private/action-handler'; +import EmberComponent from '@ember/component'; +import EmberTextArea from '@ember/component/text-area'; +import EmberTextField from '@ember/component/text-field'; +import EmberCheckbox from '@ember/component/checkbox'; +import EmberHelper from '@ember/component/helper'; +// @ember/routing +import EmberRoutingRouter from '@ember/routing/router'; +import EmberRoutingRoute from '@ember/routing/route'; +import EmberRoutingTransition from '@ember/routing/-private/transition'; +import EmberRoutingRouterService from '@ember/routing/router-service'; +import EmberRoutingHashLocation from '@ember/routing/hash-location'; +import EmberRoutingAutoLocation from '@ember/routing/auto-location'; +import EmberRoutingHistoryLocation from '@ember/routing/history-location'; +import EmberRoutingNoneLocation from '@ember/routing/none-location'; +import EmberRoutingLinkComponent from '@ember/routing/link-component'; +// @ember/application +import EmberDefaultResolver from '@ember/application/-private/default-resolver'; +import EmberEventDispatcher from '@ember/application/-private/event-dispatcher'; +import EmberRegistry from '@ember/application/-private/registry'; +import EmberResolver from '@ember/application/resolver'; +// @ember/test +import EmberTestAdapter from '@ember/test/adapter'; - type Mix = B & Pick>; - type Mix3 = Mix, C>; - type Mix4 = Mix3, C, D>; - type Mix5 = Mix4, C, D, E>; +type Mix = B & Pick>; +type Mix3 = Mix, C>; +type Mix4 = Mix3, C, D>; +type Mix5 = Mix4, C, D, E>; + +/** + * Ember.Object.extend(...) accepts any number of mixins or literals. + */ +type MixinOrLiteral = EmberMixin | T; + +/** + * Ember.CoreView is an abstract class that exists to give view-like behavior to both Ember's main + * view class Ember.Component and other classes that don't need the full functionality of Ember.Component. + * Unless you have specific needs for CoreView, you will use Ember.Component in your applications. + */ +export class CoreView extends Ember.Object.extend(Ember.Evented, Ember.ActionHandler) {} + +export namespace Ember { + const A: typeof EmberArrayNs.A; + const isArray: typeof EmberArrayNs.isArray; + type Enumerable = EmberEnumerable; + const Enumerable: typeof EmberEnumerable; + class ArrayProxy extends EmberArrayProxy {} + type Array = EmberArray; + const Array: typeof EmberArrayNs.default; + type MutableArray = EmberMutableArray; + const MutableArray: typeof EmberMutableArray; + type NativeArray = EmberNativeArray; + const NativeArray: typeof EmberNativeArray; + type MutableEnumerable = EmberMutableEnumerable; + const MutableEnumerable: typeof EmberMutableEnumerable; + class Router extends EmberRoutingRouter {} + class Route extends EmberRoutingRoute {} + const ActionHandler: typeof EmberActionHandler; + class Controller extends EmberControllerNs.default {} + class Component extends EmberComponent {} + class TextArea extends EmberTextArea {} + class TextField extends EmberTextField {} + class Checkbox extends EmberCheckbox {} + class Helper extends EmberHelper {} + + class HashLocation extends EmberRoutingHashLocation {} + class NoneLocation extends EmberRoutingNoneLocation {} + class HistoryLocation extends EmberRoutingHistoryLocation {} + class LinkComponent extends EmberRoutingLinkComponent {} + const deprecateFunc: typeof EmberApplicationDeprecateNs.deprecateFunc; + const deprecate: typeof EmberApplicationDeprecateNs.deprecate; + const getOwner: typeof EmberApplicationNs.getOwner; + const setOwner: typeof EmberApplicationNs.setOwner; + class DefaultResolver extends EmberDefaultResolver {} + class Resolver extends EmberResolver {} + class EventDispatcher extends EmberEventDispatcher {} + class Registry extends EmberRegistry {} + interface FunctionPrototypeExtensions { + /** + * The `property` extension of Javascript's Function prototype is available + * when `EmberENV.EXTEND_PROTOTYPES` or `EmberENV.EXTEND_PROTOTYPES.Function` is + * `true`, which is the default. + */ + property(...args: string[]): ComputedProperty; + /** + * The `observes` extension of Javascript's Function prototype is available + * when `EmberENV.EXTEND_PROTOTYPES` or `EmberENV.EXTEND_PROTOTYPES.Function` is + * true, which is the default. + */ + observes(...args: string[]): this; + /** + * The `on` extension of Javascript's Function prototype is available + * when `EmberENV.EXTEND_PROTOTYPES` or `EmberENV.EXTEND_PROTOTYPES.Function` is + * true, which is the default. + */ + on(...args: string[]): this; + } + + interface ArrayPrototypeExtensions extends EmberArrayProtoExtensions {} + + interface StringPrototypeExtensions { + camelize(): string; + decamelize(): string; + classify(): string; + capitalize(): string; + loc(values?: string[]): string; + dasherize(): string; + underscore(): string; + w(): string[]; + } /** - * Ember.Object.extend(...) accepts any number of mixins or literals. + * Implements some standard methods for comparing objects. Add this mixin to + * any class you create that can compare its instances. */ - type MixinOrLiteral = EmberMixin | T; + interface Comparable { + compare(a: any, b: any): number; + } + const Comparable: EmberMixin; + class ComputedProperty extends EmberObjectComputedNs.default {} + /** + * A container used to instantiate and cache objects. + */ + class Container { + /** + * Given a fullName, return the corresponding factory. The consumer of the factory + * is responsible for the destruction of any factory instances, as there is no + * way for the container to ensure instances are destroyed when it itself is + * destroyed. + */ + factoryFor(fullName: string, options?: {}): any; + } + class ContainerDebugAdapter extends _ContainerDebugAdapter {} + + // TODO: replace with a proper ES6 reexport once we remove declare module 'ember' {} + class Object extends EmberObjectNs.default {} + class ObjectProxy extends EmberObjectProxyNs.default {} + const Observable: typeof EmberObservable; + const PromiseProxyMixin: typeof EmberObjectPromiseProxyNs.default; + class CoreObject extends EmberCoreObject {} + class DataAdapter extends EmberDataAdapter {} + const Debug: { + registerDeprecationHandler: typeof EmberDebugNs.registerDeprecationHandler; + registerWarnHandler: typeof EmberDebugNs.registerWarnHandler; + }; + class EngineInstance extends EmberEngineInstanceNs.default {} + class Engine extends EmberEngineNs.default {} /** - * Ember.CoreView is an abstract class that exists to give view-like behavior to both Ember's main - * view class Ember.Component and other classes that don't need the full functionality of Ember.Component. - * Unless you have specific needs for CoreView, you will use Ember.Component in your applications. + * A subclass of the JavaScript Error object for use in Ember. */ - class CoreView extends Ember.Object.extend(Ember.Evented, Ember.ActionHandler) {} + const Error: EmberError; - export namespace Ember { - const A: typeof EmberArrayNs.A; - const isArray: typeof EmberArrayNs.isArray; - export type Enumerable = EmberEnumerable; - export const Enumerable: typeof EmberEnumerable; - class ArrayProxy extends EmberArrayProxy {} - export type Array = EmberArray; - export const Array: typeof EmberArrayNs.default; - export type MutableArray = EmberMutableArray; - export const MutableArray: typeof EmberMutableArray; - export type NativeArray = EmberNativeArray; - export const NativeArray: typeof EmberNativeArray; - export type MutableEnumerable = EmberMutableEnumerable; - export const MutableEnumerable: typeof EmberMutableEnumerable; - class Router extends EmberRoutingRouter {} - class Route extends EmberRoutingRoute {} - const ActionHandler: typeof EmberActionHandler; - class Controller extends EmberControllerNs.default {} - export class Component extends EmberComponent {} - export class TextArea extends EmberTextArea {} - export class TextField extends EmberTextField {} - export class Checkbox extends EmberCheckbox {} - export class Helper extends EmberHelper {} + const Evented: typeof EmberObjectEventedNs.default; - export class HashLocation extends EmberRoutingHashLocation {} - export class NoneLocation extends EmberRoutingNoneLocation {} - export class HistoryLocation extends EmberRoutingHistoryLocation {} - export class LinkComponent extends EmberRoutingLinkComponent {} - const deprecateFunc: typeof EmberApplicationDeprecateNs.deprecateFunc; - const deprecate: typeof EmberApplicationDeprecateNs.deprecate; - const getOwner: typeof EmberApplicationNs.getOwner; - const setOwner: typeof EmberApplicationNs.setOwner; - class DefaultResolver extends EmberDefaultResolver {} - class Resolver extends EmberResolver {} - class EventDispatcher extends EmberEventDispatcher {} - class Registry extends EmberRegistry {} - interface FunctionPrototypeExtensions { - /** - * The `property` extension of Javascript's Function prototype is available - * when `EmberENV.EXTEND_PROTOTYPES` or `EmberENV.EXTEND_PROTOTYPES.Function` is - * `true`, which is the default. - */ - property(...args: string[]): ComputedProperty; - /** - * The `observes` extension of Javascript's Function prototype is available - * when `EmberENV.EXTEND_PROTOTYPES` or `EmberENV.EXTEND_PROTOTYPES.Function` is - * true, which is the default. - */ - observes(...args: string[]): this; - /** - * The `on` extension of Javascript's Function prototype is available - * when `EmberENV.EXTEND_PROTOTYPES` or `EmberENV.EXTEND_PROTOTYPES.Function` is - * true, which is the default. - */ - on(...args: string[]): this; - } + /** + * Inside Ember-Metal, simply uses the methods from `imports.console`. + * Override this to provide more robust logging functionality. + */ + const Logger: { + /** + * If the value passed into `Ember.Logger.assert` is not truthy it will throw an error with a stack trace. + */ + assert(test: boolean, message?: string): void; + /** + * Logs the arguments to the console in blue text. + */ + debug(...args: any[]): void; + /** + * Prints the arguments to the console with an error icon, red text and a stack trace. + */ + error(...args: any[]): void; + /** + * Logs the arguments to the console. + */ + info(...args: any[]): void; + /** + * Logs the arguments to the console. + */ + log(...args: any[]): void; + /** + * Prints the arguments to the console with a warning icon. + */ + warn(...args: any[]): void; + }; + /** + * A Map stores values indexed by keys. Unlike JavaScript's + * default Objects, the keys of a Map can be any JavaScript + * object. + * @deprecated + */ + class Map { + copy(): Map; + static create(): Map; + forEach(callback: (...args: any[]) => any, self: any): void; + get(key: any): any; + has(key: any): boolean; + set(key: any, value: any): void; + length: number; + } + /** + * @deprecated + */ + class MapWithDefault extends Map { + copy(): MapWithDefault; + static create(): MapWithDefault; + } + class Mixin extends EmberMixin {} - interface ArrayPrototypeExtensions extends EmberArrayProtoExtensions {} + /** + * A Namespace is an object usually used to contain other objects or methods + * such as an application or framework. Create a namespace anytime you want + * to define one of these new containers. + */ + class Namespace extends Object {} - interface StringPrototypeExtensions { - camelize(): string; - decamelize(): string; - classify(): string; - capitalize(): string; - loc(values?: string[]): string; - dasherize(): string; - underscore(): string; - w(): string[]; - } + /** + * This class is used internally by Ember and Ember Data. + * Please do not use it at this time. We plan to clean it up + * and add many tests soon. + * @deprecated + */ + class OrderedSet { + add(obj: any): void; + clear(): void; + copy(): OrderedSet; + static create(): OrderedSet; + forEach(fn: (...args: any[]) => any, self: any): void; + has(obj: any): boolean; + isEmpty(): boolean; + toArray(): any[]; + } + + class Service extends Object {} + + interface ViewTargetActionSupport { + target: any; + actionContext: any; + } + const ViewTargetActionSupport: Mixin; + const ViewUtils: { + isSimpleClick(event: Event): boolean; + }; + + // FYI - RSVP source comes from https://github.com/tildeio/rsvp.js/blob/master/lib/rsvp/promise.js + const RSVP: typeof Rsvp; + namespace RSVP { + type Promise = Rsvp.Promise; + } + class Application extends EmberApplicationNs.default {} + class ApplicationInstance extends EmberApplicationInstanceNs.default {} + /** + * This is a container for an assortment of testing related functionality + */ + namespace Test { + class Adapter extends EmberTestAdapter {} + const registerHelper: typeof EmberTestNs.registerHelper; + const unregisterHelper: typeof EmberTestNs.unregisterHelper; + const registerWaiter: typeof EmberTestNs.registerWaiter; + const unregisterWaiter: typeof EmberTestNs.unregisterWaiter; + const registerAsyncHelper: typeof EmberTestNs.registerAsyncHelper; + /** + * Used to register callbacks to be fired whenever `App.injectTestHelpers` + * is called. + */ + function onInjectHelpers(callback: (app: Application) => void): void; + /** + * This returns a thenable tailored for testing. It catches failed + * `onSuccess` callbacks and invokes the `Ember.Test.adapter.exception` + * callback in the last chained then. + */ + function promise( + resolver: ( + resolve: (value?: T | PromiseLike) => void, + reject: (reason?: any) => void + ) => void, + label?: string + ): Promise; + /** + * Replacement for `Ember.RSVP.resolve` + * The only difference is this uses + * an instance of `Ember.Test.Promise` + */ + function resolve(value?: T | PromiseLike, label?: string): Promise; /** - * Connects the properties of two objects so that whenever the value of one property changes, - * the other property will be changed also. - * - * @deprecated https://emberjs.com/deprecations/v2.x#toc_ember-binding + * Iterates through each registered test waiter, and invokes + * its callback. If any waiter returns false, this method will return + * true indicating that the waiters have not settled yet. */ - class Binding { - constructor(toPath: string, fromPath: string); - connect(obj: any): Binding; - copy(): Binding; - disconnect(): Binding; - from(path: string): Binding; - to(path: string | string[]): Binding; - toString(): string; - } + function checkWaiters(): boolean; /** - * Implements some standard methods for comparing objects. Add this mixin to - * any class you create that can compare its instances. + * Used to allow ember-testing to communicate with a specific testing + * framework. */ - interface Comparable { - compare(a: any, b: any): number; - } - const Comparable: EmberMixin; - export class ComputedProperty extends EmberObjectComputedNs.default {} - /** - * A container used to instantiate and cache objects. - */ - class Container { - /** - * Given a fullName, return the corresponding factory. The consumer of the factory - * is responsible for the destruction of any factory instances, as there is no - * way for the container to ensure instances are destroyed when it itself is - * destroyed. - */ - factoryFor(fullName: string, options?: {}): any; - } - class ContainerDebugAdapter extends _ContainerDebugAdapter {} - - // TODO: replace with a proper ES6 reexport once we remove declare module 'ember' {} - class Object extends EmberObjectNs.default {} - class ObjectProxy extends EmberObjectProxyNs.default {} - const Observable: typeof EmberObservable; - const PromiseProxyMixin: typeof EmberObjectPromiseProxyNs.default; - class CoreObject extends EmberCoreObject {} - class DataAdapter extends EmberDataAdapter {} - const Debug: { - registerDeprecationHandler: typeof EmberDebugNs.registerDeprecationHandler; - registerWarnHandler: typeof EmberDebugNs.registerWarnHandler; - }; - class EngineInstance extends EmberEngineInstanceNs.default {} - class Engine extends EmberEngineNs.default {} + const adapter: EmberTestAdapter; /** - * A subclass of the JavaScript Error object for use in Ember. + * This class implements the methods defined by Ember.Test.Adapter for the + * QUnit testing framework. */ - const Error: EmberError; - - const Evented: typeof EmberObjectEventedNs.default; - /** - * The `Ember.Freezable` mixin implements some basic methods for marking an - * object as frozen. Once an object is frozen it should be read only. No changes - * may be made the internal state of the object. - * @deprecated Use `Object.freeze` instead. - */ - interface Freezable { - freeze(): Freezable; - isFrozen: boolean; - } - const Freezable: EmberMixin; - /** - * The purpose of the Ember Instrumentation module is - * to provide efficient, general-purpose instrumentation - * for Ember. - */ - const Instrumentation: { - instrument(name: string, payload: any, callback: (...args: any[]) => any, binding: any): void; - reset(): void; - subscribe(pattern: string, object: any): void; - unsubscribe(subscriber: any): void; - }; - /** - * Inside Ember-Metal, simply uses the methods from `imports.console`. - * Override this to provide more robust logging functionality. - */ - const Logger: { - /** - * If the value passed into `Ember.Logger.assert` is not truthy it will throw an error with a stack trace. - */ - assert(test: boolean, message?: string): void; - /** - * Logs the arguments to the console in blue text. - */ - debug(...args: any[]): void; - /** - * Prints the arguments to the console with an error icon, red text and a stack trace. - */ - error(...args: any[]): void; - /** - * Logs the arguments to the console. - */ - info(...args: any[]): void; - /** - * Logs the arguments to the console. - */ - log(...args: any[]): void; - /** - * Prints the arguments to the console with a warning icon. - */ - warn(...args: any[]): void; - }; - /** - * A Map stores values indexed by keys. Unlike JavaScript's - * default Objects, the keys of a Map can be any JavaScript - * object. - * @deprecated - */ - class Map { - copy(): Map; - static create(): Map; - forEach(callback: (...args: any[]) => any, self: any): void; - get(key: any): any; - has(key: any): boolean; - set(key: any, value: any): void; - length: number; - } - /** - * @deprecated - */ - class MapWithDefault extends Map { - copy(): MapWithDefault; - static create(): MapWithDefault; - } - class Mixin extends EmberMixin {} - - /** - * A Namespace is an object usually used to contain other objects or methods - * such as an application or framework. Create a namespace anytime you want - * to define one of these new containers. - */ - class Namespace extends Object {} - - /** - * This class is used internally by Ember and Ember Data. - * Please do not use it at this time. We plan to clean it up - * and add many tests soon. - * @deprecated - */ - class OrderedSet { - add(obj: any): void; - clear(): void; - copy(): OrderedSet; - static create(): OrderedSet; - forEach(fn: (...args: any[]) => any, self: any): void; - has(obj: any): boolean; - isEmpty(): boolean; - toArray(): any[]; - } - - class Service extends Object {} - interface Transition { - /** - * Aborts the Transition. Note you can also implicitly abort a transition - * by initiating another transition while a previous one is underway. - */ - abort(): Transition; - /** - * Retries a previously-aborted transition (making sure to abort the - * transition if it's still active). Returns a new transition that - * represents the new attempt to transition. - */ - retry(): Transition; - } - interface ViewTargetActionSupport { - target: any; - actionContext: any; - } - const ViewTargetActionSupport: Mixin; - const ViewUtils: { - isSimpleClick(event: Event): boolean; - }; - - // FYI - RSVP source comes from https://github.com/tildeio/rsvp.js/blob/master/lib/rsvp/promise.js - const RSVP: typeof Rsvp; - namespace RSVP { - type Promise = Rsvp.Promise; - } - class Application extends EmberApplicationNs.default {} - class ApplicationInstance extends EmberApplicationInstanceNs.default {} - /** - * This is a container for an assortment of testing related functionality - */ - namespace Test { - class Adapter extends EmberTestAdapter {} - const registerHelper: typeof EmberTestNs.registerHelper; - const unregisterHelper: typeof EmberTestNs.unregisterHelper; - const registerWaiter: typeof EmberTestNs.registerWaiter; - const unregisterWaiter: typeof EmberTestNs.unregisterWaiter; - const registerAsyncHelper: typeof EmberTestNs.registerAsyncHelper; - /** - * Used to register callbacks to be fired whenever `App.injectTestHelpers` - * is called. - */ - function onInjectHelpers(callback: (app: Application) => void): void; - /** - * This returns a thenable tailored for testing. It catches failed - * `onSuccess` callbacks and invokes the `Ember.Test.adapter.exception` - * callback in the last chained then. - */ - function promise( - resolver: ( + class QUnitAdapter extends EmberTestAdapter {} + class Promise extends Rsvp.Promise { + constructor( + executor: ( resolve: (value?: T | PromiseLike) => void, reject: (reason?: any) => void - ) => void, - label?: string - ): Ember.Test.Promise; - /** - * Replacement for `Ember.RSVP.resolve` - * The only difference is this uses - * an instance of `Ember.Test.Promise` - */ - function resolve(value?: T | PromiseLike, label?: string): Ember.Test.Promise; - - /** - * Iterates through each registered test waiter, and invokes - * its callback. If any waiter returns false, this method will return - * true indicating that the waiters have not settled yet. - */ - function checkWaiters(): boolean; - /** - * Used to allow ember-testing to communicate with a specific testing - * framework. - */ - const adapter: EmberTestAdapter; - - /** - * This class implements the methods defined by Ember.Test.Adapter for the - * QUnit testing framework. - */ - class QUnitAdapter extends EmberTestAdapter {} - class Promise extends Rsvp.Promise { - constructor( - executor: ( - resolve: (value?: T | PromiseLike) => void, - reject: (reason?: any) => void - ) => void - ); - } + ) => void + ); } + } + /** + * Namespace for injection helper methods. + */ + namespace inject { /** - * Namespace for injection helper methods. + * Creates a property that lazily looks up another controller in the container. + * Can only be used when defining another controller. */ - namespace inject { - /** - * Creates a property that lazily looks up another controller in the container. - * Can only be used when defining another controller. - */ - function controller(): ComputedProperty; - function controller( - name: K - ): ComputedProperty; - const service: typeof EmberServiceNs.inject; - } - namespace ENV { - const EXTEND_PROTOTYPES: typeof Ember.EXTEND_PROTOTYPES; - const LOG_BINDINGS: boolean; - const LOG_STACKTRACE_ON_DEPRECATION: boolean; - const LOG_VERSION: boolean; - const MODEL_FACTORY_INJECTIONS: boolean; - const RAISE_ON_DEPRECATION: boolean; - } - namespace EXTEND_PROTOTYPES { - const Array: boolean; - const Function: boolean; - const String: boolean; - } - namespace Handlebars { - function compile(string: string): (...args: any[]) => any; - function compile(environment: any, options?: any, context?: any, asObject?: any): any; - function precompile(string: string, options: any): void; - class Compiler {} - class JavaScriptCompiler {} - function registerPartial(name: string, str: any): void; - function K(): any; - function createFrame(objec: any): any; - function Exception(message: string): void; - const SafeString: typeof HandlebarsNamespace.SafeString; - function parse(string: string): any; - function print(ast: any): void; - const logger: typeof Ember.Logger; - function log(level: string, str: string): void; - } - namespace String { - const camelize: typeof EmberStringNs.camelize; - const capitalize: typeof EmberStringNs.capitalize; - const classify: typeof EmberStringNs.classify; - const dasherize: typeof EmberStringNs.dasherize; - const decamelize: typeof EmberStringNs.decamelize; - function fmt(...args: string[]): string; - const htmlSafe: typeof EmberStringNs.htmlSafe; - const isHTMLSafe: typeof EmberStringNs.isHTMLSafe; - const loc: typeof EmberStringNs.loc; - const underscore: typeof EmberStringNs.underscore; - const w: typeof EmberStringNs.w; - } - const computed: typeof EmberObjectNs.computed; - const run: typeof EmberRunloopNs.run; - const platform: { - defineProperty: boolean; - hasPropertyAccessors: boolean; + function controller(): ComputedProperty; + function controller( + name: K + ): ComputedProperty; + const service: typeof EmberServiceNs.inject; + } + namespace ENV { + const EXTEND_PROTOTYPES: { + Array: boolean; + Function: boolean; + String: boolean; }; - - /** - * `getEngineParent` retrieves an engine instance's parent instance. - */ - function getEngineParent(engine: EngineInstance): EngineInstance; - - const assert: typeof EmberDebugNs.assert; - const debug: typeof EmberDebugNs.debug; - const defineProperty: typeof EmberObjectNs.defineProperty; - - export const runInDebug: typeof EmberDebugNs.runInDebug; - export const warn: typeof EmberDebugNs.warn; - /** - * Global helper method to create a new binding. Just pass the root object - * along with a `to` and `from` path to create and connect the binding. - * @deprecated https://emberjs.com/deprecations/v2.x#toc_ember-binding - */ - function bind(obj: {}, to: string, from: string): Binding; - const cacheFor: typeof EmberObjectInternalsNs.cacheFor; - export const addListener: typeof EmberObjectEventsNs.addListener; - export const removeListener: typeof EmberObjectEventsNs.removeListener; - export const sendEvent: typeof EmberObjectEventsNs.sendEvent; - export const on: typeof EmberObjectEventedNs.on; - - const isBlank: typeof EmberUtilsNs.isBlank; - const isEmpty: typeof EmberUtilsNs.isEmpty; - const isNone: typeof EmberUtilsNs.isNone; - const isPresent: typeof EmberUtilsNs.isPresent; - const merge: typeof EmberPolyfillsNs.merge; - - const aliasMethod: typeof EmberObjectNs.aliasMethod; - const observer: typeof EmberObjectNs.observer; - const addObserver: typeof EmberObjectObserversNs.addObserver; - const removeObserver: typeof EmberObjectObserversNs.removeObserver; - const get: typeof EmberObjectNs.get; - const getWithDefault: typeof EmberObjectNs.getWithDefault; - const getProperties: typeof EmberObjectNs.getProperties; - const setProperties: typeof EmberObjectNs.setProperties; - const set: typeof EmberObjectNs.set; - const trySet: typeof EmberObjectNs.trySet; - const compare: typeof EmberUtilsNs.compare; - /** - * Creates a shallow copy of the passed object. A deep copy of the object is - * returned if the optional `deep` argument is `true`. - */ - const copy: typeof EmberObjectInternalsNs.copy; - const isEqual: typeof EmberUtilsNs.isEqual; - const typeOf: typeof EmberUtilsNs.typeOf; - // TODO: replace with an es6 reexport when declare module 'ember' is removed - /** - * Copy properties from a source object to a target object. - * @deprecated Use Object.assign - */ - const assign: typeof EmberPolyfillsNs.assign; - /** - * Polyfill for Object.create - * @deprecated Use Object.create - */ - function create(o: object | null): any; - /** - * Polyfill for Object.keys - * @deprecated Use Object.keys - */ - function keys(o: any): string[]; - const guidFor: typeof EmberObjectInternalsNs.guidFor; - const inspect: typeof EmberDebugNs.inspect; - const tryInvoke: typeof EmberUtilsNs.tryInvoke; - - /** - * A function may be assigned to `Ember.onerror` to be called when Ember - * internals encounter an error. This is useful for specialized error handling - * and reporting code. - */ - function onerror(error: Error): void; - /** - * An empty function useful for some operations. Always returns `this`. - * @deprecated https://emberjs.com/deprecations/v2.x/#toc_code-ember-k-code - */ - function K(this: This): This; - /** - * The semantic version - */ - const VERSION: string; - /** - * Alias for jQuery - */ - const $: JQueryStatic; - /** - * This property indicates whether or not this application is currently in - * testing mode. This is set when `setupForTesting` is called on the current - * application. - */ - const testing: boolean; - - const instrument: typeof Instrumentation.instrument; - - const reset: typeof Instrumentation.reset; - - const subscribe: typeof Instrumentation.subscribe; - - const unsubscribe: typeof Instrumentation.unsubscribe; - const expandProperties: typeof EmberObjectComputedNs.expandProperties; + const LOG_BINDINGS: boolean; + const LOG_STACKTRACE_ON_DEPRECATION: boolean; + const LOG_VERSION: boolean; + const MODEL_FACTORY_INJECTIONS: boolean; + const RAISE_ON_DEPRECATION: boolean; } - - module '@ember/service' { - interface Registry { - 'router': EmberRoutingRouterService; - } + namespace Handlebars { + function compile(string: string): (...args: any[]) => any; + function compile(environment: any, options?: any, context?: any, asObject?: any): any; + function precompile(string: string, options: any): void; + class Compiler {} + class JavaScriptCompiler {} + function registerPartial(name: string, str: any): void; + function K(): any; + function createFrame(objec: any): any; + function Exception(message: string): void; + const SafeString: typeof HandlebarsNamespace.SafeString; + function parse(string: string): any; + function print(ast: any): void; + const logger: typeof Logger; + function log(level: string, str: string): void; } + namespace String { + const camelize: typeof EmberStringNs.camelize; + const capitalize: typeof EmberStringNs.capitalize; + const classify: typeof EmberStringNs.classify; + const dasherize: typeof EmberStringNs.dasherize; + const decamelize: typeof EmberStringNs.decamelize; + function fmt(...args: string[]): string; + const htmlSafe: typeof EmberStringNs.htmlSafe; + const isHTMLSafe: typeof EmberStringNs.isHTMLSafe; + const loc: typeof EmberStringNs.loc; + const underscore: typeof EmberStringNs.underscore; + const w: typeof EmberStringNs.w; + } + const computed: typeof EmberObjectNs.computed; + const run: typeof EmberRunloopNs.run; + const platform: { + defineProperty: boolean; + hasPropertyAccessors: boolean; + }; - export default Ember; + /** + * `getEngineParent` retrieves an engine instance's parent instance. + */ + function getEngineParent(engine: EngineInstance): EngineInstance; + + const assert: typeof EmberDebugNs.assert; + const debug: typeof EmberDebugNs.debug; + const defineProperty: typeof EmberObjectNs.defineProperty; + + const runInDebug: typeof EmberDebugNs.runInDebug; + const warn: typeof EmberDebugNs.warn; + const cacheFor: typeof EmberObjectInternalsNs.cacheFor; + const addListener: typeof EmberObjectEventsNs.addListener; + const removeListener: typeof EmberObjectEventsNs.removeListener; + const sendEvent: typeof EmberObjectEventsNs.sendEvent; + const on: typeof EmberObjectEventedNs.on; + + const isBlank: typeof EmberUtilsNs.isBlank; + const isEmpty: typeof EmberUtilsNs.isEmpty; + const isNone: typeof EmberUtilsNs.isNone; + const isPresent: typeof EmberUtilsNs.isPresent; + const merge: typeof EmberPolyfillsNs.merge; + + const aliasMethod: typeof EmberObjectNs.aliasMethod; + const observer: typeof EmberObjectNs.observer; + const addObserver: typeof EmberObjectObserversNs.addObserver; + const removeObserver: typeof EmberObjectObserversNs.removeObserver; + const get: typeof EmberObjectNs.get; + const getWithDefault: typeof EmberObjectNs.getWithDefault; + const getProperties: typeof EmberObjectNs.getProperties; + const setProperties: typeof EmberObjectNs.setProperties; + const set: typeof EmberObjectNs.set; + const trySet: typeof EmberObjectNs.trySet; + const compare: typeof EmberUtilsNs.compare; + /** + * Creates a shallow copy of the passed object. A deep copy of the object is + * returned if the optional `deep` argument is `true`. + */ + const copy: typeof EmberObjectInternalsNs.copy; + const isEqual: typeof EmberUtilsNs.isEqual; + const typeOf: typeof EmberUtilsNs.typeOf; + // TODO: replace with an es6 reexport when declare module 'ember' is removed + /** + * Copy properties from a source object to a target object. + * @deprecated Use Object.assign + */ + const assign: typeof EmberPolyfillsNs.assign; + /** + * Polyfill for Object.keys + * @deprecated Use Object.keys + */ + function keys(o: any): string[]; + const guidFor: typeof EmberObjectInternalsNs.guidFor; + const inspect: typeof EmberDebugNs.inspect; + const tryInvoke: typeof EmberUtilsNs.tryInvoke; + + /** + * A function may be assigned to `Ember.onerror` to be called when Ember + * internals encounter an error. This is useful for specialized error handling + * and reporting code. + */ + function onerror(error: Error): void; + /** + * The semantic version + */ + const VERSION: string; + /** + * Alias for jQuery + */ + const $: JQueryStatic; + /** + * This property indicates whether or not this application is currently in + * testing mode. This is set when `setupForTesting` is called on the current + * application. + */ + const testing: boolean; + + const expandProperties: typeof EmberObjectComputedNs.expandProperties; } +export default Ember; + declare module 'htmlbars-inline-precompile' { interface TemplateFactory { __htmlbars_inline_precompile_template_factory: any; } + // tslint:disable-next-line:strict-export-declare-modifiers export default function hbs(tagged: TemplateStringsArray): TemplateFactory; } diff --git a/types/ember/test/ember-module-tests.ts b/types/ember/test/ember-module-tests.ts index ed90fe42ef..5935578d3e 100644 --- a/types/ember/test/ember-module-tests.ts +++ b/types/ember/test/ember-module-tests.ts @@ -275,3 +275,22 @@ Ember.String.isHTMLSafe('foo'); // $ExpectType boolean // Ember.Test Ember.Test.checkWaiters(); // $ExpectType boolean // checkWaiters + +/** + * == REMOVED FEATURES == + * These are deprecated and/or private things that have been removed from the + * Ember.* namespace. These tests asserts that the types of these things + * stay gone + */ + + Ember.bind; // $ExpectError + Ember.deprecate('foo', 'bar'); // $ExpectError + Ember.K; // $ExpectError + Ember.Binding; // $ExpectError + Ember.Transition; // $ExpectError + Ember.create; // $ExpectError + Ember.reset; // $ExpectError + Ember.unsubscribe; // $ExpectError + Ember.subscribe; // $ExpectError + Ember.instrument; // $ExpectError + Ember.Instrumentation; // $ExpectError diff --git a/types/ember/test/route.ts b/types/ember/test/route.ts index 2256ee3561..f1ca853267 100755 --- a/types/ember/test/route.ts +++ b/types/ember/test/route.ts @@ -2,6 +2,10 @@ import Route from '@ember/routing/route'; import Object from '@ember/object'; import Array from '@ember/array'; import Ember from 'ember'; // currently needed for Transition +import Transition from '@ember/routing/-private/transition'; + +// Ensure that Ember.Transition is private +Ember.Transition; // $ExpectError interface Post extends Ember.Object { title: string; @@ -10,13 +14,13 @@ interface Post extends Ember.Object { interface Posts extends Array {} Route.extend({ - beforeModel(transition: Ember.Transition) { + beforeModel(transition: Transition) { this.transitionTo('someOtherRoute'); }, }); Route.extend({ - afterModel(posts: Posts, transition: Ember.Transition) { + afterModel(posts: Posts, transition: Transition) { if (posts.length === 1) { this.transitionTo('post.show', posts.firstObject); } diff --git a/types/ember/test/transition.ts b/types/ember/test/transition.ts index 47d171e250..f06ee8865e 100755 --- a/types/ember/test/transition.ts +++ b/types/ember/test/transition.ts @@ -1,7 +1,8 @@ import Ember from 'ember'; +import Transition from '@ember/routing/-private/transition'; Ember.Route.extend({ - beforeModel(transition: Ember.Transition) { + beforeModel(transition: Transition) { if (new Date() > new Date('January 1, 1980')) { alert('Sorry, you need a time machine to enter this route.'); transition.abort(); @@ -10,7 +11,7 @@ Ember.Route.extend({ }); Ember.Controller.extend({ - previousTransition: null, + previousTransition: null, actions: { login() { diff --git a/types/ember/tslint.json b/types/ember/tslint.json index fa8da19714..1e507e3b47 100755 --- a/types/ember/tslint.json +++ b/types/ember/tslint.json @@ -1,13 +1,6 @@ { "extends": "dtslint/dt.json", "rules": { - // these are disabled because of rfc176 module exports - "strict-export-declare-modifiers": false, - "no-declare-current-package": false, - "no-self-import": false, - - "no-unnecessary-qualifier": false, - // false positives "unified-signatures": false } diff --git a/types/ember__application/deprecations.d.ts b/types/ember__application/deprecations.d.ts index a74babd084..8509e2f69d 100644 --- a/types/ember__application/deprecations.d.ts +++ b/types/ember__application/deprecations.d.ts @@ -8,23 +8,6 @@ export function deprecate( options: { id: string; until: string } ): any; -/** - * @deprecated Missing deprecation options: https://emberjs.com/deprecations/v2.x/#toc_ember-debug-function-options - */ -export function deprecate( - message: string, - test: boolean, - options?: { id?: string; until?: string } -): any; - -/** - * @deprecated Missing deprecation options: https://emberjs.com/deprecations/v2.x/#toc_ember-debug-function-options - */ -export function deprecateFunc any)>( - message: string, - func: Func -): Func; - /** * Alias an old, deprecated method with its new counterpart. */ diff --git a/types/ember__application/index.d.ts b/types/ember__application/index.d.ts index aa1a5a1889..b51fc3d0da 100644 --- a/types/ember__application/index.d.ts +++ b/types/ember__application/index.d.ts @@ -50,7 +50,7 @@ export default class Application extends Engine { * @param fullName type:name (e.g., 'model:user') * @param factory (e.g., App.Person) */ - register(fullName: string, factory: any): void; + register(fullName: string, factory: any, options?: { singleton?: boolean; instantiate?: boolean }): void; /** * This removes all helpers that have been registered, and resets and functions * that were overridden by the helpers. diff --git a/types/ember__application/test/application-instance.ts b/types/ember__application/test/application-instance.ts index 4ee5cb2027..11dfb586ab 100644 --- a/types/ember__application/test/application-instance.ts +++ b/types/ember__application/test/application-instance.ts @@ -13,6 +13,21 @@ appInstance.register('some:injection', class Foo {}, { }); appInstance.register('templates:foo/bar', hbs`

Hello World

`); +appInstance.register('templates:foo/bar', hbs`

Hello World

`, { + singleton: true +}); +appInstance.register('templates:foo/bar', hbs`

Hello World

`, { + instantiate: true +}); +appInstance.register('templates:foo/bar', hbs`

Hello World

`, { + singleton: true, + instantiate: true +}); +// $ExpectError +appInstance.register('templates:foo/bar', hbs`

Hello World

`, { + singleton: 'true', + instantiate: true +}); appInstance.register('some:injection', class Foo {}, { singleton: false, diff --git a/types/ember__application/test/deprecations.ts b/types/ember__application/test/deprecations.ts index 12639ad0b5..30d1e8a075 100644 --- a/types/ember__application/test/deprecations.ts +++ b/types/ember__application/test/deprecations.ts @@ -4,9 +4,9 @@ deprecate('this is no longer advised', false, { id: 'no-longer-advised', until: 'v4.0' }); -deprecate('this is no longer advised', false); +deprecate('this is no longer advised', false); // $ExpectError -deprecateFunc('this is no longer advised', () => {}); +deprecateFunc('this is no longer advised', () => {}); // $ExpectError deprecateFunc( 'this is no longer advised', { id: 'no-longer-do-this', until: 'v4.0' }, diff --git a/types/ember__routing/index.d.ts b/types/ember__routing/index.d.ts index 38488fa6b8..8f5085c402 100644 --- a/types/ember__routing/index.d.ts +++ b/types/ember__routing/index.d.ts @@ -7,7 +7,8 @@ export { default as Route } from '@ember/routing/route'; export { default as Router } from '@ember/routing/router'; import RouterService from '@ember/routing/router-service'; - +import '@ember/routing/-private/router-dsl'; +import '@ember/routing/-private/transition'; // tslint:disable-next-line:strict-export-declare-modifiers interface Registry { 'router': RouterService; diff --git a/types/ember__routing/tsconfig.json b/types/ember__routing/tsconfig.json index a3f936580a..c5bd434549 100644 --- a/types/ember__routing/tsconfig.json +++ b/types/ember__routing/tsconfig.json @@ -20,7 +20,6 @@ "@ember/object/*": ["ember__object/*"], "@ember/array": ["ember__array"], "@ember/array/*": ["ember__array/*"], - "@ember/service": ["ember__service"], "@ember/service/*": ["ember__service/*"], "@ember/component": ["ember__component"], "@ember/component/*": ["ember__component/*"], diff --git a/types/expo/expo-tests.tsx b/types/expo/expo-tests.tsx index 1858faa549..2e9aa07198 100644 --- a/types/expo/expo-tests.tsx +++ b/types/expo/expo-tests.tsx @@ -834,7 +834,7 @@ async () => { console.log(updateCheckResult.manifest); } - Updates.fetchUpdateAsync(updateEventListener); + Updates.fetchUpdateAsync({ eventListener: updateEventListener }); const bundleFetchResult = await Updates.fetchUpdateAsync(); diff --git a/types/expo/index.d.ts b/types/expo/index.d.ts index 36afc712ab..4633a83dd7 100644 --- a/types/expo/index.d.ts +++ b/types/expo/index.d.ts @@ -2915,6 +2915,11 @@ export namespace Updates { message?: string; } + /** An optional params object passed to fetchUpdateAsync. */ + interface FetchUpdateAsyncParams { + eventListener: UpdateEventListener; + } + type UpdateEventListener = (event: UpdateEvent) => any; /** @@ -2934,7 +2939,7 @@ export namespace Updates { * Downloads the most recent published version of your experience to the device's local cache. * Rejects if `updates.enabled` is `false` in app.json. */ - function fetchUpdateAsync(listener?: UpdateEventListener): Promise; + function fetchUpdateAsync(params?: FetchUpdateAsyncParams): Promise; /** * Immediately reloads the current experience. diff --git a/types/fastify-cors/fastify-cors-tests.ts b/types/fastify-cors/fastify-cors-tests.ts new file mode 100644 index 0000000000..5fcd7e20d4 --- /dev/null +++ b/types/fastify-cors/fastify-cors-tests.ts @@ -0,0 +1,89 @@ +import fastifyCors = require("fastify-cors"); + +fastifyCors(); + +const fastifyCorsOptions: fastifyCors.FastifyCorsOptions = { + origin: true, + allowedHeaders: "authorization,content-type", + methods: "GET,POST,PUT,PATCH,DELETE,OPTIONS", + credentials: true, + exposedHeaders: "authorization", + maxAge: 13000, + preflightContinue: false, + optionsSuccessStatus: 200, + preflight: false, +}; + +const fastifyCorsOptionsArray: fastifyCors.FastifyCorsOptions = { + origin: true, + allowedHeaders: ["authorization", "content-type"], + methods: ["GET", "POST", "PUT", "PATCH", "DELETE", "OPTIONS"], + credentials: true, + exposedHeaders: ["authorization"], + maxAge: 13000, + preflightContinue: false, + optionsSuccessStatus: 200, + preflight: false, +}; + +const originString: fastifyCors.FastifyCorsOptions = { + origin: "*", + allowedHeaders: ["authorization", "content-type"], + methods: ["GET", "POST", "PUT", "PATCH", "DELETE", "OPTIONS"], + credentials: true, + exposedHeaders: ["authorization"], + maxAge: 13000, + preflightContinue: false, + optionsSuccessStatus: 200, + preflight: false, +}; + +const originRegexp: fastifyCors.FastifyCorsOptions = { + origin: /\*/, + allowedHeaders: ["authorization", "content-type"], + methods: ["GET", "POST", "PUT", "PATCH", "DELETE", "OPTIONS"], + credentials: true, + exposedHeaders: ["authorization"], + maxAge: 13000, + preflightContinue: false, + optionsSuccessStatus: 200, + preflight: false, +}; + +const originStringArray: fastifyCors.FastifyCorsOptions = { + origin: ["*", "something"], + allowedHeaders: ["authorization", "content-type"], + methods: ["GET", "POST", "PUT", "PATCH", "DELETE", "OPTIONS"], + credentials: true, + exposedHeaders: ["authorization"], + maxAge: 13000, + preflightContinue: false, + optionsSuccessStatus: 200, + preflight: false, +}; + +const originRegexpArray: fastifyCors.FastifyCorsOptions = { + origin: [/\*/, /something/], + allowedHeaders: ["authorization", "content-type"], + methods: ["GET", "POST", "PUT", "PATCH", "DELETE", "OPTIONS"], + credentials: true, + exposedHeaders: ["authorization"], + maxAge: 13000, + preflightContinue: false, + optionsSuccessStatus: 200, + preflight: false, +}; + +const originCallback: fastifyCors.FastifyCorsOptions = { + origin: (err: Error, allow: boolean) => { + throw err; + }, + allowedHeaders: ["authorization", "content-type"], + methods: ["GET", "POST", "PUT", "PATCH", "DELETE", "OPTIONS"], + credentials: true, + exposedHeaders: ["authorization"], + maxAge: 13000, + preflightContinue: false, + optionsSuccessStatus: 200, + preflight: false, +}; diff --git a/types/fastify-cors/index.d.ts b/types/fastify-cors/index.d.ts new file mode 100644 index 0000000000..907689a72c --- /dev/null +++ b/types/fastify-cors/index.d.ts @@ -0,0 +1,68 @@ +// Type definitions for fastify-cors 0.1 +// Project: https://github.com/fastify/fastify-cors#readme +// Definitions by: Jannik Keye +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +type originCallback = (err: Error, allow: boolean) => void; + +/** + * fastify-cors enables the use of CORS in a Fastify application. + */ +declare function fastifyCors(): void; + +declare namespace fastifyCors { + /** + * Options for configuring the fastify-cors plugin. + */ + interface FastifyCorsOptions { + /** + * Configures the Access-Control-Allow-Origin CORS header. + */ + origin?: string | boolean | RegExp | string[] | RegExp[] | originCallback; + /** + * Configures the Access-Control-Allow-Credentials CORS header. + * Set to true to pass the header, otherwise it is omitted. + */ + credentials?: boolean; + /** + * Configures the Access-Control-Expose-Headers CORS header. + * Expects a comma-delimited string (ex: 'Content-Range,X-Content-Range') + * or an array (ex: ['Content-Range', 'X-Content-Range']). + * If not specified, no custom headers are exposed. + */ + exposedHeaders?: string | string[]; + /** + * Configures the Access-Control-Allow-Headers CORS header. + * Expects a comma-delimited string (ex: 'Content-Type,Authorization') + * or an array (ex: ['Content-Type', 'Authorization']). If not + * specified, defaults to reflecting the headers specified in the + * request's Access-Control-Request-Headers header. + */ + allowedHeaders?: string | string[]; + /** + * Configures the Access-Control-Allow-Methods CORS header. + * Expects a comma-delimited string (ex: 'GET,PUT,POST') or an array (ex: ['GET', 'PUT', 'POST']). + */ + methods?: string | string[]; + /** + * Configures the Access-Control-Max-Age CORS header. + * Set to an integer to pass the header, otherwise it is omitted. + */ + maxAge?: number; + /** + * Pass the CORS preflight response to the route handler (default: false). + */ + preflightContinue?: boolean; + /** + * Provides a status code to use for successful OPTIONS requests, + * since some legacy browsers (IE11, various SmartTVs) choke on 204. + */ + optionsSuccessStatus?: number; + /** + * Pass the CORS preflight response to the route handler (default: false). + */ + preflight?: boolean; + } +} + +export = fastifyCors; diff --git a/types/fastify-cors/tsconfig.json b/types/fastify-cors/tsconfig.json new file mode 100644 index 0000000000..9e696b42e2 --- /dev/null +++ b/types/fastify-cors/tsconfig.json @@ -0,0 +1,23 @@ +{ + "compilerOptions": { + "module": "commonjs", + "lib": [ + "es6" + ], + "noImplicitAny": true, + "noImplicitThis": true, + "strictNullChecks": true, + "strictFunctionTypes": true, + "baseUrl": "../", + "typeRoots": [ + "../" + ], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true + }, + "files": [ + "index.d.ts", + "fastify-cors-tests.ts" + ] +} diff --git a/types/fastify-cors/tslint.json b/types/fastify-cors/tslint.json new file mode 100644 index 0000000000..3db14f85ea --- /dev/null +++ b/types/fastify-cors/tslint.json @@ -0,0 +1 @@ +{ "extends": "dtslint/dt.json" } diff --git a/types/fromnow/fromnow-tests.ts b/types/fromnow/fromnow-tests.ts index 162491dc9a..e1ada34e6b 100644 --- a/types/fromnow/fromnow-tests.ts +++ b/types/fromnow/fromnow-tests.ts @@ -1,29 +1,35 @@ -import fromnow = require( 'fromnow' ); +import fromnow = require('fromnow'); function dateOnly() { - fromnow( '2015-12-31' ); + fromnow('2015-12-31'); } function dateObjectOnly() { - fromnow( new Date() ); + fromnow(new Date()); } -function maxChunks() { - fromnow( '2015-12-31', { - maxChunks: 12 +function max() { + fromnow('2015-12-31', { + max: 12 }); } -function useAgo() { - fromnow( '2015-12-31', { - useAgo: true +function suffix() { + fromnow('2015-12-31', { + suffix: true }); } -function useAnd() { - fromnow( '2015-12-31', { - useAnd: true +function and() { + fromnow('2015-12-31', { + and: true + }); +} + +function zero() { + fromnow('2015-12-31', { + zero: true }); } diff --git a/types/fromnow/index.d.ts b/types/fromnow/index.d.ts index 86c1610f9b..d7ef476894 100644 --- a/types/fromnow/index.d.ts +++ b/types/fromnow/index.d.ts @@ -1,4 +1,4 @@ -// Type definitions for fromnow v2.0.0 +// Type definitions for fromnow v3.0.0 // Project: https://github.com/lukeed/fromNow // Definitions by: Martin Bukovics // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped @@ -9,18 +9,20 @@ export as namespace fromNow; declare namespace FromNow { interface FromNowOpts { - maxChunks?: number, - useAgo?: boolean, - useAnd?: boolean + max?: number, + suffix?: boolean, + zero?: boolean, + and?: boolean } export interface FromNowStatic { /** * Get readable time differences from now vs past or future dates. * @param {string|Date} date * @param {object} [opts] - * @param {number} [opts.maxChucks=10] - * @param {boolean} [opts.useAgo=false] - * @param {boolean} [opts.useAnd=false] + * @param {number} [opts.max=Infinity] + * @param {boolean} [opts.suffix=false] + * @param {boolean} [opts.zero=false] + * @param {boolean} [opts.and=false] */ (date: string|Date, opts?: FromNowOpts): string } diff --git a/types/glob/glob-tests.ts b/types/glob/glob-tests.ts index e67e41317b..c73ac10815 100644 --- a/types/glob/glob-tests.ts +++ b/types/glob/glob-tests.ts @@ -29,5 +29,6 @@ const Glob = glob.Glob; console.log("after"); })(); +declare const ignore: ReadonlyArray; glob.sync('/foo/*', {realpath: true, realpathCache: {'/foo/bar': '/bar'}, ignore: '/foo/baz'}); -glob.sync('/*', {nodir: true, cache: {'/': ['bar', 'baz']}, statCache: {'/foo/bar': false, '/foo/baz': {isDirectory() { return true; }}}}); +glob.sync('/*', {ignore, nodir: true, cache: {'/': ['bar', 'baz']}, statCache: {'/foo/bar': false, '/foo/baz': {isDirectory() { return true; }}}}); diff --git a/types/glob/index.d.ts b/types/glob/index.d.ts index 9b0e1e5cb8..fc8c98853d 100644 --- a/types/glob/index.d.ts +++ b/types/glob/index.d.ts @@ -33,7 +33,7 @@ declare namespace G { stat?: boolean; silent?: boolean; strict?: boolean; - cache?: { [path: string]: boolean | 'DIR' | 'FILE' | string[] }; + cache?: { [path: string]: boolean | 'DIR' | 'FILE' | ReadonlyArray }; statCache?: { [path: string]: false | { isDirectory(): boolean} | undefined }; symlinks?: { [path: string]: boolean | undefined }; realpathCache?: { [path: string]: string }; @@ -47,7 +47,7 @@ declare namespace G { nocase?: boolean; matchBase?: any; nodir?: boolean; - ignore?: string | string[]; + ignore?: string | ReadonlyArray; follow?: boolean; realpath?: boolean; nonegate?: boolean; @@ -70,7 +70,7 @@ declare namespace G { minimatch: minimatch.IMinimatch; options: IOptions; aborted: boolean; - cache: { [path: string]: boolean | 'DIR' | 'FILE' | string[] }; + cache: { [path: string]: boolean | 'DIR' | 'FILE' | ReadonlyArray }; statCache: { [path: string]: false | { isDirectory(): boolean; } | undefined }; symlinks: { [path: string]: boolean | undefined }; realpathCache: { [path: string]: string }; diff --git a/types/google-map-react/index.d.ts b/types/google-map-react/index.d.ts index 4c566df796..a917ae426e 100644 --- a/types/google-map-react/index.d.ts +++ b/types/google-map-react/index.d.ts @@ -135,7 +135,7 @@ export interface Props { onZoomAnimationStart?(args: any): void; onZoomAnimationEnd?(args: any): void; onMapTypeIdChange?(args: any): void; - distanceToMouse?(pt: Point, mousePos: Point): void; + distanceToMouse?(pt: Point, mousePos: Point, markerProps?: object): number; googleMapLoader?(bootstrapURLKeys: any): void; onGoogleApiLoaded?(maps: { map: any, maps: any }): void; onTilesLoaded?(): void; diff --git a/types/highland/highland-tests.ts b/types/highland/highland-tests.ts index fc63a23925..cc61fcf92d 100644 --- a/types/highland/highland-tests.ts +++ b/types/highland/highland-tests.ts @@ -293,15 +293,15 @@ barStream = fooStream.flatten(); fooStream = fooStream.fork(); -fooStream = _([fooStream, fooStream]).merge(); +fooStream = fooStreamStream.merge(); fooStream = fooStream.observe(); fooStream = fooStream.otherwise(fooStream); -fooStream = fooStream.parallel(num); +fooStream = fooStreamStream.parallel(num); -barStream = fooStream.sequence(); +barStream = barStreamStream.sequence(); barStream = fooStream.series(); diff --git a/types/highland/index.d.ts b/types/highland/index.d.ts index 7203e959ab..b6372f799a 100644 --- a/types/highland/index.d.ts +++ b/types/highland/index.d.ts @@ -1049,7 +1049,7 @@ declare namespace Highland { * _([txt, md]).merge(); * // => contents of foo.txt, bar.txt and baz.txt in the order they were read */ - merge(): Stream; + merge(this: Stream>): Stream; /** * Observes a stream, allowing you to handle values as they are emitted, without @@ -1087,7 +1087,7 @@ declare namespace Highland { * @param {Number} n - the maximum number of concurrent reads/buffers * @api public */ - parallel(n: number): Stream; + parallel(this: Stream>, n: number): Stream /** * Reads values from a Stream of Streams, emitting them on a Single output @@ -1100,8 +1100,7 @@ declare namespace Highland { * @name Stream.sequence() * @api public */ - //TODO figure out typing - sequence(): Stream; + sequence(this: Stream>): Stream; /** * An alias for the [sequence](#sequence) method. diff --git a/types/knex/index.d.ts b/types/knex/index.d.ts index 329bf438b2..55aa4afc36 100644 --- a/types/knex/index.d.ts +++ b/types/knex/index.d.ts @@ -262,6 +262,7 @@ declare namespace Knex { } interface WithWrapped { + (alias: string, queryBuilder: QueryBuilder): QueryBuilder; (alias: string, callback: (queryBuilder: QueryBuilder) => any): QueryBuilder; } diff --git a/types/knex/knex-tests.ts b/types/knex/knex-tests.ts index 461e1738fe..dbd6273ff3 100644 --- a/types/knex/knex-tests.ts +++ b/types/knex/knex-tests.ts @@ -641,6 +641,9 @@ knex.with('new_books', 'select * from books where published_date >= :year', { ye knex.with('new_books', 'select * from books where published_date >= ?', [2016]) .select('*').from('new_books'); +knex.with('new_books', knex.select('*').from('books').where("published_date", ">=", 2016)) + .select('*').from('new_books'); + knex.withRaw('recent_books', 'select * from books where published_date >= :year', { year: 2013 }) .select('*').from('recent_books'); @@ -651,6 +654,9 @@ knex.withWrapped("antique_books", function (qb) { qb.select('*').from('books').where('published_date', '<', 1899); }).select('*').from('antique_books'); +knex.withWrapped('new_books', knex.select('*').from('books').where("published_date", ">=", 2016)) + .select('*').from('new_books'); + var someExternalMethod: Function; knex.transaction(function(trx) { diff --git a/types/lambda-log/index.d.ts b/types/lambda-log/index.d.ts index f54cb3dfc5..613c9f1eca 100644 --- a/types/lambda-log/index.d.ts +++ b/types/lambda-log/index.d.ts @@ -9,12 +9,43 @@ import { WriteStream } from "fs"; import { Console } from "console"; import { EventEmitter } from "events"; +export interface LogRecordOptions { + level: string; + msg: string; + meta?: any; + tags?: string[]; +} + +export interface LogRecord { + msg: string; + meta: any; + _logLevel: string; + _tags: string[]; +} + +export class LogMessage { + level: string; + msg: string; + + meta?: any; + + constructor(logRecordOptions: LogRecordOptions, opts: LambdaLogOptions); + + value: LogRecord; + log: LogRecord; + throw: undefined; + + toJSON(format?: number): string; + + static isError(val: any): boolean; +} + export interface LambdaLogOptions { meta?: any; // Global tags array to include with every log tags?: string[]; // Optional function which will run for every log to inject dynamic metadata - dynamicMeta?: null; + dynamicMeta?: (message: LogMessage) => any; // Enable debugging mode (log.debug messages) debug?: boolean; // Enable development mode which pretty-prints the log object to the console @@ -51,5 +82,10 @@ export class LambdaLog extends EventEmitter { log(level: string, msg: string, meta: object, tags: string[]): string; - assert(test: any, msg: string, meta: object, tags: string[]): boolean | string; + assert( + test: any, + msg: string, + meta: object, + tags: string[] + ): boolean | string; } diff --git a/types/lambda-log/lambda-log-tests.ts b/types/lambda-log/lambda-log-tests.ts index 259bb66684..0280c2c7f1 100644 --- a/types/lambda-log/lambda-log-tests.ts +++ b/types/lambda-log/lambda-log-tests.ts @@ -1,4 +1,10 @@ -import { LambdaLog } from "lambda-log"; +import { LambdaLog, LogMessage } from "lambda-log"; -const log = new LambdaLog(); +const log = new LambdaLog({ + dynamicMeta: (logMessage: LogMessage) => { + return { + value: logMessage.value + }; + } +}); log.log("info", "Some Message", {}, ["tag1", "tag2"]); diff --git a/types/lambda-log/tsconfig.json b/types/lambda-log/tsconfig.json index d2eb781281..75ca782413 100644 --- a/types/lambda-log/tsconfig.json +++ b/types/lambda-log/tsconfig.json @@ -1,23 +1,16 @@ { - "compilerOptions": { - "module": "commonjs", - "lib": [ - "es6" - ], - "noImplicitAny": true, - "noImplicitThis": true, - "strictNullChecks": true, - "baseUrl": "../", - "typeRoots": [ - "../" - ], - "types": [], - "noEmit": true, - "strictFunctionTypes": true, - "forceConsistentCasingInFileNames": true - }, - "files": [ - "index.d.ts", - "lambda-log-tests.ts" - ] + "compilerOptions": { + "module": "commonjs", + "lib": ["es6"], + "noImplicitAny": true, + "noImplicitThis": true, + "strictNullChecks": true, + "baseUrl": "../", + "typeRoots": ["../"], + "types": [], + "noEmit": true, + "strictFunctionTypes": true, + "forceConsistentCasingInFileNames": true + }, + "files": ["index.d.ts", "lambda-log-tests.ts"] } diff --git a/types/newman/index.d.ts b/types/newman/index.d.ts index 8f566b275c..cd2801c375 100644 --- a/types/newman/index.d.ts +++ b/types/newman/index.d.ts @@ -1,14 +1,161 @@ -// Type definitions for newman 3.9 +// Type definitions for newman 3.10 // Project: https://github.com/postmanlabs/newman // Definitions by: Leonid Logvinov +// Graham McGregor // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.4 + +import { EventEmitter } from "events"; +import { + Collection, + CollectionDefinition, + VariableScope, + VariableScopeDefinition +} from "postman-collection"; + +export interface NewmanRunOptions { + /** A JSON / Collection / String representing the collection. */ + collection: Collection | CollectionDefinition | string; + /** An environment JSON / file path for the current collection run. */ + environment?: VariableScope | VariableScopeDefinition | string; + /** A globals JSON / file path for the current collection run. */ + globals?: VariableScope | VariableScopeDefinition | string; + /** + * Specify the number of iterations to run on the collection. This is + * usually accompanied by providing a data file reference as + * iterationData + */ + iterationCount?: number; + /** + * Path to the JSON or CSV file or URL to be used as data source when + * running multiple iterations on a collection. + */ + iterationData?: any; + /** + * The name or ID of the folder (ItemGroup) in the collection which would + * be run instead of the entire collection. + */ + folder?: string; + /** + * Specify the time (in milliseconds) to wait for the entire collection run + * to complete execution. + * + * Default value: Infinity + */ + timeout?: number; + /** + * Specify the time (in milliseconds) to wait for requests to return a + * response. + * + * Default value: Infinity + */ + timeoutRequest?: number; + /** + * Specify the time (in milliseconds) to wait for scripts to return a + * response. + * + * Default value: Infinity + */ + timeoutScript?: number; + /** + * Specify the time (in milliseconds) to wait for between subsequent + * requests. + * + * Default value: 0 + */ + delayRequest?: number; + /** + * This specifies whether newman would automatically follow 3xx responses + * from servers. + * + * Default value: false + */ + ignoreRedirects?: boolean; + /** + * Disables SSL verification checks and allows self-signed SSL certificates. + * + * Default value: false + */ + insecure?: boolean; + /** + * Specify whether or not to stop a collection run on encountering the + * first test script error. + * + * "folder" allows you to skip the entire collection run in case an invalid + * folder was specified using the `folder` option or an error was + * encountered in general. + * + * "failure" would gracefully stop a collection run after completing the + * current test script. + * + * Default value: false + */ + bail?: boolean | ["folder"] | ["failure"]; + /** + * If present, allows overriding the default exit code from the current + * collection run, useful for bypassing collection result failures. + * + * Default value: false + */ + suppressExitCode?: boolean; + /** Available reporters: cli, json, html and junit. */ + reporters?: string | string[]; + /** + * Specify options for the reporter(s) declared in options.reporters. + */ + reporter?: any; + /** + * Forces colored CLI output (for use in CI / non TTY environments). + */ + color?: boolean; + /** + * Newman attempts to automatically turn off color output to terminals when + * it detects the lack of color support. With this property, one can + * forcibly turn off the usage of color in terminal output for reporters + * and other parts of Newman that output to console. + */ + noColor?: boolean; + /** + * The path to the public client certificate file. + */ + sslClientCert?: string; + /** + * The path to the private client key file. + */ + sslClientKey?: string; + /** + * The secret client key passphrase. + */ + sslClientPassphrase?: string; +} export interface NewmanRunSummary { + error?: any; + collection: any; + environment: any; + globals: any; run: NewmanRun; } export interface NewmanRun { + stats: { + iterations: NewmanRunStat; + items: NewmanRunStat; + scripts: NewmanRunStat; + prerequests: NewmanRunStat; + requests: NewmanRunStat; + tests: NewmanRunStat; + assertions: NewmanRunStat; + testScripts: NewmanRunStat; + prerequestScripts: NewmanRunStat; + }; + failures: NewmanRunFailure[]; executions: NewmanRunExecution[]; } +export interface NewmanRunStat { + total?: number; + failed?: number; + pending?: number; +} export interface NewmanRunExecution { item: NewmanRunExecutionItem; assertions: NewmanRunExecutionAssertion[]; @@ -23,4 +170,12 @@ export interface NewmanRunExecutionAssertion { export interface NewmanRunExecutionAssertionError { message: string; } -export function run(options: any, callback?: (err: Error | null, summary: NewmanRunSummary) => void): void; +export interface NewmanRunFailure { + error: NewmanRunExecutionAssertionError; + /** The event where the failure occurred */ + at: string; +} +export function run( + options: NewmanRunOptions, + callback?: (err: Error | null, summary: NewmanRunSummary) => void +): EventEmitter; diff --git a/types/newman/newman-tests.ts b/types/newman/newman-tests.ts index 82ba6002e7..51a790ab2f 100644 --- a/types/newman/newman-tests.ts +++ b/types/newman/newman-tests.ts @@ -1,3 +1,4 @@ +import { EventEmitter } from "events"; import { run, NewmanRun, @@ -5,7 +6,28 @@ import { NewmanRunExecutionAssertion, NewmanRunExecutionAssertionError, NewmanRunExecutionItem, - NewmanRunSummary, -} from 'newman'; + NewmanRunFailure, + NewmanRunSummary +} from "newman"; +import { + CollectionDefinition, + VariableScopeDefinition +} from "postman-collection"; -run({}); +const collection: CollectionDefinition = {}; +const environment: VariableScopeDefinition = {}; +const globals: VariableScopeDefinition = {}; + +// $ExpectType EventEmitter +run( + { + collection, + environment, + globals + }, + (err, summary: NewmanRunSummary) => { + summary.run; // $ExpectType NewmanRun + summary.run.executions; // $ExpectType NewmanRunExecution[] + summary.run.failures; // $ExpectType NewmanRunFailure[] + } +); diff --git a/types/react-albus/index.d.ts b/types/react-albus/index.d.ts index 9d34c93c64..be546011d4 100644 --- a/types/react-albus/index.d.ts +++ b/types/react-albus/index.d.ts @@ -2,6 +2,7 @@ // Project: https://github.com/americanexpress/react-albus#readme // Definitions by: Sindre Seppola // Conrad Reuter +// Jonas Kugelmann // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped // TypeScript Version: 2.8 @@ -23,19 +24,31 @@ export interface WizardContext { replace: (id?: string) => void; } -export const Wizard: React.ComponentType<{ +export interface WizardComponentProps { + wizard: WizardContext; +} + +export function withWizard

( + component: React.ComponentType

+): React.ComponentType

; + +export interface WizardProps { onNext?: (wizard: WizardContext) => void; render?: (wizard: WizardContext) => React.ReactNode; history?: History; -}>; + basename?: string; +} -export const Steps: React.ComponentType<{ +export const Wizard: React.ComponentType; + +export interface StepsProps { step?: WizardStepObject; -}>; +} -export const Step: React.ComponentType<{ - id: string; -} & ( - | { render?: (wizard: WizardContext) => React.ReactNode; } - | { children: (wizard: WizardContext) => React.ReactNode; } -)>; +export const Steps: React.ComponentType; + +export type StepProps = { id: string } & ( + | { render?: (wizard: WizardContext) => React.ReactNode } + | { children: (wizard: WizardContext) => React.ReactNode }); + +export const Step: React.ComponentType; diff --git a/types/react-albus/react-albus-tests.tsx b/types/react-albus/react-albus-tests.tsx index ed744c3e6f..2f31733b1d 100644 --- a/types/react-albus/react-albus-tests.tsx +++ b/types/react-albus/react-albus-tests.tsx @@ -1,8 +1,9 @@ import * as React from "react"; -import { Wizard, Step, Steps } from "react-albus"; +import { Wizard, Step, Steps, withWizard } from "react-albus"; const Example = () => ( { wiz.go(0); const location = wiz.history.location; @@ -46,6 +47,12 @@ const Example = () => ( )} + +

+

Hermoine

+ +
+

Harry

@@ -55,3 +62,8 @@ const Example = () => ( )} /> ); + +export const NextButton = withWizard<{ label: string }>(props => { + const { wizard, label } = props; + return ; +}); diff --git a/types/react-jsonschema-form/index.d.ts b/types/react-jsonschema-form/index.d.ts index f2fb1d736d..63a4de1b89 100644 --- a/types/react-jsonschema-form/index.d.ts +++ b/types/react-jsonschema-form/index.d.ts @@ -5,6 +5,7 @@ // Kurt Preston // Philippe Bourdages // Lucian Buzzo +// Sylvain Thénault // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped // TypeScript Version: 2.8 @@ -228,3 +229,15 @@ declare module "react-jsonschema-form" { formData: T; }; } + +declare module "react-jsonschema-form/lib/utils" { + import { JSONSchema6 } from "json-schema"; + + export interface IRangeSpec { + min?: number; + max?: number; + step?: number; + } + + export function rangeSpec(schema: JSONSchema6): IRangeSpec; +} diff --git a/types/require-dir/index.d.ts b/types/require-dir/index.d.ts index ba31e89f79..2792fe3914 100644 --- a/types/require-dir/index.d.ts +++ b/types/require-dir/index.d.ts @@ -1,8 +1,16 @@ -// Type definitions for require-dir 0.3 +// Type definitions for require-dir 1.0 // Project: https://github.com/aseemk/requireDir // Definitions by: weekens // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -declare function requireDir(directory: string): { [path: string]: any }; +interface options { + recurse?: boolean; + duplicates?: boolean; + filter?: any; + mapKey?: any; + mapValue?: any; +} + +declare function requireDir(directory: string, options?: options): { [path: string]: any }; export = requireDir; diff --git a/types/restify/index.d.ts b/types/restify/index.d.ts index 5d4b19285b..ee757e8a2f 100644 --- a/types/restify/index.d.ts +++ b/types/restify/index.d.ts @@ -1231,7 +1231,7 @@ export namespace plugins { maxFieldsSize?: number; - maxFileSize: number; + maxFileSize?: number; } /** diff --git a/types/sha256/index.d.ts b/types/sha256/index.d.ts new file mode 100644 index 0000000000..bf89598fc6 --- /dev/null +++ b/types/sha256/index.d.ts @@ -0,0 +1,23 @@ +// Type definitions for sha256 0.2 +// Project: https://github.com/cryptocoinjs/sha256 +// Definitions by: Nathan Hardy +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +/// + +type Message = string | Buffer | number[]; + +interface Sha256 { + (message: Message, options?: { asString: true }): string; + (message: Message, options: { asBytes: true }): number[]; +} + +interface Sha256WithX2 extends Sha256 { + x2: Sha256; +} + +declare const sha256: Sha256WithX2; + +export = sha256; + +export as namespace sha256; diff --git a/types/sha256/sha256-tests.ts b/types/sha256/sha256-tests.ts new file mode 100644 index 0000000000..22b35eff31 --- /dev/null +++ b/types/sha256/sha256-tests.ts @@ -0,0 +1,10 @@ +import sha256 = require("sha256"); + +const test1: string = sha256('message'); +const test2: number[] = sha256('message', { asBytes: true }); +const test3: string = sha256('message', { asString: true }); +const test4: string = sha256(Buffer.from('message')); +const test5: string = sha256(Array.from(Buffer.from('message'))); +const test6: string = sha256.x2('message'); +const test7: number[] = sha256.x2('message', { asBytes: true }); +const test8: string = sha256.x2('message', { asString: true }); diff --git a/types/sha256/tsconfig.json b/types/sha256/tsconfig.json new file mode 100644 index 0000000000..45039e10d8 --- /dev/null +++ b/types/sha256/tsconfig.json @@ -0,0 +1,23 @@ +{ + "compilerOptions": { + "module": "commonjs", + "lib": [ + "es6" + ], + "noImplicitAny": true, + "noImplicitThis": true, + "strictNullChecks": true, + "strictFunctionTypes": true, + "baseUrl": "../", + "typeRoots": [ + "../" + ], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true + }, + "files": [ + "index.d.ts", + "sha256-tests.ts" + ] +} diff --git a/types/sha256/tslint.json b/types/sha256/tslint.json new file mode 100644 index 0000000000..3db14f85ea --- /dev/null +++ b/types/sha256/tslint.json @@ -0,0 +1 @@ +{ "extends": "dtslint/dt.json" } diff --git a/types/ssh2/index.d.ts b/types/ssh2/index.d.ts index 6f6daae1d3..25bcfef52e 100644 --- a/types/ssh2/index.d.ts +++ b/types/ssh2/index.d.ts @@ -1,6 +1,8 @@ // Type definitions for ssh2 v0.5.x // Project: https://github.com/mscdex/ssh2 -// Definitions by: Qubo , Ron Buckton +// Definitions by: Qubo +// Ron Buckton +// Will Boyce // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped /// @@ -449,6 +451,8 @@ export interface ConnectConfig { agentForward?: boolean; /** Explicit overrides for the default transport layer algorithms used for the connection. */ algorithms?: Algorithms; + /** Compression settings: true (prefer), false (never), 'force' (require) */ + compress?: boolean | 'force'; /** A function that receives a single string argument to get detailed (local) debug information. */ debug?: (information: string) => any; } diff --git a/types/standard-error/index.d.ts b/types/standard-error/index.d.ts new file mode 100644 index 0000000000..4bdf04c33e --- /dev/null +++ b/types/standard-error/index.d.ts @@ -0,0 +1,15 @@ +// Type definitions for standard-error 1.1 +// Project: https://github.com/moll/js-standard-error +// Definitions by: Labat Robin +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +// TypeScript Version: 2.2 + +export = StandardError; + +declare class StandardError extends Error { + [key: string]: any; + + constructor(message: string, props?: any); + constructor(props: any); +} diff --git a/types/standard-error/standard-error-tests.ts b/types/standard-error/standard-error-tests.ts new file mode 100644 index 0000000000..a5184da531 --- /dev/null +++ b/types/standard-error/standard-error-tests.ts @@ -0,0 +1,13 @@ +import StandardError = require('standard-error'); + +let error = new StandardError('test'); // $ExpectType StandardError + +error.message; // $ExpectType string +error.name; // $ExpectType string +error.stack; // $ExpectType string | undefined + +error = new StandardError({ name: 'test', foo: 'bar' }); // $ExpectType StandardError + +error.foo; // $ExpectType any + +error = new StandardError('test', { foo: 'bar' }); // $ExpectType StandardError diff --git a/types/standard-error/tsconfig.json b/types/standard-error/tsconfig.json new file mode 100644 index 0000000000..b0e6e23d4b --- /dev/null +++ b/types/standard-error/tsconfig.json @@ -0,0 +1,16 @@ +{ + "compilerOptions": { + "module": "commonjs", + "lib": ["es6"], + "noImplicitAny": true, + "noImplicitThis": true, + "strictFunctionTypes": true, + "strictNullChecks": true, + "baseUrl": "../", + "typeRoots": ["../"], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true + }, + "files": ["index.d.ts", "standard-error-tests.ts"] +} diff --git a/types/standard-error/tslint.json b/types/standard-error/tslint.json new file mode 100644 index 0000000000..3db14f85ea --- /dev/null +++ b/types/standard-error/tslint.json @@ -0,0 +1 @@ +{ "extends": "dtslint/dt.json" } diff --git a/types/standard-http-error/index.d.ts b/types/standard-http-error/index.d.ts new file mode 100644 index 0000000000..9b95acebeb --- /dev/null +++ b/types/standard-http-error/index.d.ts @@ -0,0 +1,17 @@ +// Type definitions for standard-http-error 2.0 +// Project: https://github.com/moll/js-standard-http-error +// Definitions by: Labat Robin +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +// TypeScript Version: 2.2 + +import StandardError = require('standard-error'); + +export = HttpError; + +declare class HttpError extends StandardError { + code: number; + + constructor(code: number | string, message?: string, props?: object); + constructor(code: number | string, props?: object); +} diff --git a/types/standard-http-error/standard-http-error-tests.ts b/types/standard-http-error/standard-http-error-tests.ts new file mode 100644 index 0000000000..0b430774d2 --- /dev/null +++ b/types/standard-http-error/standard-http-error-tests.ts @@ -0,0 +1,16 @@ +import HttpError = require('standard-http-error'); + +let error = new HttpError(200); // $ExpectType HttpError + +error.code; // $ExpectType number +error.message; // $ExpectType string +error.name; // $ExpectType string +error.stack; // $ExpectType string | undefined + +error = new HttpError(200, 'test'); // $ExpectType HttpError +error = new HttpError('OK', 'test'); // $ExpectType HttpError +error = new HttpError(200, 'test', { foo: 'bar' }); // $ExpectType HttpError + +error.foo; // $ExpectType any + +error = new HttpError(200, { message: 'test', foo: 'bar' }); // $ExpectType HttpError diff --git a/types/standard-http-error/tsconfig.json b/types/standard-http-error/tsconfig.json new file mode 100644 index 0000000000..cc399408e1 --- /dev/null +++ b/types/standard-http-error/tsconfig.json @@ -0,0 +1,16 @@ +{ + "compilerOptions": { + "module": "commonjs", + "lib": ["es6"], + "noImplicitAny": true, + "noImplicitThis": true, + "strictFunctionTypes": true, + "strictNullChecks": true, + "baseUrl": "../", + "typeRoots": ["../"], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true + }, + "files": ["index.d.ts", "standard-http-error-tests.ts"] +} diff --git a/types/standard-http-error/tslint.json b/types/standard-http-error/tslint.json new file mode 100644 index 0000000000..3db14f85ea --- /dev/null +++ b/types/standard-http-error/tslint.json @@ -0,0 +1 @@ +{ "extends": "dtslint/dt.json" } diff --git a/types/string-argv/index.d.ts b/types/string-argv/index.d.ts new file mode 100644 index 0000000000..eeaad53c87 --- /dev/null +++ b/types/string-argv/index.d.ts @@ -0,0 +1,18 @@ +// Type definitions for string-argv 0.1 +// Project: https://github.com/mccormicka/string-argv +// Definitions by: Vladimir Tikhonov +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +export = parseArgsStringToArgv; + +/** + * Parses a string into an argument array to mimic `process.argv`. + * @param value - Arguments that you would normally pass to the command line. + * @param [env] - Adds to the environment position in the argv array. + * If ommitted then there is no need to call argv.split(2) to remove the environment/file values. + * However if your cli.parse method expects a valid argv value then you should include this value. + * @param [file] - File that called the arguments. + * If omitted then there is no need to call argv.split(2) to remove the environment/file values. + * However if your cli.parse method expects a valid argv value then you should include this value. + */ +declare function parseArgsStringToArgv(value: string, env?: string, file?: string): string[]; diff --git a/types/string-argv/string-argv-tests.ts b/types/string-argv/string-argv-tests.ts new file mode 100644 index 0000000000..87458ab6eb --- /dev/null +++ b/types/string-argv/string-argv-tests.ts @@ -0,0 +1,5 @@ +import parseArgsStringToArgv = require("string-argv"); + +const commandOnly = parseArgsStringToArgv("-test"); // $ExpectType string[] +const commandAndEnv = parseArgsStringToArgv("-test", "node"); // $ExpectType string[] +const commandEnvAndFile = parseArgsStringToArgv("-test", "node", "testing.js"); // $ExpectType string[] diff --git a/types/string-argv/tsconfig.json b/types/string-argv/tsconfig.json new file mode 100644 index 0000000000..15815c763e --- /dev/null +++ b/types/string-argv/tsconfig.json @@ -0,0 +1,23 @@ +{ + "compilerOptions": { + "module": "commonjs", + "lib": [ + "es6" + ], + "noImplicitAny": true, + "noImplicitThis": true, + "strictNullChecks": true, + "strictFunctionTypes": true, + "baseUrl": "../", + "typeRoots": [ + "../" + ], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true + }, + "files": [ + "index.d.ts", + "string-argv-tests.ts" + ] +} diff --git a/types/string-argv/tslint.json b/types/string-argv/tslint.json new file mode 100644 index 0000000000..3db14f85ea --- /dev/null +++ b/types/string-argv/tslint.json @@ -0,0 +1 @@ +{ "extends": "dtslint/dt.json" } diff --git a/types/xmlbuilder/index.d.ts b/types/xmlbuilder/index.d.ts index acaeddca11..478e5c85d4 100644 --- a/types/xmlbuilder/index.d.ts +++ b/types/xmlbuilder/index.d.ts @@ -19,7 +19,7 @@ declare namespace xmlbuilder { instruction(target: string, value: any): XMLDocType; root(): XMLDocType; document(): any; - toString(options?: Object, level?: Number): string; + toString(options?: XMLToStringOptions, level?: Number): string; ele(name: string, value?: Object): XMLDocType; att(elementName: string, attributeName: string, attributeType: string, defaultValueType?: string, defaultValue?: any): XMLDocType; @@ -49,7 +49,7 @@ declare namespace xmlbuilder { i(target: string, value: any): XMLElementOrXMLNode; i(array: Array): XMLElementOrXMLNode; i(obj: Object): XMLElementOrXMLNode; - toString(options?: Object, level?: Number): string; + toString(options?: XMLToStringOptions, level?: Number): string; // XMLNode: element(name: any, attributes?: Object, text?: any): XMLElementOrXMLNode; ele(name: any, attributes?: Object, text?: any): XMLElementOrXMLNode; @@ -67,7 +67,7 @@ declare namespace xmlbuilder { importDocument(input: XMLElementOrXMLNode): XMLElementOrXMLNode; root(): XMLElementOrXMLNode; document(): any; - end(options?: Object): string; + end(options?: XMLEndOptions): string; prev(): XMLElementOrXMLNode; next(): XMLElementOrXMLNode; nod(name: any, attributes?: Object, text?: any): XMLElementOrXMLNode; @@ -86,6 +86,48 @@ declare namespace xmlbuilder { u(): XMLElementOrXMLNode; } - function create(nameOrObjSpec: string | { [name: string]: Object }, xmldec?: Object, doctype?: any, options?: Object): XMLElementOrXMLNode; + interface XMLDec { + version?: string; + encoding?: string; + standalone?: boolean; + } + + interface XMLDtd { + pubID?: string; + sysID?: string; + } + + interface XMLStringifier { + [x: string]: ((v: any) => string) | string; + } + + interface XMLWriter { + [x: string]: ((e: XMLElementOrXMLNode, level?: number) => void); + } + + interface XMLCreateOptions { + headless?: boolean; + skipNullNodes?: boolean; + skipNullAttributes?: boolean; + ignoreDecorators?: boolean; + separateArrayItems?: boolean; + noDoubleEncoding?: boolean; + stringify?: XMLStringifier; + } + + interface XMLToStringOptions { + pretty?: boolean; + indent?: string; + offset?: number; + newline?: string; + allowEmpty?: boolean; + spacebeforeslash?: string; + } + + interface XMLEndOptions extends XMLToStringOptions { + writer?: XMLWriter; + } + + function create(nameOrObjSpec: string | { [name: string]: Object }, xmldecOrOptions?: XMLDec | XMLCreateOptions, doctypeOrOptions?: XMLDtd | XMLCreateOptions, options?: XMLCreateOptions): XMLElementOrXMLNode; function begin(): XMLElementOrXMLNode; } diff --git a/types/xmlbuilder/xmlbuilder-tests.ts b/types/xmlbuilder/xmlbuilder-tests.ts index 0364d6fed8..fb49f20e79 100644 --- a/types/xmlbuilder/xmlbuilder-tests.ts +++ b/types/xmlbuilder/xmlbuilder-tests.ts @@ -51,4 +51,65 @@ xml({ level: 'error', message: 'an error occurred' } -}); \ No newline at end of file +}); + +// https://github.com/oozcitak/xmlbuilder-js/wiki#create +xml('root', { + stringify: { + eleName: function(val) { + return 'myns:' + val; + } + } +}); + +// https://github.com/oozcitak/xmlbuilder-js/wiki#converting-to-string +xml('root').end({ + pretty: true, + indent: ' ', + newline: '\n', + allowEmpty: false, + spacebeforeslash: '' +}); + +xml('root').ele('child').toString({ + pretty: true, + indent: ' ', + offset: 1, + newline: '\n', + spacebeforeslash: '' +}); + +// https://github.com/oozcitak/xmlbuilder-js/wiki#xml-writers +xml('root').end({ + writer: { + document: (doc) => { }, + attribute: (doc) => { }, + cdata: (node, level) => { }, + comment: (node, level) => { }, + declaration: (node, level) => { }, + docType: (node, level) => { }, + element: (node, level) => { }, + processingInstruction: (node, level) => { }, + raw: (node, level) => { }, + text: (node, level) => { }, + dtdAttList: (node, level) => { }, + dtdElement: (node, level) => { }, + dtdEntity: (node, level) => { }, + dtdNotation: (node, level) => { }, + } +}); + +// https://github.com/oozcitak/xmlbuilder-js/wiki/XML-Prolog +xml('xbel', + { version: '1.0', encoding: 'UTF-8'}, + { pubID: '+//IDN python.org//DTD XML Bookmark Exchange Language 1.0//EN//XML', + sysID: 'http://www.python.org/topics/xml/dtds/xbel-1.0.dtd' + } +); + +xml('root') + .dec('1.0', 'UTF-8', true) + .ele('node'); + +xml('HTML') + .dtd('-//W3C//DTD HTML 4.01//EN', 'http://www.w3.org/TR/html4/strict.dtd');