diff --git a/notNeededPackages.json b/notNeededPackages.json index 306865851b..38c0a39808 100644 --- a/notNeededPackages.json +++ b/notNeededPackages.json @@ -60,6 +60,12 @@ "sourceRepoURL": "https://github.com/AlexTeixeira/Askmethat-Rating", "asOfVersion": "0.4.0" }, + { + "libraryName": "autobind-decorator", + "typingsPackageName": "autobind-decorator", + "sourceRepoURL": "https://github.com/andreypopp/autobind-decorator", + "asOfVersion": "2.1.0" + }, { "libraryName": "aws-sdk", "typingsPackageName": "aws-sdk", @@ -132,6 +138,12 @@ "sourceRepoURL": "https://github.com/mapbox/cheap-ruler", "asOfVersion": "2.5.0" }, + { + "libraryName": "commander", + "typingsPackageName": "commander", + "sourceRepoURL": "https://github.com/tj/commander.js", + "asOfVersion": "2.12.2" + }, { "libraryName": "constant-case", "typingsPackageName": "constant-case", @@ -360,6 +372,12 @@ "sourceRepoURL": "https://github.com/elitechance/lambda-phi", "asOfVersion": "1.0.1" }, + { + "libraryName": "left-pad", + "typingsPackageName": "left-pad", + "sourceRepoURL": "https://github.com/stevemao/left-pad", + "asOfVersion": "1.2.0" + }, { "libraryName": "Linq.JS", "typingsPackageName": "linq", @@ -558,6 +576,12 @@ "sourceRepoURL": "https://github.com/gpbl/react-day-picker", "asOfVersion": "5.3.0" }, + { + "libraryName": "react-native-elements", + "typingsPackageName": "react-native-elements", + "sourceRepoURL": "https://github.com/react-native-training/react-native-elements", + "asOfVersion": "0.18.0" + }, { "libraryName": "realm", "typingsPackageName": "realm", @@ -690,6 +714,12 @@ "sourceRepoURL": "https://github.com/JMPerez/spotify-web-api-js", "asOfVersion": "0.21.0" }, + { + "libraryName": "striptags", + "typingsPackageName": "striptags", + "sourceRepoURL": "https://github.com/ericnorris/striptags", + "asOfVersion": "3.1.1" + }, { "libraryName": "Sugar", "typingsPackageName": "sugar", diff --git a/types/accepts/index.d.ts b/types/accepts/index.d.ts index 08ac71e919..33ee0db8a1 100644 --- a/types/accepts/index.d.ts +++ b/types/accepts/index.d.ts @@ -1,13 +1,14 @@ // Type definitions for accepts 1.3 // Project: https://github.com/jshttp/accepts // Definitions by: Stefan Reichel +// Brice BERNARD // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -declare namespace accepts { - interface Headers { - [key: string]: string | string[]; - } +/// +import { IncomingMessage } from "http"; + +declare namespace accepts { interface Accepts { /** * Return the first accepted charset. If nothing in `charsets` is accepted, then `false` is returned. @@ -55,6 +56,6 @@ declare namespace accepts { } } -declare function accepts(req: { headers: accepts.Headers }): accepts.Accepts; +declare function accepts(req: IncomingMessage): accepts.Accepts; export = accepts; diff --git a/types/add-zero/add-zero-tests.ts b/types/add-zero/add-zero-tests.ts new file mode 100644 index 0000000000..ac0509d26d --- /dev/null +++ b/types/add-zero/add-zero-tests.ts @@ -0,0 +1,3 @@ +import addZero from "add-zero"; + +addZero(5, 2); diff --git a/types/add-zero/index.d.ts b/types/add-zero/index.d.ts new file mode 100644 index 0000000000..907364a62d --- /dev/null +++ b/types/add-zero/index.d.ts @@ -0,0 +1,6 @@ +// Type definitions for add-zero 1.0 +// Project: https://github.com/rafaelrinaldi/add-zero#readme +// Definitions by: Giles Roadnight +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +export default function addZero(value: string | number, digits?: number): string; diff --git a/types/add-zero/tsconfig.json b/types/add-zero/tsconfig.json new file mode 100644 index 0000000000..e71d235cdf --- /dev/null +++ b/types/add-zero/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", + "add-zero-tests.ts" + ] +} diff --git a/types/left-pad/tslint.json b/types/add-zero/tslint.json similarity index 100% rename from types/left-pad/tslint.json rename to types/add-zero/tslint.json diff --git a/types/agenda/index.d.ts b/types/agenda/index.d.ts index d170a6f6f1..426b187d7c 100644 --- a/types/agenda/index.d.ts +++ b/types/agenda/index.d.ts @@ -113,8 +113,8 @@ declare class Agenda extends EventEmitter { * @param options The options for the job. * @param handler The handler to execute. */ - define(name: string, handler: (job?: Agenda.Job, done?: (err?: Error) => void) => void): void; - define(name: string, options: Agenda.JobOptions, handler: (job?: Agenda.Job, done?: (err?: Error) => void) => void): void; + define(name: string, handler: (job: Agenda.Job, done: (err?: Error) => void) => void): void; + define(name: string, options: Agenda.JobOptions, handler: (job: Agenda.Job, done: (err?: Error) => void) => void): void; /** * Runs job name at the given interval. Optionally, data and options can be passed in. diff --git a/types/alexa-sdk/index.d.ts b/types/alexa-sdk/index.d.ts index 1c39755b2d..02def0b4d6 100644 --- a/types/alexa-sdk/index.d.ts +++ b/types/alexa-sdk/index.d.ts @@ -4,15 +4,85 @@ // Huw // pascalwhoop // Ben +// rk-7 // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped // TypeScript Version: 2.2 export function handler(event: RequestBody, context: Context, callback?: (err: any, response: any) => void): AlexaObject; export function CreateStateHandler(state: string, obj: any): any; export let StateString: string; - export type ConfirmationStatuses = "NONE" | "DENIED" | "CONFIRMED"; export type DialogStates = "STARTED" | "IN_PROGRESS" | "COMPLETED"; +export type ListItemObjectStatus = "active" | "completed"; +export type ListObjectState = "active" | "archived"; +export type ImageSourceSize = "X_SMALL" | "SMALL" | "MEDIUM" | "LARGE" | "X_LARGE"; +export type TemplateBackButtonVisibility = "HIDDEN" | "VISIBLE"; +export type TemplateType = "BodyTemplate1" | "BodyTemplate2" | "BodyTemplate3" | "BodyTemplate6" | "BodyTemplate6" | "ListTemplate1" | "ListTemplate2"; +export type AudioPlayerActivity = "IDLE" | "PAUSED" | "PLAYING" | "BUFFER_UNDERRUN" | "FINISHED" | "STOPPED"; +export type CardType = "Standard" | "Simple" | "LinkAccount" | "AskForPermissionsConsent"; +export type HintType = "PlainText"; +export type DirectiveTypes = "AudioPlayer.Play" | "AudioPlayer.Stop" | "AudioPlayer.ClearQueue" | "Display.RenderTemplate" | "Hint" | "VideoApp.Launch"; +export type TextContentType = "PlainText" | "RichText"; + +//#region Types +export interface CardImage { + /** + * Recommended size (in px): 720w x 480h + */ + smallImageUrl: string; + /** + * Recommended size (in px): 1200w x 800h + */ + largeImageUrl: string; +} +export interface ImageSource { + url: string; + widthPixels?: number; + heightPixels?: number; + /** + * Recommended sizes for the following dimensions (in px): + * 480 x 320 for X_SMALL, + * 720 x 480 for SMALL, + * 960 x 640 for MEDIUM, + * 1200 x 800 for LARGE, + * 1920 x 1280 for X_LARGE + */ + size?: ImageSourceSize; +} +export interface Image { + contentDescription: string; + sources: ImageSource[]; +} +export interface TextField { + text: string; + type: string; +} +export interface TextContent { + primaryText?: TextField; + secondaryText?: TextField; + tertiaryText?: TextField; +} +export interface ListItem { + image?: Image; + token: string; + textContent?: TextContent; +} + +export interface Template { + title?: string; + token: string; + backgroundImage?: Image; + /** + * Visibility of the back button. + */ + backButton?: TemplateBackButtonVisibility; + /** + * Template type. + */ + type: TemplateType; + image?: Image; + listItems?: ListItem[]; +} export interface AlexaObject extends Handler { _event: any; @@ -38,12 +108,16 @@ export interface Handler { emitWithState: any; state: any; handler: any; + i18n: any; + locale: any; event: RequestBody; attributes: any; context: any; + callback: (param: any) => void; name: any; isOverriden: any; t: (token: string, ...args: any[]) => void; + response: ResponseBuilder; } export interface Context { @@ -55,8 +129,28 @@ export interface Context { functionVersion: string; invokeid: string; awsRequestId: string; + System?: System; + AudioPlayer?: AudioPlayer; +} +export interface Application { + applicationId: string; + [key: string]: string; +} +export interface System { + apiAccessToken: string; + apiEndpoint: string; + application: Application; + device: any; + user: any; +} +export interface AudioPlayer { + token: string; + offsetInMilliseconds: number; + /** + * Player activity + */ + playerActivity: AudioPlayerActivity; } - export interface RequestBody { version: string; session: Session; @@ -66,20 +160,22 @@ export interface RequestBody { export interface Session { new: boolean; sessionId: string; - attributes: any; - application: SessionApplication; + attributes: { [key: string]: any }; + application: Application; user: SessionUser; } - -export interface SessionApplication { - applicationId: string; -} - export interface SessionUser { userId: string; accessToken?: string; + permissions: Permissions; +} +export interface Permissions { + /** + * @deprecated + */ + consentToken: string; + [key: string]: string; } - export interface LaunchRequest extends Request { } export interface IntentRequest extends Request { @@ -144,7 +240,8 @@ export interface Response { outputSpeech?: OutputSpeech; card?: Card; reprompt?: Reprompt; - shouldEndSession: boolean; + directives?: any; + shouldEndSession?: boolean; } export interface OutputSpeech { @@ -154,18 +251,682 @@ export interface OutputSpeech { } export interface Card { - type: "Simple" | "Standard" | "LinkAccount"; + type: CardType; title?: string; content?: string; text?: string; - image?: Image; -} - -export interface Image { - smallImageUrl: string; - largeImageUrl: string; + image?: CardImage; } export interface Reprompt { outputSpeech: OutputSpeech; } + +export interface ApiClientOptions { + hostname: string; + port: string; + path: string; + protocol: string; + headers: string; + method: string; +} +export interface ApiClientResponse { + statusCode: string; + statusText: string; + body: object; + headers: object; +} +/** + * Todo-ListItem class + * Refer https://developer.amazon.com/docs/custom-skills/access-the-alexa-shopping-and-to-do-lists.html + */ +export interface ListItemObject { + /** + * item id (String, limit 60 characters) + */ + id: string; + /** + * item value (String, limit is 256 characters) + */ + value: string; + /** + * item status + */ + status?: ListItemObjectStatus; + /** + * item version (Positive integer) + */ + version?: number | string; + /** + * created time (ISO 8601 time format with time zone) + */ + createdTime: Date; + /** + * updated time (ISO 8601 time format with time zone) + */ + updatedTime: Date; + /** + * URL to retrieve the item (String) + */ + href?: string; +} +/** + * Todo-List class + * Refer https://developer.amazon.com/docs/custom-skills/access-the-alexa-shopping-and-to-do-lists.html + */ +export interface ListObject { + /** + * list id (String) + */ + listId: string; + /** + * list name (String) + */ + name: string; + /** + * state + * "active" or "archived" (Enum) + */ + state?: ListObjectState; + /** + * Possibly status of the list (or state?) + * Fetched from commit eebba0d at https://github.com/alexa/alexa-skills-kit-sdk-for-nodejs/ + * File path: alexa-skills-kit-sdk-for-nodejs/lib/services/listManagementService.js + */ + status?: string; + /** + * list version (Positive integer) + */ + version?: number; + /** + * Urls to active and completed items + * href is lint to the items having certain status. + * The status can be "active" or "completed". + */ + statusMap: { href: string; status: ListItemObjectStatus; }; + /** + * Items that belong to this list. + */ + items: ListItemObject[]; +} +//#endregion + +//#region templateBuilders +/** + * Generates templates for Echo Show device. + */ +export namespace templateBuilders { + interface SetTextContent> { + setTextContent(primaryText: TextField, secondaryText?: TextField, tertiaryText?: TextField): T; + } + interface SetListItems> { + setListItems(listItems: ListItem[]): T; + } + /** + * Refer https://developer.amazon.com/docs/custom-skills/display-interface-reference.html#image-sizes + */ + abstract class TemplateBuilder> { + template: Template; + constructor(); + + /** + * Sets the title of the template + * @param title title + * @returns TemplateBuilder + */ + setTitle(title: string): T; + + /** + * Sets the token of the template + * @param token token + * @returns TemplateBuilder + */ + setToken(token: string): T; + + /** + * Sets the background image of the template + * @param image image + * @returns TemplateBuilder + */ + setBackgroundImage(image: Image): T; + + /** + * Sets the backButton behavior + * @param backButtonBehavior "VISIBLE" or "HIDDEN" + * @returns TemplateBuilder + */ + setBackButtonBehavior(backButtonBehavior: string): T; + + /** + * Builds the template JSON object + * @returns Template + */ + build(): Template; + } + /** + * Used to build a list of ListItems for ListTemplate + */ + class ListItemBuilder { + constructor(); + items: ListItem[]; + /** + * Add an item to the list of template + * @param image image + * @param token token + * @param primaryText primaryText + * @param secondaryText secondaryText + * @param tertiaryText tertiaryText + */ + addItem(image: Image, token: string, primaryText: TextField, secondaryText?: TextField, tertiaryText?: TextField): ListItemBuilder; + + build(): ListItem[]; + } + /** + * Used to create BodyTemplate1 objects + */ + class BodyTemplate1Builder extends TemplateBuilder implements SetTextContent { + constructor(); + /** + * Sets the text content for the template + * @param primaryText primaryText + * @param secondaryText secondaryText + * @param tertiaryText tertiaryText + * @returns BodyTemplate1Builder + */ + setTextContent(primaryText: TextField, secondaryText?: TextField, tertiaryText?: TextField): BodyTemplate1Builder; + } + /** + * Used to create BodyTemplate2 objects + */ + class BodyTemplate2Builder extends TemplateBuilder implements SetTextContent { + constructor(); + + /** + * Sets the image for the template + * @param image image + * @returns BodyTemplate2Builder + */ + setImage(image: Image): BodyTemplate2Builder; + + /** + * Sets the text content for the template + * @param primaryText primaryText + * @param secondaryText secondaryText + * @param tertiaryText tertiaryText + * @returns BodyTemplate2Builder + */ + setTextContent(primaryText: TextField, secondaryText?: TextField, tertiaryText?: TextField): BodyTemplate2Builder; + } + /** + * Used to create BodyTemplate3 objects + */ + class BodyTemplate3Builder extends TemplateBuilder implements SetTextContent { + constructor(); + + /** + * Sets the image for the template + * @param image image + * @returns BodyTemplate3Builder + */ + setImage(image: Image): BodyTemplate3Builder; + + /** + * Sets the text content for the template + * @param primaryText primaryText + * @param secondaryText secondaryText + * @param tertiaryText tertiaryText + * @returns BodyTemplate3Builder + */ + setTextContent(primaryText: TextField, secondaryText?: TextField, tertiaryText?: TextField): BodyTemplate3Builder; + } + /** + * Used to create BodyTemplate6 objects + */ + class BodyTemplate6Builder extends TemplateBuilder implements SetTextContent { + constructor(); + + /** + * Sets the image for the template + * @param image image + * @returns BodyTemplate6Builder + */ + setImage(image: Image): BodyTemplate6Builder; + + /** + * Sets the text content for the template + * @param primaryText primaryText + * @param secondaryText secondaryText + * @param tertiaryText tertiaryText + * @returns BodyTemplate6Builder + */ + setTextContent(primaryText: TextField, secondaryText?: TextField, tertiaryText?: TextField): BodyTemplate6Builder; + } + /** + * Used to create BodyTemplate7 objects + */ + class BodyTemplate7Builder extends TemplateBuilder { + constructor(); + + /** + * Sets the image for the template + * @param image image + * @returns BodyTemplate7Builder + */ + setImage(image: Image): BodyTemplate7Builder; + } + /** + * Used to create ListTemplate1 objects + */ + class ListTemplate1Builder extends TemplateBuilder implements SetListItems { + constructor(); + + /** + * Set the items for the list + * @param listItems listItems + * @returns ListTemplate1Builder + */ + setListItems(listItems: ListItem[]): ListTemplate1Builder; + } + /** + * Used to create ListTemplate2 objects + */ + class ListTemplate2Builder extends TemplateBuilder implements SetListItems { + constructor(); + + /** + * Set the items for the list + * @param listItems listItems + * @returns ListTemplate2Builder + */ + setListItems(listItems: ListItem[]): ListTemplate2Builder; + } +} +//#endregion + +//#region services +export namespace services { + interface ApiClient { + /** + * Make a POST API call to the specified uri with headers and optional body + * @param uri http(s?) endpoint to call + * @param headers Key value pair of headers + * @param body post body to send + * @returns Promise + */ + post(uri: string, headers: object, body?: string): Promise; + /** + * Make a PUT API call to the specified uri with headers and optional body + * @param uri http(s?) endpoint to call + * @param headers Key value pair of headers + * @param body post body to send + * @returns Promise + */ + put(uri: string, headers: object, body?: string): Promise; + /** + * Make a GET API call to the specified uri with headers + * @param uri http(s?) endpoint to call + * @param headers key value pair of headers + * @returns Promise + */ + get(uri: string, headers: object): Promise; + /** + * Make a DELETE API call to the specified uri with headers + * @param uri http(s?) endpoint to call + * @param headers key value pair of headers + * @returns Promise + */ + delete(uri: string, headers: object): Promise; + } + class DeviceAddressService { + /** + * Create an instance of DeviceAddressService + * @param [apiClient=new ApiClient()] ApiClient + */ + constructor(apiClient: ApiClient); + + /** + * Get full address information from Alexa Device Address API + * @param deviceId deviceId from Alexa request + * @param apiEndpoint API apiEndpoint from Alexa request + * @param token bearer token for device address permission + * @returns Promise + */ + getFullAddress(deviceId: string, apiEndpoint: string, token: string): Promise; + + /** + * Get country and postal information from Alexa Device Address API + * @param deviceId deviceId from Alexa request + * @param apiEndpoint API apiEndpoint from Alexa request + * @param token bearer token for device address permission + * @returns Promise + */ + getCountryAndPostalCode(deviceId: string, apiEndpoint: string, token: string): Promise; + } + class DirectiveService { + /** + * Creates an instance of DirectiveService. + * @param [apiClient=new ApiClient()] ApiClient + */ + constructor(apiClient: ApiClient); + + /** + * Send the specified directiveObj to Alexa directive service + * + * @param directive directive to send to service + * @param apiEndpoint API endpoint from Alexa request + * @param token bearer token for directive service + * @returns Promise + */ + enqueue(directive: object, apiEndpoint: string, token: string): Promise; + } + class ListManagementService { + /** + * Create an instance of ListManagementService + * @param apiClient apiClient + */ + constructor(apiClient: ApiClient); + + /** + * Set apiEndpoint address, default is "https://api.amazonalexa.com" + * @param apiEndpoint apiEndpoint + * @returns void + */ + setApiEndpoint(apiEndpoint: string): void; + + /** + * Get currently set apiEndpoint address + * @returns string + */ + getApiEndpoint(): string; + + /** + * Retrieve the metadata for all customer lists, including the customer's default lists + * @param token bearer token for list management permission + * @returns Promise + */ + getListsMetadata(token: string): Promise; + + /** + * Create a custom list. The new list name must be different than any existing list name + * @param listObject listObject + * @param token bearer token for list management permission + * @returns Promise + */ + createList(listObject: ListObject, token: string): Promise; + + /** + * Retrieve list metadata including the items in the list with requested status + * @param listId unique Id associated with the list + * @param itemStatus itemsStatus can be either "active" or "completed" + * @param token bearer token for list management permission + * @returns Promise + */ + getList(listId: string, itemStatus: ListItemObjectStatus, token: string): Promise; + + /** + * Update a custom list. Only the list name or state can be updated + * @param listId unique Id associated with the list + * @param listObject listObject + * @param token bearer token for list management permission + * @returns Promise + */ + updateList(listId: string, listObject: ListObject, token: string): Promise; + + /** + * Delete a custom list + * @param listId unique Id associated with the list + * @param token bearer token for list management permission + * @returns Promise + */ + deleteList(listId: string, token: string): Promise; + + /** + * Create an item in an active list or in a default list + * @param listId unique Id associated with the list + * @param listItemObject listItemObject + * @param token bearer token for list management permission + * @returns Promise + */ + createListItem(listId: string, listItemObject: ListItemObject, token: string): Promise; + + /** + * Retrieve single item within any list by listId and itemId + * @param listId unique Id associated with the list + * @param itemId unique Id associated with the item + * @param token bearer token for list management permission + * @returns Promise + */ + getListItem(listId: string, itemId: string, token: string): Promise; + + /** + * Update an item value or item status + * @param listId unique Id associated with the list + * @param itemId unique Id associated with the item + * @param listItemObject listItemObject + * @param token bearer token for list management permission + * @returns Promise + */ + updateListItem(listId: string, itemId: string, listItemObject: ListItemObject, token: string): Promise; + + /** + * Delete an item in the specified list + * @param listId unique Id associated with the list + * @param itemId unique Id associated with the item + * @param token bearer token for list management permission + * @returns Promise + */ + deleteListItem(listId: string, itemId: string, token: string): Promise; + } +} +//#endregion + +//#region ResponseBuilder +/** + * Responsible for building JSON responses as per the Alexa skills kit interface + * https://developer.amazon.com/public/solutions/alexa/alexa-skills-kit/docs/alexa-skills-kit-interface-reference#response-body-syntax + */ +export class ResponseBuilder { + constructor(alexaHandler: Handler); + + /** + * Have Alexa say the provided speechOutput to the user + * @param speechOutput speechOutput + * @returns ResponseBuilder + */ + speak(speechOutput: string): ResponseBuilder; + + /** + * Have alexa listen for speech from the user. If the user doesn't respond within 8 seconds + * then have alexa reprompt with the provided reprompt speech + * @param repromptSpeech repromptSpeech + * @returns ResponseBuilder + */ + listen(repromptSpeech: string): ResponseBuilder; + + /** + * Render a card with the following title, content and image + * @param cardTitle cardTitle + * @param cardContent cardContent + * @param cardImage cardImage + * @returns ResponseBuilder + */ + cardRenderer(cardTitle: string, cardContent: string, cardImage: CardImage): ResponseBuilder; + + /** + * Render a link account card + * @returns ResponseBuilder + */ + linkAccountCard(): ResponseBuilder; + + /** + * Render a askForPermissionsConsent card + * @param permissions permissions + * @returns ResponseBuilder + */ + askForPermissionsConsentCard(permissions: [{ [key: string]: string }]): ResponseBuilder; + + /** + * Creates a play, stop or clearQueue audioPlayer directive depending on the directive type passed in. + * @deprecated - use audioPlayerPlay, audioPlayerStop, audioPlayerClearQueue instead + * @param directiveType directiveType + * @param behavior behavior + * @param url url + * @param token token + * @param expectedPreviousToken expectedPreviousToken + * @param offsetInMilliseconds offsetInMilliseconds + * @returns ResponseBuilder + */ + audioPlayer(directiveType: string, behavior: string, url: string, token: string, expectedPreviousToken: string, offsetInMilliseconds: number): ResponseBuilder; + + /** + * Creates an AudioPlayer play directive + * @param behavior Describes playback behavior. Accepted values: + * REPLACE_ALL: Immediately begin playback of the specified stream, and replace current and enqueued streams. + * ENQUEUE: Add the specified stream to the end of the current queue. This does not impact the currently playing stream. + * REPLACE_ENQUEUED: Replace all streams in the queue. This does not impact the currently playing stream. + * @param url Identifies the location of audio content at a remote HTTPS location. + * The audio file must be hosted at an Internet-accessible HTTPS endpoint. HTTPS is required, and the domain hosting the + * files must present a valid, trusted SSL certificate. Self-signed certificates cannot be used. + * The supported formats for the audio file include AAC/MP4, MP3, HLS, PLS and M3U. Bitrates: 16kbps to 384 kbps. + * @param token A token that represents the audio stream. This token cannot exceed 1024 characters + * @param expectedPreviousToken A token that represents the expected previous stream. + * This property is required and allowed only when the playBehavior is ENQUEUE. This is used to prevent potential race conditions + * if requests to progress through a playlist and change tracks occur at the same time. + * @param offsetInMilliseconds The timestamp in the stream from which Alexa should begin playback. + * Set to 0 to start playing the stream from the beginning. Set to any other value to start playback from that associated point in the stream + * @returns ResponseBuilder + */ + audioPlayerPlay(behavior: string, url: string, token: string, expectedPreviousToken: string, offsetInMilliseconds: number): ResponseBuilder; + + /** + * Creates an AudioPlayer Stop directive - Stops the current audio Playback + * @returns ResponseBuilder + */ + audioPlayerStop(): ResponseBuilder; + + /** + * Creates an AudioPlayer ClearQueue directive - clear the queue without stopping the currently playing stream, + * or clear the queue and stop any currently playing stream. + * @param clearBehavior Describes the clear queue behavior. Accepted values: + * CLEAR_ENQUEUED: clears the queue and continues to play the currently playing stream + * CLEAR_ALL: clears the entire playback queue and stops the currently playing stream (if applicable). + * @returns ResponseBuilder + */ + audioPlayerClearQueue(clearBehavior: string): ResponseBuilder; + + /** + * Creates a Display RenderTemplate Directive + * Use a template builder to generate a template object + * @param template template + * @returns ResponseBuilder + */ + renderTemplate(template: Template): ResponseBuilder; + + /** + * Creates a hint directive - show a hint on the screen of the echo show + * @param hintText text to show on the hint + * @param hintType (optional) Default value : PlainText + * @returns ResponseBuilder + */ + hint(hintText: string, hintType?: HintType): ResponseBuilder; + + /** + * Creates a VideoApp play directive to play a video + * @param source Identifies the location of video content at a remote HTTPS location. + * The video file must be hosted at an Internet-accessible HTTPS endpoint. + * @param metadata (optional) Contains an object that provides the + * information that can be displayed on VideoApp. + * @returns ResponseBuilder + */ + playVideo(source: string, metadata?: { title: string, subtitle: string }): ResponseBuilder; +} +//#endregion + +//#region directives +export namespace directives { + class VoicePlayerSpeakDirective { + header: { requestId: string }; + directive: { type: string, speech: string }; + /** + * Creates an instance of VoicePlayerSpeakDirective. + * @param requestId - requestId from which the call is originated from + * @param speechContent - Contents of the speech directive either in plain text or SSML. + */ + constructor(requestId: string, speechContent: string); + } +} +//#endregion + +//#region utils +export namespace utils { + namespace ImageUtils { + /** + * Creates an image object with a single source + * These images may be in either JPEG or PNG formats, with the appropriate file extensions. + * An image cannot be larger than 2 MB + * You must host the images at HTTPS URLs that are publicly accessible. + * widthPixels and heightPixels are optional - Do not include them unless they are exactly correct. + * By default, for Echo Show, size takes the value X_SMALL. If the other size values are included, + * then the order of precedence for displaying images begins with X_LARGE and proceeds downward, + * which means that larger images will be downscaled for display on Echo Show if provided. + * example : ImageUtils.makeImage("https://url/to/my/img.png", 300, 400, "SMALL", "image description") + * @param url url of the image + * @param widthPixels (optional) width of the image in pixels + * @param heightPixels (optional) height of the image in pixels + * @param size size of the image (X_SMALL, SMALL, MEDIUM, LARGE, X_LARGE) + * @param description text used to describe the image in a screen reader + * @returns Image + */ + function makeImage(url: string, widthPixels?: number, heightPixels?: number, size?: ImageSourceSize, description?: string): Image; + /** + * Creates an image object with a multiple sources, source images are provided as an array of image objects + * These images may be in either JPEG or PNG formats, with the appropriate file extensions. + * An image cannot be larger than 2 MB + * You must host the images at HTTPS URLs that are publicly accessible. + * widthPixels and heightPixels are optional - Do not include them unless they are exactly correct. + * By default, for Echo Show, size takes the value X_SMALL. If the other size values are included, + * then the order of precedence for displaying images begins with X_LARGE and proceeds downward, + * which means that larger images will be downscaled for display on Echo Show if provided. + * example : + * let imgArr = [ + * { "https://url/to/my/small.png", 300, 400, "SMALL" }, + * { "https://url/to/my/large.png", 900, 1200, "LARGE" }, + * ] + * ImageUtils.makeImage(imgArr, "image description") + * + * @param imgArr Array of Image + * @param description text used to describe the image in a screen reader + * @returns Image + */ + function makeImages(imgArr: Array<{ url: string, widthPixels?: number, heightPixels?: number, size: ImageSourceSize }>, description: string): Image; + } + /** + * Utility methods for building TextField objects + */ + namespace TextUtils { + /** + * Creates a plain TextField object with contents : text + * @param text contents of plain text object + * @returns TextField + */ + function makePlainText(text: string): TextField; + + /** + * Creates a rich TextField object with contents : text + * @param text text + * @returns TextField + */ + function makeRichText(text: string): TextField; + + /** + * Creates a textContent + * @param primaryText primary Text + * @param secondaryText secondary Text + * @param tertiaryText tertiary Text + * @returns TextContent + */ + function makeTextContent(primaryText: { type: TextContentType, text: string }, + secondaryText: { type: TextContentType, text: string }, tertiaryText: { type: TextContentType, text: string }): TextContent; + } +} +//#endregion diff --git a/types/alexa-sdk/tsconfig.json b/types/alexa-sdk/tsconfig.json index acc11c8263..d1932fa469 100644 --- a/types/alexa-sdk/tsconfig.json +++ b/types/alexa-sdk/tsconfig.json @@ -20,4 +20,4 @@ "index.d.ts", "alexa-sdk-tests.ts" ] -} \ No newline at end of file +} diff --git a/types/alexa-sdk/tslint.json b/types/alexa-sdk/tslint.json index 78f1939ba2..32a9916641 100644 --- a/types/alexa-sdk/tslint.json +++ b/types/alexa-sdk/tslint.json @@ -1,10 +1,11 @@ -{ "extends": "dtslint/dt.json", - "rules": { - "object-literal-shorthand": false, - "object-literal-key-quote": false, - "no-empty-interface": false, - "prefer-method-signature": false, - "object-literal-key-quotes": false, - "no-any": false - } +{ + "extends": "dtslint/dt.json", + "rules": { + "object-literal-shorthand": false, + "object-literal-key-quote": false, + "no-empty-interface": false, + "prefer-method-signature": false, + "object-literal-key-quotes": false, + "no-any": false + } } diff --git a/types/algoliasearch/algoliasearch-tests.ts b/types/algoliasearch/algoliasearch-tests.ts index 1786b07af7..0814b0fc03 100644 --- a/types/algoliasearch/algoliasearch-tests.ts +++ b/types/algoliasearch/algoliasearch-tests.ts @@ -121,12 +121,12 @@ let _algoliaQueryParameters: AlgoliaQueryParameters = { disableTypoToleranceOnAttributes: '', aroundLatLng: '', aroundLatLngViaIP: '', - aroundRadius: '', + aroundRadius: 0, aroundPrecision: 0, minimumAroundRadius: 0, - insideBoundingBox: '', + insideBoundingBox: [[0]], queryType: '', - insidePolygon: '', + insidePolygon: [[0]], removeWordsIfNoResults: '', advancedSyntax: false, optionalWords: [''], diff --git a/types/algoliasearch/index.d.ts b/types/algoliasearch/index.d.ts index f068fc4e22..49e66d2b59 100644 --- a/types/algoliasearch/index.d.ts +++ b/types/algoliasearch/index.d.ts @@ -49,6 +49,9 @@ declare namespace algoliasearch { */ params: string; } + interface AlgoliaMultiResponse { + results: AlgoliaResponse[]; + } /* Interface for the algolia client object */ @@ -71,8 +74,8 @@ declare namespace algoliasearch { indexName: string; query: string; params: AlgoliaQueryParameters; - }, - cb: (err: Error, res: any) => void + }[], + cb: (err: Error, res: AlgoliaMultiResponse) => void ): void; /** * Query on multiple index @@ -84,7 +87,7 @@ declare namespace algoliasearch { indexName: string; query: string; params: AlgoliaQueryParameters; - }): Promise; + }[]): Promise; /** * clear browser cache * https://github.com/algolia/algoliasearch-client-js#cache @@ -319,8 +322,8 @@ declare namespace algoliasearch { getLogs(options: LogsOptions): Promise; } /** - * Interface for the index algolia object - */ + * Interface for the index algolia object + */ interface AlgoliaIndex { /** * Gets a specific object @@ -783,7 +786,7 @@ declare namespace algoliasearch { * @param err() error callback * https://github.com/algolia/algoliasearch-client-js#search-in-an-index---search */ - search(params: AlgoliaQueryParameters): Promise; + search(params: AlgoliaQueryParameters): Promise; /** * Search in an index * @param params query parameter @@ -793,7 +796,7 @@ declare namespace algoliasearch { */ search( params: AlgoliaQueryParameters, - cb: (err: Error, res: any) => void + cb: (err: Error, res: AlgoliaResponse) => void ): void; /** * Search in an index @@ -809,8 +812,7 @@ declare namespace algoliasearch { }: { facetName: string; facetQuery: string; - } & AlgoliaQueryParameters - ): Promise; + } & AlgoliaQueryParameters): Promise; /** * Search in an index * @param params query parameter @@ -1071,8 +1073,8 @@ Interface describing options available for gettings the logs type?: string; } /** - * Describe the action object used for batch operation - */ + * Describe the action object used for batch operation + */ interface AlgoliaAction { /** * Type of the batch action @@ -1098,8 +1100,8 @@ Interface describing options available for gettings the logs body: {}; } /** - * Describes the option used when creating user key - */ + * Describes the option used when creating user key + */ interface AlgoliaApiKeyOptions { /** * Add a validity period. The key will be valid for a specific period of time (in seconds). @@ -1364,8 +1366,8 @@ Interface describing options available for gettings the logs } /** - * Describes the settings available for configure your index - */ + * Describes the settings available for configure your index + */ interface AlgoliaIndexSettings { /** * The list of attributes you want index @@ -1770,7 +1772,7 @@ Interface describing options available for gettings the logs * You can specify aroundRadius=all if you want to compute the geo distance without filtering in a geo area * https://github.com/algolia/algoliasearch-client-js#aroundradius */ - aroundRadius?: any; + aroundRadius?: number | 'all'; /** * Control the precision of a geo search * default: null @@ -1788,7 +1790,7 @@ Interface describing options available for gettings the logs * default: null * https://github.com/algolia/algoliasearch-client-js#insideboundingbox */ - insideBoundingBox?: string; + insideBoundingBox?: number[][]; /** * Selects how the query words are interpreted * default: 'prefixLast' @@ -1803,7 +1805,7 @@ Interface describing options available for gettings the logs * defauly: '' * https://github.com/algolia/algoliasearch-client-js#insidepolygon */ - insidePolygon?: string; + insidePolygon?: number[][]; /** * This option is used to select a strategy in order to avoid having an empty result page * default: 'none' diff --git a/types/amcharts/index.d.ts b/types/amcharts/index.d.ts index 0dae492a76..4bb6631292 100644 --- a/types/amcharts/index.d.ts +++ b/types/amcharts/index.d.ts @@ -1549,7 +1549,7 @@ If you do not set properties such as dashLength, lineAlpha, lineColor, etc - val /** Hides cursor. */ hideCursor(): void; /** You can force cursor to appear at specified cateogry or date. */ - showCursorAt(category: string): void; + showCursorAt(category: string | Date): void; /** Adds event listener of the type "changed" to the object. @param type Always "changed". @param handler Dispatched when cursor position is changed. "index" is a series index over which chart cursors currently is. "zooming" specifies if user is currently zooming (is selecting) the chart. mostCloseGraph property is set only when oneBalloonOnly is set to true.*/ @@ -1652,6 +1652,727 @@ If you do not set properties such as dashLength, lineAlpha, lineColor, etc - val zoomToIndexes(start: Date, end: Date): void; } + // AmAngularGauge Extension for AmChart to create gauge charts. + class AmAngularGauge extends AmChart { + /** When enabled, chart adds aria-label attributes to columns, bullets or map objects. You can control values of these labels using properties like accessibleLabel of AmGraph. Note, not all screen readers support these tags. We tested this mostly with NVDA Screen reader. WAI-ARIA is now official W3 standard, so in future more readers will handle this well. We will be improving accessibility on our charts, so we would be glad to hear your feedback. + @default true + */ + accessible: boolean; + + /** Description which will be added to node of SVG element. Most of the screen readers will read this description. */ + accessibleDescription: string; + + /** Description which is added to of a SVG element. Some of the screen readers will read this description. */ + accessibleTitle: string; + + /** Specifies, if class names should be added to chart elements. + @default false + */ + addClassNames: boolean; + + /** Uses the whole space of the canvas to draw the gauge. + @default true + */ + adjustSize: boolean; + + /** Array of Labels. Example of label object, with all possible properties: + {"x": 20, "y": 20, "text": "this is label", "align": "left", "size": 12, "color": "#CC0000", "alpha": 1, "rotation": 0, "bold": true, "url": "http://www.amcharts.com"} + @default [] + */ + allLabels: [Label] + + /** Array of arrows. */ + arrows: [GaugeArrow]; + + /** If you set it to true the chart will automatically monitor changes of display style of chart’s container (or any of it’s parents) and will render chart correctly if it is changed from none to block. We recommend setting it to true if you change this style at a run time, as it affects performance a bit. + @default false + */ + autoDisplay: boolean; + + /** Set this to false if you don't want chart to resize itself whenever its parent container size changes. + @default true + */ + autoResize: boolean; + + /** If you set it to true and your chart div (or any of the parent div) has css scale applied, the chart will position mouse at a correct position. Default value is false because this operation consumes some CPU and quite a few people are using css transfroms. + @default false + */ + autoTransform: boolean; + + /** Array of axes. + @default [GaugeAxis] + */ + axes: [GaugeAxis]; + + /** Opacity of background. Set it to >0 value if you want backgroundColor to work. However we recommend changing div's background-color style for changing background color. + @default 0 + */ + backgroundAlpha: number; + + /** Background color. You should set backgroundAlpha to >0 value in order background to be visible. We recommend setting background color directly on a chart's DIV instead of using this property. + @default #FFFFFF + */ + backgroundColor: string; + + /** The chart creates AmBalloon class itself. If you want to customize balloon, get balloon instance using this property, and then change balloon's properties. + @default AmBalloon + */ + balloon: AmBalloon; + + /** Opacity of chart's border. Value range is 0 - 1. + @default 0 + */ + borderAlpha: number; + + /** Color of chart's border. You should set borderAlpha >0 in order border to be visible. We recommend setting border color directly on a chart's DIV instead of using this property. + @default #000000 + */ + borderColor: string; + + /** This prefix is added to all class names which are added to all visual elements of a chart in case addClassNames is set to true. + @default amcharts + */ + classNamePrefix: string; + + /** In case you use gauge to create a clock, set this to true. + @default false + */ + clockWiseOnly: boolean; + + /** Text color. + @default #000000 + */ + color: string; + + /** Non-commercial version only. Specifies position of link to amCharts site. Allowed values are: top-left, top-right, bottom-left and bottom-right. + @default 'top - left' + */ + creditsPosition: string; + + /** A config object for Data Loader plugin. Please refer to the following page for more information. */ + dataLoader: Object; + + /** Array of data objects, for example: [{country:"US", value:524},{country:"UK", value:624},{country:"Lithuania", value:824}]. You can have any number of fields and use any field names. In case of AmMap, data provider should be MapData object. + + The data set data. + + Important: if you are using date/time-based category axis, the data points needs to come pre-ordered in ascending order. Data with incorrect order might result in visual and functional glitches on the chart. */ + dataProvider: [Object]; + + /** Decimal separator. + @default . + */ + decimalSeparator: string; + + /** Using this property you can add any additional information to SVG, like SVG filters or clip paths. The structure of this object should be identical to XML structure of a object you are adding, only in JSON format. */ + defs: Object; + + /** Export config. Specifies how export to image/data export/print/annotate menu will look and behave. You can find a lot of examples in amcharts/plugins/export folder. More details can be found here. */ + export: ExportSettings; + + /** Gauge face opacity. + @default 0 + */ + faceAlpha: number; + + /** Gauge face border opacity. + @default 0 + */ + faceBorderAlpha: number; + + /** Gauge face border color. + @default #555555 + */ + faceBorderColor: string; + + /** Gauge face border width. + @default 1 + */ + faceBorderWidth: number; + + /** Gauge face color, requires faceAlpha > 0 + @default #FAFAFA + */ + faceColor: string; + + /** Gauge face image-pattern. + Example: {"url":"../amcharts/patterns/black/pattern1.png", "width":4, "height":4} + fontFamily String Verdana Font family. + fontSize Number 11 Font size. */ + facePattern: Object; + + /** Gauge's horizontal position in pixel, origin is the center. Centered by default. */ + gaugeX: number; + + /** Gauge's vertical position in pixel, origin is the center. Centered by default. */ + gaugeY: number; + + /** If you set this to true, the lines of the chart will be distorted and will produce hand-drawn effect. Try to adjust chart.handDrawScatter and chart.handDrawThickness properties for a more scattered result. + @default false + */ + handDrawn: boolean; + + /** Defines by how many pixels hand-drawn line (when handDrawn is set to true) will fluctuate. + @default 2 + */ + handDrawScatter: number; + + /** Defines by how many pixels line thickness will fluctuate (when handDrawn is set to true). + @default 1 + */ + handDrawThickness: number; + + /** Time, in milliseconds after which balloon is hidden if the user rolls-out of the object. Might be useful for AmMap to avoid balloon flickering while moving mouse over the areas. Note, this is not duration of fade-out. Duration of fade-out is set in AmBalloon class. + @default 150 + */ + hideBalloonTime: number; + + /** Allows changing language easily. Note, you should include language js file from amcharts/lang or ammap/lang folder and then use variable name used in this file, like chart.language = "de"; Note, for maps this works differently - you use language only for country names, as there are no other strings in the maps application. */ + language: string; + + /** Legend of a chart. */ + legend: AmLegend; + + /** Read-only. Reference to the div of the legend. */ + legendDiv: HTMLElement; + + /** You can add listeners of events using this property. Example: listeners = [{"event":"dataUpdated", "method":handleEvent}]; + @default [Object] + */ + listeners: [Object]; + + /** Bottom spacing between chart and container. + @default 10 + */ + marginBottom: number; + + /** Left-hand spacing between chart and container. + @default 10 + */ + marginLeft: number; + + /** Right-hand spacing between chart and container. + @default 10 + */ + marginRight: number; + + /** Top spacing between chart and container. + @default 10 + */ + marginTop: number; + + /** Minimum radius of a gauge. + @default 10 + */ + minRadius: number; + + /** This setting affects touch-screen devices only. If a chart is on a page, and panEventsEnabled are set to true, the page won't move if the user touches the chart first. If a chart is big enough and occupies all the screen of your touch device, the user won’t be able to move the page at all. If you think that selecting/panning the chart or moving/pinching the map is a primary purpose of your users, you should set panEventsEnabled to true, otherwise - false. + @default true + */ + panEventsEnabled: boolean; + + /** Specifies absolute or relative path to amCharts files, i.e."amcharts/". (where all.js files are located) + If relative URLs are used, they will be relative to the current web page, displaying the chart. + You can also set path globally, using global JavaScript variable AmCharts_path.If this variable is set, and "path" is not set in chart config, the chart will assume the path from the global variable.This allows setting amCharts path globally.I.e.: + var AmCharts_path = "/libs/amcharts/"; + "path" parameter will be used by the charts to locate it's files, like images, plugins or patterns. + @default 'amcharts/' + */ + path: string; + + /** Specifies path to the folder where images like resize grips, lens and similar are. + + IMPORTANT: Since V3.14.12, you should use "path" to point to amCharts directory instead. The "pathToImages" will be automatically set and does not need to be in the chart config, unless you keep your images separately from other amCharts files. */ + pathToImages: string; + + /** Precision of percent values. -1 means percent values won't be rounded at all and show as they are. + @default 2 + */ + percentPrecision: number; + + /** Precision of values. -1 means values won't be rounded at all and show as they are. + @default -1 + */ + precision: number; + + /**Prefixes which are used to make big numbers shorter: 2M instead of 2000000, etc.Prefixes are used on value axes and in the legend.To enable prefixes, set usePrefixes property to true. + @default [{ "number": 1e+3, "prefix": "k" }, { "number": 1e+6, "prefix": "M" }, { "number": 1e+9, "prefix": "G" }, { "number": 1e+12, "prefix": "T" }, { "number": 1e+15, "prefix": "P" }, { "number": 1e+18, "prefix": "E" }, { "number": 1e+21, "prefix": "Z" }, { "number": 1e+24, "prefix": "Y" }] + */ + prefixesOfBigNumbers: [Object]; + + /** Prefixes which are used to make small numbers shorter: 2μ instead of 0.000002, etc.Prefixes are used on value axes and in the legend.To enable prefixes, set usePrefixes property to true. + @default [{ "number": 1e-24, "prefix": "y" }, { "number": 1e-21, "prefix": "z" }, { "number": 1e-18, "prefix": "a" }, { "number": 1e-15, "prefix": "f" }, { "number": 1e-12, "prefix": "p" }, { "number": 1e-9, "prefix": "n" }, { "number": 1e-6, "prefix": "μ" }, { "number": 1e-3, "prefix": "m" }] + */ + prefixesOfSmallNumbers: [Object]; + + /** If processTimeout is > 0, 1000 data items will be parsed at a time, then the chart will make pause and continue parsing data until it finishes. + @default 1000 + */ + processCount: number; + + /** If you set it to 1 millisecond or some bigger value, chart will be built in chunks instead of all at once. This is useful if you work with a lot of data and the initial build of the chart takes a lot of time, which freezes the whole web application by not allowing other processes to do their job while the chart is busy. + @default 0 + */ + processTimeout: number; + + /** A config object for Responsive plugin. Please refer to the following page for more information. */ + responsive: Object + + /** Duration of arrow animation. + @default 1 + */ + startDuration: number; + + /** Transition effect of the arrows, possible effects: easeOutSine, easeInSine, elastic, bounce. + @default easeInSine + */ + startEffect: string; + + /** Charts will use SVG icons (some are loaded from images folder and some are drawn inline) if browser supports SVG. his makes icons look good on retina displays on all resolutions. + @default true + */ + svgIcons: boolean; + + /** Charts which require gestures like swipe (charts with scrollbar/cursor) or pinch (maps) used to prevent regular page scrolling and could result page to stick to the same spot if the chart occupied whole screen. Now, in order these gestures to start working user has to touch the chart/maps once. Regular touch events like touching on the bar/slice/map area do not require the first tap and will show balloons and perform other tasks as usual. If you have a map or chart which occupies full screen and your page does not require scrolling, set tapToActivate to false – this will bring old behavior back. + @default true + */ + tapToActivate: boolean; + + /** Theme of a chart. Config files of themes can be found in amcharts/themes/ folder. More info about using themes. + @default none + */ + theme: string; + + /** Thousands separator. + @default , + */ + thousandsSeparator: string; + + /** Array of Title objects. + @default [] + */ + titles: [Title]; + + /** If you set it to 200 (milliseconds) or so, the chart will fire clickGraphItem or clickSlice (AmSlicedChart) or clickMapObject only if user holds his/her finger for 0.2 seconds (200 ms) on the column/bullet/slice/map object. + @default 0 + */ + touchClickDuration: number; + + /** Type of a chart. Required when creating chart using JSON. Possible types are: serial, pie, xy, radar, funnel, gauge, map, gantt, stock. */ + type: string; + + /** If true, prefixes will be used for big and small numbers.You can set arrays of prefixes via prefixesOfSmallNumbers and prefixesOfBigNumbers properties. + @default false + */ + usePrefixes: boolean; + + /** Read-only. Indicates current version of a script. */ + version: string; + + /** Adds arrow to the chart. */ + addArrow(arrow: GaugeArrow): void; + + /** Adds axis to angular gauge. */ + addAxis(axis: GaugeAxis): void; + + /** Adds a label on a chart. You can use it for labeling axes, adding chart title, etc. x and y coordinates can be set in number, percent, or a number with ! in front of it - coordinate will be calculated from right or bottom instead of left or top. */ + addLabel(x: number, y: number, text: string, align: string, size: number, color: string, rotation: number, alpha: number, bold: boolean, url: string): void; + + /** Adds a legend to the chart. By default, you don't need to create div for your legend, however if you want it to be positioned in some different way, you can create div anywhere you want and pass id or reference to your div as a second parameter. (NOTE: This method will not work on StockPanel.) */ + addLegend(legend: AmLegend, legendDivId?: string): void; + /** Adds a legend to the chart. + By default, you don't need to create div for your legend, however if you want it to be positioned in some different way, you can create div anywhere you want and pass id or reference to your div as a second parameter. + (NOTE: This method will not work on StockPanel.) + @param legend + @param legendDiv - Legend div (optional). + */ + addLegend(legend: AmLegend, legendDiv: HTMLElement): void; + + /** Adds event listener to the object. */ + addListener(type: string, handler: Function): void; + + /** Adds title to the top of the chart. Pie, Radar positions are updated so that they won't overlap. Plot area of Serial/XY chart is also updated unless autoMargins property is set to false. You can add any number of titles - each of them will be placed in a new line. To remove titles, simply clear titles array: chart.titles = []; and call chart.validateNow() method. */ + addTitle(text: string, size: number, color: string, alpha: number, bold: boolean): void; + + /** Clears the chart area, intervals, etc. */ + clear(): void; + + /** Removes all labels added to the chart. */ + clearLabels(): void; + + /** Use this method to force the chart to resize to it's current container size. */ + invalidateSize(): void; + + /** This method allows to create charts with a single config. */ + makeChart(container: string, config: any, delay: number): AmChart; + + /** Removes arrow from the chart. */ + removeArrow(arrow: GaugeArrow): void; + + /** Removes axis from the chart. */ + removeAxis(axis: GaugeAxis): void; + + /** Removes chart's legend. */ + removeLegend(): void; + + /** Removes event listener from chart object. */ + removeListener(chart: AmChart, type: string, handler: any): void; + + /** This method should be called after data in your data provider changed or a new array was set to dataProvider. After calling this method the chart will parse data and redraw. */ + validateData(): void; + + /** This method should be called after you changed one or more properties of any class. The chart will redraw after this method is called.Both attributes, validateData and skipEvents are optional (false by default). */ + validateNow(): void; + + /** Adds chart to the specified DIV. + @param container DIV object which will hold the chart. */ + write(container: HTMLElement): void; + /** Adds chart to the specified DIV. + @param container Id of a DIV which will hold the chart. */ + write(container: string): void; + } + + class GaugeArrow { + /** Opacity of an arrow. + @default 1 + */ + alpha: number; + + /** Axis of the arrow. You can use reference to the axis or id of the axis. If you don't set any axis, the first axis of a chart will be used. + @default GaugeAxis + */ + axis: GaugeAxis + + /** Opacity of arrow border. + @default 1 + */ + borderAlpha: number; + + /** In case you need the arrow to rotate only clock-wise, set this property to true. + @default false + */ + clockWiseOnly: boolean; + + /** Color of an arrow. + @default #000000 + */ + color: string; + + /** Unique id of an arrow. */ + id: string; + + /** Inner radius of an arrow. + @default 0 + */ + innerRadius: any; + + /** Opacity of a nail, holding the arrow. + @default 1 + */ + nailAlpha: number; + + /** Opacity of nail border. + @default 0 + */ + nailBorderAlpha: number; + + /** Thickness of nail border. + @default 1 + */ + nailBorderThickness: number; + + /** Radius of a nail, holding the arrow. + @default 8 + */ + nailRadius: number; + + /** Radius of an arrow. + @default '90%' + */ + radius: any; + + /** Width of arrow root. + @default 8 + */ + startWidth: number; + + /** Value to which the arrow should point at. */ + value: number; + + /** Sets value for the arrow. Arrow will animate to this value if you do it after chart is written to it's container. */ + setValue(value: number): void; + } + + class GaugeAxis { + /** Axis opacity. + @default 1 + */ + axisAlpha: number; + + /** Axis color. + @default #000000 + */ + axisColor: string; + + /** Thickness of the axis outline. + @default 1 + */ + axisThickness: number; + + /** Opacity of band fills. + @default 1 + */ + bandAlpha: number; + + /** Example: [-0.2, 0, -0.2]. Will make bands to be filled with color gradients. Negative value means the color will be darker than the original, and positive number means the color will be lighter. + @default [] + */ + bandGradientRatio: [number]; + + /** Opacity of band outlines. + @default 0 + */ + bandOutlineAlpha: number; + + /** Color of band outlines. + @default #000000 + */ + bandOutlineColor: string; + + /** Thickness of band outlines. + @default 0 + */ + bandOutlineThickness: number; + + /** Array of bands - GaugeBand objects. Bands are used to draw color fills between specified values. */ + bands: [GaugeBand]; + + /** Text displayed below the axis center. */ + bottomText: string; + + /** Specifies if text should be bold. + @default true + */ + bottomTextBold: boolean; + + /** Bottom text color. */ + bottomTextColor: string; + + /** Font size of bottom text. */ + bottomTextFontSize: number; + + /** Y offset of bottom text. + @default 0 + */ + bottomTextYOffset: number; + + /** X position of the axis, relative to the center of the gauge. + @default '0%' + */ + centerX: any; + + /** Y position of the axis, relative to the center of the gauge. + @default '0%' + */ + centerY: any; + + /** Specifies labels color of the axis. */ + color: string + + /** Axis end angle. Valid values are from - 180 to 180. + @default 120 + */ + endAngle: number; + + /** Axis end (max) value */ + endValue: number; + + /** Font size for axis labels. */ + fontSize: number; + + /** Number of grid lines. Note, GaugeAxis doesn't adjust gridCount, so you should check your values and choose a proper gridCount which would result grids at round numbers. + @default 5 + */ + gridCount: number; + + /** Specifies if grid should be drawn inside or outside the axis. + @default true + */ + gridInside: boolean; + + /** Unique id of an axis. */ + id: any; + + /** Specifies if labels should be placed inside or outside the axis. + @default true + */ + inside: boolean; + + /** Frequency of labels. + @default 1 + */ + labelFrequency: number; + + /** You can use this function to format axis labels. This function is called and value is passed as a attribute: labelFunction(value); */ + labelFunction: Function; + + /** Distance from axis to the labels. + @default 15 + */ + labelOffset: number; + + /** Specifies if labels on the axis should be shown. + @default true + */ + labelsEnabled: boolean; + + /** You can add listeners of events using this property. Example: listeners = [{"event":"clickBand", "method":handleClick}]; */ + listeners: Object[]; + + /** Interval, at which minor ticks should be placed. */ + minorTickInterval: number; + + /** Length of a minor tick. + @default 5 + */ + minorTickLength: number + + /** Axis radius. + @default '95%' + */ + radius: any; + + /** Specifies if the first label should be shown. + @default true + */ + showFirstLabel: boolean; + + /** Specifies if the last label should be shown. + @default true + */ + showLastLabel: boolean; + + /** Axis start angle. Valid values are from - 180 to 180. + @default -120 + */ + startAngle: number; + + /** Axis start (min) value. + @default 0 + */ + startValue: number; + + /** Opacity of axis ticks. + @default 1 + */ + tickAlpha: number; + + /** Color of axis ticks. + @default #555555 + */ + tickColor: string; + + /** Length of a major tick. + @default 10 + */ + tickLength: number; + + /** Tick thickness. + @default 1 + */ + tickThickness: number; + + /** Text displayed above the axis center. */ + topText: string + + /** Specifies if text should be bold. + @default true + */ + topTextBold: boolean; + + /** Color of top text. */ + topTextColor: string + + /** Font size of top text. */ + topTextFontSize: number + + /** Y offset of top text. + @default 0 + */ + topTextYOffset: number; + + /** A string which can be placed next to axis labels. */ + unit: string; + + /** Position of the unit. + @default right + */ + unitPosition: string; + + /** Specifies if small and big numbers should use prefixes to make them more readable. + @default false + */ + usePrefixes: boolean; + + /** Interval, at which ticks with values should be placed. */ + valueInterval: number; + + /** Adds event listener to the object. */ + addListener(type: string, handler: any); + + /** Removes event listener from chart object. */ + removeListener(chart: AmChart, type: string, handler: any); + + /** Sets bottom text. */ + setBottomText(text: string); + + /** Sets top text. */ + setTopText(textstring); + + /** Returns angle of the value. */ + value2angle(value: number); + } + + class GaugeBand { + /** Opacity of band fill. Will use axis.bandAlpha if not set any. */ + alpha: number; + + /** When rolled-over, band will display balloon if you set some text for this property. */ + balloonText: string; + + /** Color of a band. */ + color: string; + + /** End value of a fill. */ + endValue: number + + /** Example: [-0.2, 0, -0.2]. Will make bands to be filled with color gradients. Negative value means the color will be darker than the original, and positive number means the color will be lighter. + @default [] + */ + gradientRatio: [number]; + + /** Unique id of a band. */ + id: string; + + /** Inner radius of a band. If not set any, the band will end with the end of minor ticks. Set 0 if you want the band to be drawn to the axis center. */ + innerRadius: any; + + /** Band radius. If not set any, the band will start with the axis outline. */ + radius: any; + + /** Start value of a fill. */ + startValue: number; + + /** Gauge band can be clickable and can lead to some page. */ + url: string; + + /** Sets end value for the band. */ + setEndValue(value); + + /** Sets start value for the band. */ + setStartValue(value); + } + class PeriodSelector { /** Date format of date input fields. Check [[http://help.adobe.com/en_US/FlashPlatform/reference/actionscript/3/mx/formatters/DateFormatter.html DD-MM-YYYY */ dateFormat: string; diff --git a/types/angular-websocket/angular-websocket-tests.ts b/types/angular-websocket/angular-websocket-tests.ts index 1df77b7a2a..51246c529a 100644 --- a/types/angular-websocket/angular-websocket-tests.ts +++ b/types/angular-websocket/angular-websocket-tests.ts @@ -1,69 +1,62 @@ -let dummySocket: ng.websocket.IWebSocket; -let dummyPromise: ng.IPromise; -let dummyScope: ng.IScope; +import * as ng from 'angular'; -let provider: ng.websocket.IWebSocketProvider = (url: string, protocols?:string[] | ng.websocket.IWebSocketConfigOptions, options?: ng.websocket.IWebSocketConfigOptions) => { - return dummySocket; -} +(promise: angular.IPromise, scope: ng.IScope, provider: ng.websocket.IWebSocketProvider) => { + const socket = provider("wss://localhost"); + const socketWithProtocols = provider("wss://localhost", ["protocol-a", "protocol-b"]); -let socketWithProtocol = provider("wss://localhost", "protocol"); -let socketWithProtocols = provider("wss://localhost", ["protocol-a", "protocol-b"]); + const socketWithOptions = provider("wss://localhost", { + scope, + rootScopeFailOver: true, + useApplyAsync: true, + initialTimeout: 100, + maxTimeout: 300000, + reconnectIfNotNormalClose: true, + binaryType: "blob" + }); -let socketWithOptions = provider("wss://localhost", { - scope: dummyScope, - rootScopeFailOver: true, - useApplyAsync: true, - initialTimeout: 100, - maxTimeout: 300000, - reconnectIfNotNormalClose: true, - binaryType: "blob" -}); + const socketWithProtocolAndOptions = provider("wss://localhost", "protocol", { + scope, + rootScopeFailOver: true, + useApplyAsync: true, + initialTimeout: 100, + maxTimeout: 300000, + reconnectIfNotNormalClose: true, + binaryType: "blob" + }); -let socketWithProtocolAndOptions = provider("wss://localhost", "protocol", { - scope: dummyScope, - rootScopeFailOver: true, - useApplyAsync: true, - initialTimeout: 100, - maxTimeout: 300000, - reconnectIfNotNormalClose: true, - binaryType: "blob" -}); + socket.onOpen((event: Event) => {}) + .onClose((event: Event) => {}) + .onError((event: Event) => {}) + .onMessage((event: Event) => {}); -let socket = provider("wss://localhost"); + socket.onMessage((event: Event) => {}, { filter: /Some Filter/ }) + .onMessage((event: Event) => {}, { filter: 'Some Filter' }) + .onMessage((event: Event) => {}, { filter: 'Some Filter', autoApply: true }) + .onMessage((event: Event) => {}, { autoApply: false }); -socket.onOpen((event) => {}) - .onClose((event) => {}) - .onError((event) => {}) - .onMessage((event) => {}); + socket.close(true); + socket.close(); -socket.onMessage((event) => {}, { filter: /Some Filter/ }) - .onMessage((event) => {}, { filter: 'Some Filter' }) - .onMessage((event) => {}, { filter: 'Some Filter', autoApply: true }) - .onMessage((event) => {}, { autoApply: false }); + socket.send("Some great data here!").finally(() => {}); + socket.send({ list: [1, 2, 3, 4] }); -socket.close(true); -socket.close(); + socket.socket.send("data"); + socket.socket.close(); + socket.socket.close(1); + socket.socket.close(1, "reason"); -socket.send("Some great data here!").finally(() => {}); -socket.send({ list: [1, 2, 3, 4] }); + socket.sendQueue.push({ message: "msg", defered: promise }); -socket.socket.send("data"); -socket.socket.close(); -socket.socket.close(1); -socket.socket.close(1, "reason"); + socket.onOpenCallbacks.push((event: Event) => {}); + socket.onCloseCallbacks.push((event: CloseEvent) => {}); + socket.onErrorCallbacks.push((event: Event) => {}); + socket.onMessageCallbacks.push({ fn: (event: MessageEvent) => {}, pattern: 'Some Filter', autoApply: true }); + socket.onMessageCallbacks.push({ fn: (event: MessageEvent) => {}, pattern: /Some Filter/, autoApply: true }); + socket.onMessageCallbacks.push({ fn: (event: MessageEvent) => {}, autoApply: true }); -socket.sendQueue.push({ message: "msg", defered: dummyPromise }); + socket.readyState = 0; -socket.onOpenCallbacks.push((event: Event) => {}); -socket.onCloseCallbacks.push((event: CloseEvent) => {}); -socket.onErrorCallbacks.push((event: Event) => {}); -socket.onMessageCallbacks.push({ fn: (event: MessageEvent) => {}, pattern: 'Some Filter', autoApply: true }); -socket.onMessageCallbacks.push({ fn: (event: MessageEvent) => {}, pattern: /Some Filter/, autoApply: true }); -socket.onMessageCallbacks.push({ fn: (event: MessageEvent) => {}, pattern: undefined, autoApply: true }); - -socket.readyState = 0; - -socket.initialTimeout = 10; - -socket.maxTimeout = 5000; + socket.initialTimeout = 10; + socket.maxTimeout = 5000; +}; diff --git a/types/angular-websocket/index.d.ts b/types/angular-websocket/index.d.ts index b7b3f55093..0b26bd2cfd 100644 --- a/types/angular-websocket/index.d.ts +++ b/types/angular-websocket/index.d.ts @@ -1,39 +1,45 @@ -// Type definitions for angular-websocket v2.0 +// Type definitions for angular-websocket 2.0 // Project: https://github.com/AngularClass/angular-websocket // Definitions by: Nick Veys // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped // TypeScript Version: 2.3 -import * as ng from "angular"; +import * as angular from "angular"; + +export type IWebSocketConfigOptions = angular.websocket.IWebSocketConfigOptions; +export type IWebSocketProvider = angular.websocket.IWebSocketProvider; +export type IWebSocketMessageOptions = angular.websocket.IWebSocketMessageOptions; +export type IWebSocketMessageHandler = angular.websocket.IWebSocketMessageHandler; +export type IWebSocketQueueItem = angular.websocket.IWebSocketQueueItem; +export type IWebSocket = angular.websocket.IWebSocket; declare module "angular" { namespace websocket { - /** * Options available to be specified for IWebSocketProvider. */ - type IWebSocketConfigOptions = { - scope?: ng.IScope; - rootScopeFailOver?: boolean; - useApplyAsync?: boolean; - initialTimeout?: number; - maxTimeout?: number; - binaryType?: "blob" | "arraybuffer"; - reconnectIfNotNormalClose?: boolean; - } - interface IWebSocketProvider { - /** - * Creates and opens an IWebSocket instance. - * - * @param url url to connect to - * @return websocket instance - */ - (url: string, protocols?: string | string[] | IWebSocketConfigOptions, options?: IWebSocketConfigOptions): IWebSocket; + interface IWebSocketConfigOptions { + scope?: IScope; + rootScopeFailOver?: boolean; + useApplyAsync?: boolean; + initialTimeout?: number; + maxTimeout?: number; + binaryType?: "blob" | "arraybuffer"; + reconnectIfNotNormalClose?: boolean; } + /** + * Creates and opens an IWebSocket instance. + * + * @param url url to connect to + * @return websocket instance + */ + type IWebSocketProvider = + (url: string, protocols?: string | string[] | IWebSocketConfigOptions, + options?: IWebSocketConfigOptions) => IWebSocket; + /** Options available to be specified for IWebSocket.onMessage */ - type IWebSocketMessageOptions = { - + interface IWebSocketMessageOptions { /** * If specified, only messages that match the filter will cause the message event * to be fired. @@ -44,21 +50,20 @@ declare module "angular" { autoApply?: boolean; } - /** Type corresponding to onMessage callbaks stored in $Websocket#onMessageCallbacks instance. */ - type IWebSocketMessageHandler = { - fn: (evt: MessageEvent) => void; - pattern: string | RegExp; - autoApply: boolean; + /** Type corresponding to onMessage callbacks stored in $Websocket#onMessageCallbacks instance. */ + interface IWebSocketMessageHandler { + fn: (evt: MessageEvent) => void; + pattern?: string | RegExp; + autoApply: boolean; } /** Type corresponding to items stored in $WebSocket#sendQueue instance. */ - type IWebSocketQueueItem = { - message: any; - defered: ng.IPromise; + interface IWebSocketQueueItem { + message: any; + defered: IPromise; } interface IWebSocket { - /** * Adds a callback to be executed each time a socket connection is opened for * this instance. @@ -108,7 +113,7 @@ declare module "angular" { * * @param data data to send, if this is an object, it will be stringified before sending */ - send(data: string | {}): ng.IPromise; + send(data: string | {}): IPromise; /** * WebSocket instance. @@ -123,7 +128,7 @@ declare module "angular" { /** * List of callbacks to be executed when the socket is opened. */ - onOpenCallbacks: ((evt: Event) => void)[]; + onOpenCallbacks: Array<((evt: Event) => void)>; /** * List of callbacks to be executed when a message is received from the socket. @@ -133,12 +138,12 @@ declare module "angular" { /** * List of callbacks to be executed when an error is received from the socket. */ - onErrorCallbacks: ((evt: Event) => void)[]; + onErrorCallbacks: Array<((evt: Event) => void)>; /** * List of callbacks to be executed when the socket is closed. */ - onCloseCallbacks: ((evt: CloseEvent) => void)[]; + onCloseCallbacks: Array<((evt: CloseEvent) => void)>; /** * Returns either the readyState value from the underlying WebSocket instance diff --git a/types/angular-websocket/tsconfig.json b/types/angular-websocket/tsconfig.json index 96aab30ef0..89d5cb9dc3 100644 --- a/types/angular-websocket/tsconfig.json +++ b/types/angular-websocket/tsconfig.json @@ -1,8 +1,4 @@ { - "files": [ - "index.d.ts", - "angular-websocket-tests.ts" - ], "compilerOptions": { "module": "commonjs", "lib": [ @@ -11,8 +7,8 @@ ], "noImplicitAny": true, "noImplicitThis": true, - "strictNullChecks": false, - "strictFunctionTypes": false, + "strictNullChecks": true, + "strictFunctionTypes": true, "baseUrl": "../", "typeRoots": [ "../" @@ -20,5 +16,9 @@ "types": [], "noEmit": true, "forceConsistentCasingInFileNames": true - } -} \ No newline at end of file + }, + "files": [ + "index.d.ts", + "angular-websocket-tests.ts" + ] +} diff --git a/types/angular-websocket/tslint.json b/types/angular-websocket/tslint.json index a41bf5d19a..2c7c1bed53 100644 --- a/types/angular-websocket/tslint.json +++ b/types/angular-websocket/tslint.json @@ -1,79 +1,6 @@ { "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 + "interface-name": false } } diff --git a/types/ansi-regex/ansi-regex-tests.ts b/types/ansi-regex/ansi-regex-tests.ts new file mode 100644 index 0000000000..a5787902f0 --- /dev/null +++ b/types/ansi-regex/ansi-regex-tests.ts @@ -0,0 +1,13 @@ +import ansiRegex = require("ansi-regex"); + +ansiRegex(); // $ExpectType RegExp + +// From the ansi-regex README.md +ansiRegex().test('\u001B[4mcake\u001B[0m'); // $ExpectType boolean +// => true + +ansiRegex().test('cake'); // $ExpectType boolean +// => false + +'\u001B[4mcake\u001B[0m'.match(ansiRegex()); // $ExpectType RegExpMatchArray | null +// => ['\u001B[4m', '\u001B[0m'] diff --git a/types/ansi-regex/index.d.ts b/types/ansi-regex/index.d.ts new file mode 100644 index 0000000000..34890912dc --- /dev/null +++ b/types/ansi-regex/index.d.ts @@ -0,0 +1,7 @@ +// Type definitions for ansi-regex 3.0 +// Project: https://github.com/chalk/ansi-regex#readme +// Definitions by: Manish Vachharajani +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +declare function r(): RegExp; +export = r; diff --git a/types/ansi-regex/tsconfig.json b/types/ansi-regex/tsconfig.json new file mode 100644 index 0000000000..cf1ac84a5c --- /dev/null +++ b/types/ansi-regex/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", + "ansi-regex-tests.ts" + ] +} diff --git a/types/react-native-elements/tslint.json b/types/ansi-regex/tslint.json similarity index 100% rename from types/react-native-elements/tslint.json rename to types/ansi-regex/tslint.json diff --git a/types/appdmg/appdmg-tests.ts b/types/appdmg/appdmg-tests.ts new file mode 100644 index 0000000000..47800d622f --- /dev/null +++ b/types/appdmg/appdmg-tests.ts @@ -0,0 +1,47 @@ +import appdmg = require("appdmg"); +import { Options, Specification, SpecificationOptions } from "appdmg"; + +const proc = appdmg({ + target: "/foo/bar.dmg", + basepath: "/baz", + specification: { + title: "Happy", + icon: "happy.icns", + background: "happy.tiff", + format: "UDBZ", + "icon-size": 98, + contents: [ + { + x: 405, + y: 150, + type: "link", + path: "/Applications" + }, + { + x: 127, + y: 150, + type: "file", + path: "/foo/bar.app" + } + ] + } +}); + +proc.on("progress", info => { + if (info.type === "step-begin") { + process.stdout.write(`${info.title}... `); + } + + if (info.type === "step-end") { + process.stdout.write(`${info.status}\n`); + } +}); + +proc.on("finish", () => { + console.log('Installer was created successfully!'); +}); + +proc.on("error", (err) => { + console.error('Installer could not be created', err); + process.exit(1); +}); diff --git a/types/appdmg/index.d.ts b/types/appdmg/index.d.ts new file mode 100644 index 0000000000..2e23009f44 --- /dev/null +++ b/types/appdmg/index.d.ts @@ -0,0 +1,70 @@ +// Type definitions for appdmg 0.5 +// Project: https://github.com/LinusU/node-appdmg#readme +// Definitions by: Daniel Perez Alvarez +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +/// + +declare namespace appdmg { + interface Progress { + current: number; + total: number; + type: "step-begin" | "step-end"; + title: string; + status: "ok" | "skip" | "fail"; + } + + interface EventEmitter extends NodeJS.EventEmitter { + on(event: "progress", listener: (info: Progress) => void): this; + on(event: "finish", listener: () => void): this; + on(event: "error", listener: (err: any) => void): this; + } + + interface SpecificationOptions { + app: string; + background: string; + icon: string; + iconSize: number; + title: string; + } + + interface SpecificationWindow { + position?: { x: number; y: number }; + size?: { width: number; height: number }; + } + + interface SpecificationContents { + x: number; + y: number; + type: "link" | "file" | "position"; + path: string; + name?: string; + } + + interface SpecificationCodeSign { + "signing-identity": string; + identifier?: string; + } + + interface Specification { + title: string; + icon?: string; + background?: string; + "background-color"?: string; + "icon-size"?: number; + window?: SpecificationWindow; + format: "UDRW" | "UDRO" | "UDCO" | "UDZO" | "UDBZ" | "ULFO"; + contents: SpecificationContents[]; + "code-sign"?: SpecificationCodeSign; + } + + interface Options { + target: string; + basepath: string; + specification: Specification; + } +} + +declare function appdmg(options?: appdmg.Options): appdmg.EventEmitter; + +export = appdmg; diff --git a/types/appdmg/tsconfig.json b/types/appdmg/tsconfig.json new file mode 100644 index 0000000000..f4ca0f95c5 --- /dev/null +++ b/types/appdmg/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", + "appdmg-tests.ts" + ] +} diff --git a/types/appdmg/tslint.json b/types/appdmg/tslint.json new file mode 100644 index 0000000000..3db14f85ea --- /dev/null +++ b/types/appdmg/tslint.json @@ -0,0 +1 @@ +{ "extends": "dtslint/dt.json" } diff --git a/types/applepayjs/applepayjs-tests.ts b/types/applepayjs/applepayjs-tests.ts index 505dbd2daf..99b323453b 100644 --- a/types/applepayjs/applepayjs-tests.ts +++ b/types/applepayjs/applepayjs-tests.ts @@ -22,7 +22,7 @@ describe("ApplePaySession", () => { }); it("can create a new instance", () => { const version = 1; - const paymentRequest = { + const paymentRequest: ApplePayJS.ApplePayPaymentRequest = { countryCode: "US", currencyCode: "USD", supportedNetworks: [ @@ -57,8 +57,8 @@ describe("ApplePaySession", () => { }); }); it("can call instance methods", () => { - const version = 1; - const paymentRequest = { + const version = 3; + const paymentRequest: ApplePayJS.ApplePayPaymentRequest = { countryCode: "US", currencyCode: "USD", supportedNetworks: [ @@ -66,7 +66,9 @@ describe("ApplePaySession", () => { "visa" ], merchantCapabilities: [ - "supports3DS" + "supports3DS", + "supportsCredit", + "supportsDebit" ], total: { label: "My Store", @@ -80,15 +82,29 @@ describe("ApplePaySession", () => { session.completeMerchantValidation({ foo: "bar" }); + session.completePayment(ApplePaySession.STATUS_SUCCESS); - const total = { + const authorizationResult: ApplePayJS.ApplePayPaymentAuthorizationResult = { + status: ApplePaySession.STATUS_FAILURE, + errors: [ + { + code: "addressUnserviceable", + contactField: "postalCode", + message: "The specified postal code cannot be delivered to." + } + ] + }; + + session.completePayment(authorizationResult); + + const total: ApplePayJS.ApplePayLineItem = { label: "Subtotal", type: "final", amount: "35.00" }; - const lineItems = [ + const lineItems: ApplePayJS.ApplePayLineItem[] = [ { label: "Subtotal", type: "final", @@ -97,11 +113,12 @@ describe("ApplePaySession", () => { { label: "Free Shipping", amount: "0.00", - type: "pending" + type: "final" }, { label: "Estimated Tax", - amount: "3.06" + amount: "3.06", + type: "pending" } ]; @@ -120,17 +137,35 @@ describe("ApplePaySession", () => { session.completePaymentMethodSelection(total, lineItems); + const paymentUpdate = { + newTotal: total + }; + + session.completePaymentMethodSelection(paymentUpdate); + session.completeShippingContactSelection( ApplePaySession.STATUS_INVALID_SHIPPING_POSTAL_ADDRESS, shippingMethods, total, lineItems); + const contactUpdate = { + newTotal: total + }; + + session.completeShippingContactSelection(contactUpdate); + session.completeShippingMethodSelection( ApplePaySession.STATUS_SUCCESS, total, lineItems); + const shippingUpdate = { + newTotal: total + }; + + session.completeShippingMethodSelection(shippingUpdate); + session.oncancel = (event: ApplePayJS.Event): void => { event.cancelBubble = true; }; @@ -201,7 +236,9 @@ describe("ApplePayPaymentRequest", () => { "1 Infinite Loop" ], locality: "Cupertino", + subLocality: "", administrativeArea: "CA", + subAdministrativeArea: "", postalCode: "95014", country: "United States", countryCode: "US" @@ -233,7 +270,7 @@ describe("ApplePayPaymentRequest", () => { "postalAddress", "name", "phone", - "email" + "name" ]; paymentRequest.shippingContact = { @@ -241,11 +278,15 @@ describe("ApplePayPaymentRequest", () => { familyName: "Patel", givenName: "Ravi", phoneNumber: "(408) 555-5555", + phoneticFamilyName: "Patel", + phoneticGivenName: "Ravi", addressLines: [ "1 Infinite Loop" ], locality: "Cupertino", + subLocality: "", administrativeArea: "CA", + subAdministrativeArea: "", postalCode: "95014", country: "United States", countryCode: "US" @@ -265,5 +306,6 @@ describe("ApplePayPaymentRequest", () => { ]; paymentRequest.shippingType = "storePickup"; + paymentRequest.shippingType = "delivery"; }); }); diff --git a/types/applepayjs/index.d.ts b/types/applepayjs/index.d.ts index f705a4fad2..a37f60b6fd 100644 --- a/types/applepayjs/index.d.ts +++ b/types/applepayjs/index.d.ts @@ -1,26 +1,26 @@ -// Type definitions for Apple Pay JS 1.0 +// Type definitions for Apple Pay JS 3.0 // Project: https://developer.apple.com/reference/applepayjs -// Definitions by: Martin Costello +// Definitions by: Martin Costello // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped /** - * A session object for managing the payment process on the web. + * ApplePaySession is the entry point for Apple Pay on the web. */ declare class ApplePaySession extends EventTarget { /** - * Creates a new instance of the ApplePaySession class. - * @param version - The version of the ApplePay JS API you are using. - * @param paymentRequest - An ApplePayPaymentRequest object that contains the information that is displayed on the Apple Pay payment sheet. + * The entry point for Apple Pay on the web. + * @param version - The version number of the ApplePay JS API you are using. The current API version number is 3. + * @param paymentRequest - An ApplePayPaymentRequest object that contains the information to be displayed on the Apple Pay payment sheet. */ constructor(version: number, paymentRequest: ApplePayJS.ApplePayPaymentRequest); /** - * A callback function that is automatically called when the payment UI is dismissed with an error. + * A callback function that is automatically called when the payment UI is dismissed. */ oncancel: (event: ApplePayJS.Event) => void; /** - * A callback function that is automatically called when the user has authorized the Apple Pay payment, typically via TouchID. + * A callback function that is automatically called when the user has authorized the Apple Pay payment with Touch ID, Face ID, or passcode. */ onpaymentauthorized: (event: ApplePayJS.ApplePayPaymentAuthorizedEvent) => void; @@ -45,28 +45,28 @@ declare class ApplePaySession extends EventTarget { onvalidatemerchant: (event: ApplePayJS.ApplePayValidateMerchantEvent) => void; /** - * Indicates whether or not the device supports Apple Pay. + * Indicates whether the device supports Apple Pay. * @returns true if the device supports making payments with Apple Pay; otherwise, false. */ static canMakePayments(): boolean; /** - * Indicates whether or not the device supports Apple Pay and if the user has an active card in Wallet. - * @param merchantIdentifier - The merchant ID received when the merchant enrolled in Apple Pay. - * @returns true if the device supports Apple Pay and there is at least one active card in Wallet; otherwise, false. + * Indicates whether the device supports Apple Pay and whether the user has an active card in Wallet. + * @param merchantIdentifier - The merchant ID created when the merchant enrolled in Apple Pay. + * @returns true if the device supports Apple Pay and there is at least one active card in Wallet that is qualified for payments on the web; otherwise, false. */ static canMakePaymentsWithActiveCard(merchantIdentifier: string): Promise; /** * Displays the Set up Apple Pay button. - * @param merchantIdentifier - The merchant ID received when the merchant enrolled in Apple Pay. + * @param merchantIdentifier - The merchant ID created when the merchant enrolled in Apple Pay. * @returns A boolean value indicating whether setup was successful. */ static openPaymentSetup(merchantIdentifier: string): Promise; /** - * Verifies if a web browser supports a given Apple Pay JS API version. - * @param version - A number representing the Apple Pay JS API version being checked. The initial version is 1. + * Verifies whether a web browser supports a given Apple Pay JS API version. + * @param version - A number representing the Apple Pay JS API version being checked. The initial version is 1. The latest version is 3. * @returns A boolean value indicating whether the web browser supports the given API version. Returns false if the web browser does not support the specified version. */ static supportsVersion(version: number): boolean; @@ -82,26 +82,33 @@ declare class ApplePaySession extends EventTarget { begin(): void; /** - * Call after the merchant has been validated. + * Completes the validation for a merchant session. * @param merchantSession - An opaque message session object. */ completeMerchantValidation(merchantSession: any): void; /** - * Call when a payment has been authorized. - * @param status - The status of the payment. + * Completes the payment authorization with a result. + * @param result - The status of the payment, whether it succeeded or failed for Apple Pay JS versions 1 and 2, + * or the result of the payment authorization, including its status and list of errors for Apple Pay JS version 3. */ - completePayment(status: number): void; + completePayment(result: number | ApplePayJS.ApplePayPaymentAuthorizationResult): void; /** - * Call after a payment method has been selected. + * Call after a payment method has been selected for Apple Pay JS versions 1 and 2. * @param newTotal - An ApplePayLineItem dictionary representing the total price for the purchase. * @param newLineItems - A sequence of ApplePayLineItem dictionaries. */ completePaymentMethodSelection(newTotal: ApplePayJS.ApplePayLineItem, newLineItems: ApplePayJS.ApplePayLineItem[]): void; /** - * Call after a shipping contact has been selected. + * Completes the selection of a payment method with an update for Apple Pay JS version 3. + * @param update - The updated payment method. + */ + completePaymentMethodSelection(update: ApplePayJS.ApplePayPaymentMethodUpdate): void; + + /** + * Completes the selection of a shipping contact with an update for Apple Pay JS versions 1 and 2. * @param status - The status of the shipping contact update. * @param newShippingMethods - A sequence of ApplePayShippingMethod dictionaries. * @param newTotal - An ApplePayLineItem dictionary representing the total price for the purchase. @@ -114,13 +121,25 @@ declare class ApplePaySession extends EventTarget { newLineItems: ApplePayJS.ApplePayLineItem[]): void; /** - * Call after the shipping method has been selected. + * Completes the selection of a shipping contact with an update for Apple Pay JS version 3. + * @param update - The updated shipping contact. + */ + completeShippingContactSelection(update: ApplePayJS.ApplePayShippingContactUpdate): void; + + /** + * Call after the shipping method has been selected for Apple Pay JS versions 1 and 2. * @param status - The status of the shipping method update. * @param newTotal - An ApplePayLineItem dictionary representing the total price for the purchase. * @param newLineItems - A sequence of ApplePayLineItem dictionaries. */ completeShippingMethodSelection(status: number, newTotal: ApplePayJS.ApplePayLineItem, newLineItems: ApplePayJS.ApplePayLineItem[]): void; + /** + * Completes the selection of a shipping method with an update for Apple Pay JS version 3. + * @param update - The updated shipping method. + */ + completeShippingMethodSelection(update: ApplePayJS.ApplePayShippingMethodUpdate): void; + /** * The requested action succeeded. */ @@ -163,6 +182,78 @@ declare class ApplePaySession extends EventTarget { } declare namespace ApplePayJS { + /** + * Field names used for requesting contact information in a payment request. + */ + type ApplePayContactField = + 'email' | + 'name' | + 'phone' | + 'postalAddress' | + 'phoneticName'; + + /** + * A customizable error type that you create to indicate problems with the address or contact information on an Apple Pay sheet. + */ + interface ApplePayError { + /** + * The error code for this instance. + */ + code: ApplePayErrorCode; + + /** + * The name of the field that contains the error. + */ + contactField?: ApplePayErrorContactField; + + /** + * A localized, user-facing string that describes the error. + */ + message: string; + } + + /** + * The error code that indicates whether an error on the payment sheet is for shipping or billing information, or for another kind of error. + */ + type ApplePayErrorCode = + /** + * Shipping address or contact information is invalid or missing. + */ + 'shippingContactInvalid' | + + /** + * Billing address information is invalid or missing. + */ + 'billingContactInvalid' | + + /** + * The merchant cannot provide service to the shipping address (for example, can't deliver to a P.O. Box). + */ + 'addressUnserviceable' | + + /** + * An unknown but nonfatal error occurred during payment processing. The user can attempt authorization again. + */ + 'unknown'; + + /** + * Names of the fields in the shipping or billing contact information, used to locate errors in the payment sheet. + */ + type ApplePayErrorContactField = + 'phoneNumber' | + 'emailAddress' | + 'name' | + 'phoneticName' | + 'postalAddress' | + 'addressLines' | + 'locality' | + 'subLocality' | + 'postalCode' | + 'administrativeArea' | + 'subAdministrativeArea' | + 'country' | + 'countryCode'; + /** * Defines a line item in a payment request - for example, total, tax, discount, or grand total. */ @@ -180,15 +271,53 @@ declare namespace ApplePayJS { /** * A value that indicates if the line item is final or pending. */ - type?: string; + type?: ApplePayLineItemType; } + /** + * A type that indicates whether a line item is final or pending. + */ + type ApplePayLineItemType = + /** + * A line item representing the known, final cost. + */ + 'final' | + + /** + * A line item representing an estimated or unknown cost. + */ + 'pending'; + + /** + * The payment capabilities supported by the merchant. + */ + type ApplePayMerchantCapability = + /** + * Required. This value must be supplied. + */ + 'supports3DS' | + + /** + * Include this value only if you support China Union Pay transactions. + */ + 'supportsEMV' | + + /** + * Optional. If present, only transactions that are categorized as credit cards are allowed. + */ + 'supportsCredit' | + + /** + * Optional. If present, only transactions that are categorized as debit cards are allowed. + */ + 'supportsDebit'; + /** * Represents the result of authorizing a payment request and contains encrypted payment information. */ interface ApplePayPayment { /** - * The encrypted token for an authorized payment. + * The encrypted information for an authorized payment. */ token: ApplePayPaymentToken; @@ -208,11 +337,26 @@ declare namespace ApplePayJS { */ abstract class ApplePayPaymentAuthorizedEvent extends Event { /** - * The payment token used to authorize a payment. + * The authorized payment information for this transaction. */ readonly payment: ApplePayPayment; } + /** + * The result of payment authorization, including status and errors. + */ + interface ApplePayPaymentAuthorizationResult { + /** + * The status code for the authorization result. + */ + status: number; + + /** + * A list of custom errors to display on the payment sheet. + */ + errors?: ApplePayError[]; + } + /** * Encapsulates contact information needed for billing and shipping. */ @@ -220,56 +364,76 @@ declare namespace ApplePayJS { /** * An email address for the contact. */ - emailAddress: string; + emailAddress?: string; /** * The contact's family name. */ - familyName: string; + familyName?: string; /** * The contact's given name. */ - givenName: string; + givenName?: string; /** * A phone number for the contact. */ - phoneNumber: string; + phoneNumber?: string; /** - * The address for the contact. + * The phonetic spelling of the contact's family name. */ - addressLines: string[]; + phoneticFamilyName?: string; + + /** + * The phonetic spelling of the contact's given name. + */ + phoneticGivenName?: string; + + /** + * The street portion of the address for the contact. + */ + addressLines?: string[]; /** * The city for the contact. */ - locality: string; + locality?: string; + + /** + * Additional information associated with the location, typically defined at the city or town level (such as district or neighborhood), in a postal address. + */ + subLocality?: string; /** * The state for the contact. */ - administrativeArea: string; + administrativeArea?: string; /** - * The zip code, where applicable, for the contact. + * The subadministrative area (such as a county or other region) in a postal address. */ - postalCode: string; + subAdministrativeArea?: string; /** - * The colloquial country name for the contact. + * The zip code or postal code, where applicable, for the contact. */ - country: string; + postalCode?: string; /** - * The contact's ISO country code. + * The name of the country for the contact. */ - countryCode: string; + country?: string; + + /** + * The contact’s two-letter ISO 3166 country code. + */ + countryCode?: string; } /** - * Contains information about an Apple Pay payment card. + * A dictionary that describes an Apple Pay payment card. */ interface ApplePayPaymentMethod { /** @@ -279,21 +443,29 @@ declare namespace ApplePayJS { /** * A string, suitable for display, that is the name of the payment network backing the card. - * The value is one of the supported networks specified in the supportedNetworks property of the ApplePayPaymentRequest. */ network: string; /** * A value representing the card's type of payment. */ - type: string; + type: ApplePayPaymentMethodType; /** - * The payment pass object associated with the payment. + * The payment pass object currently selected to complete the payment. */ paymentPass: ApplePayPaymentPass; } + /** + * A payment card's type of payment. + */ + type ApplePayPaymentMethodType = + 'debit' | + 'credit' | + 'prepaid' | + 'store'; + /** * The ApplePayPaymentMethodSelectedEvent class defines the attributes contained by the ApplePaySession.onpaymentmethodselected callback function. */ @@ -304,6 +476,21 @@ declare namespace ApplePayJS { readonly paymentMethod: ApplePayPaymentMethod; } + /** + * Updated transaction details resulting from a change in payment method. + */ + interface ApplePayPaymentMethodUpdate { + /** + * An optional list of line items. + */ + newLineItems?: ApplePayLineItem[]; + + /** + * The new total resulting from a change in the payment method. + */ + newTotal: ApplePayLineItem; + } + /** * Represents a provisioned payment card for Apple Pay payments. */ @@ -331,9 +518,38 @@ declare namespace ApplePayJS { /** * The activation state of the pass. */ - activationState: string; + activationState: ApplePayPaymentPassActivationState; } + /** + * Payment pass activation states. + */ + type ApplePayPaymentPassActivationState = + /** + * Active and ready to be used for payment. + */ + 'activated' | + + /** + * Not active but may be activated by the issuer. + */ + 'requiresActivation' | + + /** + * Not ready for use but activation is in progress. + */ + 'activating' | + + /** + * Not active and can't be activated. + */ + 'suspended' | + + /** + * Not active because the issuer has disabled the account associated with the device. + */ + 'deactivated'; + /** * Encapsulates a request for payment, including information about payment processing capabilities, the payment amount, and shipping information. */ @@ -357,7 +573,7 @@ declare namespace ApplePayJS { * The payment capabilities supported by the merchant. * The value must at least contain ApplePayMerchantCapability.supports3DS. */ - merchantCapabilities: string[]; + merchantCapabilities: ApplePayMerchantCapability[]; /** * The payment networks supported by the merchant. @@ -377,12 +593,12 @@ declare namespace ApplePayJS { /** * The billing information that you require from the user in order to process the transaction. */ - requiredBillingContactFields?: string[]; + requiredBillingContactFields?: ApplePayContactField[]; /** * The shipping information that you require from the user in order to fulfill the order. */ - requiredShippingContactFields?: string[]; + requiredShippingContactFields?: ApplePayContactField[]; /** * Shipping contact information for the user. @@ -397,7 +613,12 @@ declare namespace ApplePayJS { /** * How the items are to be shipped. */ - shippingType?: string; + shippingType?: ApplePayShippingType; + + /** + * A list of ISO 3166 country codes for limiting payments to cards from specific countries. + */ + supportedCountries?: string[]; /** * Optional user-defined data. @@ -406,7 +627,7 @@ declare namespace ApplePayJS { } /** - * Contains the user's payment credentials. + * An object that contains the user's payment credentials. */ interface ApplePayPaymentToken { /** @@ -426,7 +647,7 @@ declare namespace ApplePayJS { } /** - * The ApplePayShippingContactSelectedEvent class defines the attributes contained by the ApplePaySession.onshippingcontactselected callback function. + * Encapsulates the attributes contained by the onshippingcontactselected callback function. */ abstract class ApplePayShippingContactSelectedEvent extends Event { /** @@ -435,6 +656,31 @@ declare namespace ApplePayJS { readonly shippingContact: ApplePayPaymentContact; } + /** + * Updated transaction details resulting from a change in shipping contact, including any errors. + */ + class ApplePayShippingContactUpdate { + /** + * List of custom errors to display on the payment sheet. + */ + errors?: ApplePayError[]; + + /** + * An optional list of updated line items. + */ + newLineItems?: ApplePayLineItem[]; + + /** + * A list of shipping methods that are available to the updated shipping contact. + */ + newShippingMethods?: ApplePayShippingMethod[]; + + /** + * The new total resulting from a change in the shipping contact. + */ + newTotal: ApplePayLineItem; + } + /** * Defines a shipping method for delivering physical goods. */ @@ -471,11 +717,35 @@ declare namespace ApplePayJS { } /** - * The ApplePayValidateMerchantEvent class defines the attributes contained by the ApplePaySession.onvalidatemerchant callback function. + * Updated transaction details resulting from a change in shipping method. + */ + interface ApplePayShippingMethodUpdate { + /** + * An optional list of updated line items. + */ + newLineItems?: ApplePayLineItem[]; + + /** + * The new total resulting from a change in the shipping method. + */ + newTotal: ApplePayLineItem; + } + + /** + * A type that indicates how purchased items are to be shipped. + */ + type ApplePayShippingType = + 'shipping' | + 'delivery' | + 'storePickup' | + 'servicePickup'; + + /** + * The attributes contained by the onvalidatemerchant callback function. */ abstract class ApplePayValidateMerchantEvent extends Event { /** - * The URL used to validate the merchant server. + * The URL your server must use to validate itself and obtain a merchant session object. */ readonly validationURL: string; } diff --git a/types/ascii2mathml/ascii2mathml-tests.ts b/types/ascii2mathml/ascii2mathml-tests.ts index 7280900922..cbd63e649f 100644 --- a/types/ascii2mathml/ascii2mathml-tests.ts +++ b/types/ascii2mathml/ascii2mathml-tests.ts @@ -1,6 +1,6 @@ import * as ascii2mathml from 'ascii2mathml'; -const fn = ascii2mathml({}); // $ExpectType any +const fn = ascii2mathml({}); // $ExpectType ascii2mathml fn(''); // $ExpectType string ascii2mathml('', {}); // $ExpectType string diff --git a/types/asynciterator/index.d.ts b/types/asynciterator/index.d.ts index a7be809137..950fb16bbd 100644 --- a/types/asynciterator/index.d.ts +++ b/types/asynciterator/index.d.ts @@ -9,16 +9,16 @@ import { EventEmitter } from "events"; export abstract class AsyncIterator extends NodeJS.EventEmitter { - protected static STATES: ['INIT', 'OPEN', 'CLOSING', 'CLOSED', 'ENDED']; - protected static INIT: 0; - protected static OPEN: 1; - protected static CLOSING: 2; - protected static CLOSED: 3; - protected static ENDED: 4; + static STATES: ['INIT', 'OPEN', 'CLOSING', 'CLOSED', 'ENDED']; + static INIT: 0; + static OPEN: 1; + static CLOSING: 2; + static CLOSED: 3; + static ENDED: 4; - protected _state: number; - protected _readable: boolean; - protected _destination?: AsyncIterator; + _state: number; + _readable: boolean; + _destination?: AsyncIterator; readable: boolean; closed: boolean; @@ -30,11 +30,11 @@ export abstract class AsyncIterator extends NodeJS.EventEmitter { each(callback: (data: T) => void, self?: any): void; close(): void; - protected _changeState(newState: number, eventAsync?: boolean): void; + _changeState(newState: number, eventAsync?: boolean): void; private _hasListeners(eventName: string | symbol): boolean; // tslint:disable-next-line ban-types private _addSingleListener(eventName: string | symbol, listener: Function): void; - protected _end(): void; + _end(): void; getProperty(propertyName: string, callback?: (value: any) => void): any; setProperty(propertyName: string, value: any): void; @@ -43,7 +43,7 @@ export abstract class AsyncIterator extends NodeJS.EventEmitter { copyProperties(source: AsyncIterator, propertyNames: string[]): void; toString(): string; - protected _toStringDetails(): string; + _toStringDetails(): string; transform(options?: SimpleTransformIteratorOptions): SimpleTransformIterator; map(mapper: (item: T) => T2, self?: object): SimpleTransformIterator; @@ -78,9 +78,9 @@ export interface IntegerIteratorOptions { } export class IntegerIterator extends AsyncIterator { - protected _step: number; - protected _last: number; - protected _next: number; + _step: number; + _last: number; + _next: number; constructor(options?: IntegerIteratorOptions); } @@ -92,16 +92,16 @@ export interface BufferedIteratorOptions { export class BufferedIterator extends AsyncIterator { maxBufferSize: number; - protected _pushedCount: number; - protected _buffer: T[]; + _pushedCount: number; + _buffer: T[]; - protected _init(autoStart: boolean): void; - protected _begin(done: () => void): void; - protected _read(count: number, done: () => void): void; - protected _push(item: T): void; - protected _fillBuffer(): void; - protected _completeClose(): void; - protected _flush(done: () => void): void; + _init(autoStart: boolean): void; + _begin(done: () => void): void; + _read(count: number, done: () => void): void; + _push(item: T): void; + _fillBuffer(): void; + _completeClose(): void; + _flush(done: () => void): void; constructor(options?: BufferedIteratorOptions); } @@ -112,12 +112,12 @@ export interface TransformIteratorOptions extends BufferedIteratorOptions { } export class TransformIterator extends BufferedIterator { - protected _optional: boolean; + _optional: boolean; source: AsyncIterator; - protected _validateSource(source: AsyncIterator, allowDestination?: boolean): void; - protected _transform(item: S, done: (result: T) => void): void; - protected _closeWhenDone(): void; + _validateSource(source: AsyncIterator, allowDestination?: boolean): void; + _transform(item: S, done: (result: T) => void): void; + _closeWhenDone(): void; constructor(source?: AsyncIterator | TransformIteratorOptions, options?: TransformIteratorOptions); } @@ -134,16 +134,16 @@ export interface SimpleTransformIteratorOptions extends TransformIteratorO } export class SimpleTransformIterator extends TransformIterator { - protected _offset: number; - protected _limit: number; - protected _prepender?: ArrayIterator; - protected _appender?: ArrayIterator; + _offset: number; + _limit: number; + _prepender?: ArrayIterator; + _appender?: ArrayIterator; - protected _filter?(item: S): boolean; - protected _map?(item: S): T; - protected _transform(item: S, done: (result: T) => void): void; + _filter?(item: S): boolean; + _map?(item: S): T; + _transform(item: S, done: (result: T) => void): void; - protected _insert(inserter: AsyncIterator, done: () => void): void; + _insert(inserter: AsyncIterator, done: () => void): void; constructor(source?: AsyncIterator | SimpleTransformIteratorOptions, options?: SimpleTransformIteratorOptions); @@ -152,7 +152,7 @@ export class SimpleTransformIterator extends TransformIterator { export class MultiTransformIterator extends TransformIterator { _transformerQueue: S[]; - protected _createTransformer(): AsyncIterator; + _createTransformer(element: S): AsyncIterator; constructor(source?: AsyncIterator | TransformIteratorOptions, options?: TransformIteratorOptions); } diff --git a/types/atom-keymap/index.d.ts b/types/atom-keymap/index.d.ts index 1d67a20ba2..3660fff3f4 100644 --- a/types/atom-keymap/index.d.ts +++ b/types/atom-keymap/index.d.ts @@ -2,7 +2,7 @@ // Project: https://github.com/atom/atom-keymap // Definitions by: GlenCFL // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -// TypeScript Version: 2.2 +// TypeScript Version: 2.3 import { Disposable } from "event-kit"; diff --git a/types/atom/atom-tests.ts b/types/atom/atom-tests.ts index e0699463b1..6ea7b9ae1f 100644 --- a/types/atom/atom-tests.ts +++ b/types/atom/atom-tests.ts @@ -844,9 +844,12 @@ function testDock() { } // Emitter ==================================================================== +interface TestEmissions { + "test-event": string; +} + function testEmitter() { emitter = new Atom.Emitter(); - emitter.clear(); emitter.dispose(); @@ -858,6 +861,27 @@ function testEmitter() { // Event Emission emitter.emit("test-event"); emitter.emit("test-event", 42); + + // Optional Value Emitter + const optEmitter = new Atom.Emitter<{ "test-event": string }>(); + optEmitter.emit("test-event"); + optEmitter.emit("test-event", "test"); + optEmitter.on("test-event", value => { + str = value ? value : ""; + }); + + // Required Value Emitter + const reqEmitter = new Atom.Emitter<{}, TestEmissions>(); + reqEmitter.on("test-event", value => { + str = value; + }); + reqEmitter.emit("test-event", "test"); + + // Mixed Value Emitter + const mixedEmitter = new Atom.Emitter<{ "t1": "test" }, { "t2": "test" }>(); + mixedEmitter.emit("t1"); + mixedEmitter.emit("t1", "test"); + mixedEmitter.emit("t2", "test"); } // File ======================================================================= @@ -2939,7 +2963,7 @@ function testTooltipManager() { subscription = atom.tooltips.add(element, { class: "test-class" }); subscription = atom.tooltips.add(element, { placement: "top" }); - subscription = atom.tooltips.add(element, { placement: () => "left" }); + subscription = atom.tooltips.add(element, { placement: () => "auto left" }); subscription = atom.tooltips.add(element, { trigger: "click" }); subscription = atom.tooltips.add(element, { delay: { hide: 42, show: 42 }}); diff --git a/types/atom/index.d.ts b/types/atom/index.d.ts index 2a13373b7d..4adac61dc1 100644 --- a/types/atom/index.d.ts +++ b/types/atom/index.d.ts @@ -717,7 +717,9 @@ export class Disposable implements DisposableLike { * Utility class to be used when implementing event-based APIs that allows * for handlers registered via ::on to be invoked with calls to ::emit. */ -export class Emitter implements DisposableLike { +// tslint:disable-next-line:no-any +export class Emitter + implements DisposableLike { /** Construct an emitter. */ constructor(); @@ -729,27 +731,47 @@ export class Emitter implements DisposableLike { // Event Subscription /** Registers a handler to be invoked whenever the given event is emitted. */ - on(eventName: T, handler: (value?: Emissions[T]) => void): - Disposable; + on(eventName: T, handler: (value?: + OptionalEmissions[T]) => void): Disposable; + /** Registers a handler to be invoked whenever the given event is emitted. */ + on(eventName: T, handler: (value: + RequiredEmissions[T]) => void): Disposable; /** * Register the given handler function to be invoked the next time an event * with the given name is emitted via ::emit. */ - once(eventName: T, handler: (value?: Emissions[T]) => void): - Disposable; + once(eventName: T, handler: (value?: + OptionalEmissions[T]) => void): Disposable; + /** + * Register the given handler function to be invoked the next time an event + * with the given name is emitted via ::emit. + */ + once(eventName: T, handler: (value: + RequiredEmissions[T]) => void): Disposable; /** * Register the given handler function to be invoked before all other * handlers existing at the time of subscription whenever events by the * given name are emitted via ::emit. */ - preempt(eventName: T, handler: (value?: Emissions[T]) => void): - Disposable; + preempt(eventName: T, handler: (value?: + OptionalEmissions[T]) => void): Disposable; + /** + * Register the given handler function to be invoked before all other + * handlers existing at the time of subscription whenever events by the + * given name are emitted via ::emit. + */ + preempt(eventName: T, handler: (value: + RequiredEmissions[T]) => void): Disposable; // Event Emission /** Invoke the handlers registered via ::on for the given event name. */ - emit(eventName: T, value?: Emissions[T]): void; + emit(eventName: T, value?: + OptionalEmissions[T]): void; + /** Invoke the handlers registered via ::on for the given event name. */ + emit(eventName: T, value: + RequiredEmissions[T]): void; } /** @@ -1015,10 +1037,7 @@ export class Point { * Create a Point from an array containing two numbers representing the * row and column. */ - static fromObject(object: [number, number]): Point; - - /** Create a Point from an existing object which implements PointLike. */ - static fromObject(object: PointLike, copy?: boolean): Point; + static fromObject(object: PointCompatible, copy?: boolean): Point; /** Construct a Point object */ constructor(row?: number, column?: number); @@ -1775,7 +1794,8 @@ export class TextEditor { void; /** Add a cursor at the given position in buffer coordinates. */ - addCursorAtBufferPosition(bufferPosition: PointCompatible): Cursor; + addCursorAtBufferPosition(bufferPosition: PointCompatible, options?: + { autoscroll?: boolean }): Cursor; /** Add a cursor at the position in screen coordinates. */ addCursorAtScreenPosition(screenPosition: PointCompatible): Cursor; @@ -2403,27 +2423,25 @@ export interface TextEditorRegistry { observe(callback: (editor: TextEditor) => void): Disposable; } +export type TooltipPlacement = + |"top"|"bottom"|"left"|"right" + |"auto"|"auto top"|"auto bottom"|"auto left"|"auto right"; + /** Associates tooltips with HTML elements or selectors. */ export interface TooltipManager { /** Add a tooltip to the given element. */ add(target: HTMLElement, options: { - title?: string, - html?: boolean, - item?: HTMLElement|{ element: HTMLElement }, - class?: string, - placement?: "top"|"bottom"|"left"|"right"|"auto"|(() => string), - trigger?: "click"|"hover"|"focus"|"manual", - delay?: { show: number, hide: number }, - keyBindingCommand?: string, - keyBindingTarget?: HTMLElement + item?: object, } | { title?: string|(() => string), html?: boolean, - item?: HTMLElement|{ element: HTMLElement }, - class?: string, - placement?: "top"|"bottom"|"left"|"right"|"auto"|(() => string), + keyBindingCommand?: string, + keyBindingTarget?: HTMLElement + } & { + class?: string; + placement?: TooltipPlacement|(() => TooltipPlacement), trigger?: "click"|"hover"|"focus"|"manual", - delay?: { show: number, hide: number }, + delay?: { show: number, hide: number } }): Disposable; /** Find the tooltips that have been applied to the given element. */ @@ -5795,16 +5813,6 @@ export interface ConfigValues { [key: string]: any; } -/** - * Allows you to strongly type event emissions across your codebase. Additional - * key:value pairings merged into this interface will result in emissions under - * the value of each key being templated by the type of the associated value. - */ -export interface Emissions { - // tslint:disable-next-line:no-any - [key: string]: any; -} - // Options ==================================================================== // The option objects that the user is expected to fill out and provide to // specific API call. @@ -6094,7 +6102,7 @@ export interface SharedDecorationOptions { * An HTMLElement or a model Object with a corresponding view registered. Only * applicable to the gutter, overlay and block types. */ - item?: HTMLElement; + item?: object; /** * If true, the decoration will only be applied to the head of the DisplayMarker. diff --git a/types/auth0-js/auth0-js-tests.ts b/types/auth0-js/auth0-js-tests.ts index 06d428de20..d05ee2251e 100644 --- a/types/auth0-js/auth0-js-tests.ts +++ b/types/auth0-js/auth0-js-tests.ts @@ -109,7 +109,9 @@ webAuth.renewAuth({}, (err, authResult) => {}); webAuth.renewAuth({ nonce: '123', state: '456', - postMessageDataType: 'auth0:silent-authentication' + postMessageDataType: 'auth0:silent-authentication', + usePostMessage: true, + timeout: 30 * 1000 }, (err, authResult) => { // Renewed tokens or error }); @@ -172,6 +174,23 @@ webAuth.login({username: 'bar', password: 'foo'}, (err, data) => {}); webAuth.crossOriginAuthenticationCallback(); +webAuth.checkSession({ + audience: 'https://mystore.com/api/v2', + scope: 'read:order write:order', + redirectUri: 'https://example.com/auth/silent-callback' + }, (err, authResult) => { + // Authentication tokens or error +}); + +webAuth.checkSession({ + audience: 'https://mystore.com/api/v2', + scope: 'read:order write:order', + redirectUri: 'https://example.com/auth/silent-callback', + usePostMessage: true + }, (err, authResult) => { + // Renewed tokens or error +}); + const authentication = new auth0.Authentication({ domain: 'me.auth0.com', clientID: '...', diff --git a/types/auth0-js/index.d.ts b/types/auth0-js/index.d.ts index 76a2c5f319..6110f2fe52 100644 --- a/types/auth0-js/index.d.ts +++ b/types/auth0-js/index.d.ts @@ -1,7 +1,8 @@ -// Type definitions for Auth0.js 8.10 +// Type definitions for Auth0.js 8.11 // Project: https://github.com/auth0/auth0.js // Definitions by: Adrian Chia // Matt Durrant +// Peter Blazejewicz // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped export as namespace auth0; @@ -267,6 +268,14 @@ export class WebAuth { * @param options: */ passwordlessVerify(options: PasswordlessVerifyOptions, callback: Auth0Callback): void; + + /** + * Renews an existing session on Auth0's servers using `response_mode=web_message` (i.e. Auth0's hosted login page) + * + * @param options options used in {@link authorize} call + * @param callback: any(err, token_payload) + */ + checkSession(options: CheckSessionOptions, callback: Auth0Callback): void; } export class Redirect { @@ -525,14 +534,19 @@ export interface Auth0Error { statusText?: string; } +/** + * The contents of the authResult object returned by {@link WebAuth#parseHash } + */ export interface Auth0DecodedHash { accessToken?: string; idToken?: string; idTokenPayload?: any; + appState?: any; refreshToken?: string; state?: string; expiresIn?: number; tokenType?: string; + scope?: string; } /** Represents the response from an API Token Delegation request. */ @@ -667,17 +681,72 @@ export interface ParseHashOptions { } export interface RenewAuthOptions { + /** + * your Auth0 domain + */ domain?: string; + /** + * your Auth0 client identifier obtained when creating the client in the Auth0 Dashboard + */ clientID?: string; + /** + * url that the Auth0 will redirect after Auth with the Authorization Response + */ redirectUri?: string; + /** + * type of the response used by OAuth 2.0 flow. It can be any space separated + * list of the values `code`, `token`, `id_token`. + * {@link https://openid.net/specs/oauth-v2-multiple-response-types-1_0} + */ responseType?: string; + /** + * how the Auth response is encoded and redirected back to the client. + * Supported values are `query`, `fragment` and `form_post`. + * The `query` value is only supported when `responseType` is `code`. + * {@link https://openid.net/specs/oauth-v2-multiple-response-types-1_0.html#ResponseModes} + */ responseMode?: string; + /** + * value used to mitigate XSRF attacks. + * {@link https://auth0.com/docs/protocols/oauth2/oauth-state} + */ state?: string; + /** + * value used to mitigate replay attacks when using Implicit Grant. + * {@link https://auth0.com/docs/api-auth/tutorials/nonce} + */ nonce?: string; + /** + * scopes to be requested during Auth. e.g. `openid email` + */ scope?: string; + /** + * identifier of the resource server who will consume the access token issued after Auth + */ audience?: string; - usePostMessage?: boolean; + /** + * identifier data type to look for in postMessage event data, where events are initiated + * from silent callback urls, before accepting a message event is the event expected. + * A value of false means any postMessage event will trigger a callback. + */ postMessageDataType?: string; + /** + * origin of redirectUri to expect postMessage response from. + * Defaults to the origin of the receiving window. Only used if usePostMessage is truthy. + */ + postMessageOrigin?: string; + /** + * value in milliseconds used to timeout when the `/authorize` call is failing + * as part of the silent authentication with postmessage enabled due to a configuration. + */ + timeout?: number; + /** + * use postMessage to comunicate between the silent callback and the SPA. + * When false the SDK will attempt to parse the url hash should ignore the url hash + * and no extra behaviour is needed + * @default false + */ + usePostMessage?: boolean; } export interface AuthorizeOptions { @@ -692,3 +761,10 @@ export interface AuthorizeOptions { scope?: string; audience?: string; } + +export interface CheckSessionOptions extends AuthorizeOptions { + /** + * optional parameter for auth0 to use postMessage to communicate between the silent callback and the SPA. + */ + usePostMessage?: boolean; +} diff --git a/types/auth0-lock/auth0-lock-tests.ts b/types/auth0-lock/auth0-lock-tests.ts index 0642453a13..c2107b11e4 100644 --- a/types/auth0-lock/auth0-lock-tests.ts +++ b/types/auth0-lock/auth0-lock-tests.ts @@ -10,6 +10,17 @@ lock.show(); lock.hide(); lock.logout(() => {}); +lock.checkSession({}, function(error: auth0.Auth0Error, authResult: AuthResult): void { + if (error || !authResult) { + lock.show(); + } else { + // user has an active session, so we can use the accessToken directly. + lock.getUserInfo(authResult.accessToken, function(error, profile) { + console.log(error, profile); + }); + } +}); + // Show supports UI arguments const showOptions : Auth0LockShowOptions = { @@ -37,7 +48,7 @@ lock.show(showOptions); // "on" event-driven example -lock.on("authenticated", function(authResult : any) { +lock.on("authenticated", function(authResult: AuthResult) { lock.getProfile(authResult.idToken, function(error: auth0.Auth0Error, profile: auth0.Auth0UserProfile) { if (error) { // Handle error @@ -49,7 +60,7 @@ lock.on("authenticated", function(authResult : any) { }); }); -lock.on("authenticated", function(authResult : any) { +lock.on("authenticated", function(authResult: AuthResult) { lock.getUserInfo(authResult.accessToken, function(error, profile) { if (error) { // Handle error diff --git a/types/auth0-lock/index.d.ts b/types/auth0-lock/index.d.ts index 0a57d988ce..8ed6b50c87 100644 --- a/types/auth0-lock/index.d.ts +++ b/types/auth0-lock/index.d.ts @@ -154,6 +154,7 @@ interface Auth0LockStatic { // deprecated getProfile(token: string, callback: (error: auth0.Auth0Error, profile: auth0.Auth0UserProfile) => void): void; getUserInfo(token: string, callback: (error: auth0.Auth0Error, profile: auth0.Auth0UserProfile) => void): void; + checkSession(options: any, callback: (error: auth0.Auth0Error, authResult: AuthResult | undefined) => void): void; // https://github.com/auth0/lock#resumeauthhash-callback resumeAuth(hash: string, callback: (error: auth0.Auth0Error, authResult: AuthResult) => void): void; show(options?: Auth0LockShowOptions): void; diff --git a/types/auth0/auth0-tests.ts b/types/auth0/auth0-tests.ts index 08a866e9b1..521738db7e 100644 --- a/types/auth0/auth0-tests.ts +++ b/types/auth0/auth0-tests.ts @@ -111,3 +111,12 @@ management // Update app metadata using callback management .updateAppMetadata({id: "user_id"}, {"key": "value"}, (err: Error, users: auth0.User) => {}); + + +management.getUsersByEmail('email@address.com', (err, users) => { + console.log(users); +}); + +management.getUsersByEmail('email@address.com').then((users) => { + console.log(users); +}); diff --git a/types/auth0/index.d.ts b/types/auth0/index.d.ts index d24cb40081..12829b5b67 100644 --- a/types/auth0/index.d.ts +++ b/types/auth0/index.d.ts @@ -482,6 +482,9 @@ export class ManagementClient { getUser(params: ObjectWithId): Promise; getUser(params: ObjectWithId, cb?: (err: Error, user: User) => void): void; + getUsersByEmail(email: string): Promise; + getUsersByEmail(email: string, cb?: (err: Error, users: User[]) => void): void; + createUser(data: CreateUserData): Promise; createUser(data: CreateUserData, cb: (err: Error, user: User) => void): void; diff --git a/types/autobind-decorator/autobind-decorator-tests.ts b/types/autobind-decorator/autobind-decorator-tests.ts deleted file mode 100644 index f5a0c76328..0000000000 --- a/types/autobind-decorator/autobind-decorator-tests.ts +++ /dev/null @@ -1,42 +0,0 @@ - -import autobind = require('autobind-decorator'); - -class Test { - public static what: string = 'static'; - - @autobind - public static test(): void { - console.log(this.what); - } - - public constructor(public what: string) { - this.what = what; - } - - @autobind - public test(): void { - console.warn(this.what); - } -} - -const tester: Test = new Test('bind'); -const { test } = tester; -tester.test(); // warns 'bind'. -test(); // warns 'bind'. -Test.test(); // logs 'static'. - -@autobind -class Component { - public constructor(private someMember: string) { - this.someMember = someMember; - } - - public someMethod(): void { - console.error(this.someMember); - } -} - -const component: Component = new Component('React vs Angular2'); -const { someMethod } = component; -component.someMethod(); // errors 'React vs Angular2' -someMethod(); // errors 'React vs Angular2' diff --git a/types/autobind-decorator/index.d.ts b/types/autobind-decorator/index.d.ts deleted file mode 100644 index d8d74bbfec..0000000000 --- a/types/autobind-decorator/index.d.ts +++ /dev/null @@ -1,10 +0,0 @@ -// Type definitions for autobind-decorator v1.3.3 -// Project: https://github.com/andreypopp/autobind-decorator -// Definitions by: Ivo Stratev -// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped - -declare module 'autobind-decorator' { - function autobind(target: TFunction): TFunction | void; - function autobind(target: Object, propertyKey: string | symbol, descriptor: TypedPropertyDescriptor): TypedPropertyDescriptor | void; - export = autobind; -} diff --git a/types/aws-lambda/aws-lambda-tests.ts b/types/aws-lambda/aws-lambda-tests.ts index ebd31429de..7cd969b6c6 100644 --- a/types/aws-lambda/aws-lambda-tests.ts +++ b/types/aws-lambda/aws-lambda-tests.ts @@ -109,6 +109,101 @@ str = apiGwEvt.queryStringParameters["example"]; str = apiGwEvt.stageVariables["example"]; apiGwEvtReqCtx = apiGwEvt.requestContext; +/* DynamoDB Stream Event */ +var dynamoDBStreamEvent: AWSLambda.DynamoDBStreamEvent = { + Records: [ + { + eventID: '1', + eventVersion: '1.0', + dynamodb: { + Keys: { + Id: { + N: 101 + } + }, + NewImage: { + Message: { + S: 'New item!' + }, + Id: { + N: 101 + } + }, + StreamViewType: 'NEW_AND_OLD_IMAGES', + SequenceNumber: '111', + SizeBytes: 26 + }, + awsRegion: 'us-west-2', + eventName: 'INSERT', + eventSourceARN: + 'arn:aws:dynamodb:us-west-2:account-id:table/ExampleTableWithStream/stream/2015-06-27T00:48:05.899', + eventSource: 'aws:dynamodb' + }, + { + eventID: '2', + eventVersion: '1.0', + dynamodb: { + OldImage: { + Message: { + S: 'New item!' + }, + Id: { + N: 101 + } + }, + SequenceNumber: '222', + Keys: { + Id: { + N: 101 + } + }, + SizeBytes: 59, + NewImage: { + Message: { + S: 'This item has changed' + }, + Id: { + N: 101 + } + }, + StreamViewType: 'NEW_AND_OLD_IMAGES' + }, + awsRegion: 'us-west-2', + eventName: 'MODIFY', + eventSourceARN: + 'arn:aws:dynamodb:us-west-2:account-id:table/ExampleTableWithStream/stream/2015-06-27T00:48:05.899', + eventSource: 'aws:dynamodb' + }, + { + eventID: '3', + eventVersion: '1.0', + dynamodb: { + Keys: { + Id: { + N: 101 + } + }, + SizeBytes: 38, + SequenceNumber: '333', + OldImage: { + Message: { + S: 'This item has changed' + }, + Id: { + N: 101 + } + }, + StreamViewType: 'NEW_AND_OLD_IMAGES' + }, + awsRegion: 'us-west-2', + eventName: 'REMOVE', + eventSourceARN: + 'arn:aws:dynamodb:us-west-2:account-id:table/ExampleTableWithStream/stream/2015-06-27T00:48:05.899', + eventSource: 'aws:dynamodb' + } + ] +}; + /* SNS Event */ snsEvtRecs = snsEvt.Records; @@ -294,6 +389,9 @@ function callback(cb: AWSLambda.Callback) { cb(null); cb(error); cb(null, anyObj); + cb(null, b); + cb(null, str); + cb(null, num); } /* Proxy Callback */ @@ -312,6 +410,131 @@ function customAuthorizerCallback(cb: AWSLambda.CustomAuthorizerCallback) { cb(null, authResponse); } +/* CloudFront events, see http://docs.aws.amazon.com/AmazonCloudFront/latest/DeveloperGuide/lambda-event-structure.html */ +var CloudFrontRequestEvent: AWSLambda.CloudFrontRequestEvent = { + "Records": [ + { + "cf": { + "config": { + "distributionId": "EDFDVBD6EXAMPLE", + "requestId": "MRVMF7KydIvxMWfJIglgwHQwZsbG2IhRJ07sn9AkKUFSHS9EXAMPLE==" + }, + "request": { + "clientIp": "2001:0db8:85a3:0:0:8a2e:0370:7334", + "method": "GET", + "uri": "/picture.jpg", + "querystring": "size=large", + "headers": { + "host": [ + { + "key": "Host", + "value": "d111111abcdef8.cloudfront.net" + } + ], + "user-agent": [ + { + "key": "User-Agent", + "value": "curl/7.51.0" + } + ] + }, + "origin": { + "custom": { + "customHeaders": { + "my-origin-custom-header": [ + { + "key": "My-Origin-Custom-Header", + "value": "Test" + } + ] + }, + "domainName": "example.com", + "keepaliveTimeout": 5, + "path": "/custom_path", + "port": 443, + "protocol": "https", + "readTimeout": 5, + "sslProtocols": [ + "TLSv1", + "TLSv1.1" + ] + }, + "s3": { + "authMethod": "origin-access-identity", + "customHeaders": { + "my-origin-custom-header": [ + { + "key": "My-Origin-Custom-Header", + "value": "Test" + } + ] + }, + "domainName": "my-bucket.s3.amazonaws.com", + "path": "/s3_path", + "region": "us-east-1" + } + } + } + } + } + ] +}; + +var CloudFrontResponseEvent: AWSLambda.CloudFrontResponseEvent = { + "Records": [ + { + "cf": { + "config": { + "distributionId": "EDFDVBD6EXAMPLE", + "requestId": "xGN7KWpVEmB9Dp7ctcVFQC4E-nrcOcEKS3QyAez--06dV7TEXAMPLE==" + }, + "request": { + "clientIp": "2001:0db8:85a3:0:0:8a2e:0370:7334", + "method": "GET", + "uri": "/picture.jpg", + "querystring": "size=large", + "headers": { + "host": [ + { + "key": "Host", + "value": "d111111abcdef8.cloudfront.net" + } + ], + "user-agent": [ + { + "key": "User-Agent", + "value": "curl/7.18.1" + } + ] + } + }, + "response": { + "status": "200", + "statusDescription": "OK", + "headers": { + "server": [ + { + "key": "Server", + "value": "MyCustomOrigin" + } + ], + "set-cookie": [ + { + "key": "Set-Cookie", + "value": "theme=light" + }, + { + "key": "Set-Cookie", + "value": "sessionToken=abc123; Expires=Wed, 09 Jun 2021 10:18:14 GMT" + } + ] + } + } + } + } + ] +}; + /* Compatibility functions */ context.done(); context.done(error); diff --git a/types/aws-lambda/index.d.ts b/types/aws-lambda/index.d.ts index 3b9e31f14c..172ee69210 100644 --- a/types/aws-lambda/index.d.ts +++ b/types/aws-lambda/index.d.ts @@ -8,7 +8,10 @@ // Yoriki Yamaguchi // wwwy3y3 // Ishaan Malhi +// Michael Marner // Daniel Cottone +// Kostya Misura +// Markus Tacker // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped // TypeScript Version: 2.2 @@ -63,6 +66,53 @@ interface CustomAuthorizerEvent { requestContext?: APIGatewayEventRequestContext; } +// Context +// http://docs.aws.amazon.com/amazondynamodb/latest/APIReference/API_streams_AttributeValue.html +interface AttributeValue { + B?: string; + BS?: Array; + BOOL?: boolean; + L?: Array; + M?: { [id: string]: AttributeValue }; + N?: number; + NS?: Array; + NULL?: boolean; + S?: string; + SS?: Array; +} + +// Context +// http://docs.aws.amazon.com/amazondynamodb/latest/APIReference/API_streams_StreamRecord.html +interface StreamRecord { + ApproximateCreationTime?: number; + Keys?: { [key: string]: AttributeValue }; + NewImage?: { [key: string]: AttributeValue }; + OldImage?: { [key: string]: AttributeValue }; + SequenceNumber?: string; + SizeBytes?: number; + StreamViewType?: 'KEYS_ONLY' | 'NEW_IMAGE' | 'OLD_IMAGE' | 'NEW_AND_OLD_IMAGES'; +} + +// Context +// http://docs.aws.amazon.com/amazondynamodb/latest/APIReference/API_streams_Record.html +interface DynamoDBRecord { + awsRegion?: string; + dynamodb?: StreamRecord; + eventID?: string; + eventName?: 'INSERT' | 'MODIFY' | 'REMOVE'; + eventSource?: string; + eventSourceARN?: string; + eventVersion?: string; + userIdentity?: any; +} + +// AWS Lambda Stream event +// Context +// http://docs.aws.amazon.com/lambda/latest/dg/eventsources.html#eventsources-ddb-update +interface DynamoDBStreamEvent { + Records: Array; +} + // SNS "event" interface SNSMessageAttribute { Type: string; @@ -345,6 +395,55 @@ interface AuthResponseContext { [name: string]: string | number | boolean; } +/** + * CloudFront events + * http://docs.aws.amazon.com/AmazonCloudFront/latest/DeveloperGuide/lambda-event-structure.html + */ +type CloudFrontHeaders = { + [name: string]: { + key: string; + value: string; + }[] +}; + +type CloudFrontResponse = { + status: string; + statusDescription: string; + headers: CloudFrontHeaders; +}; + +type CloudFrontRequest = { + clientIp: string; + method: string; + uri: string; + querystring: string; + headers: CloudFrontHeaders; +}; + +type CloudFrontEvent = { + config: { + distributionId: string; + requestId: string; + } +} + +export type CloudFrontResponseEvent = { + Records: { + cf: CloudFrontEvent & { + request: CloudFrontRequest; + response: CloudFrontResponse; + } + }[] +}; + +export type CloudFrontRequestEvent = { + Records: { + cf: CloudFrontEvent & { + request: CloudFrontRequest; + } + }[] +}; + /** * AWS Lambda handler function. * http://docs.aws.amazon.com/lambda/latest/dg/nodejs-prog-model-handler.html @@ -364,7 +463,7 @@ export type CustomAuthorizerHandler = (event: CustomAuthorizerEvent, context: Co * @param error – an optional parameter that you can use to provide results of the failed Lambda function execution. * @param result – an optional parameter that you can use to provide the result of a successful function execution. The result provided must be JSON.stringify compatible. */ -export type Callback = (error?: Error | null, result?: object) => void; +export type Callback = (error?: Error | null, result?: object | boolean | number | string) => void; export type ProxyCallback = (error?: Error | null, result?: ProxyResult) => void; export type CustomAuthorizerCallback = (error?: Error | null, result?: AuthResponse) => void; diff --git a/types/azure-sb/azure-sb-tests.ts b/types/azure-sb/azure-sb-tests.ts index 68b0fc8df7..411862a3b2 100644 --- a/types/azure-sb/azure-sb-tests.ts +++ b/types/azure-sb/azure-sb-tests.ts @@ -1,16 +1,82 @@ +import { Azure } from 'azure-sb'; +import AzureSB = require('azure-sb'); +import Models = Azure.ServiceBus.Results.Models; -var nh = new Azure.ServiceBus.NotificationHubService(); -nh.send('tag', '', function (error, result) {}); -nh.send('tag', '', { headers: {} }, function (error, result) {}); +function createResultCallback() { + return (err: Error | null, result: T, response: Azure.ServiceBus.Response) => { + }; +} -nh.apns.send('tag', { payload: { } }, function (error, result) {}); -nh.apns.send(['tag'], { payload: { } }, function (error, result) {}); -nh.gcm.send('tag', { }, function (error, result) {}); -nh.gcm.send(['tag'], { }, function (error, result) {}); -nh.wns.send('tag', '', 'wns/toast', function (error, result) {}); -nh.wns.send(['tag'], '', 'wns/toast', function (error, result) {}); -nh.wns.send('tag', '', 'wns/toast', { headers: {} }, function (error, result) {}); -nh.wns.sendToastText01('tag', '', function (error, result) {}); -nh.wns.sendToastText01(['tag'], '', function (error, result) {}); -nh.wns.sendToastText01('tag', '', { headers: {} }, function (error, result) {}); \ No newline at end of file +function ResponseCallback(err: Error | null, response: Azure.ServiceBus.Response) { +} + +const ServiceBus = AzureSB.createServiceBusService('connectionstring'); + +// Queues +ServiceBus.listQueues('', createResultCallback()); +ServiceBus.createQueue('test', createResultCallback()); +ServiceBus.createQueueIfNotExists('test', createResultCallback()); +ServiceBus.getQueue('test', createResultCallback()); +ServiceBus.deleteQueue('test', ResponseCallback); + +// Topics +ServiceBus.listTopics('', createResultCallback()); +ServiceBus.createTopic('test', createResultCallback()); +ServiceBus.createTopicIfNotExists('test', createResultCallback()); +ServiceBus.getTopic('test', createResultCallback()); +ServiceBus.deleteTopic('test', ResponseCallback); + +// Subscriptions +ServiceBus.listSubscriptions('test', createResultCallback()); +ServiceBus.createSubscription('test', 'test', createResultCallback()); +ServiceBus.createSubscription('test', 'test', { + DefaultMessageTimeToLive: 'PT10M' +}, createResultCallback()); +ServiceBus.getSubscription('test', 'test', createResultCallback()); +ServiceBus.deleteSubscription('test', 'test', ResponseCallback); + +ServiceBus.listRules('testTopic', 'testSub', createResultCallback()); +ServiceBus.createRule('testTopic', 'testSub', 'testRule', createResultCallback()); +ServiceBus.getRule('testTopic', 'testSub', 'testRule', createResultCallback()); +ServiceBus.deleteRule('testTopic', 'testSub', 'testRule', ResponseCallback); + +// Messages +ServiceBus.sendQueueMessage('testTopic', 'My data', ResponseCallback); +ServiceBus.sendQueueMessage('testTopic', { + body: '{"data":"MyData"}', + contentType: 'application/json', + brokerProperties: { + CorrelationId: '123' + } +}, ResponseCallback); +ServiceBus.receiveQueueMessage('testQueue', createResultCallback()); + +ServiceBus.sendTopicMessage('testTopic', 'My data', ResponseCallback); +ServiceBus.sendTopicMessage('testTopic', { + body: '{"data":"MyData"}', + contentType: 'application/json', + brokerProperties: { + CorrelationId: '123' + } +}, ResponseCallback); +ServiceBus.receiveSubscriptionMessage('testTopic', 'testSub', createResultCallback()); + +ServiceBus.renewLockForMessage('test', ResponseCallback); +ServiceBus.unlockMessage('test', ResponseCallback); +ServiceBus.deleteMessage('test', ResponseCallback); + +// NotificationHub +const nh = AzureSB.createNotificationHubService('test'); +nh.send('tag', '', ResponseCallback); +nh.send('tag', '', { headers: {} }, ResponseCallback); +nh.apns.send('tag', { payload: {} }, ResponseCallback); +nh.apns.send(['tag'], { payload: {} }, ResponseCallback); +nh.gcm.send('tag', {}, ResponseCallback); +nh.gcm.send(['tag'], {}, ResponseCallback); +nh.wns.send('tag', '', 'wns/toast', ResponseCallback); +nh.wns.send(['tag'], '', 'wns/toast', ResponseCallback); +nh.wns.send('tag', '', 'wns/toast', { headers: {} }, ResponseCallback); +nh.wns.sendToastText01('tag', '', ResponseCallback); +nh.wns.sendToastText01(['tag'], '', ResponseCallback); +nh.wns.sendToastText01('tag', '', { headers: {} }, ResponseCallback); diff --git a/types/azure-sb/index.d.ts b/types/azure-sb/index.d.ts index bae1af04a9..ba92395c0f 100644 --- a/types/azure-sb/index.d.ts +++ b/types/azure-sb/index.d.ts @@ -2,172 +2,322 @@ // Project: https://github.com/Azure/azure-sdk-for-node/tree/master/lib/services/serviceBus // Definitions by: Microsoft Azure // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.4 -declare namespace Azure.ServiceBus { - interface Callback { - (error: any, response: any): void; +export import ServiceBusService = require('./lib/servicebusservice'); +export import NotificationHubService = require('./lib/notificationhubservice'); +export import WrapService = require('./lib/wrapservice'); + +export function createServiceBusService(namespaceOrConnectionString?: string, + accessKey?: string, + issuer?: string, + acsNamespace?: string, + host?: string, + authenticationProvider?: object): ServiceBusService; + +export function createNotificationHubService(hubName: string, + endpointOrConnectionString?: string, + sharedAccessKeyName?: string, + sharedAccessKeyValue?: string): NotificationHubService; + +export function createWrapService(acsHost: string, + issuer?: string, + accessKey?: string): WrapService; + +export namespace Azure.ServiceBus { + export type Duration = string; + export type DateString = string; + + export interface Dictionary { + [k: string]: T; } - interface NotificationHubRegistration { - RegistrationId: string; + export interface ReceiveQueueMessageOptions { + timeoutIntervalInS?: number; + } + + export interface ReceiveSubscriptionMessageOptions extends ReceiveQueueMessageOptions { + isPeekLock?: boolean; + } + + interface IBrokerPropertiesResponse { + readonly DeliveryCount: number; + readonly LockedUntil: DateString; + readonly LockToken: string; + readonly SequenceNumber: number; + } + + interface IBrokerProperties { + CorrelationId: string; + Label: string; + MessageId: string; + PartitionKey: string; + ReplyTo: string; + ReplyToSessionId: string; + ScheduledEnqueueTimeUtc: string; + SessionId: string; + TimeToLive: string; + To: string; + } + + export interface Message { + body: string; + brokerProperties?: BrokerProperties; + contentType?: string; + customProperties?: Dictionary; + } + + /* + * Options interfaces + */ + + interface CreateOptions { + DefaultMessageTimeToLive: string; + DuplicateDetectionHistoryTimeWindow: string; + EnablePartitioning: boolean; + MaxSizeInMegaBytes: number; + RequiresDuplicateDetection: boolean; + } + + interface IQueueOptions extends CreateOptions { + AutoDeleteOnIdle: string; + DeadLetteringOnMessageExpiration: boolean; + LockDuration: string; + RequiresSession: boolean; + } + + interface ICreateTopicOptions extends CreateOptions { + EnableBatchedOperations: boolean; + SizeInBytes: boolean; + SupportOrdering: boolean; + } + + interface ICreateTopicIfNotExistsOptions extends ICreateTopicOptions { + EnableDeadLetteringOnFilterEvaluationExceptions: boolean; + EnableDeadLetteringOnMessageExpiration: boolean; + MaxCorrelationFiltersPerTopic: number; + MaxSqlFiltersPerTopic: number; + MaxSubscriptionsPerTopic: number; + } + + interface ICreateSubscriptionOptions { + DefaultMessageTimeToLive: string; + EnableDeadLetteringOnFilterEvaluationExceptions: boolean; + EnableDeadLetteringOnMessageExpiration: boolean; + LockDuration: string; + RequiresSession: boolean; + } + + interface PaginationOptions { + top: number; + skip: number; + } + + interface ICreateRuleOptions { + trueFilter: string; + falseFilter: string; + sqlExpressionFilter: string; + correlationIdFilter: string; + sqlRuleAction: string; + } + + interface ICreateNotificationHubOptions { + apns: Dictionary; + gcm: Dictionary; + mpns: Dictionary; + wns: Dictionary; + } + + export interface NotificationHubRegistration { + BodyTemplate?: any; ChannelUri?: string; DeviceToken?: string; - gcmRegistrationId?: string; - Tags?: string; - BodyTemplate?: any; - WnsHeaders?: any; - MpnsHeaders?: any; Expiry?: Date; + gcmRegistrationId?: string; + MpnsHeaders?: any; + RegistrationId: string; + Tags?: string; + WnsHeaders?: any; } - export class NotificationHubService { - new(hubName: string, endpointOrConnectionString: string, sharedAccessKeyName?: string, sharedAccessKeyValue?: string): NotificationHubService; - hubName: string; - wns: Wns.Service; - apns: Apns.Service; - gcm: Gcm.Service; - mpns: Mpns.Service; - send(tags: string, payload: Object | string, optionsOrCallback?: { headers: Object } | Callback, callback?: Callback): void; - - createOrUpdateInstallation(installation: string, options: any, callback?: Callback): void; - patchInstallation(installationId: string, partialUpdateOperations: any[], options: any, callback?: Callback): void; - deleteInstallation(installationId: string, options: any, callback?: Callback): void; - getInstallation(installationId: string, options: any, callback?: Callback): void; - - /* - // old school? - createRegistrationId(callback?: Callback): void; - getRegistration(registrationId: string, options: any, callback?: Callback): void; - deleteRegistration(registrationId: string, options?: { etag: any }, callback?: Callback): void; - updateRegistration(registration: NotificationHubRegistration, options?: { etag: any }, callback?: Callback): void; - createOrUpdateRegistration(registration: NotificationHubRegistration, options?: { etag: any }, callback?: Callback): void; - listRegistrations(options?: { top: number, skip: number }, callback?: Callback): void; - listRegistrationsByTag(tag: string, options?: { top: number, skip: number }, callback?: Callback): void; - */ + export interface Response { + body: Dictionary; + headers: Dictionary; + isSuccessful: boolean; + md5?: string; + statusCode: number; } - export module Apns { - interface Payload { - expiry?: Date; - aps?: Object; - badge?: number; - alert?: string; - sound?: string; - payload: Object; + export interface ErrorResponse extends Response { + body: { + Error: { + Code: string; + Detail: string; + }; + }; + } + + export namespace Results.Models { + export enum EntityStatus { + Active = 'Active', + Creating = 'Creating', + Deleting = 'Deleting', + Disabled = 'Disabled', + ReceiveDisabled = 'ReceiveDisabled', + Renaming = 'Renaming', + Restoring = 'Restoring', + SendDisabled = 'SendDisabled', + Unknown = 'Unknown' } - interface Service { - new(service: NotificationHubService): Service; - send(tags: string | string[], payload: Apns.Payload, callback?: Callback): void; - createNativeRegistration(token: string, tags: string | string[], optionsOrCallback?: Object | Callback, callback?: Callback): void; - createOrUpdateNativeRegistration(registrationId: string, token: string, tags: string | string[], optionsOrCallback?: Object | Callback, callback?: Callback): void; - createTemplateRegistration(token: string, tags: string | string[], template: Apns.Payload, optionsOrCallback?: Object | Callback, callback?: Callback): void; - createOrUpdateTemplateRegistration(registrationId: string, token: string, tags: string | string[], template: Apns.Payload, optionsOrCallback?: Object | Callback, callback?: Callback): void; - updateTemplateRegistration(registrationId: string, token: string, tags: string | string[], template: Apns.Payload, optionsOrCallback?: Object | Callback, callback?: Callback): void; - listRegistrationsByToken(token: string, optionsOrCallback?: { top: number, skip: number } | Callback, callback?: Callback): void; + export enum EntityAvailabilityStatus { + Available = 'Available', + Limited = 'Limited', + Renaming = 'Renaming', + Restoring = 'Restoring', + Unknown = 'Unknown' } - } - export module Gcm { - interface Service { - new(service: NotificationHubService): Service; - send(tags: string | string[], payload: any, callback?: Callback): void; - createNativeRegistration(gcmRegistrationId: string, tags: string | string[], optionsOrCallback?: Object | Callback, callback?: Callback): void; - createOrUpdateNativeRegistration(registrationId: string, gcmRegistrationId: string, tags: string | string[], optionsOrCallback?: Object | Callback, callback?: Callback): void; - createTemplateRegistration(gcmRegistrationId: string, tags: string | string[], template: any, optionsOrCallback?: Object | Callback, callback?: Callback): void; - createOrUpdateTemplateRegistration(registrationId: string, gcmRegistrationId: string, tags: string | string[], template: any, optionsOrCallback?: Object | Callback, callback?: Callback): void; - updateTemplateRegistration(registrationId: string, gcmRegistrationId: string, tags: string | string[], template: any, optionsOrCallback?: Object | Callback, callback?: Callback): void; - listRegistrationsByGcmRegistrationId(gcmRegistrationId: string, optionsOrCallback?: { top: number, skip: number } | Callback, callback?: Callback): void; + + interface Base { + _: { + ContentRootElement: string; + id: string; + title: string; + published: DateString; + updated: DateString; + author?: { + name: string; + }; + link: string; + }; + CreatedAt: DateString; + } + + interface ExtendedBase extends Base { + AuthorizationRules: string; + AutoDeleteOnIdle: string; + DefaultMessageTimeToLive: string; + DuplicateDetectionHistoryTimeWindow: Duration; + EnableBatchedOperations: string; + EnableExpress: string; + EnablePartitioning: string; + EntityAvailabilityStatus: string; + IsAnonymousAccessible: string; + MaxSizeInMegabytes: string; + RequiresDuplicateDetection: string; + SizeInBytes: string; + Status: EntityStatus; + UpdatedAt: DateString; + } + + // export interface Generic extends Base { + // [x: string]: string | Dictionary; + // } + + export interface Topic extends ExtendedBase { + AccessedAt: DateString; + CountDetails: { + 'd2p1:ActiveMessageCount': string; + 'd2p1:DeadLetterMessageCount': string; + 'd2p1:ScheduledMessageCount': string; + 'd2p1:TransferMessageCount': string; + 'd2p1:TransferDeadLetterMessageCount': string; + }; + EnableSubscriptionPartitioning: string; + FilteringMessagesBeforePublishing: string; + IsExpress: string; + SubscriptionCount: string; + SupportOrdering: string; + TopicName: string; + } + + export interface Queue extends ExtendedBase { + DeadLetteringOnMessageExpiration: string; + LockDuration: Duration; + MaxDeliveryCount: string; + MessageCount: string; + QueueName: string; + RequiresSession: string; + SupportOrdering: string; + } + + export interface Subscription extends ExtendedBase { + CountDetails: { + 'd3p1:ActiveMessageCount': string; + 'd3p1:DeadLetterMessageCount': string; + 'd3p1:ScheduledMessageCount': string; + 'd3p1:TransferMessageCount': string; + 'd3p1:TransferDeadLetterMessageCount': string; + }; + DeadLetteringOnFilterEvaluationExceptions: string; + DeadLetteringOnMessageExpiration: string; + LockDuration: string; + MaxDeliveryCount: string; + MessageCount: string; + RequiresSession: string; + SubscriptionName: string; + TopicName: string; + } + + /** + * @see https://docs.microsoft.com/en-us/azure/service-bus-messaging/service-bus-messaging-sql-filter + */ + interface SqlFilter { + readonly CompatibilityLevel: string; + Parameters?: Dictionary; + RequiresPreprocessing?: string; + SqlExpression: string; + } + + type CorrelationFilter = Partial<{ + ContentType: string; + CorrelationId: string; + Label: string; + Properties: string; + ReplyTo: string; + ReplyToSessionId: string; + RequiresPreprocessing: string; + SessionId: string; + To: string; + }>; + + export interface Rule extends Base { + Action: string | SqlFilter; + Filter: SqlFilter | CorrelationFilter; + Name: string; + TopicName: string; + SubscriptionName: string; + RuleName: string; } } - export module Mpns { interface Service { } } + /* + * Callbacks + */ + export type ResponseCallback = (error: Error | null, response: Response) => void; - export module Wns { - interface Payload { - text1?: string; - text2?: string; - text3?: string; - text4?: string; - image1src?: string; - image1alt?: string; - image2src?: string; - image2alt?: string; - image3src?: string; - image3alt?: string; - image4src?: string; - image4alt?: string; - lang?: string; - type?: string; - } + export type ResultAndResponseCallback = (error: Error | null, + result: boolean | Results.Models.Base | Results.Models.Base[], + response: Response) => void; - interface Options { - headers: Object; - } + export type TypedResultAndResponseCallback = (error: Error | null, + result: T, + response: Response) => void; - interface Service { - new(service: NotificationHubService): Service; - sendTileSquareBlock(tags: string | string[], payload: any, optionsOrCallback?: Options | Callback, callback?: Callback): void; - sendTileSquareText01(tags: string | string[], payload: any, optionsOrCallback?: Options | Callback, callback?: Callback): void; - sendTileSquareText02(tags: string | string[], payload: any, optionsOrCallback?: Options | Callback, callback?: Callback): void; - sendTileSquareText03(tags: string | string[], payload: any, optionsOrCallback?: Options | Callback, callback?: Callback): void; - sendTileSquareText04(tags: string | string[], payload: any, optionsOrCallback?: Options | Callback, callback?: Callback): void; - sendTileWideText01(tags: string | string[], payload: any, optionsOrCallback?: Options | Callback, callback?: Callback): void; - sendTileWideText02(tags: string | string[], payload: any, optionsOrCallback?: Options | Callback, callback?: Callback): void; - sendTileWideText03(tags: string | string[], payload: any, optionsOrCallback?: Options | Callback, callback?: Callback): void; - sendTileWideText04(tags: string | string[], payload: any, optionsOrCallback?: Options | Callback, callback?: Callback): void; - sendTileWideText05(tags: string | string[], payload: any, optionsOrCallback?: Options | Callback, callback?: Callback): void; - sendTileWideText06(tags: string | string[], payload: any, optionsOrCallback?: Options | Callback, callback?: Callback): void; - sendTileWideText07(tags: string | string[], payload: any, optionsOrCallback?: Options | Callback, callback?: Callback): void; - sendTileWideText08(tags: string | string[], payload: any, optionsOrCallback?: Options | Callback, callback?: Callback): void; - sendTileWideText09(tags: string | string[], payload: any, optionsOrCallback?: Options | Callback, callback?: Callback): void; - sendTileWideText10(tags: string | string[], payload: any, optionsOrCallback?: Options | Callback, callback?: Callback): void; - sendTileWideText11(tags: string | string[], payload: any, optionsOrCallback?: Options | Callback, callback?: Callback): void; - sendTileSquareImage(tags: string | string[], payload: any, optionsOrCallback?: Options | Callback, callback?: Callback): void; - sendTileSquarePeekImageAndText01(tags: string | string[], payload: any, optionsOrCallback?: Options | Callback, callback?: Callback): void; - sendTileSquarePeekImageAndText02(tags: string | string[], payload: any, optionsOrCallback?: Options | Callback, callback?: Callback): void; - sendTileSquarePeekImageAndText03(tags: string | string[], payload: any, optionsOrCallback?: Options | Callback, callback?: Callback): void; - sendTileSquarePeekImageAndText04(tags: string | string[], payload: any, optionsOrCallback?: Options | Callback, callback?: Callback): void; - sendTileWideImage(tags: string | string[], payload: any, optionsOrCallback?: Options | Callback, callback?: Callback): void; - sendTileWideImageCollection(tags: string | string[], payload: any, optionsOrCallback?: Options | Callback, callback?: Callback): void; - sendTileWideImageAndText01(tags: string | string[], payload: any, optionsOrCallback?: Options | Callback, callback?: Callback): void; - sendTileWideImageAndText02(tags: string | string[], payload: any, optionsOrCallback?: Options | Callback, callback?: Callback): void; - sendTileWideBlockAndText01(tags: string | string[], payload: any, optionsOrCallback?: Options | Callback, callback?: Callback): void; - sendTileWideBlockAndText02(tags: string | string[], payload: any, optionsOrCallback?: Options | Callback, callback?: Callback): void; - sendTileWideSmallImageAndText01(tags: string | string[], payload: any, optionsOrCallback?: Options | Callback, callback?: Callback): void; - sendTileWideSmallImageAndText02(tags: string | string[], payload: any, optionsOrCallback?: Options | Callback, callback?: Callback): void; - sendTileWideSmallImageAndText03(tags: string | string[], payload: any, optionsOrCallback?: Options | Callback, callback?: Callback): void; - sendTileWideSmallImageAndText04(tags: string | string[], payload: any, optionsOrCallback?: Options | Callback, callback?: Callback): void; - sendTileWideSmallImageAndText05(tags: string | string[], payload: any, optionsOrCallback?: Options | Callback, callback?: Callback): void; - sendTileWidePeekImageCollection01(tags: string | string[], payload: any, optionsOrCallback?: Options | Callback, callback?: Callback): void; - sendTileWidePeekImageCollection02(tags: string | string[], payload: any, optionsOrCallback?: Options | Callback, callback?: Callback): void; - sendTileWidePeekImageCollection03(tags: string | string[], payload: any, optionsOrCallback?: Options | Callback, callback?: Callback): void; - sendTileWidePeekImageCollection04(tags: string | string[], payload: any, optionsOrCallback?: Options | Callback, callback?: Callback): void; - sendTileWidePeekImageCollection05(tags: string | string[], payload: any, optionsOrCallback?: Options | Callback, callback?: Callback): void; - sendTileWidePeekImageCollection06(tags: string | string[], payload: any, optionsOrCallback?: Options | Callback, callback?: Callback): void; - sendTileWidePeekImageAndText01(tags: string | string[], payload: any, optionsOrCallback?: Options | Callback, callback?: Callback): void; - sendTileWidePeekImageAndText02(tags: string | string[], payload: any, optionsOrCallback?: Options | Callback, callback?: Callback): void; - sendTileWidePeekImage01(tags: string | string[], payload: any, optionsOrCallback?: Options | Callback, callback?: Callback): void; - sendTileWidePeekImage02(tags: string | string[], payload: any, optionsOrCallback?: Options | Callback, callback?: Callback): void; - sendTileWidePeekImage03(tags: string | string[], payload: any, optionsOrCallback?: Options | Callback, callback?: Callback): void; - sendTileWidePeekImage04(tags: string | string[], payload: any, optionsOrCallback?: Options | Callback, callback?: Callback): void; - sendTileWidePeekImage05(tags: string | string[], payload: any, optionsOrCallback?: Options | Callback, callback?: Callback): void; - sendTileWidePeekImage06(tags: string | string[], payload: any, optionsOrCallback?: Options | Callback, callback?: Callback): void; - sendToastText01(tags: string | string[], payload: any, optionsOrCallback?: Options | Callback, callback?: Callback): void; - sendToastText02(tags: string | string[], payload: any, optionsOrCallback?: Options | Callback, callback?: Callback): void; - sendToastText03(tags: string | string[], payload: any, optionsOrCallback?: Options | Callback, callback?: Callback): void; - sendToastText04(tags: string | string[], payload: any, optionsOrCallback?: Options | Callback, callback?: Callback): void; - sendToastImageAndText01(tags: string | string[], payload: any, optionsOrCallback?: Options | Callback, callback?: Callback): void; - sendToastImageAndText02(tags: string | string[], payload: any, optionsOrCallback?: Options | Callback, callback?: Callback): void; - sendToastImageAndText03(tags: string | string[], payload: any, optionsOrCallback?: Options | Callback, callback?: Callback): void; - sendToastImageAndText04(tags: string | string[], payload: any, optionsOrCallback?: Options | Callback, callback?: Callback): void; - // badges = ['none','activity','alert','available','away','busy','newMessage','paused','playing','unavailable','error', 'attention'] - sendBadge(tags: string | string[], value: string | number, optionsOrCallback?: Options | Callback, callback?: Callback): void; - sendRaw(tags: string | string[], payload: any, optionsOrCallback?: Options | Callback, callback?: Callback): void; - // types = ['wns/toast', 'wns/badge', 'wns/tile', 'wns/raw'] - send(tags: string | string[], payload: string, type: string, optionsOrCallback?: Options | Callback, callback?: Callback): void; - createNativeRegistration(channel: string, tags: string | string[], optionsOrCallback?: Options | Callback, callback?: Callback): void; - createOrUpdateNativeRegistration(registrationId: string, channel: string, tags: string | string[], optionsOrCallback?: Options | Callback, callback?: Callback): void; - listRegistrationsByChannel(channel: string, optionsOrCallback?: { top: number, skip: number } | Callback, callback?: Callback): void; - } - } + /* + * Options interfaces with all properties as optional + */ + export type BrokerProperties = Partial; + export type BrokerPropertiesResponse = IBrokerPropertiesResponse & Partial; + export type CreateQueueOptions = Partial; + export type CreateTopicOptions = Partial; + export type CreateTopicIfNotExistsOptions = Partial; + export type CreateSubscriptionOptions = Partial; + export type ListSubscriptionsOptions = Partial; + export type ListRulesOptions = Partial; + export type CreateRuleOptions = Partial; + export type CreateNotificationHubOptions = Partial; + export type ListNotificationHubsOptions = Partial; + + export type MessageOrName = Message | string; } diff --git a/types/azure-sb/lib/apnsservice.d.ts b/types/azure-sb/lib/apnsservice.d.ts new file mode 100644 index 0000000000..05ca2f7b43 --- /dev/null +++ b/types/azure-sb/lib/apnsservice.d.ts @@ -0,0 +1,83 @@ +import { Azure } from '../index'; +import NotificationHubService = require('azure-sb/lib/notificationhubservice'); +import ResponseCallback = Azure.ServiceBus.ResponseCallback; +import NotificationHubRegistration = Azure.ServiceBus.NotificationHubRegistration; +import ListNotificationHubsOptions = Azure.ServiceBus.ListNotificationHubsOptions; +import Dictionary = Azure.ServiceBus.Dictionary; + +type Template = Partial<{ + expiry: Date; + aps: object; + badge: number; + alert: string; + sound: string; + payload: object; +}>; + +declare class ApnsService { + constructor(notificationHubService: NotificationHubService); + + public notificationHubService: NotificationHubService; + + public send(tags: string | string[], + payload: object | string, + callback: ResponseCallback): void; + + public send(tags: string | string[], + payload: object | string, + options: { headers: Dictionary }, + callback: ResponseCallback): void; + + public createNativeRegistration(token: string, + tags: string | string[], + callback: ResponseCallback): void; + + public createNativeRegistration(token: string, + tags: string | string[], + options: object, + callback: ResponseCallback): void; + + public createOrUpdateNativeRegistration(registrationId: string, + token: string, + tags: string | string[], + callback: ResponseCallback): void; + + public createOrUpdateNativeRegistration(registrationId: string, + token: string, + tags: string | string[], + options: object, + callback: ResponseCallback): void; + + public createTemplateRegistration(token: string, + tags: string | string[], + template: Template | string, + callback: ResponseCallback): void; + + public createTemplateRegistration(token: string, + tags: string | string[], + template: Template | string, + options: object, + callback: ResponseCallback): void; + + public updateTemplateRegistration(registrationId: string, + token: string, + tags: string | string[], + template: Template | string, + callback: ResponseCallback): void; + + public updateTemplateRegistration(registrationId: string, + token: string, + tags: string | string[], + template: Template | string, + options: { headers: Dictionary }, + callback: ResponseCallback): void; + + public listRegistrationsByToken(token: string, + callback: ResponseCallback): void; + + public listRegistrationsByToken(token: string, + options: ListNotificationHubsOptions, + callback: ResponseCallback): void; +} + +export = ApnsService; diff --git a/types/azure-sb/lib/gcmservice.d.ts b/types/azure-sb/lib/gcmservice.d.ts new file mode 100644 index 0000000000..4d1c8f203c --- /dev/null +++ b/types/azure-sb/lib/gcmservice.d.ts @@ -0,0 +1,71 @@ +import { Azure } from '../index'; +import NotificationHubService = require('azure-sb/lib/notificationhubservice'); +import ResponseCallback = Azure.ServiceBus.ResponseCallback; +import NotificationHubRegistration = Azure.ServiceBus.NotificationHubRegistration; +import ListNotificationHubsOptions = Azure.ServiceBus.ListNotificationHubsOptions; +import Dictionary = Azure.ServiceBus.Dictionary; + +type Template = Partial<{}>; + +declare class GcmService { + constructor(notificationHubService: NotificationHubService); + + public notificationHubService: NotificationHubService; + + public send(tags: string | string[], + payload: object | string, + callback: ResponseCallback): void; + + public createNativeRegistration(gcmRegistrationId: string, + tags: string | string[], + callback: ResponseCallback): void; + + public createNativeRegistration(token: string, + tags: string | string[], + options: object, + callback: ResponseCallback): void; + + public createOrUpdateNativeRegistration(registrationId: string, + gcmRegistrationId: string, + tags: string | string[], + callback: ResponseCallback): void; + + public createOrUpdateNativeRegistration(registrationId: string, + gcmRegistrationId: string, + tags: string | string[], + options: object, + callback: ResponseCallback): void; + + public createTemplateRegistration(gcmRegistrationId: string, + tags: string | string[], + template: Template | string, + callback: ResponseCallback): void; + + public createTemplateRegistration(gcmRegistrationId: string, + tags: string | string[], + template: Template | string, + options: object, + callback: ResponseCallback): void; + + public updateTemplateRegistration(registrationId: string, + gcmRegistrationId: string, + tags: string | string[], + template: Template | string, + callback: ResponseCallback): void; + + public updateTemplateRegistration(registrationId: string, + gcmRegistrationId: string, + tags: string | string[], + template: Template | string, + options: { headers: Dictionary }, + callback: ResponseCallback): void; + + public listRegistrationsByGcmRegistrationId(gcmRegistrationId: string, + callback: ResponseCallback): void; + + public listRegistrationsByGcmRegistrationId(gcmRegistrationId: string, + options: ListNotificationHubsOptions, + callback: ResponseCallback): void; +} + +export = GcmService; diff --git a/types/azure-sb/lib/models/acstokenresult.d.ts b/types/azure-sb/lib/models/acstokenresult.d.ts new file mode 100644 index 0000000000..531c606de1 --- /dev/null +++ b/types/azure-sb/lib/models/acstokenresult.d.ts @@ -0,0 +1,29 @@ +// +// Copyright (c) Microsoft and contributors. All rights reserved. +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// +// See the License for the specific language governing permissions and +// limitations under the License. +// + +import { Azure } from 'azure-sb'; +import Dictionary = Azure.ServiceBus.Dictionary; + +export namespace Azure.ServiceBus.Results { + export interface AcsTokenResponse extends Dictionary> { + WrapAccessToken: Dictionary; + WrapAccessTokenExpiresIn: Dictionary; + } + + export interface AcsTokenResult { + parse(acsTokenQueryString: string): AcsTokenResponse; + } +} diff --git a/types/azure-sb/lib/models/notificationhubresult.d.ts b/types/azure-sb/lib/models/notificationhubresult.d.ts new file mode 100644 index 0000000000..1aef66c3d6 --- /dev/null +++ b/types/azure-sb/lib/models/notificationhubresult.d.ts @@ -0,0 +1,26 @@ +// +// Copyright (c) Microsoft and contributors. All rights reserved. +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// +// See the License for the specific language governing permissions and +// limitations under the License. +// + +import { Azure } from 'azure-sb'; +import Dictionary = Azure.ServiceBus.Dictionary; + +export namespace Azure.ServiceBus.Results { + export interface NotificationHubResult { + serialize(resource: Azure.ServiceBus.CreateNotificationHubOptions): string; + + parse(xml: object): object | object[]; + } +} diff --git a/types/azure-sb/lib/models/queuemessageresult.d.ts b/types/azure-sb/lib/models/queuemessageresult.d.ts new file mode 100644 index 0000000000..a50d0965cb --- /dev/null +++ b/types/azure-sb/lib/models/queuemessageresult.d.ts @@ -0,0 +1,40 @@ +// +// Copyright (c) Microsoft and contributors. All rights reserved. +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// +// See the License for the specific language governing permissions and +// limitations under the License. +// + +// Module dependencies. +import { Azure } from 'azure-sb'; +import Dictionary = Azure.ServiceBus.Dictionary; + +export namespace Azure.ServiceBus.Results { + export interface QueueResponse { + body: any; + headers: Dictionary + } + + export interface QueueMessageResponse { + body: any; + brokerProperties?: Azure.ServiceBus.BrokerProperties; + customProperties?: Dictionary; + contentType?: string; + location?: string; + } + + export interface QueueMessageResult { + parse(responseObject: object): QueueMessageResponse; + + isRFC1123(value: string | any): boolean; + } +} diff --git a/types/azure-sb/lib/models/queueresult.d.ts b/types/azure-sb/lib/models/queueresult.d.ts new file mode 100644 index 0000000000..abeed96dff --- /dev/null +++ b/types/azure-sb/lib/models/queueresult.d.ts @@ -0,0 +1,41 @@ +// +// Copyright (c) Microsoft and contributors. All rights reserved. +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// +// See the License for the specific language governing permissions and +// limitations under the License. +// + +import { Azure } from 'azure-sb'; +import Dictionary = Azure.ServiceBus.Dictionary; + +export namespace Azure.ServiceBus.Results { + export interface QueueProperties { + DeadLetteringOnMessageExpiration: string; + DefaultMessageTimeToLive: string; + DuplicateDetectionHistoryTimeWindow: string; + EnableBatchedOperations: boolean; + EnablePartitioning: boolean; + LockDuration: string; + MaxDeliveryCount: number; + MaxSizeInMegabytes: number; + MessageCount: number; + RequiresDuplicateDetection: boolean; + RequiresSession: boolean; + SizeInBytes: number; + } + + export interface QueueResult { + serialize(resource: QueueProperties): string; + + parse(xml: object): object | object[]; + } +} diff --git a/types/azure-sb/lib/models/registrationresult.d.ts b/types/azure-sb/lib/models/registrationresult.d.ts new file mode 100644 index 0000000000..81c1fdd824 --- /dev/null +++ b/types/azure-sb/lib/models/registrationresult.d.ts @@ -0,0 +1,26 @@ +// +// Copyright (c) Microsoft and contributors. All rights reserved. +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// +// See the License for the specific language governing permissions and +// limitations under the License. +// + +import { Azure } from 'azure-sb'; +import Dictionary = Azure.ServiceBus.Dictionary; + +export namespace Azure.ServiceBus.Results { + export interface RegistrationResult { + serialize(type: string, resource: object, properties: string[]): string; + + parse(xml: object): object | object[]; + } +} diff --git a/types/azure-sb/lib/models/resourceresult.d.ts b/types/azure-sb/lib/models/resourceresult.d.ts new file mode 100644 index 0000000000..b9654b0438 --- /dev/null +++ b/types/azure-sb/lib/models/resourceresult.d.ts @@ -0,0 +1,28 @@ +// +// Copyright (c) Microsoft and contributors. All rights reserved. +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// +// See the License for the specific language governing permissions and +// limitations under the License. +// + +import { Azure } from 'azure-sb'; +import Dictionary = Azure.ServiceBus.Dictionary; + +export namespace Azure.ServiceBus.Results { + export interface ResourceResult { + setName(entry: Dictionary | { _: { id: string } }, nameProperty: string): void; + + serialize(resourceName: string, resource: object, properties: string[]): string; + + parse(resourceName: string, nameProperty: string, xml: object): object | object[]; + } +} diff --git a/types/azure-sb/lib/models/ruleresult.d.ts b/types/azure-sb/lib/models/ruleresult.d.ts new file mode 100644 index 0000000000..369a4ddeb7 --- /dev/null +++ b/types/azure-sb/lib/models/ruleresult.d.ts @@ -0,0 +1,26 @@ +// +// Copyright (c) Microsoft and contributors. All rights reserved. +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// +// See the License for the specific language governing permissions and +// limitations under the License. +// + +// Module dependencies. +import { Azure } from 'azure-sb'; + +export namespace Azure.ServiceBus.Results { + export interface RuleResult { + serialize(rule: Azure.ServiceBus.CreateRuleOptions): string; + + parse(xml: object): object | object[]; + } +} diff --git a/types/azure-sb/lib/models/subscriptionresult.d.ts b/types/azure-sb/lib/models/subscriptionresult.d.ts new file mode 100644 index 0000000000..003c085da0 --- /dev/null +++ b/types/azure-sb/lib/models/subscriptionresult.d.ts @@ -0,0 +1,37 @@ +// +// Copyright (c) Microsoft and contributors. All rights reserved. +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// +// See the License for the specific language governing permissions and +// limitations under the License. +// + +import { Azure } from 'azure-sb'; + +export namespace Azure.ServiceBus.Results { + export interface SubscriptionProperties { + LockDuration: string; + RequiresSession: boolean; + DefaultMessageTimeToLive: string; + DeadLetteringOnMessageExpiration: string; + DeadLetteringOnFilterEvaluationExceptions: string; + MessageCount: number; + MaxDeliveryCount: number; + EnableBatchedOperations: boolean; + AutoDeleteOnIdle: boolean; + } + + export interface SubscriptionResult { + serialize(resource: SubscriptionProperties): string; + + parse(xml: object): object | object[]; + } +} diff --git a/types/azure-sb/lib/models/topicresult.d.ts b/types/azure-sb/lib/models/topicresult.d.ts new file mode 100644 index 0000000000..7f20125b51 --- /dev/null +++ b/types/azure-sb/lib/models/topicresult.d.ts @@ -0,0 +1,32 @@ +// +// Copyright (c) Microsoft and contributors. All rights reserved. +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// +// See the License for the specific language governing permissions and +// limitations under the License. +// + +export namespace Azure.ServiceBus.Results { + export interface TopicProperties { + DefaultMessageTimeToLive: string; + MaxSizeInMegabytes: number; + RequiresDuplicateDetection: boolean; + DuplicateDetectionHistoryTimeWindow: string; + EnableBatchedOperations: boolean; + SizeInBytes: number; + SupportOrdering: boolean; + EnablePartitioning: boolean; + } +} + +export function serialize(resource: Azure.ServiceBus.Results.TopicProperties): string; + +export function parse(xml: object): object | object[]; diff --git a/types/azure-sb/lib/mpnservice.d.ts b/types/azure-sb/lib/mpnservice.d.ts new file mode 100644 index 0000000000..d476f4d984 --- /dev/null +++ b/types/azure-sb/lib/mpnservice.d.ts @@ -0,0 +1,116 @@ +import { Azure } from '../index'; +import NotificationHubService = require('azure-sb/lib/notificationhubservice'); +import ResponseCallback = Azure.ServiceBus.ResponseCallback; +import NotificationHubRegistration = Azure.ServiceBus.NotificationHubRegistration; +import ListNotificationHubsOptions = Azure.ServiceBus.ListNotificationHubsOptions; +import Dictionary = Azure.ServiceBus.Dictionary; + +type Template = TileTemplate | FlipTileTemplate | ToastTemplate; + +interface TileTemplate { + backgroundImage: string; + count: string; + title: string; + backBackgroundImage: string; + backTitle: string; + backContent: string; + id: string; +} + +interface FlipTileTemplate extends TileTemplate { + smallBackgroundImage: string; + wideBackgroundImage: string; + wideBackContent: string; + wideBackBackgroundImage: string; +} + +interface ToastTemplate { + text1: string; + text2: string; + param?: string; +} + +declare class MpnsService { + constructor(notificationHubService: NotificationHubService); + + public notificationHubService: NotificationHubService; + + public send(tags: string | string[], + payload: object | string, + targetName: string, + notificationClass: string, + callback: ResponseCallback): void; + + public send(tags: string | string[], + payload: object | string, + targetName: string, + notificationClass: string, + options: { headers: Dictionary }, + callback: ResponseCallback): void; + + public createNativeRegistration(channel: string, + tags: string | string[], + callback: ResponseCallback): void; + + public createNativeRegistration(channel: string, + tags: string | string[], + options: object, + callback: ResponseCallback): void; + + public createOrUpdateNativeRegistration(registrationId: string, + channel: string, + tags: string | string[], + callback: ResponseCallback): void; + + public createOrUpdateNativeRegistration(registrationId: string, + channel: string, + tags: string | string[], + options: object, + callback: ResponseCallback): void; + + public createRawTemplateRegistration(channel: string, + tags: string | string[], + template: Template | string, + callback: ResponseCallback): void; + + public createRawTemplateRegistration(channel: string, + tags: string | string[], + template: Template | string, + options: object, + callback: ResponseCallback): void; + + public createOrUpdateRawTemplateRegistration(registrationId: string, + channel: string, + tags: string | string[], + template: Template | string, + callback: ResponseCallback): void; + + public createOrUpdateRawTemplateRegistration(registrationId: string, + channel: string, + tags: string | string[], + template: Template | string, + options: object, + callback: ResponseCallback): void; + + public updatesRawTemplateRegistration(registrationId: string, + channel: string, + tags: string | string[], + template: Template | string, + callback: ResponseCallback): void; + + public updatesRawTemplateRegistration(registrationId: string, + channel: string, + tags: string | string[], + template: Template | string, + options: object, + callback: ResponseCallback): void; + + public listRegistrationsByChannel(channel: string, + callback: ResponseCallback): void; + + public listRegistrationsByChannel(channel: string, + options: ListNotificationHubsOptions, + callback: ResponseCallback): void; +} + +export = MpnsService; diff --git a/types/azure-sb/lib/notificationhubservice.d.ts b/types/azure-sb/lib/notificationhubservice.d.ts new file mode 100644 index 0000000000..d56b53d9d5 --- /dev/null +++ b/types/azure-sb/lib/notificationhubservice.d.ts @@ -0,0 +1,102 @@ +import { Azure } from 'azure-sb'; +import Callback = Azure.ServiceBus.ResponseCallback; +import NotificationHubRegistration = Azure.ServiceBus.NotificationHubRegistration; +import ListNotificationHubsOptions = Azure.ServiceBus.ListNotificationHubsOptions; + +import ApnsService = require('./apnsservice'); +import GcmService = require('./gcmservice'); +import MpnsService = require('./mpnservice'); +import WnsService = require('./wnsservice'); + +declare class NotificationHubService { + constructor(hubName: string, + endpointOrConnectionString: string, + sharedAccessKeyName: string, + sharedAccessKeyValue: string); + + public hubName: string; + public wns: WnsService; + public apns: ApnsService; + public gcm: GcmService; + public mpns: MpnsService; + + public send(tags: string, + payload: object | string, + callback: Callback): void; + + public send(tags: string, + payload: object | string, + options: { headers: object }, + callback: Callback): void; + + public createOrUpdateInstallation(installation: string, + callback: Callback): void; + + public createOrUpdateInstallation(installation: string, + options: any, + callback: Callback): void; + + public patchInstallation(installationId: string, + partialUpdateOperations: any[], + callback: Callback): void; + + public patchInstallation(installationId: string, + partialUpdateOperations: any[], + options: any, + callback: Callback): void; + + public deleteInstallation(installationId: string, + callback: Callback): void; + + public deleteInstallation(installationId: string, + options: any, + callback: Callback): void; + + public getInstallation(installationId: string, + callback: Callback): void; + + public getInstallation(installationId: string, + options: any, + callback: Callback): void; + + public createRegistrationId(callback: Callback): void; + + public getRegistration(registrationId: string, + callback: Callback): void; + + public getRegistration(registrationId: string, + options: any, + callback: Callback): void; + + public deleteRegistration(registrationId: string, + callback: Callback): void; + + public deleteRegistration(registrationId: string, + options: { etag: any }, + callback: Callback): void; + + public updateRegistration(registration: NotificationHubRegistration, + callback: Callback): void; + + public updateRegistration(registration: NotificationHubRegistration, + options: { etag: any }, + callback: Callback): void; + + public createOrUpdateRegistration(registration: NotificationHubRegistration, + options: { etag: any }, + callback: Callback): void; + + public listRegistrations(callback: Callback): void; + + public listRegistrations(options: ListNotificationHubsOptions, + callback: Callback): void; + + public listRegistrationsByTag(tag: string, + callback: Callback): void; + + public listRegistrationsByTag(tag: string, + options: ListNotificationHubsOptions, + callback: Callback): void; +} + +export = NotificationHubService; diff --git a/types/azure-sb/lib/servicebusservice.d.ts b/types/azure-sb/lib/servicebusservice.d.ts new file mode 100644 index 0000000000..44f2b2c522 --- /dev/null +++ b/types/azure-sb/lib/servicebusservice.d.ts @@ -0,0 +1,206 @@ +import { Azure } from '../index'; + +import ServiceBusServiceBase = require('./servicebusservicebase'); + +import CreateNotificationHubOptions = Azure.ServiceBus.CreateNotificationHubOptions; +import CreateQueueOptions = Azure.ServiceBus.CreateQueueOptions; +import CreateRuleOptions = Azure.ServiceBus.CreateRuleOptions; +import CreateSubscriptionOptions = Azure.ServiceBus.CreateSubscriptionOptions; +import CreateTopicIfNotExistsOptions = Azure.ServiceBus.CreateTopicIfNotExistsOptions; +import CreateTopicOptions = Azure.ServiceBus.CreateTopicOptions; +import ListNotificationHubsOptions = Azure.ServiceBus.ListNotificationHubsOptions; +import ListRulesOptions = Azure.ServiceBus.ListRulesOptions; +import ListSubscriptionsOptions = Azure.ServiceBus.ListSubscriptionsOptions; +import MessageOrName = Azure.ServiceBus.MessageOrName; +import Queue = Azure.ServiceBus.Results.Models.Queue; +import ReceiveQueueMessageOptions = Azure.ServiceBus.ReceiveQueueMessageOptions; +import ReceiveSubscriptionMessageOptions = Azure.ServiceBus.ReceiveSubscriptionMessageOptions; +import ResponseCallback = Azure.ServiceBus.ResponseCallback; +import ResultAndResponseCallback = Azure.ServiceBus.ResultAndResponseCallback; +import Rule = Azure.ServiceBus.Results.Models.Rule; +import Subscription = Azure.ServiceBus.Results.Models.Subscription; +import Topic = Azure.ServiceBus.Results.Models.Topic; +import TypedResultAndResponseCallback = Azure.ServiceBus.TypedResultAndResponseCallback; +import Message = Azure.ServiceBus.Message; + +declare class ServiceBusService extends ServiceBusServiceBase { + constructor(configOrNamespaceOrConnectionString?: string, + accessKey?: string, + issuer?: string, + acsNamespace?: string, + host?: string, + authenticationProvider?: object); + + public receiveQueueMessage(queuePath: string, + callback: TypedResultAndResponseCallback): void; + + public receiveQueueMessage(queuePath: string, + options: ReceiveQueueMessageOptions, + callback: TypedResultAndResponseCallback): void; + + public receiveSubscriptionMessage(topicPath: string, + subscriptionPath: string, + callback: TypedResultAndResponseCallback): void; + + public receiveSubscriptionMessage(topicPath: string, + subscriptionPath: string, + options: ReceiveSubscriptionMessageOptions, + callback: TypedResultAndResponseCallback): void; + + public deleteMessage(message: MessageOrName, + callback: ResponseCallback): void; + + public unlockMessage(message: MessageOrName, + callback: ResponseCallback): void; + + public renewLockForMessage(message: MessageOrName, + callback: ResponseCallback): void; + + public sendQueueMessage(queuePath: string, + message: MessageOrName, + callback: ResponseCallback): void; + + public sendTopicMessage(topicPath: string, + message: MessageOrName, + callback: ResponseCallback): void; + + /* + * Queue Management functions + */ + + public createQueue(queuePath: string, + callback: TypedResultAndResponseCallback): void; + + public createQueue(queuePath: string, + options: CreateQueueOptions, + callback: TypedResultAndResponseCallback): void; + + public createQueueIfNotExists(queuePath: string, + callback: TypedResultAndResponseCallback): void; + + public createQueueIfNotExists(queuePath: string, + options: CreateQueueOptions, + callback: TypedResultAndResponseCallback): void; + + public deleteQueue(queuePath: string, + callback: ResponseCallback): void; + + public getQueue(queuePath: string, + callback: TypedResultAndResponseCallback): void; + + public listQueues(queuePath: string, + callback: TypedResultAndResponseCallback): void; + + /* + * Topic Management functions + */ + + public createTopic(topicPath: string, + callback: TypedResultAndResponseCallback): void; + + public createTopic(topicPath: string, + options: CreateTopicOptions, + callback: TypedResultAndResponseCallback): void; + + public createTopicIfNotExists(topicPath: string, + callback: TypedResultAndResponseCallback): void; + + public createTopicIfNotExists(topicPath: string, + options: CreateTopicIfNotExistsOptions, + callback: TypedResultAndResponseCallback): void; + + public deleteTopic(topicPath: string, + callback: ResponseCallback): void; + + public getTopic(topicPath: string, + callback: TypedResultAndResponseCallback): void; + + public listTopics(topicPath: string, + callback: TypedResultAndResponseCallback): void; + + /* + * Subscription functions + */ + + public createSubscription(topicPath: string, + subscriptionPath: string, + callback: TypedResultAndResponseCallback): void; + + public createSubscription(topicPath: string, + subscriptionPath: string, + options: CreateSubscriptionOptions, + callback: TypedResultAndResponseCallback): void; + + public deleteSubscription(topicPath: string, + subscriptionPath: string, + callback: ResponseCallback): void; + + public getSubscription(topicPath: string, + subscriptionPath: string, + callback: TypedResultAndResponseCallback): void; + + public listSubscriptions(topicPath: string, + callback: TypedResultAndResponseCallback): void; + + public listSubscriptions(topicPath: string, + options: ListSubscriptionsOptions, + callback: TypedResultAndResponseCallback): void; + + /* + * Rule functions + */ + + public createRule(topicPath: string, + subscriptionPath: string, + rulePath: string, + callback: TypedResultAndResponseCallback): void; + + public createRule(topicPath: string, + subscriptionPath: string, + rulePath: string, + options: CreateRuleOptions, + callback: TypedResultAndResponseCallback): void; + + public deleteRule(topicPath: string, + subscriptionPath: string, + rulePath: string, + callback: ResponseCallback): void; + + public getRule(topicPath: string, + subscriptionPath: string, + rulePath: string, + callback: TypedResultAndResponseCallback): void; + + public listRules(topicPath: string, + subscriptionPath: string, + callback: TypedResultAndResponseCallback): void; + + public listRules(topicPath: string, + subscriptionPath: string, + options: ListRulesOptions, + callback: TypedResultAndResponseCallback): void; + + /* + * NotificationHub functions + */ + + public createNotificationHub(hubPath: string, + callback: ResultAndResponseCallback): void; + + public createNotificationHub(hubPath: string, + options: CreateNotificationHubOptions, + callback: ResultAndResponseCallback): void; + + public getNotificationHub(hubPath: string, + callback: ResultAndResponseCallback): void; + + public listNotificationHubs(callback: ResultAndResponseCallback): void; + + public listNotificationHubs(options: ListNotificationHubsOptions, + callback: ResultAndResponseCallback): void; + + public deleteNotificationHub(hubPath: string, + callback: ResponseCallback): void; +} + +export = ServiceBusService; diff --git a/types/azure-sb/lib/servicebusservicebase.d.ts b/types/azure-sb/lib/servicebusservicebase.d.ts new file mode 100644 index 0000000000..c29ead478c --- /dev/null +++ b/types/azure-sb/lib/servicebusservicebase.d.ts @@ -0,0 +1,12 @@ +import ServiceBusServiceClient = require('azure-sb/lib/servicebusserviceclient'); + +declare class ServiceBusServiceBase extends ServiceBusServiceClient { + constructor(configOrNamespaceOrConnectionString: string, + accessKey?: string, + issuer?: string, + acsNamespace?: string, + host?: string, + authenticationProvider?: object); +} + +export = ServiceBusServiceBase; diff --git a/types/azure-sb/lib/servicebusserviceclient.d.ts b/types/azure-sb/lib/servicebusserviceclient.d.ts new file mode 100644 index 0000000000..c97b1e3107 --- /dev/null +++ b/types/azure-sb/lib/servicebusserviceclient.d.ts @@ -0,0 +1,14 @@ +/// +import EventEmitter = NodeJS.EventEmitter; + +declare class ServiceBusServiceClient extends EventEmitter { + constructor(accessKey?: string, + issuer?: string, + sharedAccessKeyName?: string, + sharedAccessKeyValue?: string, + host?: string, + acsHost?: string, + authenticationProvider?: object); +} + +export = ServiceBusServiceClient; diff --git a/types/azure-sb/lib/wnsservice.d.ts b/types/azure-sb/lib/wnsservice.d.ts new file mode 100644 index 0000000000..1fef2da042 --- /dev/null +++ b/types/azure-sb/lib/wnsservice.d.ts @@ -0,0 +1,377 @@ +import NotificationHubService = require('azure-sb/lib/notificationhubservice'); +import Callback = Azure.ServiceBus.ResponseCallback; +import { Azure } from 'azure-sb'; +import ListNotificationHubsOptions = Azure.ServiceBus.ListNotificationHubsOptions; +import Dictionary = Azure.ServiceBus.Dictionary; + +type Payload = Partial<{ + text1: string; + text2: string; + text3: string; + text4: string; + image1src: string; + image1alt: string; + image2src: string; + image2alt: string; + image3src: string; + image3alt: string; + image4src: string; + image4alt: string; + lang: string; + type: string; +}>; + +interface Options { + headers: Dictionary; +} + +type badges = + 'none' + | 'activity' + | 'alert' + | 'available' + | 'away' + | 'busy' + | 'newMessage' + | 'paused' + | 'playing' + | 'unavailable' + | 'error' + | 'attention'; + +type types = 'wns/toast' | 'wns/badge' | 'wns/tile' | 'wns/raw'; + +declare class WnsService { + constructor(service: NotificationHubService); + + public notificationHubService: NotificationHubService; + + sendTileSquareBlock(tags: string | string[], + payload: any, + optionsOrCallback: Options | Callback, + callback?: Callback): void; + + sendTileSquareText01(tags: string | string[], + payload: any, + optionsOrCallback: Options | Callback, + callback?: Callback): void; + + sendTileSquareText02(tags: string | string[], + payload: any, + optionsOrCallback: Options | Callback, + callback?: Callback): void; + + sendTileSquareText03(tags: string | string[], + payload: any, + optionsOrCallback: Options | Callback, + callback?: Callback): void; + + sendTileSquareText04(tags: string | string[], + payload: any, + optionsOrCallback: Options | Callback, + callback?: Callback): void; + + sendTileWideText01(tags: string | string[], + payload: any, + optionsOrCallback: Options | Callback, + callback?: Callback): void; + + sendTileWideText02(tags: string | string[], + payload: any, + optionsOrCallback: Options | Callback, + callback?: Callback): void; + + sendTileWideText03(tags: string | string[], + payload: any, + optionsOrCallback: Options | Callback, + callback?: Callback): void; + + sendTileWideText04(tags: string | string[], + payload: any, + optionsOrCallback: Options | Callback, + callback?: Callback): void; + + sendTileWideText05(tags: string | string[], + payload: any, + optionsOrCallback: Options | Callback, + callback?: Callback): void; + + sendTileWideText06(tags: string | string[], + payload: any, + optionsOrCallback: Options | Callback, + callback?: Callback): void; + + sendTileWideText07(tags: string | string[], + payload: any, + optionsOrCallback: Options | Callback, + callback?: Callback): void; + + sendTileWideText08(tags: string | string[], + payload: any, + optionsOrCallback: Options | Callback, + callback?: Callback): void; + + sendTileWideText09(tags: string | string[], + payload: any, + optionsOrCallback: Options | Callback, + callback?: Callback): void; + + sendTileWideText10(tags: string | string[], + payload: any, + optionsOrCallback: Options | Callback, + callback?: Callback): void; + + sendTileWideText11(tags: string | string[], + payload: any, + optionsOrCallback: Options | Callback, + callback?: Callback): void; + + sendTileSquareImage(tags: string | string[], + payload: any, + optionsOrCallback: Options | Callback, + callback?: Callback): void; + + sendTileSquarePeekImageAndText01(tags: string | string[], + payload: any, + optionsOrCallback: Options | Callback, + callback?: Callback): void; + + sendTileSquarePeekImageAndText02(tags: string | string[], + payload: any, + optionsOrCallback: Options | Callback, + callback?: Callback): void; + + sendTileSquarePeekImageAndText03(tags: string | string[], + payload: any, + optionsOrCallback: Options | Callback, + callback?: Callback): void; + + sendTileSquarePeekImageAndText04(tags: string | string[], + payload: any, + optionsOrCallback: Options | Callback, + callback?: Callback): void; + + sendTileWideImage(tags: string | string[], + payload: any, + optionsOrCallback: Options | Callback, + callback?: Callback): void; + + sendTileWideImageCollection(tags: string | string[], + payload: any, + optionsOrCallback: Options | Callback, + callback?: Callback): void; + + sendTileWideImageAndText01(tags: string | string[], + payload: any, + optionsOrCallback: Options | Callback, + callback?: Callback): void; + + sendTileWideImageAndText02(tags: string | string[], + payload: any, + optionsOrCallback: Options | Callback, + callback?: Callback): void; + + sendTileWideBlockAndText01(tags: string | string[], + payload: any, + optionsOrCallback: Options | Callback, + callback?: Callback): void; + + sendTileWideBlockAndText02(tags: string | string[], + payload: any, + optionsOrCallback: Options | Callback, + callback?: Callback): void; + + sendTileWideSmallImageAndText01(tags: string | string[], + payload: any, + optionsOrCallback: Options | Callback, + callback?: Callback): void; + + sendTileWideSmallImageAndText02(tags: string | string[], + payload: any, + optionsOrCallback: Options | Callback, + callback?: Callback): void; + + sendTileWideSmallImageAndText03(tags: string | string[], + payload: any, + optionsOrCallback: Options | Callback, + callback?: Callback): void; + + sendTileWideSmallImageAndText04(tags: string | string[], + payload: any, + optionsOrCallback: Options | Callback, + callback?: Callback): void; + + sendTileWideSmallImageAndText05(tags: string | string[], + payload: any, + optionsOrCallback: Options | Callback, + callback?: Callback): void; + + sendTileWidePeekImageCollection01(tags: string | string[], + payload: any, + optionsOrCallback: Options | Callback, + callback?: Callback): void; + + sendTileWidePeekImageCollection02(tags: string | string[], + payload: any, + optionsOrCallback: Options | Callback, + callback?: Callback): void; + + sendTileWidePeekImageCollection03(tags: string | string[], + payload: any, + optionsOrCallback: Options | Callback, + callback?: Callback): void; + + sendTileWidePeekImageCollection04(tags: string | string[], + payload: any, + optionsOrCallback: Options | Callback, + callback?: Callback): void; + + sendTileWidePeekImageCollection05(tags: string | string[], + payload: any, + optionsOrCallback: Options | Callback, + callback?: Callback): void; + + sendTileWidePeekImageCollection06(tags: string | string[], + payload: any, + optionsOrCallback: Options | Callback, + callback?: Callback): void; + + sendTileWidePeekImageAndText01(tags: string | string[], + payload: any, + optionsOrCallback: Options | Callback, + callback?: Callback): void; + + sendTileWidePeekImageAndText02(tags: string | string[], + payload: any, + optionsOrCallback: Options | Callback, + callback?: Callback): void; + + sendTileWidePeekImage01(tags: string | string[], + payload: any, + optionsOrCallback: Options | Callback, + callback?: Callback): void; + + sendTileWidePeekImage02(tags: string | string[], + payload: any, + optionsOrCallback: Options | Callback, + callback?: Callback): void; + + sendTileWidePeekImage03(tags: string | string[], + payload: any, + optionsOrCallback: Options | Callback, + callback?: Callback): void; + + sendTileWidePeekImage04(tags: string | string[], + payload: any, + optionsOrCallback: Options | Callback, + callback?: Callback): void; + + sendTileWidePeekImage05(tags: string | string[], + payload: any, + optionsOrCallback: Options | Callback, + callback?: Callback): void; + + sendTileWidePeekImage06(tags: string | string[], + payload: any, + optionsOrCallback: Options | Callback, + callback?: Callback): void; + + sendToastText01(tags: string | string[], + payload: any, + optionsOrCallback: Options | Callback, + callback?: Callback): void; + + sendToastText02(tags: string | string[], + payload: any, + optionsOrCallback: Options | Callback, + callback?: Callback): void; + + sendToastText03(tags: string | string[], + payload: any, + optionsOrCallback: Options | Callback, + callback?: Callback): void; + + sendToastText04(tags: string | string[], + payload: any, + optionsOrCallback: Options | Callback, + callback?: Callback): void; + + sendToastImageAndText01(tags: string | string[], + payload: any, + optionsOrCallback: Options | Callback, + callback?: Callback): void; + + sendToastImageAndText02(tags: string | string[], + payload: any, + optionsOrCallback: Options | Callback, + callback?: Callback): void; + + sendToastImageAndText03(tags: string | string[], + payload: any, + optionsOrCallback: Options | Callback, + callback?: Callback): void; + + sendToastImageAndText04(tags: string | string[], + payload: any, + optionsOrCallback: Options | Callback, + callback?: Callback): void; + + sendBadge(tags: badges | badges[], + value: string | number, + callback?: Callback): void; + + sendBadge(tags: badges | badges[], + value: string | number, + options: Options, + callback?: Callback): void; + + sendRaw(tags: string | string[], + payload: any, + callback?: Callback): void; + + sendRaw(tags: string | string[], + payload: any, + options: Options, + callback?: Callback): void; + + send(tags: string | string[], + payload: string, + type: types, + callback?: Callback): void; + + send(tags: string | string[], + payload: string, + type: types, + options: Options, + callback: Callback): void; + + createNativeRegistration(channel: string, + tags: string | string[], + callback: Callback): void; + + createNativeRegistration(channel: string, + tags: string | string[], + options: Options, + callback: Callback): void; + + createOrUpdateNativeRegistration(registrationId: string, + channel: string, + tags: string | string[], + callback: Callback): void; + + createOrUpdateNativeRegistration(registrationId: string, + channel: string, + tags: string | string[], + options: Options, + callback: Callback): void; + + listRegistrationsByChannel(channel: string, + callback: Callback): void; + + listRegistrationsByChannel(channel: string, + options: ListNotificationHubsOptions, + callback: Callback): void; + +} + +export = WnsService; diff --git a/types/azure-sb/lib/wrapservice.d.ts b/types/azure-sb/lib/wrapservice.d.ts new file mode 100644 index 0000000000..5fbbc87345 --- /dev/null +++ b/types/azure-sb/lib/wrapservice.d.ts @@ -0,0 +1,21 @@ +import { Azure } from 'azure-sb'; + +declare class WrapService { + constructor(acsHost: string, issuer?: string, accessKey?: string); + + public issuer?: string; + public accessKey?: string; + public authenticationProvider: { + signRequest(webResource: any, callback: () => void): void; + }; + public strictSSL: boolean; + + public wrapAccessToken(uri: string, + callback: Azure.ServiceBus.ResponseCallback): void; + + public wrapAccessToken(uri: string, + options: object, + callback: Azure.ServiceBus.ResponseCallback): void; +} + +export = WrapService; diff --git a/types/azure-sb/tsconfig.json b/types/azure-sb/tsconfig.json index 525d24577e..09c9a2a9e4 100644 --- a/types/azure-sb/tsconfig.json +++ b/types/azure-sb/tsconfig.json @@ -17,7 +17,26 @@ "forceConsistentCasingInFileNames": true }, "files": [ - "index.d.ts", - "azure-sb-tests.ts" + "lib/servicebusservice.d.ts", + "lib/wrapservice.d.ts", + "lib/servicebusservicebase.d.ts", + "lib/notificationhubservice.d.ts", + "lib/models/topicresult.d.ts", + "lib/models/queuemessageresult.d.ts", + "lib/models/acstokenresult.d.ts", + "lib/models/registrationresult.d.ts", + "lib/models/ruleresult.d.ts", + "lib/models/queueresult.d.ts", + "lib/models/subscriptionresult.d.ts", + "lib/models/notificationhubresult.d.ts", + "lib/models/resourceresult.d.ts", + "lib/servicebusserviceclient.d.ts", + "lib/gcmservice.d.ts", + "lib/wnsservice.d.ts", + "lib/mpnservice.d.ts", + "lib/apnsservice.d.ts", + "azure-sb-tests.ts", + "index.d.ts" ] -} \ No newline at end of file +} + diff --git a/types/backbone/index.d.ts b/types/backbone/index.d.ts index 1a186d9924..3d4c90d369 100644 --- a/types/backbone/index.d.ts +++ b/types/backbone/index.d.ts @@ -392,7 +392,7 @@ declare namespace Backbone { decodeFragment(fragment: string): string; getSearch(): string; stop(): void; - route(route: string, callback: Function): number; + route(route: string|RegExp, callback: Function): number; checkUrl(e?: any): void; getPath(): string; matchRoot(): boolean; diff --git a/types/better-scroll/index.d.ts b/types/better-scroll/index.d.ts index 559b21bba2..3f48fed9db 100644 --- a/types/better-scroll/index.d.ts +++ b/types/better-scroll/index.d.ts @@ -1,12 +1,14 @@ -// Type definitions for better-scroll.js 1.3 +// Type definitions for better-scroll.js 1.4 // Project: https://github.com/ustbhuangyi/better-scroll // Definitions by: linxiaowu66 // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped // TypeScript Version: 2.2 interface WheelOption { - selectedIndex?: number; + selectedIndex: number; rotate?: number; adjustTime?: number; + wheelWrapperClass?: string; + wheelItemClass?: string; } interface SlideOption { @@ -16,6 +18,7 @@ interface SlideOption { stepX?: number; stepY?: number; listenFlick?: boolean; + speed?: number; } interface ScrollBarOption { fade?: boolean; @@ -27,6 +30,12 @@ interface PullDownOption { interface PullUpOption { threshold?: number; } +interface PageOption { + x: number; + y: number; + pageX: number; + pageY: number; +} interface BsOption { startX?: number; startY?: number; @@ -62,10 +71,12 @@ interface BsOption { * wheel: { * selectedIndex: 0; * rotate: 25; - * adjustTime: 400 + * adjustTime: 400; + * wheelWrapperClass: 'wheel-scroll'; + * wheelItemClass: 'wheel-item'; * } */ - wheel?: WheelOption | boolean; + wheel?: Partial | boolean; /** * for slide * snap: { @@ -77,14 +88,14 @@ interface BsOption { * listenFlick: true * } */ - snap?: SlideOption | boolean; + snap?: Partial | boolean; /** * for scrollbar * scrollbar: { * fade: true * } */ - scrollbar?: ScrollBarOption | boolean; + scrollbar?: Partial | boolean; /** * for pull down and refresh * pullDownRefresh: { @@ -92,20 +103,30 @@ interface BsOption { * stop: 20 * } */ - pullDownRefresh?: PullDownOption | boolean; + pullDownRefresh?: Partial | boolean; /** * for pull up and load * pullUpLoad: { * threshold: 50 * } */ - pullUpLoad?: PullUpOption | boolean; + pullUpLoad?: Partial | boolean; } declare class BScroll { constructor(element: Element | string, options?: BsOption); // 重新计算 better-scroll,当 DOM 结构发生变化的时候务必要调用确保滚动的效果正常 x: number; y: number; + maxScrollX: number; + maxScrollY: number; + movingDirectionX: number; + movingDirectionY: number; + directionX: number; + directionY: number; + enabled: boolean; + isInTransition: boolean; + isAnimating: boolean; + options: BsOption; refresh(): void; // 启用 better-scroll; 默认 开启 @@ -130,11 +151,11 @@ declare class BScroll { // 滚动到上一个页面 prev(time: number, easing: object): void; // 获取当前页面的信息 - getCurrentPage(): void; + getCurrentPage(): PageOption; // 当我们做 picker 组件的时候,调用该方法可以滚动到索引对应的位置 wheelTo(index: number): void; // 获取当前选中的索引值 - getSelectedIndex(): void; + getSelectedIndex(): number; // 当下拉刷新数据加载完毕后,需要调用此方法告诉 better-scroll 数据已加载 finishPullDown(): void; // 当上拉加载数据加载完毕后,需要调用此方法告诉 better-scroll 数据已加载 diff --git a/types/bindings/bindings-tests.ts b/types/bindings/bindings-tests.ts new file mode 100644 index 0000000000..e66ab51353 --- /dev/null +++ b/types/bindings/bindings-tests.ts @@ -0,0 +1,4 @@ +import bindings = require('bindings'); + +// Use your bindings defined in your C files +const result = bindings('binding.node').your_c_function(); diff --git a/types/bindings/index.d.ts b/types/bindings/index.d.ts new file mode 100644 index 0000000000..9403a7a92b --- /dev/null +++ b/types/bindings/index.d.ts @@ -0,0 +1,13 @@ +// Type definitions for bindings 1.3 +// Project: https://github.com/TooTallNate/node-bindings +// Definitions by: Daniel Perez Alvarez +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +/** + * The main `bindings()` function loads the compiled bindings for a given module. + * It uses V8's Error API to determine the parent filename that this function is + * being invoked from, which is then used to find the root directory. + */ +declare function bindings(mod: string): any; + +export = bindings; diff --git a/types/bindings/tsconfig.json b/types/bindings/tsconfig.json new file mode 100644 index 0000000000..fb9350642a --- /dev/null +++ b/types/bindings/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", + "bindings-tests.ts" + ] +} diff --git a/types/bindings/tslint.json b/types/bindings/tslint.json new file mode 100644 index 0000000000..3db14f85ea --- /dev/null +++ b/types/bindings/tslint.json @@ -0,0 +1 @@ +{ "extends": "dtslint/dt.json" } diff --git a/types/braft-editor/braft-editor-tests.tsx b/types/braft-editor/braft-editor-tests.tsx new file mode 100644 index 0000000000..354c4cbb5b --- /dev/null +++ b/types/braft-editor/braft-editor-tests.tsx @@ -0,0 +1,31 @@ +import * as React from "react"; +import * as BraftEditor from "braft-editor"; +import { + RawDraftContentState, +} from 'draft-js'; +class BraftEditorTest extends React.Component { + state = { + content: null + }; + render() { + const editorProps = { + height: 500, + initialContent: this.state.content, + onChange: this.handleChange, + onHTMLChange: this.handleHTMLChange + }; + return ( +
+ +
+ ); + } + private handleChange = (content: RawDraftContentState) => { + console.log(content); + } + private handleHTMLChange = (html: string) => { + console.log(html); + } +} diff --git a/types/braft-editor/index.d.ts b/types/braft-editor/index.d.ts new file mode 100644 index 0000000000..225d32722d --- /dev/null +++ b/types/braft-editor/index.d.ts @@ -0,0 +1,59 @@ +// Type definitions for braft-editor 1.1 +// Project: https://github.com/margox/braft#readme +// Definitions by: My Self +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.3 + +import * as React from "react"; +import { RawDraftContentState } from 'draft-js'; +export as namespace BraftEditor; +export = BraftEditor; +declare namespace BraftEditor { + interface fontFamiliesRange { + name: string; + family: string; + } + interface editorProps { + editorState?: any; + contentFormat?: RawDraftContentState; + initialContent?: RawDraftContentState | null; + onChange?: (content: RawDraftContentState) => void; + onRawChange?: (content: RawDraftContentState) => void; + onHTMLChange?: (content: string) => void; + controls?: string[]; + extendControls?: any[]; + height?: number; + language?: string; + placeholder?: string; + viewWrapper?: string; + colors?: string[]; + fontSizes?: number[]; + fontFamilies?: fontFamiliesRange[]; + media?: { [key: string]: any }; + getContent?: (format?: string) => RawDraftContentState; + setContent?: (content: RawDraftContentState, format?: string) => void; + toggleSelectionBlockType?: (blockquote: string) => any; + toggleSelectionInlineStyle?: (style: string, stylesToBeRemoved?: string[]) => any; + insertMedias?: (medias: Array<{ type: string, name: string, url: string }>) => void; + insertText?: (text: string, replace?: boolean) => void; + toggleSelectionLink?: (href: string, target: string) => void; + toggleSelectionAlignment?: (alignment: string) => any; + toggleSelectionColor?: (hexColor: string) => void; + toggleSelectionBackgroundColor?: (hexColor: string) => void; + toggleSelectionFontSize?: (fontSize: number) => void; + toggleSelectionFontFamily?: (fontFamily: string) => void; + selectionCollapsed?: () => boolean; + selectionHasInlineStyle?: () => boolean; + getSelectionBlockType?: () => string; + getEditorState?: () => void; + forceRender?: () => void; + getDraftInstance?: () => any; + getMediaLibraryInstance?: () => any; + getSelectionInlineStyle?: () => any; + undo?: () => any; + redo?: () => any; + focus?: () => void; + blur?: () => void; + } +} +declare class BraftEditor extends React.Component { } diff --git a/types/braft-editor/tsconfig.json b/types/braft-editor/tsconfig.json new file mode 100644 index 0000000000..f04b8febfe --- /dev/null +++ b/types/braft-editor/tsconfig.json @@ -0,0 +1,25 @@ +{ + "compilerOptions": { + "module": "commonjs", + "lib": [ + "es6", + "dom" + ], + "noImplicitAny": true, + "noImplicitThis": true, + "strictNullChecks": true, + "strictFunctionTypes": true, + "baseUrl": "../", + "jsx": "react", + "typeRoots": [ + "../" + ], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true + }, + "files": [ + "index.d.ts", + "braft-editor-tests.tsx" + ] +} \ No newline at end of file diff --git a/types/braft-editor/tslint.json b/types/braft-editor/tslint.json new file mode 100644 index 0000000000..3db14f85ea --- /dev/null +++ b/types/braft-editor/tslint.json @@ -0,0 +1 @@ +{ "extends": "dtslint/dt.json" } diff --git a/types/bson/index.d.ts b/types/bson/index.d.ts index 2b6a636e89..380e6e380c 100644 --- a/types/bson/index.d.ts +++ b/types/bson/index.d.ts @@ -39,6 +39,9 @@ export class Binary { constructor(buffer: Buffer, subType?: number); + /** The underlying Buffer which stores the binary data. */ + readonly buffer: Buffer; + /** The length of the binary. */ length(): number; /** Updates this binary with byte_value */ @@ -55,6 +58,9 @@ export class Code { } export class DBRef { constructor(namespace: string, oid: ObjectID, db?: string); + namespace: string; + oid: ObjectID; + db?: string; } export class Double { constructor(value: number); diff --git a/types/cancan/cancan-tests.ts b/types/cancan/cancan-tests.ts new file mode 100644 index 0000000000..0d6ab3e9a7 --- /dev/null +++ b/types/cancan/cancan-tests.ts @@ -0,0 +1,32 @@ +import CanCan = require('cancan'); + +const cancan = new CanCan(); + +// $ExpectType void +cancan.allow('admin', 'manage', 'all'); + +// $ExpectType void +cancan.allow('user', 'read', 'post', {public: true}); + +// $ExpectType boolean +cancan.can('user', 'read', 'post'); + +// $ExpectType boolean +cancan.cannot('user', 'delete', 'post'); + +// $ExpectType void +cancan.authorize('user', 'delete', 'post'); + +// $ExpectType boolean +cancan.can('user', 'read', 'post', {fields: ['title']}); + +// $ExpectType boolean +cancan.cannot('user', 'delete', 'post', {fields: ['title']}); + +// $ExpectType void +cancan.authorize('user', 'delete', 'post', {fields: ['title']}); + +const cancanWithOption = new CanCan({ + instanceOf: (_instance, _model) => true, + createError: () => true +}); diff --git a/types/cancan/index.d.ts b/types/cancan/index.d.ts new file mode 100644 index 0000000000..e739af1ef5 --- /dev/null +++ b/types/cancan/index.d.ts @@ -0,0 +1,29 @@ +// Type definitions for cancan 3.1 +// Project: https://github.com/vadimdemedes/cancan +// Definitions by: Vincent Pang +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.4 + +declare namespace CanCan { + interface Option { + instanceOf?: (instance: any, model: any) => boolean; + createError?: () => any; + } +} + +declare class CanCan { + constructor(options?: CanCan.Option); + + allow(model: any, + actions: string | ReadonlyArray, + targets: T | ReadonlyArray | string | ReadonlyArray, + condition?: object | ((performer: any, target: any, options?: any) => boolean)): void; + + can(performer: any, action: string, target: any, options?: any): boolean; + + cannot(performer: any, action: string, target: any, options?: any): boolean; + + authorize(performer: any, action: string, target: any, options?: any): void; +} + +export = CanCan; diff --git a/types/cancan/tsconfig.json b/types/cancan/tsconfig.json new file mode 100644 index 0000000000..8aace9dd52 --- /dev/null +++ b/types/cancan/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", + "cancan-tests.ts" + ] +} diff --git a/types/cancan/tslint.json b/types/cancan/tslint.json new file mode 100644 index 0000000000..3db14f85ea --- /dev/null +++ b/types/cancan/tslint.json @@ -0,0 +1 @@ +{ "extends": "dtslint/dt.json" } diff --git a/types/chai/chai-tests.ts b/types/chai/chai-tests.ts index 401e5f468a..fba32ec840 100644 --- a/types/chai/chai-tests.ts +++ b/types/chai/chai-tests.ts @@ -1,3 +1,4 @@ +/// import * as chai from "chai"; const expect = chai.expect; @@ -132,7 +133,9 @@ function _typeof() { expect(5).to.be.a('number'); (5).should.be.a('number'); + // tslint:disable-next-line:no-construct expect(new Number(1)).to.be.a('number'); + // tslint:disable-next-line:no-construct (new Number(1)).should.be.a('number'); expect(Number(1)).to.be.a('number'); Number(1).should.be.a('number'); @@ -348,10 +351,6 @@ function eql() { (4).should.eql(3, 'blah'); } -class Buffer { - constructor(arr: number[]) { - } -} function buffer() { expect(new Buffer([1])).to.eql(new Buffer([1])); (new Buffer([1])).should.eql(new Buffer([1])); @@ -726,7 +725,6 @@ function frozen() { Object.freeze({}).should.be.frozen; } - class PoorlyConstructedError { } function _throw() { // See GH-45: some poorly-constructed custom errors don't have useful names @@ -736,11 +734,11 @@ function _throw() { const specificError = new RangeError('boo'); - const goodFn = () => { } - , badFn = () => { throw new Error('testing'); } - , refErrFn = () => { throw new ReferenceError('hello'); } - , ickyErrFn = () => { throw new PoorlyConstructedError(); } - , specificErrFn = () => { throw specificError; }; + const goodFn = () => { }; + const badFn = () => { throw new Error('testing'); }; + const refErrFn = () => { throw new ReferenceError('hello'); }; + const ickyErrFn = () => { throw new PoorlyConstructedError(); }; + const specificErrFn = () => { throw specificError; }; expect(goodFn).to.not.throw(); goodFn.should.not.throw(); @@ -891,7 +889,7 @@ function use() { _chai.can.use.any(); }); - let expect = chai + const expect = chai .use((_chai, util) => {}) .use((_chai, util) => {}) .expect; @@ -1090,7 +1088,7 @@ function oneOf() { expect(obj).to.not.be.oneOf([{ z: 3 }]); } -//tdd +// tdd declare function suite(description: string, action: Function): void; declare function test(description: string, action: Function): void; @@ -1105,9 +1103,8 @@ class CrashyObject { } suite('assert', () => { - test('assert', () => { - const foo: string = 'bar'; + const foo = 'bar' as string; assert(foo === 'bar', 'expected foo to equal `bar`'); assert(foo === 'baz', 'expected foo to equal `bar`'); @@ -1207,26 +1204,26 @@ suite('assert', () => { assert.deepEqual({ tea: 'chai' }, { tea: 'chai' }); assert.deepEqual({ tea: 'chai' }, { tea: 'black' }); - const obja = Object.create({ tea: 'chai' }) - , objb = Object.create({ tea: 'chai' }); + const obja = Object.create({ tea: 'chai' }); + const objb = Object.create({ tea: 'chai' }); assert.deepEqual(obja, objb); - const obj1 = Object.create({ tea: 'chai' }) - , obj2 = Object.create({ tea: 'black' }); + const obj1 = Object.create({ tea: 'chai' }); + const obj2 = Object.create({ tea: 'black' }); assert.deepEqual(obj1, obj2); }); test('deepEqual (ordering)', () => { - const a = { a: 'b', c: 'd' } - , b = { c: 'd', a: 'b' }; + const a = { a: 'b', c: 'd' }; + const b = { c: 'd', a: 'b' }; assert.deepEqual(a, b); }); test('deepEqual (circular)', () => { - const circularObject: any = {} - , secondCircularObject: any = {}; + const circularObject: any = {}; + const secondCircularObject: any = {}; circularObject.field = circularObject; secondCircularObject.field = secondCircularObject; @@ -1242,8 +1239,8 @@ suite('assert', () => { }); test('notDeepEqual (circular)', () => { - const circularObject: any = {} - , secondCircularObject: any = { tea: 'jasmine' }; + const circularObject: any = {}; + const secondCircularObject: any = { tea: 'jasmine' }; circularObject.field = circularObject; secondCircularObject.field = secondCircularObject; @@ -1309,6 +1306,7 @@ suite('assert', () => { test('isString', () => { assert.isString('Foo'); + // tslint:disable-next-line:no-construct assert.isString(new String('foo')); assert.isString(1); }); @@ -1372,13 +1370,13 @@ suite('assert', () => { }); test('nestedInclude', () => { - assert.nestedInclude({'.a': {'b': 'x'}}, {'\\.a.[b]': 'x'}); - assert.nestedInclude({'a': {'[b]': 'x'}}, {'a.\\[b\\]': 'x'}); + assert.nestedInclude({'.a': {b: 'x'}}, {'\\.a.[b]': 'x'}); + assert.nestedInclude({a: {'[b]': 'x'}}, {'a.\\[b\\]': 'x'}); }); test('notNestedInclude', () => { - assert.notNestedInclude({'.a': {'b': 'x'}}, {'\\.a.b': 'y'}); - assert.notNestedInclude({'a': {'[b]': 'x'}}, {'a.\\[b\\]': 'y'}); + assert.notNestedInclude({'.a': {b: 'x'}}, {'\\.a.b': 'y'}); + assert.notNestedInclude({a: {'[b]': 'x'}}, {'a.\\[b\\]': 'y'}); }); test('deepNestedInclude', () => { @@ -1387,7 +1385,7 @@ suite('assert', () => { }); test('notDeepNestedInclude', () => { - assert.notDeepNestedInclude({a: {b: [{x: 1}]}}, {'a.b[0]': {y: 1}}) + assert.notDeepNestedInclude({a: {b: [{x: 1}]}}, {'a.b[0]': {y: 1}}); assert.notDeepNestedInclude({'.a': {'[b]': {x: 1}}}, {'\\.a.\\[b\\]': {y: 2}}); }); @@ -1548,7 +1546,6 @@ suite('assert', () => { assert.sameMembers([1, 54], [6, 1, 54]); }); - test('isAbove', () => { assert.isAbove(10, 5); assert.isAbove(1, 5); @@ -1738,7 +1735,7 @@ suite('assert', () => { test('hasAllKeys', () => { assert.hasAllKeys({foo: 1, bar: 2, baz: 3}, ['foo', 'bar', 'baz']); assert.hasAllKeys({foo: 1, bar: 2, baz: 3}, {foo: 30, bar: 99, baz: 1337}); - assert.hasAllKeys(new Map([[{foo: 1}, 'bar'], ['key', 'value']]), [{foo: 1}, 'key']); + assert.hasAllKeys(new Map([[{foo: 1}, 'bar'], ['key', 'value']]), [{foo: 1}, 'key']); assert.hasAllKeys(new Set([{foo: 'bar'}, 'anotherKey']), [{foo: 'bar'}, 'anotherKey']); }); @@ -1747,8 +1744,8 @@ suite('assert', () => { assert.containsAllKeys({foo: 1, bar: 2, baz: 3}, ['foo', 'bar', 'baz']); assert.containsAllKeys({foo: 1, bar: 2, baz: 3}, {foo: 30, baz: 1337}); assert.containsAllKeys({foo: 1, bar: 2, baz: 3}, {foo: 30, bar: 99, baz: 1337}); - assert.containsAllKeys(new Map([[{foo: 1}, 'bar'], ['key', 'value']]), [{foo: 1}]); - assert.containsAllKeys(new Map([[{foo: 1}, 'bar'], ['key', 'value']]), [{foo: 1}, 'key']); + assert.containsAllKeys(new Map([[{foo: 1}, 'bar'], ['key', 'value']]), [{foo: 1}]); + assert.containsAllKeys(new Map([[{foo: 1}, 'bar'], ['key', 'value']]), [{foo: 1}, 'key']); assert.containsAllKeys(new Set([{foo: 'bar'}, 'anotherKey']), [{foo: 'bar'}]); assert.containsAllKeys(new Set([{foo: 'bar'}, 'anotherKey']), [{foo: 'bar'}, 'anotherKey']); }); @@ -1756,21 +1753,21 @@ suite('assert', () => { test('doesNotHaveAnyKeys', () => { assert.doesNotHaveAnyKeys({foo: 1, bar: 2, baz: 3}, ['one', 'two', 'example']); assert.doesNotHaveAnyKeys({foo: 1, bar: 2, baz: 3}, {one: 1, two: 2, example: 'foo'}); - assert.doesNotHaveAnyKeys(new Map([[{foo: 1}, 'bar'], ['key', 'value']]), [{one: 'two'}, 'example']); + assert.doesNotHaveAnyKeys(new Map([[{foo: 1}, 'bar'], ['key', 'value']]), [{one: 'two'}, 'example']); assert.doesNotHaveAnyKeys(new Set([{foo: 'bar'}, 'anotherKey']), [{one: 'two'}, 'example']); }); test('doesNotHaveAllKeys', () => { assert.doesNotHaveAllKeys({foo: 1, bar: 2, baz: 3}, ['one', 'two', 'example']); assert.doesNotHaveAllKeys({foo: 1, bar: 2, baz: 3}, {one: 1, two: 2, example: 'foo'}); - assert.doesNotHaveAllKeys(new Map([[{foo: 1}, 'bar'], ['key', 'value']]), [{one: 'two'}, 'example']); + assert.doesNotHaveAllKeys(new Map([[{foo: 1}, 'bar'], ['key', 'value']]), [{one: 'two'}, 'example']); assert.doesNotHaveAllKeys(new Set([{foo: 'bar'}, 'anotherKey']), [{one: 'two'}, 'example']); }); test('hasAnyDeepKeys', () => { - assert.hasAnyDeepKeys(new Map([[{one: 'one'}, 'valueOne'], [1, 2]]), {one: 'one'}); - assert.hasAnyDeepKeys(new Map([[{one: 'one'}, 'valueOne'], [1, 2]]), [{one: 'one'}, {two: 'two'}]); - assert.hasAnyDeepKeys(new Map([[{one: 'one'}, 'valueOne'], [{two: 'two'}, 'valueTwo']]), [{one: 'one'}, {two: 'two'}]); + assert.hasAnyDeepKeys(new Map([[{one: 'one'}, 'valueOne'], [1, 2]]), {one: 'one'}); + assert.hasAnyDeepKeys(new Map([[{one: 'one'}, 'valueOne'], [1, 2]]), [{one: 'one'}, {two: 'two'}]); + assert.hasAnyDeepKeys(new Map([[{one: 'one'}, 'valueOne'], [{two: 'two'}, 'valueTwo']]), [{one: 'one'}, {two: 'two'}]); assert.hasAnyDeepKeys(new Set([{one: 'one'}, {two: 'two'}]), {one: 'one'}); assert.hasAnyDeepKeys(new Set([{one: 'one'}, {two: 'two'}]), [{one: 'one'}, {three: 'three'}]); assert.hasAnyDeepKeys(new Set([{one: 'one'}, {two: 'two'}]), [{one: 'one'}, {two: 'two'}]); @@ -1778,28 +1775,28 @@ suite('assert', () => { test('hasAllDeepKeys', () => { assert.hasAllDeepKeys(new Map([[{one: 'one'}, 'valueOne']]), {one: 'one'}); - assert.hasAllDeepKeys(new Map([[{one: 'one'}, 'valueOne'], [{two: 'two'}, 'valueTwo']]), [{one: 'one'}, {two: 'two'}]); + assert.hasAllDeepKeys(new Map([[{one: 'one'}, 'valueOne'], [{two: 'two'}, 'valueTwo']]), [{one: 'one'}, {two: 'two'}]); assert.hasAllDeepKeys(new Set([{one: 'one'}]), {one: 'one'}); assert.hasAllDeepKeys(new Set([{one: 'one'}, {two: 'two'}]), [{one: 'one'}, {two: 'two'}]); }); test('containsAllDeepKeys', () => { - assert.containsAllDeepKeys(new Map([[{one: 'one'}, 'valueOne'], [1, 2]]), {one: 'one'}); - assert.containsAllDeepKeys(new Map([[{one: 'one'}, 'valueOne'], [{two: 'two'}, 'valueTwo']]), [{one: 'one'}, {two: 'two'}]); + assert.containsAllDeepKeys(new Map([[{one: 'one'}, 'valueOne'], [1, 2]]), {one: 'one'}); + assert.containsAllDeepKeys(new Map([[{one: 'one'}, 'valueOne'], [{two: 'two'}, 'valueTwo']]), [{one: 'one'}, {two: 'two'}]); assert.containsAllDeepKeys(new Set([{one: 'one'}, {two: 'two'}]), {one: 'one'}); assert.containsAllDeepKeys(new Set([{one: 'one'}, {two: 'two'}]), [{one: 'one'}, {two: 'two'}]); }); test('doesNotHaveAnyDeepKeys', () => { - assert.doesNotHaveAnyDeepKeys(new Map([[{one: 'one'}, 'valueOne'], [1, 2]]), {thisDoesNot: 'exist'}); - assert.doesNotHaveAnyDeepKeys(new Map([[{one: 'one'}, 'valueOne'], [{two: 'two'}, 'valueTwo']]), [{twenty: 'twenty'}, {fifty: 'fifty'}]); + assert.doesNotHaveAnyDeepKeys(new Map([[{one: 'one'}, 'valueOne'], [1, 2]]), {thisDoesNot: 'exist'}); + assert.doesNotHaveAnyDeepKeys(new Map([[{one: 'one'}, 'valueOne'], [{two: 'two'}, 'valueTwo']]), [{twenty: 'twenty'}, {fifty: 'fifty'}]); assert.doesNotHaveAnyDeepKeys(new Set([{one: 'one'}, {two: 'two'}]), {twenty: 'twenty'}); assert.doesNotHaveAnyDeepKeys(new Set([{one: 'one'}, {two: 'two'}]), [{twenty: 'twenty'}, {fifty: 'fifty'}]); }); test('doesNotHaveAllDeepKeys', () => { - assert.doesNotHaveAllDeepKeys(new Map([[{one: 'one'}, 'valueOne'], [1, 2]]), {thisDoesNot: 'exist'}); - assert.doesNotHaveAllDeepKeys(new Map([[{one: 'one'}, 'valueOne'], [{two: 'two'}, 'valueTwo']]), [{twenty: 'twenty'}, {one: 'one'}]); + assert.doesNotHaveAllDeepKeys(new Map([[{one: 'one'}, 'valueOne'], [1, 2]]), {thisDoesNot: 'exist'}); + assert.doesNotHaveAllDeepKeys(new Map([[{one: 'one'}, 'valueOne'], [{two: 'two'}, 'valueTwo']]), [{twenty: 'twenty'}, {one: 'one'}]); assert.doesNotHaveAllDeepKeys(new Set([{one: 'one'}, {two: 'two'}]), {twenty: 'twenty'}); assert.doesNotHaveAllDeepKeys(new Set([{one: 'one'}, {two: 'two'}]), [{one: 'one'}, {fifty: 'fifty'}]); }); diff --git a/types/chai/index.d.ts b/types/chai/index.d.ts index faafa3b2a8..8c19f1f54a 100644 --- a/types/chai/index.d.ts +++ b/types/chai/index.d.ts @@ -1,4 +1,4 @@ -// Type definitions for chai 4.0.0 +// Type definitions for chai 4.0 // Project: http://chaijs.com/ // Definitions by: Jed Mao , // Bart van der Schoor , @@ -13,7 +13,6 @@ // declare namespace Chai { - interface ChaiStatic { expect: ExpectStatic; should(): Should; @@ -55,8 +54,7 @@ declare namespace Chai { } interface ShouldThrow { - (actual: Function): void; - (actual: Function, expected: string|RegExp, message?: string): void; + (actual: Function, expected?: string|RegExp, message?: string): void; (actual: Function, constructor: Error|Function, expected?: string|RegExp, message?: string): void; } @@ -219,9 +217,7 @@ declare namespace Chai { } interface Include { - (value: Object, message?: string): Assertion; - (value: string, message?: string): Assertion; - (value: number, message?: string): Assertion; + (value: Object | string | number, message?: string): Assertion; keys: Keys; deep: Deep; ordered: Ordered; @@ -236,18 +232,12 @@ declare namespace Chai { interface Keys { (...keys: string[]): Assertion; - (keys: any[]): Assertion; - (keys: Object): Assertion; + (keys: any[]|Object): Assertion; } interface Throw { - (): Assertion; - (expected: string, message?: string): Assertion; - (expected: RegExp, message?: string): Assertion; - (constructor: Error, expected?: string, message?: string): Assertion; - (constructor: Error, expected?: RegExp, message?: string): Assertion; - (constructor: Function, expected?: string, message?: string): Assertion; - (constructor: Function, expected?: RegExp, message?: string): Assertion; + (expected?: string|RegExp, message?: string): Assertion; + (constructor: Error|Function, expected?: string|RegExp, message?: string): Assertion; } interface RespondTo { @@ -698,21 +688,11 @@ declare namespace Chai { /** * Asserts that haystack does not include needle. * - * @param haystack Container string. + * @param haystack Container string or array. * @param needle Potential expected substring of haystack. * @param message Message to display on error. */ - notInclude(haystack: string, needle: any, message?: string): void; - - /** - * Asserts that haystack does not include needle. - * - * @param haystack Container array. - * @param needle Potential value contained in haystack. - * @param message Message to display on error. - */ - notInclude(haystack: any[], needle: any, message?: string): void; - + notInclude(haystack: string | any[], needle: any, message?: string): void; /** * Asserts that haystack includes needle. Can be used to assert the inclusion of a value in an array or a subset of properties in an object. Deep equality is used. @@ -735,20 +715,11 @@ declare namespace Chai { /** * Asserts that haystack does not include needle. Can be used to assert the absence of a value in an array or a subset of properties in an object. Deep equality is used. * - * @param haystack Container string. + * @param haystack Container string or array. * @param needle Potential expected substring of haystack. * @param message Message to display on error. */ - notDeepInclude(haystack: string, needle: any, message?: string): void; - - /** - * Asserts that haystack does not include needle. Can be used to assert the absence of a value in an array or a subset of properties in an object. Deep equality is used. - * - * @param haystack - * @param needle - * @param message Message to display on error. - */ - notDeepInclude(haystack: any[], needle: any, message?: string): void; + notDeepInclude(haystack: string | any[], needle: any, message?: string): void; /** * Asserts that ‘haystack’ includes ‘needle’. Can be used to assert the inclusion of a subset of properties in an object. @@ -1014,19 +985,10 @@ declare namespace Chai { * Asserts that function will throw an error with message matching regexp. * * @param fn Function that may throw. - * @param regExp Potential expected message match. + * @param errType Potential expected message match or error constructor. * @param message Message to display on error. */ - throws(fn: Function, regExp: RegExp, message?: string): void; - - /** - * Asserts that function will throw an error that is an instance of constructor. - * - * @param fn Function that may throw. - * @param constructor Potential expected error constructor. - * @param message Message to display on error. - */ - throws(fn: Function, errType: Function, message?: string): void; + throws(fn: Function, errType: RegExp|Function, message?: string): void; /** * Asserts that function will throw an error that is an instance of constructor @@ -1289,7 +1251,7 @@ declare namespace Chai { * @param property Property of object expected to be modified. * @param message Message to display on error. */ - changes(modifier: Function, object: T, property: string /* keyof T */, message?: string): void + changes(modifier: Function, object: T, property: string /* keyof T */, message?: string): void; /** * Asserts that a function does not change the value of a property. @@ -1300,7 +1262,7 @@ declare namespace Chai { * @param property Property of object expected not to be modified. * @param message Message to display on error. */ - doesNotChange(modifier: Function, object: T, property: string /* keyof T */, message?: string): void + doesNotChange(modifier: Function, object: T, property: string /* keyof T */, message?: string): void; /** * Asserts that a function increases an object property. @@ -1311,7 +1273,7 @@ declare namespace Chai { * @param property Property of object expected to be increased. * @param message Message to display on error. */ - increases(modifier: Function, object: T, property: string /* keyof T */, message?: string): void + increases(modifier: Function, object: T, property: string /* keyof T */, message?: string): void; /** * Asserts that a function does not increase an object property. @@ -1322,7 +1284,7 @@ declare namespace Chai { * @param property Property of object expected not to be increased. * @param message Message to display on error. */ - doesNotIncrease(modifier: Function, object: T, property: string /* keyof T */, message?: string): void + doesNotIncrease(modifier: Function, object: T, property: string /* keyof T */, message?: string): void; /** * Asserts that a function decreases an object property. @@ -1333,7 +1295,7 @@ declare namespace Chai { * @param property Property of object expected to be decreased. * @param message Message to display on error. */ - decreases(modifier: Function, object: T, property: string /* keyof T */, message?: string): void + decreases(modifier: Function, object: T, property: string /* keyof T */, message?: string): void; /** * Asserts that a function does not decrease an object property. @@ -1344,7 +1306,7 @@ declare namespace Chai { * @param property Property of object expected not to be decreased. * @param message Message to display on error. */ - doesNotDecrease(modifier: Function, object: T, property: string /* keyof T */, message?: string): void + doesNotDecrease(modifier: Function, object: T, property: string /* keyof T */, message?: string): void; /** * Asserts if value is not a false value, and throws if it is a true value. diff --git a/types/chai/tslint.json b/types/chai/tslint.json index a41bf5d19a..f99183c97d 100644 --- a/types/chai/tslint.json +++ b/types/chai/tslint.json @@ -1,79 +1,14 @@ { "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 + "strict-export-declare-modifiers": false } } diff --git a/types/chart.js/chart.js-tests.ts b/types/chart.js/chart.js-tests.ts index 9ec7fde23f..d1e86fd317 100644 --- a/types/chart.js/chart.js-tests.ts +++ b/types/chart.js/chart.js-tests.ts @@ -44,7 +44,8 @@ const chart: Chart = new Chart(new CanvasRenderingContext2D(), { zeroLineBorderDashOffset: 2 } }] - } + }, + plugins: { arbitraryPlugin: {option: "value"} } } }); chart.update(); diff --git a/types/chart.js/index.d.ts b/types/chart.js/index.d.ts index 049488f8db..614fbe26ef 100644 --- a/types/chart.js/index.d.ts +++ b/types/chart.js/index.d.ts @@ -176,6 +176,8 @@ declare namespace Chart { cutoutPercentage?: number; circumference?: number; rotation?: number; + // Plugins can require any options + plugins?: any; } interface ChartFontOptions { @@ -362,7 +364,7 @@ declare namespace Chart { interface TickOptions { autoSkip?: boolean; - autoSkipPadding?: boolean; + autoSkipPadding?: number; callback?(value: any, index: any, values: any): string|number; display?: boolean; fontColor?: ChartColor; diff --git a/types/chocolatechipjs/index.d.ts b/types/chocolatechipjs/index.d.ts index 4c1d49f6d1..2b53368f08 100644 --- a/types/chocolatechipjs/index.d.ts +++ b/types/chocolatechipjs/index.d.ts @@ -10,7 +10,6 @@ interface ChocolateChipStatic { * * @param selector A string containing a selector expression * @param context A DOM HTMLElement to use as context - * @return HTMLElement[] */ (selector: string | HTMLElement | Document, context?: HTMLElement | ChocolateChipElementArray): ChocolateChipElementArray; @@ -18,7 +17,6 @@ interface ChocolateChipStatic { * Binds a function to be executed when the DOM has finished loading. * * @param callback A function to execute after the DOM is ready. - * @return void */ (callback: () => any): void; @@ -26,7 +24,6 @@ interface ChocolateChipStatic { * Accepts a string containing a CSS selector which is then used to match a set of elements. * * @param element A DOM element to wrap in an array. - * @return HTMLElement[] */ (element: HTMLElement): ChocolateChipElementArray; @@ -34,7 +31,6 @@ interface ChocolateChipStatic { * Accepts a string containing a CSS selector which is then used to match a set of elements. * * @param elementArray An array of DOM elements to convert into a ChocolateChip Collection. - * @return HTMLElement[] */ (elementArray: ChocolateChipElementArray): ChocolateChipElementArray; @@ -42,13 +38,11 @@ interface ChocolateChipStatic { * Accepts the document element and returns it wrapped in an array. * * @param document The document object. - * @return document[] */ (document: Document): Document[]; /** * If no argument is provided, return the document as a ChocolateChipElementArray. - * @return Document[] */ (): Document[]; @@ -94,8 +88,6 @@ interface ChocolateChipStatic { /** * An empty function. - * - * @return void. */ noop(): void; @@ -106,40 +98,27 @@ interface ChocolateChipStatic { /** * Create a random number to use as a uuid. - * - * @return number. */ uuidNum(): number; /** * Creates a uuid using uuidNum(). - * - * @return A string. */ makeUuid(): string; /** * Create a ChocolateChip collection object by creating elements from an HTML string. - * - * @param selector - * @return any */ make(selector: string): ChocolateChipElementArray; /** * Create a ChocolateChip collection object by creating elements from an HTML string. This is an alias for $.make. - * - * @param selector - * @return any */ html(selector: string): ChocolateChipElementArray; /** * Replace one element with another. - * - * @param new HTMLElement - * @param old HTMLElement - * @return HTMLElement[] + * @return {HTMLElement[]} */ replace(newElement: ChocolateChipElementArray, oldElement: ChocolateChipElementArray): void; @@ -148,7 +127,7 @@ interface ChocolateChipStatic { * * @param url A string containing the URL where the script resides. * @param callback A callback function that is executed after the script loads. - * @return void + * @return {void} */ require(url: string, callback: Function): Function; @@ -157,7 +136,7 @@ interface ChocolateChipStatic { * * @param url A string containing the URL where the script resides. * @param callback A callback function that is executed after the script loads. - * @return Function + * @return {Function} */ processJSON(json: string, name?: string): any; @@ -173,7 +152,6 @@ interface ChocolateChipStatic { * Parse the data in a Promise response as JSON. * * @param response The response from a Promise. - * @result */ json(reponse: Response): JSON; @@ -182,7 +160,6 @@ interface ChocolateChipStatic { * * @param callback A function to execute. * @param duration The number of milliseconds to delay execution. - * @return any */ delay(callback: Function, duration?: number): any; @@ -190,7 +167,6 @@ interface ChocolateChipStatic { * The method will defer the execution of its callback until the call stack is clear. * * @param callback A callback to execute after a delay. - * @return Function. */ defer(callback: Function): Function; @@ -215,16 +191,14 @@ interface ChocolateChipStatic { /** * This method will concatenate strings or values as a cleaner alternative to using the '+' operator. * - * @param string or number A comma separated series of strings to concatenate. - * @return string + * @param {string | number} A comma separated series of strings to concatenate. */ concat(...string: string[]): string; /** * This method takes a space-delimited string of words and returns it as an array where the individual words are indices. * - * @param string Any string with values separated by spaces. - * @return string[] + * @param Any string with values separated by spaces. */ w(string: string): string[]; @@ -232,7 +206,6 @@ interface ChocolateChipStatic { * This method converts a string of hyphenated tokens into a camel cased string. * * @param string A string of hyphenated tokens. - * @return string */ camelize(string: string): string; @@ -240,16 +213,11 @@ interface ChocolateChipStatic { * This method converts a camel case string into lowercase with hyphens. * * @param string A camel case string. - * @return string */ deCamelize(string: string): string; /** * This method capitalizes the first letter of a string. - * - * @param string A string. - * @param boolean A boolean value. - * @return string */ capitalize(string: string, boolean?: boolean): string; @@ -257,7 +225,6 @@ interface ChocolateChipStatic { * Determine whether the argument is a string. * * @param obj Object to test whether or not it is a string. - * @return boolean */ isString(obj: any): boolean; @@ -265,7 +232,6 @@ interface ChocolateChipStatic { * Determine whether the argument is an array. * * @param obj Object to test whether or not it is an array. - * @return boolean */ isArray(obj: any): boolean; @@ -273,7 +239,6 @@ interface ChocolateChipStatic { * Determine whether the argument is a function. * * @param obj Object to test whether or not it is an function. - * @return boolean */ isFunction(obj: any): boolean; @@ -281,7 +246,6 @@ interface ChocolateChipStatic { * Determine whether the argument is an object. * * @param obj Object to test whether or not it is an object. - * @return boolean */ isObject(obj: any): boolean; @@ -297,7 +261,6 @@ interface ChocolateChipStatic { * Determine whether the argument is an empty object. * * @param obj Object to test whether or not it is an empty object. - * @return boolean */ isEmptyObject(obj: any): boolean; @@ -305,7 +268,6 @@ interface ChocolateChipStatic { * Determine whether the argument is a number. * * @param obj Object to test whether or not it is a number. - * @return boolean */ isNumber(obj: any): boolean; @@ -313,7 +275,6 @@ interface ChocolateChipStatic { * Determine whether the argument is an integer. * * @param obj Object to test whether or not it is an integer. - * @return boolean */ isInteger(obj: any): boolean; @@ -321,7 +282,6 @@ interface ChocolateChipStatic { * Determine whether the argument is a float. * * @param obj Object to test whether or not it is a float. - * @return boolean */ isFloat(obj: any): boolean; @@ -443,8 +403,8 @@ interface ChocolateChipStatic { /** * Grabs values from a form and converts them into a JSON object. * - * @param rootNode: string | HTMLElement A form whose values you want to convert to JSON. - * @param delimiter string A delimiter to namespace your form values. The default is "." + * @param rootNode: A form whose values you want to convert to JSON. + * @param delimiter A delimiter to namespace your form values. The default is "." * You use the form input's name to set up the namespace structure for your JSON, e.g. name="newUser.name.first". */ form2JSON(rootNode: string | HTMLElement, delimiter: string): Object; @@ -453,35 +413,33 @@ interface ChocolateChipStatic { * Subscribe to a publication. You provide the topic you want to subscribe to, as well as a callback to execute when a publication occurs. * Any data passed by the publisher is exposed to the callback as its second parameter. The callback's first parameter is the published topic. * - * @param topic string A topic to subscribe to. This can be a single term, or any type of namespaced term with delimiters. - * @data any You can receive any type: string, number, array, object, etc. - * @return any + * @param topic A topic to subscribe to. This can be a single term, or any type of namespaced term with delimiters. + * @param callback You can receive any type: string, number, array, object, etc. */ subscribe(topic: string, callback: (topic: string, data: any) => any): boolean; /** * Unsubscribe from a topic. Pass this the topic you wish to unsubscribe from. The subscription will be terminated immediately. * - * @param topic string The name of the topic to unsubscribe from. - * @return void + * @param topic The name of the topic to unsubscribe from. */ unsubscribe(topic: string): void; /** * Publish a topic with data for the topic's subscribers to receive. * - * @param topic string The topic you wish to publish. + * @param topic The topic you wish to publish. * @param data The data to send with the publication. This can be of any type: string, number, array, object, etc. - * @return void + * @return {void} */ publish(topic: string, data: any): string; /** * Object used to store string templates and parsed templates. * - * @param string A string defining the template. - * @param string A label used to access an object's properties in the template. If none is provided it defaults to "data": [[= data.name]]. - * @return void + * @param {strin} A string defining the template. + * @param {string} A label used to access an object's properties in the template. If none is provided it defaults to "data": [[= data.name]]. + * @return {void} */ templates: Object; @@ -495,7 +453,6 @@ interface ChocolateChipStatic { * * @param template A string of markup to use as a template. * @param variable An option name to use in the template. If it were "myData": [[= myData.name]]. Otherwise it defaults to "data": [[= data.name]]. - * @return A function. */ (template: string, variable?: string): Function; @@ -514,7 +471,6 @@ interface ChocolateChipStatic { * @param element The target container into which the content will be inserted. * @param template A string of markup. * @param data The iterable data the template will consume. - * @return void. */ (element: ChocolateChipElementArray, template: string, data: any): void; } @@ -523,7 +479,6 @@ interface ChocolateChipStatic { * An object that holds the reference to the controller for a repeater. * This is used to cache the data that a repeater uses. After the repeater is rendered, the reference is deleted from this object. * Example: $.template.data["myRepeater"] = [{name: "Joe"}, {name: "Sue"}]; - * */ data: any; @@ -567,16 +522,11 @@ interface ChocolateChipStatic { interface ChocolateChipElementArray extends Array { /** * Iterate over an Array object, executing a function for each matched element. - * - * @param Function - * @return void */ each(func: (ctx: any, idx: number) => void): void; /** * Sorts an array and removes duplicates before returning it. - * - * @return Array */ unique(): ChocolateChipElementArray; @@ -585,16 +535,13 @@ interface ChocolateChipElementArray extends Array { * When dealing with document nodes, this allows you to cherry pick a node from its collection based on its * position amongst its siblings. * - * @param number Index value indicating the node you wish to access from a collection. This is zero-based. - * @return HTMLElement + * @param index Value indicating the node you wish to access from a collection. This is zero-based. */ eq(index: number): ChocolateChipElementArray; /** * Search for a given element from among the matched elements on a collection. * This method returns the index value as an integer. - * - * @return number */ index(): number; @@ -603,7 +550,6 @@ interface ChocolateChipElementArray extends Array { * This method returns the index value as an integer. * * @param selector A selector representing an element to look for in a collection of elements. - * @return number */ index(selector: string | HTMLElement[]): number; @@ -612,7 +558,6 @@ interface ChocolateChipElementArray extends Array { * if it matches the given arguments. * * @param selector A string containing a selector expression to match elements against. - * @return HTMLElement[] */ is(selector: string): ChocolateChipElementArray; @@ -621,7 +566,6 @@ interface ChocolateChipElementArray extends Array { * if it matches the given arguments. * * @param elements One or more elements to match the current set of elements against. - * @ return HTMLElement[] */ is(element: any): ChocolateChipElementArray; @@ -630,7 +574,6 @@ interface ChocolateChipElementArray extends Array { * if it does not match the given arguments. * * @param selector A string containing a selector expression to match elements against. - * @ return HTMLElement[] */ isnt(selector: string): ChocolateChipElementArray; @@ -639,7 +582,6 @@ interface ChocolateChipElementArray extends Array { * if it does not match the given arguments. * * @param elements One or more elements to match the current set of elements against. - * @ return HTMLElement[] */ isnt(element: any): ChocolateChipElementArray; @@ -647,7 +589,6 @@ interface ChocolateChipElementArray extends Array { * Reduce the set of matched elements to those that have a descendant that matches the selector or DOM element. * * @param selector A string containing a selector expression to match elements against. - * @ return HTMLElement[] */ has(selector: string): ChocolateChipElementArray; @@ -655,7 +596,6 @@ interface ChocolateChipElementArray extends Array { * Reduce the set of matched elements to those that have a descendant that matches the selector or DOM element. * * @param contained A DOM element to match elements against. - * @ return HTMLElement[] */ has(contained: HTMLElement): ChocolateChipElementArray; @@ -671,7 +611,6 @@ interface ChocolateChipElementArray extends Array { * Reduce the set of matched elements to those that have a descendant that does not match the selector or DOM element. * * @param contained A DOM element to match elements against. - * @ return HTMLElement[] */ hasnt(contained: HTMLElement): ChocolateChipElementArray; @@ -684,7 +623,6 @@ interface ChocolateChipElementArray extends Array { * Get the descendants of each element in the current set of matched elements, filtered by a selector or element. * * @param selector A string containing a selector expression to match elements against. - * @ return HTMLElement[] */ find(selector: string): ChocolateChipElementArray; @@ -692,21 +630,16 @@ interface ChocolateChipElementArray extends Array { * Get the descendants of each element in the current set of matched elements, filtered by a selector or element. * * @param element An element to match elements against. - * @ return HTMLElement[] */ find(element: HTMLElement): ChocolateChipElementArray; /** * Get the immediately preceding sibling of each element in the set of matched elements. - * - * @ return HTMLElement[] */ prev(): ChocolateChipElementArray; /** * Get the immediately following sibling of each element in the set of matched elements. - * - * @ return HTMLElement[] */ next(): ChocolateChipElementArray; @@ -717,8 +650,6 @@ interface ChocolateChipElementArray extends Array { /** * Reduce the set of matched elements to the last in the set. - * - * @return HTMLElement[] */ last(): ChocolateChipElementArray; @@ -726,7 +657,6 @@ interface ChocolateChipElementArray extends Array { * Get the children of each element in the set of matched elements, optionally filtered by a selector. * * @param selector A string containing a selector expression to match elements against. - * @return HTMLElement[] */ children(selector?: string): ChocolateChipElementArray; @@ -735,7 +665,6 @@ interface ChocolateChipElementArray extends Array { * If multiple elements have the same parent, only one instance of the parent is returned. * * @param selector A string containing a selector expression to match elements against. - * @return HTMLElement[] */ parent(selector?: string): ChocolateChipElementArray; @@ -745,7 +674,6 @@ interface ChocolateChipElementArray extends Array { * retrieving that ancestor based on its distance from the element. * * @param selector A string containing a selector expression to match elements against. - * @return HTMLElement[] */ ancestor(selector: string | number): ChocolateChipElementArray; @@ -754,7 +682,6 @@ interface ChocolateChipElementArray extends Array { * itself and traversing up through its ancestors in the DOM tree. * * @param selector A string containing a selector expression to match elements against. - * @return HTMLElement[] */ closest(selector: string | number): ChocolateChipElementArray; @@ -762,14 +689,11 @@ interface ChocolateChipElementArray extends Array { * Get the siblings of each element in the set of matched elements, optionally filtered by a selector. * * @param selector A string containing a selector expression to match elements against. - * @return HTMLElement[] */ siblings(selector?: string): ChocolateChipElementArray; /** * Get the HTML contents of the first element in the set of matched elements. - * - * @return HTMLElement[] */ html(): ChocolateChipElementArray; @@ -777,7 +701,6 @@ interface ChocolateChipElementArray extends Array { * Set the HTML contents of each element in the set of matched elements. * * @param htmlString A string of HTML to set as the content of each matched element. - * @return HTMLElement[] */ html(htmlString: string): ChocolateChipElementArray; @@ -785,7 +708,6 @@ interface ChocolateChipElementArray extends Array { * Get the value of style properties for the first element in the set of matched elements. * * @param propertyName A CSS property. - * @return string */ css(propertyName: string): string; @@ -794,7 +716,6 @@ interface ChocolateChipElementArray extends Array { * * @param propertyName A CSS property name. * @param value A value to set for the property. - * @return HTMLElement[] */ css(propertyName: string, value: string): ChocolateChipElementArray; @@ -802,7 +723,6 @@ interface ChocolateChipElementArray extends Array { * Set one or more CSS properties for the set of matched elements. * * @param properties An object of property-value pairs to set. - * @return HTMLElement[] */ css(properties: Object): ChocolateChipElementArray; @@ -819,7 +739,6 @@ interface ChocolateChipElementArray extends Array { * * @param attributeName A string indicating the attribute to set. * @param value A string indicating the value to set the attribute to. - * @return HTMLElement[] */ attr(attributeName: string, value: string): ChocolateChipElementArray; @@ -827,7 +746,6 @@ interface ChocolateChipElementArray extends Array { * Remove an attribute from a node. * * @param attributeName A string indicating the attribute to remove. - * @return HTMLElement[] */ removeAttr(attributeName: string): ChocolateChipElementArray; @@ -835,7 +753,6 @@ interface ChocolateChipElementArray extends Array { * Return any of the matched elements that have the given attribute. * * @param className The class name to search for. - * @return HTMLElement[] */ hasAttr(attributeName: string): ChocolateChipElementArray; @@ -843,7 +760,6 @@ interface ChocolateChipElementArray extends Array { * Test whether an attribute exists on the first element in the set of matched elements. The value returned is a boolean. * * @param attributeName The name of the attribute to get. - * @return boolean */ prop(propertyName: string): boolean; @@ -852,7 +768,6 @@ interface ChocolateChipElementArray extends Array { * * @param propertyName A string indicating the property to set. * @param value A string indicating the value to set the property to. - * @return HTMLElement[] */ prop(propertyName: string, value: any | boolean): ChocolateChipElementArray; @@ -860,7 +775,6 @@ interface ChocolateChipElementArray extends Array { * Remove an element property. * * @param property The property to remove. - * @return HTMLElement[] */ removeProp(property: string): ChocolateChipElementArray; @@ -868,7 +782,6 @@ interface ChocolateChipElementArray extends Array { * Adds the specified class(es) to each of the set of matched elements. * * @param className One or more space-separated classes to be added to the class attribute of each matched element. - * @return HTMLElement[] */ addClass(className: string): ChocolateChipElementArray; @@ -876,7 +789,6 @@ interface ChocolateChipElementArray extends Array { * Remove a single class or multiple classes from each element in the set of matched elements. * * @param className One or more space-separated classes to be removed from the class attribute of each matched element. - * @return HTMLElement[] */ removeClass(className?: string): ChocolateChipElementArray; @@ -884,7 +796,6 @@ interface ChocolateChipElementArray extends Array { * Add or remove a classe from each element in the set of matched elements, depending on whether the class is present or not. * * @param className One or more class names (separated by spaces) to be toggled for each element in the matched set. - * @return HTMLElement[] */ toggleClass(className: string, swtch?: boolean): ChocolateChipElementArray; @@ -892,7 +803,6 @@ interface ChocolateChipElementArray extends Array { * Return any of the matched elements that have the given class. * * @param className The class name to search for. - * @return HTMLElement[] */ hasClass(className: string): ChocolateChipElementArray; @@ -901,7 +811,6 @@ interface ChocolateChipElementArray extends Array { * * @param key A string naming the piece of data to set. * @param value The new data value; it can be any Javascript type including Array or Object. - * @return HTMLElement[] */ data(key: string, value: any): ChocolateChipElementArray; @@ -910,7 +819,6 @@ interface ChocolateChipElementArray extends Array { * data(name). * * @param key Name of the data stored. - * @return any */ data(key: string): any; @@ -918,7 +826,6 @@ interface ChocolateChipElementArray extends Array { * Remove the value at the named data store for the first element in the element collection, as set by data(name, value). * * @param key Name of the data stored. - * @return any */ removeData(key?: string): any; @@ -927,7 +834,6 @@ interface ChocolateChipElementArray extends Array { * * @param key A string naming the piece of data to set. * @param value The new data value; it must be a string. You can convert JSON into a string to use with this. - * @return HTMLElement[] */ dataset(key: string, value: any): ChocolateChipElementArray; @@ -935,7 +841,6 @@ interface ChocolateChipElementArray extends Array { * Retrieve a dataset key's value for the first element in the element collection. * * @param key A string naming the piece of data to set. - * @return HTMLElement[] */ dataset(key: string): ChocolateChipElementArray; @@ -943,7 +848,6 @@ interface ChocolateChipElementArray extends Array { * Return the value at the named data store for the first element in the element collection, as set by data(name, value). * * @param key Name of the data stored. - * @return any */ data(key: string): any; @@ -952,7 +856,6 @@ interface ChocolateChipElementArray extends Array { * * @param key A string naming the piece of data to set. * @param value The new data value; it can be any Javascript type including Array or Object. - * @return HTMLElement[] */ data(key: string, value?: any): ChocolateChipElementArray; @@ -966,21 +869,16 @@ interface ChocolateChipElementArray extends Array { * * @param value A string of text or an array of strings corresponding to the value of each matched element * to set as selected/checked. - * @return any */ val(value: string): ChocolateChipElementArray; /** * Set the property of an element to enabled by removing the "disabled" attribute. - * - * @return HTMLElement[] */ enable(): ChocolateChipElementArray; /** * Set the property of an element to "disabled". - * - * @return HTMLElement[] */ disable(): ChocolateChipElementArray; @@ -989,7 +887,6 @@ interface ChocolateChipElementArray extends Array { * * @param speed A string or number determining how long the animation will run. * @param callback A function to call once the animation is complete. - * @return HTMLElement[] */ show(duration?: number | string, callback?: Function): ChocolateChipElementArray; @@ -998,7 +895,6 @@ interface ChocolateChipElementArray extends Array { * * @param duration A string or number determining how long the animation will run. * @param callback A function to call once the animation is complete. - * @return HTMLElement[] */ hide(duration?: number | string, callback?: Function): ChocolateChipElementArray; @@ -1006,7 +902,6 @@ interface ChocolateChipElementArray extends Array { * Insert content, specified by the parameter, before each element in the set of matched elements. * * @param content HTML string, DOM element, array of elements to insert before each element in the set of matched elements. - * @return HTMLElement[] */ before(content: ChocolateChipElementArray | HTMLElement | string): ChocolateChipElementArray; @@ -1014,7 +909,6 @@ interface ChocolateChipElementArray extends Array { * Insert content, specified by the parameter, after each element in the set of matched elements. * * @param content HTML string, DOM element, array of elements to insert after each element in the set of matched elements. - * @return HTMLElement[] */ after(content: ChocolateChipElementArray | HTMLElement | string): ChocolateChipElementArray; @@ -1023,7 +917,6 @@ interface ChocolateChipElementArray extends Array { * * @param content DOM element, array of elements, or HTML string to insert at the end of each element in the set * of matched elements. - * @return HTMLElement[] */ append(content: ChocolateChipElementArray | HTMLElement | Text | string): ChocolateChipElementArray; @@ -1031,7 +924,6 @@ interface ChocolateChipElementArray extends Array { * Insert content, specified by the parameter, at the beginning of each element in the set of matched elements. * * @param content DOM element, array of elements, or HTML string to insert at the beginning of each element in the set of matched elements. - * @return HTMLElement[] */ prepend(content: ChocolateChipElementArray | HTMLElement | Text | string): ChocolateChipElementArray; @@ -1039,7 +931,6 @@ interface ChocolateChipElementArray extends Array { * Insert every element in the set of matched elements to the beginning of the target. * * @param target A selector, element, or HTML string. The matched set of elements will be inserted at the beginning of the element specified by this parameter. - * @return HTMLElement[] */ prependTo(target: any[] | HTMLElement | string): ChocolateChipElementArray; @@ -1048,14 +939,11 @@ interface ChocolateChipElementArray extends Array { * * @param target A selector, element, or HTML string. The matched set of elements will be inserted at the end of the element specified by this parameter. * If no position value is provided it will simply append the content to the target. - * @return HTMLElement[] */ appendTo(target: any[] | HTMLElement | string): ChocolateChipElementArray; /** * Insert element(s) into the target element. - * - * @return HTMLElement[] */ insert(content: string, position?: number | string): ChocolateChipElementArray; @@ -1063,7 +951,6 @@ interface ChocolateChipElementArray extends Array { * Create a copy of the set of matched elements. * * @param value A Boolean indicating whether to copy the element(s) with their children. A true value copies the children. - * @return HTMLElement[] */ clone(value?: boolean): ChocolateChipElementArray; @@ -1071,14 +958,11 @@ interface ChocolateChipElementArray extends Array { * Wrap an HTML structure around each element in the set of matched elements. * * @param wrappingElement A selector or HTML string specifying the structure to wrap around the matched elements. - * @return HTMLElement[] */ wrap(wrappingElement: string): ChocolateChipElementArray; /** * Remove the parents of the set of matched elements from the DOM, leaving the matched elements in their place. - * - * @return HTMLElement[] */ unwrap(): ChocolateChipElementArray; @@ -1086,21 +970,17 @@ interface ChocolateChipElementArray extends Array { * Remove the set of matched elements from the DOM. If there are any attached events, this will remove them to prevent memory leaks. * * @param selector A selector expression that filters the set of matched elements to be removed. - * @return HTMLElement[] */ remove(selector?: string): ChocolateChipElementArray; /** * Remove all child nodes of the set of matched elements from the DOM. - * - * @return HTMLElement[] */ empty(): ChocolateChipElementArray; /** * Get an object of the current coordinates of the first element in the set of matched elements, relative to the document. * These are: top, left, bottom and right. The values are numbers representing pixel values. - * @return Object */ offset(): { top: number; @@ -1112,23 +992,17 @@ interface ChocolateChipElementArray extends Array { /** * Get the current computed width for the first element in the set of matched elements, * including padding but excluding borders. - * - * @return number */ width(): number; /** * Get the current computed height for the first element in the set of matched elements, * including padding but excluding borders. - * - * @return number */ height(): number; /** - * Get the combined text contents of each element in the set of matched elements, including their descendants. - * - * @return string + * Get the combined text contents of each element in the set of matched elements, including their descendants */ text(): string; @@ -1139,7 +1013,6 @@ interface ChocolateChipElementArray extends Array { * The text to set as the content of each matched element. * When Number is supplied, it will be converted to a String representation. * To delete text, use ChocolateChipElementArray.empty() or ChocolateChipElementArray.remove(). - * @return HTMLElement */ text(text: string | number): HTMLElement; @@ -1149,7 +1022,6 @@ interface ChocolateChipElementArray extends Array { * @param options And object of key value pairs define the CSS properties and values to animate. * @param duration A string representing the time. Should have a time identifier: "200s", "200ms", etc. * @param easing A string indicating the easing for the animation, such as "ease-out", "ease-in", "ease-in-out". - * @return void */ animate(options: Object, duration?: string, easing?: string): void; @@ -1159,7 +1031,6 @@ interface ChocolateChipElementArray extends Array { * @param eventType A string containing one or more DOM event types, such as "click" or "submit," or custom event names. * @param handler A function to execute each time the event is triggered. * @param useCapture Setting the third argument to true will trigger event bubbling. The default is false. - * @return ChocolateChipStatic */ bind(eventType: string, handler: (eventObject: Event) => any, useCapture?: boolean): ChocolateChipStatic; @@ -1169,7 +1040,6 @@ interface ChocolateChipElementArray extends Array { * @param eventType A string containing one or more DOM event types, such as "click" or "submit," or custom event names. * @param handler A function to execute each time the event is triggered. * @param useCapture Setting the third argument to true will trigger event bubbling. The default is false. - * @return ChocolateChipStatic */ unbind(eventType?: string, handler?: (eventObject: Event) => any, useCapture?: boolean): ChocolateChipStatic; @@ -1181,7 +1051,6 @@ interface ChocolateChipElementArray extends Array { * @param handler A function to execute each time the event is triggered. The keyword "this" will refer * to the element receiving the event. * @param useCapture Setting the third argument to true will trigger event bubbling. The default is false. - * @return ChocolateChipStatic */ delegate(selector: any, eventType: string, handler: (eventObject: Event) => any, useCapture?: boolean): ChocolateChipStatic; @@ -1192,7 +1061,6 @@ interface ChocolateChipElementArray extends Array { * @param eventType A string containing one or more DOM event types, such as "click" or "submit," or custom event names. * @param handler A function handler assigned to this event. * @param useCapture Setting the third argument to true will trigger event bubbling. The default is false. - * @return ChocolateChipStatic */ undelegate(selector?: any, eventType?: string, handler?: (eventObject: Event) => any, useCapture?: boolean): ChocolateChipStatic; @@ -1203,7 +1071,6 @@ interface ChocolateChipElementArray extends Array { * @param selector A string defining the descendant elements are listening for the event. * @param handler A function handler assigned to this event. * @param useCapture Setting the third argument to true will trigger event bubbling. The default is false. - * @return ChocolateChipStatic */ on(eventType: string, selector: any, handler?: (eventObject: Event) => any, capturePhase?: boolean): ChocolateChipStatic; @@ -1215,7 +1082,6 @@ interface ChocolateChipElementArray extends Array { * @param selector A string defining the descendant elements are listening for the event. * @param handler A function handler assigned to this event. * @param useCapture Setting the third argument to true will trigger event bubbling. The default is false. - * @return ChocolateChipStatic */ off(eventType?: string, selector?: any, handler?: (eventObject: Event) => any, capturePhase?: boolean): ChocolateChipStatic; @@ -1223,7 +1089,6 @@ interface ChocolateChipElementArray extends Array { * Trigger an event on an element. * * @param eventType The event to trigger. - * @return void */ trigger(eventType: string): void; } diff --git a/types/chocolatechipjs/tslint.json b/types/chocolatechipjs/tslint.json index ce367ade18..9969e961d1 100644 --- a/types/chocolatechipjs/tslint.json +++ b/types/chocolatechipjs/tslint.json @@ -7,6 +7,10 @@ "dt-header": false, "no-any-union": false, "unified-signatures": false, - "no-unnecessary-generics": false + "no-unnecessary-generics": false, + // TODO: left in redundant jsdoc that conflicts with type declarations + // Need to go over each and decide whether the jsdoc or type is correct + "no-redundant-jsdoc": false, + "no-redundant-jsdoc-2": false } } diff --git a/types/chokidar/index.d.ts b/types/chokidar/index.d.ts index 229ffb556f..396ad10e0a 100644 --- a/types/chokidar/index.d.ts +++ b/types/chokidar/index.d.ts @@ -1,4 +1,4 @@ -// Type definitions for chokidar 1.7.1 +// Type definitions for chokidar 1.7 // Project: https://github.com/paulmillr/chokidar // Definitions by: Stefan Steinhart // Felix Becker @@ -19,7 +19,6 @@ export interface WatchedPaths { } export class FSWatcher extends EventEmitter implements fs.FSWatcher { - /** * Constructs a new FSWatcher instance with optional WatchOptions parameter. */ @@ -52,7 +51,6 @@ export class FSWatcher extends EventEmitter implements fs.FSWatcher { } export interface WatchOptions { - /** * Indicates whether the process should continue to run as long as files are being watched. If * set to `false` when using `fsevents` to watch, no more events will be emitted after `ready`, @@ -86,7 +84,7 @@ export interface WatchOptions { * be relative to this. */ cwd?: string; - + /** * If set to true then the strings passed to .watch() and .add() are treated as literal path * names, even if they look like globs. Default: false. @@ -155,7 +153,6 @@ export interface WatchOptions { } export interface AwaitWriteFinishOptions { - /** * Amount of time in milliseconds for a file size to remain constant before emitting its event. */ diff --git a/types/chokidar/tslint.json b/types/chokidar/tslint.json index a41bf5d19a..3db14f85ea 100644 --- a/types/chokidar/tslint.json +++ b/types/chokidar/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/chrome/chrome-app.d.ts b/types/chrome/chrome-app.d.ts index f80b335125..561544c00c 100644 --- a/types/chrome/chrome-app.d.ts +++ b/types/chrome/chrome-app.d.ts @@ -1,6 +1,6 @@ // Type definitions for Chrome packaged application development // Project: http://developer.chrome.com/apps/ -// Definitions by: Adam Lay , MIZUNE Pine , MIZUSHIMA Junki , Ingvar Stepanyan +// Definitions by: Adam Lay , MIZUNE Pine , MIZUSHIMA Junki , Ingvar Stepanyan , Adam Pyle // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped /// @@ -21,12 +21,39 @@ declare namespace chrome.app { // App Runtime //////////////////// declare namespace chrome.app.runtime { + enum LaunchSource { + "untracked" = "untracked", + "app_launcher" = "app_launcher", + "new_tab_page" = "new_tab_page", + "reload" = "reload", + "restart" = "restart", + "load_and_launch" = "load_and_launch", + "command_line" = "command_line", + "file_handler" = "file_handler", + "url_handler" = "url_handler", + "system_tray" = "system_tray", + "about_page" = "about_page", + "keyboard" = "keyboard", + "extensions_page" = "extensions_page", + "management_api" = "management_api", + "ephemeral_app" = "ephemeral_app", + "background" = "background", + "kiosk" = "kiosk", + "chrome_internal" = "chrome_internal", + "test" = "test", + "installed_notification" = "installed_notification", + "context_menu" = "context_menu", + } + interface LaunchData { id?: string; items?: LaunchDataItem[]; url?: string; referrerUrl?: string; isKioskSession?: boolean; + isPublicSession?: boolean; + source?: LaunchSource; + actionData?: {}; } interface LaunchDataItem { diff --git a/types/chrome/index.d.ts b/types/chrome/index.d.ts index bb2b4afcb5..16ed80730f 100644 --- a/types/chrome/index.d.ts +++ b/types/chrome/index.d.ts @@ -2,7 +2,7 @@ // Project: http://developer.chrome.com/extensions/ // Definitions by: Matthew Kimber , otiai10 , couven92 , RReverser , sreimer15 // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -// TypeScript Version: 2.3 +// TypeScript Version: 2.4 /// diff --git a/types/clamp-js-main/clamp-js-main-tests.ts b/types/clamp-js-main/clamp-js-main-tests.ts new file mode 100644 index 0000000000..f903b82a06 --- /dev/null +++ b/types/clamp-js-main/clamp-js-main-tests.ts @@ -0,0 +1,22 @@ +import clamp, { ClampOptions, ClampResponse } from 'clamp-js-main'; + +const element: HTMLElement = document.createElement('div'); +element.style.setProperty('width', '5px'); +element.style.setProperty('height', '5px'); +element.style.setProperty('font-size', '12px'); + +const span: HTMLSpanElement = document.createElement('span'); +span.textContent = "Lorem ipsum. Lorem ipsum"; +element.appendChild(span); + +const simpleClamp: ClampResponse = clamp(element); + +const options: ClampOptions = { + clamp: 2, + useNativeClamp: false, + splitOnChars: ['.'], + animate: true, + truncationChar: '--', + truncationHTML: '' +}; +const clampWithOptions: ClampResponse = clamp(element, options); diff --git a/types/clamp-js-main/index.d.ts b/types/clamp-js-main/index.d.ts new file mode 100644 index 0000000000..75286172cb --- /dev/null +++ b/types/clamp-js-main/index.d.ts @@ -0,0 +1,20 @@ +// Type definitions for clamp-js-main 0.11 +// Project: https://github.com/jmenglis/clamp-js-main#readme +// Definitions by: Sinziana Nicolae +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +export interface ClampOptions { + clamp?: number|string; + useNativeClamp?: boolean; + splitOnChars?: string[]; + animate?: boolean; + truncationChar?: string; + truncationHTML?: string | null; +} + +export interface ClampResponse { + original: string; + clamped: string; +} + +export default function clamp(element: HTMLElement, options?: ClampOptions): ClampResponse; diff --git a/types/clamp-js-main/tsconfig.json b/types/clamp-js-main/tsconfig.json new file mode 100644 index 0000000000..5c05321afc --- /dev/null +++ b/types/clamp-js-main/tsconfig.json @@ -0,0 +1,24 @@ +{ + "compilerOptions": { + "module": "commonjs", + "lib": [ + "es6", + "dom" + ], + "noImplicitAny": true, + "noImplicitThis": true, + "strictNullChecks": true, + "strictFunctionTypes": true, + "baseUrl": "../", + "typeRoots": [ + "../" + ], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true + }, + "files": [ + "index.d.ts", + "clamp-js-main-tests.ts" + ] +} diff --git a/types/clamp-js-main/tslint.json b/types/clamp-js-main/tslint.json new file mode 100644 index 0000000000..3db14f85ea --- /dev/null +++ b/types/clamp-js-main/tslint.json @@ -0,0 +1 @@ +{ "extends": "dtslint/dt.json" } diff --git a/types/coinbase/coinbase-tests.ts b/types/coinbase/coinbase-tests.ts new file mode 100644 index 0000000000..793833355e --- /dev/null +++ b/types/coinbase/coinbase-tests.ts @@ -0,0 +1,108 @@ +import * as coinbase from "coinbase"; + +const client = new coinbase.Client({ apiKey: "key", apiSecret: "secret", version: "2017-10-22" }); + +client.getAccounts({}, (error: Error, result: coinbase.Account[]): void => undefined); + +client.getAccount("abcdef", (error: Error, account: coinbase.Account): void => { + account.buy({ amount: "1", commit: false, currency: "BTC", payment_method: "abcdef" }, (error: Error, buy: coinbase.Buy): void => { + buy.commit((error: Error, buy: coinbase.Buy): void => undefined); + }); + + account.createAddress({ name: "foo" }, (error: Error, address: coinbase.Address): void => { + address.getTransactions({}, (error: Error, transactions: coinbase.Transaction[]): void => undefined); + }); + + account.delete((error: Error): void => undefined); + + account.deposit({ amount: "1", commit: false, currency: "USD", payment_method: "abcdef" }, (error: Error, deposit: coinbase.Deposit): void => { + deposit.commit((error: Error, deposit: coinbase.Deposit): void => undefined); + }); + + account.getAddress("abcdef", (error: Error, address: coinbase.Address): void => undefined); + + account.getAddresses((error: Error, address: coinbase.Address[]): void => undefined); + + account.getBuy("abcdef", (error: Error, buy: coinbase.Buy): void => undefined); + + account.getBuys((error: Error, buy: coinbase.Buy[]): void => undefined); + + account.getDeposit("abcdef", (error: Error, deposit: coinbase.Deposit): void => undefined); + + account.getDeposits((error: Error, deposit: coinbase.Deposit[]): void => undefined); + + account.getSell("abcdef", (error: Error, deposit: coinbase.Sell): void => undefined); + + account.getSells((error: Error, deposit: coinbase.Sell[]): void => undefined); + + account.getTransaction("abcdef", (error: Error, deposit: coinbase.Transaction): void => undefined); + + account.getTransactions((error: Error, deposit: coinbase.Transaction[]): void => undefined); + + account.getWithdrawal("abcdef", (error: Error, deposit: coinbase.Withdrawal): void => undefined); + + account.getWithdrawals((error: Error, deposit: coinbase.Withdrawal[]): void => undefined); + + account.requestMoney( + { amount: "1", currency: "EUR", description: "foo", to: "bar", type: "request" }, + (error: Error, result: coinbase.Transaction) => undefined + ); + account.requestMoney({ amount: "1", currency: "EUR", to: "bar", type: "request" }, (error: Error, tx: coinbase.Transaction) => { + tx.cancel((error: Error, tx: coinbase.Transaction): void => undefined); + tx.complete((error: Error, tx: coinbase.Transaction): void => undefined); + tx.resend((error: Error, tx: coinbase.Transaction): void => undefined); + }); + + account.sell( + { agree_btc_amount_varies: true, amount: "1", commit: true, currency: "BTC", payment_method: "abcdef", quote: true}, + (error: Error, sell: coinbase.Sell): void => { + sell.commit((error: Error, sell: coinbase.Sell): void => undefined); + } + ); + account.sell( + { currency: "BTC", payment_method: "abcdef", total: "3"}, + (error: Error, sell: coinbase.Sell): void => { + sell.commit((error: Error, sell: coinbase.Sell): void => undefined); + } + ); + + account.sendMoney( + { amount: "1", currency: "EUR", description: "foo", fee: "2", idem: "bar", to: "baz", type: "send" }, + (error: Error, result: coinbase.Transaction) => undefined + ); + + account.setPrimary((error: Error, result: coinbase.Account): void => undefined); + + account.transferMoney( + { amount: "1", currency: "USD", description: "foo", to: "bar", type: "transfer" }, + (error: Error, tx: coinbase.Transaction): void => undefined + ); + + account.update({ name: "foo" }, (error: Error, result: coinbase.Account): void => undefined); + + account.withdraw({ amount: "1", commit: false, currency: "ETH", payment_method: "abcdef"}, (error: Error, result: coinbase.Withdrawal): void => { + result.commit((error: Error, result: coinbase.Withdrawal): void => undefined); + }); +}); + +client.getBuyPrice({ currencyPair: "USD-BTC" }, (error: Error, result: coinbase.MoneyHash): void => undefined); + +client.getCurrencies((error: Error, result: coinbase.Currency[]): void => undefined); + +client.getExchangeRates({currency: "ETC"}, (error: Error, result: coinbase.ExchangeRate): void => undefined); + +client.getPaymentMethod("foo", (error: Error, result: coinbase.PaymentMethod): void => undefined); + +client.getPaymentMethods((error: Error, result: coinbase.PaymentMethod[]): void => undefined); + +client.getSellPrice({ currencyPair: "USD-BTC" }, (error: Error, result: coinbase.MoneyHash): void => undefined); + +client.getSpotPrice({ currencyPair: "USD-BTC" }, (error: Error, result: coinbase.MoneyHash): void => undefined); +client.getSpotPrice({ currencyPair: "USD-BTC", date: "2017-22-01" }, (error: Error, result: coinbase.MoneyHash): void => undefined); + +client.getTime((error: Error, result: coinbase.Time): void => undefined); + +client.getUser("abcdef", (error: Error, user: coinbase.User): void => { + user.showAuth((error: Error, auth: coinbase.Auth): void => undefined); + user.update({ name: "foo", time_zone: "bar", native_currency: "USD" }, (error: Error, user: coinbase.User): void => undefined); +}); diff --git a/types/coinbase/index.d.ts b/types/coinbase/index.d.ts new file mode 100644 index 0000000000..ae1e041203 --- /dev/null +++ b/types/coinbase/index.d.ts @@ -0,0 +1,1333 @@ +// Type definitions for coinbase 2.0 +// Project: https://github.com/coinbase/coinbase-node +// Definitions by: Rogier Schouten +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +export interface ClientConstructOpts { + /** + * API key (obtain this from the coinbase website) + */ + apiKey?: string; + /** + * API key secret (obtain this from the coinbase website) + */ + apiSecret?: string; + /** + * OAuth2 access token + */ + accessToken?: string; + /** + * API version in 'yyyy-mm-dd' format, see https://developers.coinbase.com/api/v2#changelog + */ + version?: string; +} + +export interface CreateAccountOpts { + /** + * Account name + */ + name?: string; +} + +export interface GetExchangeRateOpts { + /** + * Base currency, default USD + */ + currency?: string; +} + +export interface GetBuyPriceOpts { + /** + * Currency pair, e.g. 'BTC-USD' + */ + currencyPair: string; +} + +export interface GetSellPriceOpts { + /** + * Currency pair, e.g. 'BTC-USD' + */ + currencyPair: string; +} + +export interface GetSpotPriceOpts { + /** + * Currency pair, e.g. 'BTC-USD' + */ + currencyPair: string; + /** + * Specify date for historic spot price in format YYYY-MM-DD (UTC) + */ + date?: string; +} + +export interface UpdateAccountOpts { + /** + * Account name + */ + name?: string; +} + +export interface CreateAddressOpts { + /** + * Address label + */ + name?: string; +} + +export interface SendMoneyOpts { + /** + * Type send is required when sending money + */ + type: "send"; + /** + * A bitcoin address, litecoin address, ethereum address, or an email of the recipient + */ + to: string; + /** + * Amount to be sent + */ + amount: string; + /** + * Currency for the amount (see Client#getCurrencies() for available strings) + */ + currency: string; + /** + * Notes to be included in the email that the recipient receives + */ + description?: string; + /** + * Don’t send notification emails for small amounts (e.g. tips) + */ + skip_notifications?: boolean; + /** + * Transaction fee in BTC/ETH/LTC if you would like to pay it. Fees can be added as a string, such as 0.0005 + */ + fee?: string; + /** + * *Recommended* A token to ensure idempotence. If a previous transaction with the same idem parameter already exists for this sender, + * that previous transaction will be returned and a new one will not be created. Max length 100 characters + */ + idem?: string; + /** + * Whether this send is to another financial institution or exchange. Required if this send is to an address and is valued at over USD$3000. + */ + to_financial_institution?: boolean; + /** + * The website of the financial institution or exchange. Required if to_financial_institution is true. + */ + financial_institution_website?: string; +} + +export interface TransferMoneyOpts { + /** + * Type transfer is required when transferring bitcoin or ethereum between accounts + */ + type: "transfer"; + /** + * ID of the receiving account + */ + to: string; + /** + * Amount to be transferred + */ + amount: string; + /** + * Currency for the amount (see Client#getCurrencies() for available strings) + */ + currency: string; + /** + * Notes to be included in the transfer + */ + description?: string; +} + +export interface RequestMoneyOpts { + /** + * Type request is required when sending money + */ + type: "request"; + /** + * An email of the recipient + */ + to: string; + /** + * Amount to be transferred + */ + amount: string; + /** + * Currency for the amount (see Client#getCurrencies() for available strings) + */ + currency: string; + /** + * Notes to be included in the email that the recipient receives + */ + description?: string; +} + +export interface UpdateUserOpts { + /** + * User’s name + */ + name?: string; + /** + * Time zone + */ + time_zone?: string; + /** + * Local currency used to display amounts converted from BTC + */ + native_currency?: string; +} + +export interface BuyOpts { + /** + * Buy amount without fees (alternative to total) + */ + amount?: string; + /** + * Buy amount with fees (alternative to amount) + */ + total?: string; + /** + * Currency for the amount (see Client#getCurrencies() for available strings) + */ + currency: string; + /** + * The ID of the payment method that should be used for the buy. (todo get payment methods) + */ + payment_method?: string; + /** + * Whether or not you would still like to buy if you have to wait for your money to arrive to lock in a price + */ + agree_btc_amount_varies?: boolean; + /** + * If set to false, this buy will not be immediately completed. Use the commit call to complete it. Default value: true + */ + commit?: boolean; + /** + * If set to true, response will return an unsave buy for detailed price quote. Default value: false + */ + quote?: boolean; +} + +export interface SellOpts { + /** + * Sell amount without fees (alternative to total) + */ + amount?: string; + /** + * Sell amount with fees (alternative to amount) + */ + total?: string; + /** + * Currency for the amount (see Client#getCurrencies() for available strings) + */ + currency: string; + /** + * The ID of the payment method that should be used for the sell. + */ + payment_method?: string; + /** + * Whether or not you would still like to sell if you have to wait for your money to arrive to lock in a price + */ + agree_btc_amount_varies?: boolean; + /** + * If set to false, this sell will not be immediately completed. Use the commit call to complete it. Default value: true + */ + commit?: boolean; + /** + * If set to true, response will return an unsave sell for detailed price quote. Default value: false + */ + quote?: boolean; +} + +export interface DepositOpts { + /** + * Deposit amount + */ + amount: string; + /** + * Currency for the amount (see Client#getCurrencies() for available strings) + */ + currency: string; + /** + * The ID of the payment method that should be used for the buy. (todo get payment methods) + */ + payment_method?: string; + /** + * If set to false, this deposit will not be immediately completed. Use the commit call to complete it. Default value: true + */ + commit?: boolean; +} + +export interface WithdrawOpts { + /** + * Withdrawal amount + */ + amount: string; + /** + * Currency for the amount (see Client#getCurrencies() for available strings) + */ + currency: string; + /** + * The ID of the payment method that should be used for the buy. (todo get payment methods) + */ + payment_method?: string; + /** + * If set to false, this withdrawal will not be immediately completed. Use the commit call to complete it. Default value: true + */ + commit?: boolean; +} + +/** + * Combination of an amount and a currency + */ +export interface MoneyHash { + /** + * Amount as floating-point in a string + */ + amount: string; + /** + * Currency e.g. "BTC" (see Client#getCurrencies() for available strings) + */ + currency: string; +} + +export type ResourceType = "account" | "transaction" | "address" | "user" | "buy" | "sell" | "deposit" | "withdrawal" | "payment_method"; + +/** + * Base interface for all resources + */ +export interface Resource { + /** + * Resource type + */ + resource: ResourceType; +} + +export class User implements Resource { + /** + * Resource type, constant "user" + */ + resource: "user"; + + /** + * Resource ID + */ + id: string; + + /** + * ISO timestamp (sometimes needs additional permissions) + */ + created_at?: string; + + /** + * ISO timestamp (sometimes needs additional permissions) + */ + updated_at?: string; + + /** + * REST endpoint + */ + resource_path: string; + + /** + * User’s name + */ + name?: string; + + /** + * + */ + username?: string; + + /** + * Location for user’s profile + */ + profile_location?: string; + + /** + * Bio for user’s profile + */ + profile_bio?: string; + + /** + * profile location if user has one + */ + profile_url?: string; + + /** + * User’s avatar url + */ + avatar_url: string; + + /** + * Time zone (needs wallet:user:read permission) + */ + time_zone?: string; + + /** + * Native currency (needs wallet:user:read permission) + */ + native_currency?: string; + + /** + * (needs wallet:user:read permission) + */ + bitcoin_unit?: string; + + /** + * (needs wallet:user:read permission) + */ + country?: Country; + + /** + * Email address (needs wallet:user:email permission) + */ + email?: string; + + /** + * Get current user’s authorization information including granted scopes and send limits when using OAuth2 authentication + * No permission required + */ + showAuth(cb: (error: Error, result: Auth) => void): void; + + /** + * Change user properties + * Scope: wallet:user:update + */ + update(opts: UpdateUserOpts, cb: (error: Error, result: User) => void): void; +} + +export interface Auth { + /** + * Authentication method e.g. "oauth" + */ + method: string; + /** + * Permissions for this user e.g. "wallet:user:read" + */ + scopes: string[]; + + oauth_meta?: any; +} + +export interface Country { + /** + * 2-letter country code + */ + code: string; + /** + * Country name + */ + name: string; +} + +/** + * Bitcoin, Litecoin or Ethereum address + */ +export class Address implements Resource { + /** + * Type of resource, constant string "address" + */ + resource: "address"; + + /** + * Bitcoin, Litecoin or Ethereum address + */ + address: string; + + /** + * User defined label for the address + */ + name?: string; + + /** + * List transactions that have been sent to a specific address. + * Scope: wallet:transactions:read + */ + getTransactions(opts: {}, cb: (error: Error, result: Transaction[]) => void): void; +} + +export type AccountType = "wallet" | "fiat" | "multisig" | "vault" | "multisig_vault"; + +/** + * Account resource represents all of a user’s accounts, including bitcoin, litecoin and ethereum wallets, fiat currency accounts, + * and vaults. This is represented in the type field. It’s important to note that new types can be added over time so you want to + * make sure this won’t break your implementation. + * User can only have one primary account and it’s type can only be wallet. + */ +export class Account implements Resource { + /** + * Type of resource, constant string "account" + */ + resource: "account"; + + /** + * Resource ID + */ + id: string; + + /** + * ISO timestamp (sometimes needs additional permissions) + */ + created_at?: string; + + /** + * ISO timestamp (sometimes needs additional permissions) + */ + updated_at?: string; + + /** + * REST endpoint + */ + resource_path: string; + + /** + * User or system defined name + */ + name: string; + + /** + * Primary account + */ + primary: boolean; + + /** + * Account’s type + */ + type: AccountType; + + /** + * Account’s currency (see Client#getCurrencies() for available strings) + */ + currency: string; + + /** + * Balance + */ + balance: MoneyHash; + + /** + * Promote an account as primary account. + * Scope: wallet:accounts:update + */ + setPrimary(cb: (error: Error, result: Account) => void): void; + + /** + * Modifies user’s account. + * Scope: wallet:accounts:update + */ + update(opts: UpdateAccountOpts, cb: (error: Error, result: Account) => void): void; + + /** + * Removes user’s account. In order to remove an account it can’t be: + * - Primary account + * - Account with non-zero balance + * - Fiat account + * - Vault with a pending withdrawal + * Scope: wallet:accounts:delete + */ + delete(cb: (error: Error) => void): void; + + /** + * Lists addresses for an account. Important: Addresses should be considered one time use only. Create new addresses. + * Scope: wallet:addresses:read + */ + getAddresses(cb: (error: Error, result: Address[]) => void): void; + + /** + * Show an individual address for an account. A regular bitcoin, litecoin or ethereum address can be used in place of `id` but the + * address has to be associated to the correct account. Important: Addresses should be considered one time use only. Create new addresses. + * Scope: wallet:addresses:read + * @param id resource id or a regular bitcoin, litecoin or ethereum address + */ + getAddress(id: string, cb: (error: Error, result: Address) => void): void; + + /** + * Creates a new address for an account. As all the arguments are optinal, it’s possible just to do a empty POST which will create a new + * address. This is handy if you need to create new receive addresses for an account on-demand. + * Addresses can be created for all account types. With fiat accounts, funds will be received with Instant Exchange + * Scope: wallet:addresses:create + * @param opts can be null, optional address name + */ + createAddress(opts: CreateAddressOpts | null, cb: (error: Error, result: Address) => void): void; + + /** + * Lists account’s transactions. + * Scope: wallet:transactions:read + */ + getTransactions(cb: (error: Error, result: Transaction[]) => void): void; + + /** + * Show an individual transaction for an account + * Scope: wallet:transactions:read + * @param id resource id + */ + getTransaction(id: string, cb: (error: Error, result: Transaction) => void): void; + + /** + * Send funds to a bitcoin address, litecoin address, ethereum address, or email address. No transaction fees are required for off + * blockchain bitcoin transactions. + * + * It’s recommended to always supply a unique `idem` field for each transaction. This prevents you from sending the same transaction + * twice if there has been an unexpected network outage or other issue. + * + * When used with OAuth2 authentication, this endpoint requires two factor authentication unless used with + * wallet:transactions:send:bypass-2fa scope. + * + * If the user is able to buy bitcoin, they can send funds from their fiat account using instant exchange feature. + * Buy fees will be included in the created transaction and the recipient will receive the user defined amount. + * To create a multisig transaction, visit Multisig documentation. + * + * Scope: wallet:transactions:send, wallet:transactions:send:bypass-2fa + */ + sendMoney(opts: SendMoneyOpts, cb: (error: Error, result: Transaction) => void): void; + + /** + * Transfer bitcoin, litecoin or ethereum between two of a user’s accounts. Following transfers are allowed: + * - wallet to wallet + * - wallet to vault + * Scope: wallet:transactions:transfer + */ + transferMoney(opts: TransferMoneyOpts, cb: (error: Error, result: Transaction) => void): void; + + /** + * Requests money from an email address. + * Scope: wallet:transactions:request + */ + requestMoney(opts: RequestMoneyOpts, cb: (error: Error, result: Transaction) => void): void; + + /** + * Lists buys for an account. + * Scope: wallet:buys:read + */ + getBuys(cb: (error: Error, result: Buy[]) => void): void; + + /** + * Show an individual buy. + * Scope: wallet:buys:read + * @param id resource id + */ + getBuy(id: string, cb: (error: Error, result: Buy) => void): void; + + /** + * Buys a user-defined amount of bitcoin, litecoin or ethereum. + * There are two ways to define buy amounts–you can use either the amount or the total parameter: + * - When supplying amount, you’ll get the amount of bitcoin, litecoin or ethereum defined. With amount it’s recommended to use BTC or + * ETH as the currency value, but you can always specify a fiat currency and and the amount will be converted to BTC or ETH respectively. + * - When supplying total, your payment method will be debited the total amount and you’ll get the amount in BTC or ETH after fees have + * been reduced from the total. With total it’s recommended to use the currency of the payment method as the currency parameter, + * but you can always specify a different currency and it will be converted. + * Given the price of digital currency depends on the time of the call and on the amount of purchase, it’s recommended to use the + * commit: false parameter to create an uncommitted buy to show the confirmation for the user or get the final quote, and commit that + * with a separate request. + * If you need to query the buy price without locking in the buy, you can use quote: true option. This returns an unsaved buy and + * unlike commit: false, this buy can’t be completed. This option is useful when you need to show the detailed buy price quote + * for the user when they are filling a form or similar situation. + * Scope: wallet:buys:create + * @param opts indicates what to buy + * @param cb receives transaction that you can use to commit the buy + */ + buy(opts: BuyOpts, cb: (error: Error, result: Buy) => void): void; + + /** + * Lists sells for an account. + * Scope: wallet:sells:read + */ + getSells(cb: (error: Error, result: Sell[]) => void): void; + + /** + * Show an individual sell. + * Scope: wallet:sells:read + * @param id resource id + */ + getSell(id: string, cb: (error: Error, result: Sell) => void): void; + + /** + * Sells a user-defined amount of bitcoin, litecoin or ethereum. + * + * There are two ways to define sell amounts–you can use either the amount or the total parameter: + * - When supplying amount, you’ll get the amount of bitcoin, litecoin or ethereum defined. With amount it’s recommended to use BTC or + * ETH as the currency value, but you can always specify a fiat currency and the amount will be converted to BTC or ETH respectively. + * - When supplying total, your payment method will be credited the total amount and you’ll get the amount in BTC or ETH after fees + * have been reduced from the subtotal. With total it’s recommended to use the currency of the payment method as the currency parameter, + * but you can always specify a different currency and it will be converted. + * + * Given the price of digital currency depends on the time of the call and amount of the sell, it’s recommended to use the commit: false + * parameter to create an uncommitted sell to get a quote and then to commit that with a separate request. + * + * If you need to query the sell price without locking in the sell, you can use quote: true option. This returns an unsaved sell and + * unlike commit: false, this sell can’t be completed. This option is useful when you need to show the detailed sell price quote for + * the user when they are filling a form or similar situation. + * Scope: wallet:sells:create + */ + sell(opts: SellOpts, cb: (error: Error, result: Sell) => void): void; + + /** + * Lists deposits for an account. + * Scope: wallet:deposits:read + */ + getDeposits(cb: (error: Error, result: Deposit[]) => void): void; + + /** + * Show an individual deposit. + * Scope: wallet:deposits:read + * @param id resource id + */ + getDeposit(id: string, cb: (error: Error, result: Deposit) => void): void; + + /** + * Deposits user-defined amount of funds to a fiat account. + * Scope: wallet:deposits:create + */ + deposit(opts: DepositOpts, cb: (error: Error, result: Deposit) => void): void; + + /** + * Lists withdrawals for an account. + * Scope: wallet:withdrawals:read + */ + getWithdrawals(cb: (error: Error, result: Withdrawal[]) => void): void; + + /** + * Show an individual withdrawal. + * Scope: wallet:withdrawals:read + * @param id resource id + */ + getWithdrawal(id: string, cb: (error: Error, result: Withdrawal) => void): void; + + /** + * Withdraws user-defined amount of funds from a fiat account. + * Scope: wallet:withdrawals:create + */ + withdraw(opts: WithdrawOpts, cb: (error: Error, result: Withdrawal) => void): void; +} + +/** + * Reference to any resource + */ +export interface ResourceRef { + id: string; + resource: ResourceType; + resource_path: string; +} + +export type TransactionType = "send" | "request" | "transfer" | "buy" | "sell" | "fiat_deposit" | "fiat_withdrawal" | "exchange_deposit" + | "exchange_withdrawal" | "vault_withdrawal"; + +export type TransactionStatus = "pending" | "completed" | "failed" | "expired" | "canceled" | "waiting_for_signature" | "waiting_for_clearing"; + +export class Transaction implements Resource { + /** + * Constant "transaction" + */ + resource: "transaction"; + + /** + * Transaction type + */ + type: TransactionType; + + /** + * Transaction status + */ + status: TransactionStatus; + + /** + * Amount in bitcoin, litecoin or ethereum + */ + amount: MoneyHash; + + /** + * Amount in user's native currency + */ + native_amount: MoneyHash; + + /** + * Account associated with the transaction + */ + account: Account; + + /** + * User defined description + */ + description: string; + + /** + * Indicator if the transaction was instant exchanged (received into a bitcoin address for a fiat account) + */ + instant_exchange: boolean; + + /** + * Detailed information about the transaction + */ + details: any; + + /** + * Information about bitcoin, litecoin or ethereum network including network transaction hash if transaction was on-blockchain. + * Only available for certain types of transactions + */ + network?: any; + + /** + * The receiving party of a debit transaction. Usually another resource but can also be another type like email. + * Only available for certain types of transactions + */ + to?: ResourceRef | string; + + /** + * The originating party of a credit transaction. Usually another resource but can also be another type like bitcoin network. + * Only available for certain types of transactions + */ + from?: ResourceRef | string; + + /** + * Associated bitcoin, litecoin or ethereum address for received payment + */ + address?: Address; + + /** + * Associated OAuth2 application + */ + application?: any; + + /** + * Lets the recipient of a money request complete the request by sending money to the user who requested the money. + * This can only be completed by the user to whom the request was made, not the user who sent the request. + * Scope: wallet:transactions:request + */ + complete(cb: (error: Error, result: Transaction) => void): void; + + /** + * Lets the user resend a money request. This will notify recipient with a new email. + * Scope: wallet:transactions:request + */ + resend(cb: (error: Error, result: Transaction) => void): void; + + /** + * Lets a user cancel a money request. Money requests can be canceled by the sender or the recipient. + * Scope: wallet:transactions:request + */ + cancel(cb: (error: Error, result: Transaction) => void): void; +} + +export type BuyStatus = "created" | "completed" | "canceled"; + +/** + * Buy resource + */ +export class Buy implements Resource { + /** + * Constant "buy" + */ + resource: "buy"; + + /** + * Status + */ + status: BuyStatus; + + /** + * Associated payment method (e.g. a bank, fiat account) + */ + payment_method: ResourceRef; + + /** + * Associated transaction (e.g. a bank, fiat account) + */ + transaction: ResourceRef; + + /** + * Amount in bitcoin, litecoin or ethereum + */ + amount: MoneyHash; + + /** + * Fiat amount with fees + */ + total: MoneyHash; + + /** + * Fiat amount without fees + */ + subtotal: MoneyHash; + + /** + * Fee associated to this buy + */ + fee: MoneyHash; + + /** + * Has this buy been committed? + */ + committed: boolean; + + /** + * Was this buy executed instantly? + */ + instant: boolean; + + /** + * When a buy isn’t executed instantly, it will receive a payout date for the time it will be executed. ISO timestamp + */ + payout_at?: string; + + /** + * Completes a buy that is created in commit: false state. + * If the exchange rate has changed since the buy was created, this call will fail with the error “The exchange rate updated while you + * were waiting. The new total is shown below”. The buy’s total will also be updated. You can repeat the `commit` call to accept the new + * values and start the buy at the new rates. + * Scope: wallet:buys:create + */ + commit(cb: (error: Error, transaction: Buy) => void): void; +} + +export type SellStatus = "created" | "completed" | "canceled"; + +/** + * Sell resource + */ +export class Sell implements Resource { + /** + * Constant "sell" + */ + resource: "sell"; + + /** + * Status of the sell. Currently available values: created, completed, canceled + */ + status: BuyStatus; + + /** + * Associated payment method (e.g. a bank, fiat account) + */ + payment_method: ResourceRef; + + /** + * Associated transaction (e.g. a bank, fiat account) + */ + transaction: ResourceRef; + + /** + * Amount in bitcoin, litecoin or ethereum + */ + amount: MoneyHash; + + /** + * Fiat amount with fees + */ + total: MoneyHash; + + /** + * Fiat amount without fees + */ + subtotal: MoneyHash; + + /** + * Fee associated to this sell + */ + fee: MoneyHash; + + /** + * Has this sell been committed? + */ + committed: boolean; + + /** + * Was this sell executed instantly? + */ + instant: boolean; + + /** + * When a sell isn’t executed instantly, it will receive a payout date for the time it will be executed. ISO timestamp + */ + payout_at?: string; + + /** + * Completes a sell that is created in commit: false state. + * If the exchange rate has changed since the sell was created, this call will fail with the error “The exchange rate updated while you + * were waiting. The new total is shown below”. The buy’s total will also be updated. You can repeat the `commit` call to accept the new + * values and start the buy at the new rates. + * Scope: wallet:sells:create + */ + commit(cb: (error: Error, transaction: Sell) => void): void; +} + +export type DepositStatus = "created" | "completed" | "canceled"; + +/** + * Deposit resource represents a deposit of funds using a payment method (e.g. a bank). Each committed deposit also has an associated transaction. + * Deposits can be started with commit: false which is useful when displaying the confirmation for a deposit. + * These deposits will never complete and receive an associated transaction unless they are committed separately. + */ +export class Deposit implements Resource { + resource: "deposit"; + + /** + * Resource ID + */ + id: string; + + /** + * ISO timestamp (sometimes needs additional permissions) + */ + created_at?: string; + + /** + * ISO timestamp (sometimes needs additional permissions) + */ + updated_at?: string; + + /** + * REST endpoint + */ + resource_path: string; + + /** + * Status of the deposit. Currently available values: created, completed, canceled + */ + status: DepositStatus; + + /** + * Associated payment method (e.g. a bank) + */ + payment_method: ResourceRef; + + /** + * Associated transaction (e.g. a bank, fiat account) + */ + transaction: ResourceRef; + + /** + * Amount + */ + amount: MoneyHash; + + /** + * Amount without fees + */ + subtotal: MoneyHash; + + /** + * Fee associated to this deposit + */ + fee: MoneyHash; + + /** + * Has this deposit been committed? + */ + committed: boolean; + + /** + * When a deposit isn’t executed instantly, it will receive a payout date for the time it will be executed. ISO timestamp + */ + payout_at?: string; + + /** + * Completes a deposit that is created in commit: false state. + * Scope: wallet:deposits:create + */ + commit(cb: (error: Error, result: Deposit) => void): void; +} + +export type WithdrawalStatus = "created" | "completed" | "canceled"; + +/** + * Withdrawal resource represents a withdrawal of funds using a payment method (e.g. a bank). Each committed withdrawal also has a associated + * transaction. + * Withdrawal can be started with commit: false which is useful when displaying the confirmation for a withdrawal. These withdrawals will + * never complete and receive an associated transaction unless they are committed separately. + */ +export class Withdrawal implements Resource { + resource: "deposit"; + + /** + * Resource ID + */ + id: string; + + /** + * ISO timestamp (sometimes needs additional permissions) + */ + created_at?: string; + + /** + * ISO timestamp (sometimes needs additional permissions) + */ + updated_at?: string; + + /** + * REST endpoint + */ + resource_path: string; + + /** + * Status of the deposit. Currently available values: created, completed, canceled + */ + status: WithdrawalStatus; + + /** + * Associated payment method (e.g. a bank) + */ + payment_method: ResourceRef; + + /** + * Associated transaction (e.g. a bank, fiat account) + */ + transaction: ResourceRef; + + /** + * Amount + */ + amount: MoneyHash; + + /** + * Amount without fees + */ + subtotal: MoneyHash; + + /** + * Fee associated to this withdrawal + */ + fee: MoneyHash; + + /** + * Has this withdrawal been committed? + */ + committed: boolean; + + /** + * When a withdrawal isn’t executed instantly, it will receive a payout date for the time it will be executed. ISO timestamp + */ + payout_at?: string; + + /** + * Completes a withdrawal that is created in commit: false state. + * Scope: wallet:withdrawals:create + */ + commit(cb: (error: Error, result: Withdrawal) => void): void; +} + +export type PaymentMethodType = "ach_bank_account" | "sepa_bank_account" | "ideal_bank_account" | "fiat_account" | "bank_wire" + | "credit_card" | "secure3d_card" | "eft_bank_account" | "interac"; + +/** + * Payment method resource represents the different kinds of payment methods that can be used when buying and selling bitcoin, litecoin or + * ethereum. + * As fiat accounts can be used for buying and selling, they have an associated payment method. This type of a payment method will also have + * a fiat_account reference to the actual account. + * + * Currently available type values: + * - ach_bank_account - Regular US bank account + * - sepa_bank_account - European SEPA bank account + * - ideal_bank_account - iDeal bank account (Europe) + * - fiat_account - Fiat nominated Coinbase account + * - bank_wire - Bank wire (US only) + * - credit_card - Credit card (can’t be used for buying/selling) + * - secure3d_card - Secure3D verified payment card + * - eft_bank_account - Canadian EFT bank account + * - interac - Interac Online for Canadian bank accounts + */ +export interface PaymentMethod extends Resource { + /** + * Resource type, constant "payment_method" + */ + resource: "payment_method"; + + /** + * Payment method type + */ + type: PaymentMethodType; + + /** + * Method name + */ + name: string; + + /** + * Payment method’s native currency (see Client#getCurrencies() for available strings) + */ + currency: string; + + /** + * Is primary buying method? + */ + primary_buy: boolean; + + /** + * Is primary selling method? + */ + primary_sell: boolean; + + /** + * Is buying allowed with this method? + */ + allow_buy: boolean; + + /** + * Is selling allowed with this method? + */ + allow_sell: boolean; + + /** + * Does this method allow for instant buys? + */ + instant_buy: boolean; + + /** + * Does this method allow for instant sells? + */ + instant_sell: boolean; + + /** + * If the user has obtained optional wallet:payment-methods:limits permission, an additional field, limits, will be embedded into payment + * method data. It will contain information about buy, instant buy, sell and deposit limits (there’s no limits for withdrawals at this time). + * As each one of these can have several limits you should always look for the lowest remaining value when performing the relevant action. + */ + limits?: PaymentMethodLimits; +} + +/** + * This contains information about buy, instant buy, sell and deposit limits (there’s no limits for withdrawals at this time). + * As each one of these can have several limits you should always look for the lowest remaining value when performing the relevant action. + */ +export interface PaymentMethodLimits { + buy: PaymentMethodLimit[]; + instant_buy: PaymentMethodLimit[]; + sell: PaymentMethodLimit[]; + deposit: PaymentMethodLimit[]; +} + +export interface PaymentMethodLimit { + period_in_days: number; + total: MoneyHash; + remaining: MoneyHash; +} + +/** + * Information about one supported currency. Currency codes will conform to the ISO 4217 standard where possible. + * Currencies which have or had no representation in ISO 4217 may use a custom code (e.g. BTC). + */ +export interface Currency { + /** + * Abbreviation e.g. "USD" or "BTC" + */ + id: string; + /** + * Full name e.g. "United Arab Emirates Dirham" + */ + name: string; + /** + * Floating-point number in a string + */ + min_size: string; +} + +export interface ExchangeRate { + /** + * Base currency + */ + currency: string; + /** + * Rates as floating points in strings; indexed by currency id + */ + rates: { [index: string]: string }; +} + +export interface Time { + iso: string; + epoch: number; +} + +export class Client { + constructor(opts: ClientConstructOpts); + + /** + * Get any user’s information with their ID. + * Scopes: none + * @param id resource id + */ + getUser(id: string, cb: (error: Error, result: User) => void): void; + + /** + * Get the current user. To get user’s email or private information, use permissions wallet:user:email and wallet:user:read. If current + * request has a wallet:transactions:send scope, then the response will contain a boolean sends_disabled field that indicates + * if the user’s send functionality has been disabled. + */ + getCurrentUser(cb: (error: Error, result: User) => void): void; + + /** + * Returns all accounts for the current user + * Scope: wallet:accounts:read + */ + getAccounts(opts: {}, cb: (error: Error, result: Account[]) => void): void; + + /** + * Get one account by its Resource ID + * Scope: wallet:accounts:read + * @param id resource ID or "primary" + */ + getAccount(id: string, cb: (error: Error, result: Account) => void): void; + + /** + * Creates a new account for user. + * Scopes: wallet:accounts:create + */ + createAccount(opts: CreateAccountOpts, cb: (error: Error, result: Account) => void): void; + + /** + * Lists current user’s payment methods + * Scope: wallet:payment-methods:read + */ + getPaymentMethods(cb: (error: Error, result: PaymentMethod[]) => void): void; + + /** + * Show current user’s payment method. + * Scope: wallet:payment-methods:read + */ + getPaymentMethod(id: string, cb: (error: Error, result: PaymentMethod) => void): void; + + /** + * List known currencies. Currency codes will conform to the ISO 4217 standard where possible. Currencies which have or had no + * representation in ISO 4217 may use a custom code (e.g. BTC). + * Scope: none + */ + getCurrencies(cb: (error: Error, result: Currency[]) => void): void; + + /** + * Get current exchange rates. Default base currency is USD but it can be defined as any supported currency. + * Returned rates will define the exchange rate for one unit of the base currency. + * Scope: none + */ + getExchangeRates(opts: GetExchangeRateOpts, cb: (error: Error, result: ExchangeRate) => void): void; + + /** + * Get the total price to buy one bitcoin or ether. Note that exchange rates fluctuates so the price is only correct for seconds at the time. + * This buy price includes standard Coinbase fee (1%) but excludes any other fees including bank fees. + * If you need more accurate price estimate for a specific payment method or amount, @see Account#buy() and `quote: true` option. + * Scope: none + */ + getBuyPrice(opts: GetBuyPriceOpts, cb: (error: Error, result: MoneyHash) => void): void; + + /** + * Get the total price to sell one bitcoin or ether. Note that exchange rates fluctuates so the price is only correct for seconds at the time. + * This sell price includes standard Coinbase fee (1%) but excludes any other fees including bank fees. If you need more accurate price + * estimate for a specific payment method or amount, see sell bitcoin endpoint and quote: true option. + * Scope: none + */ + getSellPrice(opts: GetSellPriceOpts, cb: (error: Error, result: MoneyHash) => void): void; + + /** + * Get the current market price for bitcoin. This is usually somewhere in between the buy and sell price. + * Note that exchange rates fluctuates so the price is only correct for seconds at the time. + * You can also get historic prices with date parameter. + * Scope: none + */ + getSpotPrice(opts: GetSpotPriceOpts, cb: (error: Error, result: MoneyHash) => void): void; + + /** + * Get the API server time. + */ + getTime(cb: (error: Error, result: Time) => void): void; +} diff --git a/types/coinbase/tsconfig.json b/types/coinbase/tsconfig.json new file mode 100644 index 0000000000..6f8b261d27 --- /dev/null +++ b/types/coinbase/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", + "coinbase-tests.ts" + ] +} diff --git a/types/coinbase/tslint.json b/types/coinbase/tslint.json new file mode 100644 index 0000000000..3db14f85ea --- /dev/null +++ b/types/coinbase/tslint.json @@ -0,0 +1 @@ +{ "extends": "dtslint/dt.json" } diff --git a/types/combokeys/index.d.ts b/types/combokeys/index.d.ts index f7e1e5b035..24f3313582 100644 --- a/types/combokeys/index.d.ts +++ b/types/combokeys/index.d.ts @@ -35,7 +35,7 @@ declare namespace Combokeys { * @param {handler} optional - one of "keypress", "keydown", or "keyup" * @returns void */ - bind(keys: string | string[], callback: () => void, action?: string): void; + bind(keys: string | string[], callback: (event: KeyboardEvent) => void, action?: string): void; /** diff --git a/types/commander/commander-tests.ts b/types/commander/commander-tests.ts deleted file mode 100644 index 46aa77d92c..0000000000 --- a/types/commander/commander-tests.ts +++ /dev/null @@ -1,99 +0,0 @@ -import * as program from 'commander'; - -interface ExtendedOptions extends program.CommandOptions { - isNew: any; -} - -const commandInstance = new program.Command('-f'); -const optionsInstance = new program.Option('-f'); - -const name = program.name(); - -program - .name('set name') - .version('0.0.1') - .option('-p, --peppers', 'Add peppers') - .option('-P, --pineapple', 'Add pineapple') - .option('-b, --bbq', 'Add bbq sauce') - .option('-c, --cheese [type]', 'Add the specified type of cheese [marble]', 'marble') - .parse(process.argv); - -console.log('you ordered a pizza with:'); -if (program['peppers']) console.log(' - peppers'); -if (program['pineapple']) console.log(' - pineapple'); -if (program['bbq']) console.log(' - bbq'); -console.log(' - %s cheese', program['cheese']); - -function range(val: string) { - return val.split('..').map(Number); -} - -function list(val: string) { - return val.split(','); -} - -function collect(val: string, memo: string[]) { - memo.push(val); - return memo; -} - -function increaseVerbosity(v: any, total: number) { - return total + 1; -} - -program - .version('0.0.1') - .usage('[options] ') - .option('-i, --integer ', 'An integer argument', parseInt) - .option('-f, --float ', 'A float argument', parseFloat) - .option('-r, --range ..', 'A range', range) - .option('-l, --list ', 'A list', list) - .option('-o, --optional [value]', 'An optional value') - .option('-c, --collect [value]', 'A repeatable value', collect, []) - .option('-v, --verbose', 'A value that can be increased', increaseVerbosity, 0) - .parse(process.argv); - -console.log(' int: %j', program['integer']); -console.log(' float: %j', program['float']); -console.log(' optional: %j', program['optional']); -program['range'] = program['range'] || []; -console.log(' range: %j..%j', program['range'][0], program['range'][1]); -console.log(' list: %j', program['list']); -console.log(' collect: %j', program['collect']); -console.log(' verbosity: %j', program['verbose']); -console.log(' args: %j', program['args']); - -program - .version('0.0.1') - .option('-f, --foo', 'enable some foo') - .option('-b, --bar', 'enable some bar') - .option('-B, --baz', 'enable some baz'); - -// must be before .parse() since -// node's emit() is immediate - -program.on('--help', () => { - console.log(' Examples:'); - console.log(''); - console.log(' $ custom-help --help'); - console.log(' $ custom-help -h'); - console.log(''); -}); - -program - .command('allow-unknown-option') - .allowUnknownOption() - .action(() => { - console.log('unknown option is allowed'); - }); - -program - .version('0.0.1') - .arguments(' [env]') - .action((cmd, env) => { - console.log(cmd, env); - }); - -program.parse(process.argv); - -console.log('stuff'); diff --git a/types/commander/index.d.ts b/types/commander/index.d.ts deleted file mode 100644 index c732d43c7c..0000000000 --- a/types/commander/index.d.ts +++ /dev/null @@ -1,299 +0,0 @@ -// Type definitions for commander 2.11 -// Project: https://github.com/visionmedia/commander.js -// Definitions by: Alan Agius , Marcelo Dezem , vvakame -// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped - -/// - -declare class Option { - flags: string; - required: boolean; - optional: boolean; - bool: boolean; - short?: string; - long: string; - description: string; - - /** - * Initialize a new `Option` with the given `flags` and `description`. - * - * @param {string} flags - * @param {string} [description] - */ - constructor(flags: string, description?: string); -} - -declare class Command extends NodeJS.EventEmitter { - [key: string]: any; - - args: string[]; - - /** - * Initialize a new `Command`. - * - * @param {string} [name] - */ - constructor(name?: string); - - /** - * Set the program version to `str`. - * - * This method auto-registers the "-V, --version" flag - * which will print the version number when passed. - * - * @param {string} str - * @param {string} [flags] - * @returns {Command} for chaining - */ - version(str: string, flags?: string): Command; - - /** - * Add command `name`. - * - * The `.action()` callback is invoked when the - * command `name` is specified via __ARGV__, - * and the remaining arguments are applied to the - * function for access. - * - * When the `name` is "*" an un-matched command - * will be passed as the first arg, followed by - * the rest of __ARGV__ remaining. - * - * @example - * program - * .version('0.0.1') - * .option('-C, --chdir ', 'change the working directory') - * .option('-c, --config ', 'set config path. defaults to ./deploy.conf') - * .option('-T, --no-tests', 'ignore test hook') - * - * program - * .command('setup') - * .description('run remote setup commands') - * .action(function() { - * console.log('setup'); - * }); - * - * program - * .command('exec ') - * .description('run the given remote command') - * .action(function(cmd) { - * console.log('exec "%s"', cmd); - * }); - * - * program - * .command('teardown [otherDirs...]') - * .description('run teardown commands') - * .action(function(dir, otherDirs) { - * console.log('dir "%s"', dir); - * if (otherDirs) { - * otherDirs.forEach(function (oDir) { - * console.log('dir "%s"', oDir); - * }); - * } - * }); - * - * program - * .command('*') - * .description('deploy the given env') - * .action(function(env) { - * console.log('deploying "%s"', env); - * }); - * - * program.parse(process.argv); - * - * @param {string} name - * @param {string} [desc] for git-style sub-commands - * @param {CommandOptions} [opts] command options - * @returns {Command} the new command - */ - command(name: string, desc?: string, opts?: commander.CommandOptions): Command; - - /** - * Define argument syntax for the top-level command. - * - * @param {string} desc - * @returns {Command} for chaining - */ - arguments(desc: string): Command; - - /** - * Parse expected `args`. - * - * For example `["[type]"]` becomes `[{ required: false, name: 'type' }]`. - * - * @param {string[]} args - * @returns {Command} for chaining - */ - parseExpectedArgs(args: string[]): Command; - /** - * Register callback `fn` for the command. - * - * @example - * program - * .command('help') - * .description('display verbose help') - * .action(function() { - * // output help here - * }); - * - * @param {(...args: any[]) => void} fn - * @returns {Command} for chaining - */ - action(fn: (...args: any[]) => void): Command; - - /** - * Define option with `flags`, `description` and optional - * coercion `fn`. - * - * The `flags` string should contain both the short and long flags, - * separated by comma, a pipe or space. The following are all valid - * all will output this way when `--help` is used. - * - * "-p, --pepper" - * "-p|--pepper" - * "-p --pepper" - * - * @example - * // simple boolean defaulting to false - * program.option('-p, --pepper', 'add pepper'); - * - * --pepper - * program.pepper - * // => Boolean - * - * // simple boolean defaulting to true - * program.option('-C, --no-cheese', 'remove cheese'); - * - * program.cheese - * // => true - * - * --no-cheese - * program.cheese - * // => false - * - * // required argument - * program.option('-C, --chdir ', 'change the working directory'); - * - * --chdir /tmp - * program.chdir - * // => "/tmp" - * - * // optional argument - * program.option('-c, --cheese [type]', 'add cheese [marble]'); - * - * @param {string} flags - * @param {string} [description] - * @param {((arg1: any, arg2: any) => void) | RegExp} [fn] function or default - * @param {*} [defaultValue] - * @returns {Command} for chaining - */ - option(flags: string, description?: string, fn?: ((arg1: any, arg2: any) => void) | RegExp, defaultValue?: any): Command; - option(flags: string, description?: string, defaultValue?: any): Command; - - /** - * Allow unknown options on the command line. - * - * @param {boolean} [arg] if `true` or omitted, no error will be thrown for unknown options. - * @returns {Command} for chaining - */ - allowUnknownOption(arg?: boolean): Command; - - /** - * Parse `argv`, settings options and invoking commands when defined. - * - * @param {string[]} argv - * @returns {Command} for chaining - */ - parse(argv: string[]): Command; - - /** - * Parse options from `argv` returning `argv` void of these options. - * - * @param {string[]} argv - * @returns {ParseOptionsResult} - */ - parseOptions(argv: string[]): commander.ParseOptionsResult; - - /** - * Return an object containing options as key-value pairs - * - * @returns {{[key: string]: string}} - */ - opts(): { [key: string]: string }; - - /** - * Set the description to `str`. - * - * @param {string} str - * @return {(Command | string)} - */ - description(str: string): Command; - description(): string; - - /** - * Set an alias for the command. - * - * @param {string} alias - * @return {(Command | string)} - */ - alias(alias: string): Command; - alias(): string; - - /** - * Set or get the command usage. - * - * @param {string} str - * @return {(Command | string)} - */ - usage(str: string): Command; - usage(): string; - - /** - * Set the name of the command. - * - * @param {string} str - * @return {Command} - */ - name(str: string): Command; - - /** - * Get the name of the command. - * - * @return {string} - */ - name(): string; - - /** - * Output help information for this command. - * - * @param {(str: string) => string} [cb] - */ - outputHelp(cb?: (str: string) => string): void; - - /** Output help information and exit. */ - help(): void; -} - -declare namespace commander { - - interface CommandOptions { - noHelp?: boolean; - isDefault?: boolean; - } - - interface ParseOptionsResult { - args: string[]; - unknown: string[]; - } - - interface CommanderStatic extends Command { - Command: typeof Command; - Option: typeof Option; - CommandOptions: CommandOptions; - ParseOptionsResult: ParseOptionsResult; - } - -} - -declare const commander: commander.CommanderStatic; -export = commander; diff --git a/types/concaveman/concaveman-tests.ts b/types/concaveman/concaveman-tests.ts index 736d616ad9..1d951b5448 100644 --- a/types/concaveman/concaveman-tests.ts +++ b/types/concaveman/concaveman-tests.ts @@ -1,4 +1,4 @@ import * as concaveman from 'concaveman'; var points = [[10, 20], [30, 12.5]]; -var polygon = concaveman(points); \ No newline at end of file +var polygon = concaveman(points); diff --git a/types/concaveman/index.d.ts b/types/concaveman/index.d.ts index a5b55c8fa3..ed5da84fc9 100644 --- a/types/concaveman/index.d.ts +++ b/types/concaveman/index.d.ts @@ -3,10 +3,11 @@ // Definitions by: Denis Carriere // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + declare module "concaveman" { /** * A very fast 2D concave hull algorithm in JavaScript (generates a general outline of a point set). - * + * * @name concaveman * @param {Array>} points is an array of [x, y] points. * @param {number} [concavity=2] is a relative measure of concavity. 1 results in a relatively detailed shape, Infinity results in a convex hull. You can use values lower than 1, but they can produce pretty crazy shapes. @@ -15,7 +16,7 @@ declare module "concaveman" { * @example * var points = [[10, 20], [30, 12.5], ...]; * var polygon = concaveman(points); - * + * * //=hull */ function concaveman(points: number[][], concavity?: number, lengthThreshold?: number): number[][]; diff --git a/types/confirmdialog/confirmdialog-tests.ts b/types/confirmdialog/confirmdialog-tests.ts new file mode 100644 index 0000000000..cd2ad0e8ca --- /dev/null +++ b/types/confirmdialog/confirmdialog-tests.ts @@ -0,0 +1,129 @@ +class Confirm { + private title_: string; + private conTent_: string; + constructor(title: string, content: string) { + this.title_ = title; + this.conTent_ = content; + } + + confirm() { + $.confirm({ + title: 'Confirm!', + content: 'Simple confirm!', + buttons: { + confirm: () => { + $.alert('Confirmed!'); + }, + cancel: (cancel: string) => { + $.alert('Canceled! ' + cancel); + }, + somethingElse: { + text: 'Something else', + btnClass: 'btn-blue', + keys: ['enter', 'shift'], + action: () => { + alert('Something else?'); + } + } + } + }); + } + + alert() { + $.alert({ + title: 'Alert!', + content: 'Simple alert!', + }); + } + + globalSettings() { + jconfirm.defaults = { + title: 'Hello', + titleClass: '', + type: 'default', + typeAnimated: true, + draggable: true, + dragWindowGap: 15, + dragWindowBorder: true, + animateFromElement: true, + smoothContent: true, + content: 'Are you sure to continue?', + buttons: {}, + defaultButtons: { + ok: { + action: () => { + } + }, + close: { + action: () => { + } + }, + }, + + icon: '', + lazyOpen: false, + bgOpacity: null, + theme: 'light', + animation: 'scale', + closeAnimation: 'scale', + animationSpeed: 400, + animationBounce: 1, + rtl: false, + container: 'body', + containerFluid: false, + backgroundDismiss: false, + backgroundDismissAnimation: 'shake', + autoClose: false, + closeIcon: null, + closeIconClass: false, + watchInterval: 100, + columnClass: 'col-md-4 col-md-offset-4 col-sm-6 col-sm-offset-3 col-xs-10 col-xs-offset-1', + boxWidth: '50%', + scrollToPreviousElement: true, + scrollToPreviousElementAnimate: true, + useBootstrap: true, + offsetTop: 40, + offsetBottom: 40, + bootstrapClasses: { + container: 'container', + containerFluid: 'container-fluid', + row: 'row', + }, + onContentReady: () => {}, + onOpenBefore: () => {}, + onOpen: () => {}, + onClose: () => {}, + onDestroy: () => {}, + onAction: () => {} +}; + } + + api() { + const jc = $.confirm({ + title: 'awesome', + onContentReady: () => { + jc.setTitle(); + } +}); + } + + confirm_84() { + $.confirm({ + closeIcon: true, + buttons: { + buttonA: { + text: 'button a', + action: (buttonA: string) => { + return false; // prevent the modal from closing + } + }, + resetButton: (resetButton: string) => { + } + } +}); + } +} + +let firstName = 'Pierre'; +let lastName = 'Yotti'; +let type = new Confirm(firstName, lastName); diff --git a/types/confirmdialog/index.d.ts b/types/confirmdialog/index.d.ts new file mode 100644 index 0000000000..9b98ab2389 --- /dev/null +++ b/types/confirmdialog/index.d.ts @@ -0,0 +1,93 @@ +// Type definitions for confirmdialog 3.3 +// Project: https://github.com/allipierre/Type-definitions-for-jquery-confirm/tree/master/types/confirmDialog-js +// Definitions by: Alli Pierre Yotti +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.3 + +/// + + interface JQueryStatic { + /** + * confirm Dialog + * {confirmOptions} pOtions + */ + confirm(pOtions: options.confirmOptions | string, title?: string): any; + + /** + * confirm alert + * {any} pMessage + */ + alert(pMessage?: any, title?: string): any; + + /** + * confirm Dialog + * {any} pMessage + */ + dialog(pOtions: options.confirmOptions | string): any; +} + + interface JQuery { + /** + * confirm Dialog + * {confirmOptions} pOtions + */ + confirm(pOtions: options.confirmOptions | string, title?: string): any; + + /** + * confirm alert + * {any} pMessage + */ + alert(pMessage?: any, title?: string): any; + + /** + * confirm Dialog + * {any} pMessage + */ + dialog(pOtions: options.confirmOptions): any; +} + +interface Window { + setContentAppend: any; +} + +declare namespace options { + interface confirmOptions { + buttons?: any; + title?: string | boolean; + content?: any; + onContentReady?: any; + lazyOpen?: boolean; + closeIcon?: any; + type?: string; + typeAnimated?: boolean; + icon?: string; + closeIconClass?: string; + columnClass?: string; + containerFluid?: boolean; + boxWidth?: string; + useBootstrap?: boolean; + bootstrapClasses?: any; + draggable?: boolean; + dragWindowBorder?: boolean; + dragWindowGap?: number; + contentLoaded?: () => void; + autoClose?: string; + backgroundDismiss?: any; + backgroundDismissAnimation?: string; + escapeKey?: string | boolean; + onOpenBefore?: () => void; + onOpen?: () => void; + onClose?: () => void; + onDestroy?: () => void; + onAction?: () => void; + } + + interface buttonOptionss { + cancel?: () => void; + confirm?: () => void; + } +} + +declare namespace jconfirm { + let defaults: any; +} diff --git a/types/confirmdialog/tsconfig.json b/types/confirmdialog/tsconfig.json new file mode 100644 index 0000000000..95f33eb036 --- /dev/null +++ b/types/confirmdialog/tsconfig.json @@ -0,0 +1,23 @@ +{ + "compilerOptions": { + "module": "commonjs", + "lib": [ + "es6", + "dom" + ], + "noImplicitAny": true, + "noImplicitThis": true, + "strictNullChecks": true, + "strictFunctionTypes": true, + "baseUrl": "../", + "typeRoots": ["../"], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true, + "target": "es6" + }, + "files": [ + "index.d.ts", + "confirmdialog-tests.ts" + ] +} diff --git a/types/confirmdialog/tslint.json b/types/confirmdialog/tslint.json new file mode 100644 index 0000000000..3db14f85ea --- /dev/null +++ b/types/confirmdialog/tslint.json @@ -0,0 +1 @@ +{ "extends": "dtslint/dt.json" } diff --git a/types/cordova-plugin-inappbrowser/index.d.ts b/types/cordova-plugin-inappbrowser/index.d.ts index 1cf2c67642..47c58eadfa 100644 --- a/types/cordova-plugin-inappbrowser/index.d.ts +++ b/types/cordova-plugin-inappbrowser/index.d.ts @@ -39,7 +39,7 @@ interface InAppBrowser extends Window { * @param callback the function that executes when the event fires. The function is * passed an InAppBrowserEvent object as a parameter. */ - addEventListener(type: channel, callback: (event: InAppBrowserEvent) => void): void; + addEventListener(type: channel, callback: InAppBrowserEventListenerOrEventListenerObject): void; // removeEventListener overloads /** * Removes a listener for an event from the InAppBrowser. @@ -51,7 +51,7 @@ interface InAppBrowser extends Window { * @param callback the function that executes when the event fires. The function is * passed an InAppBrowserEvent object as a parameter. */ - removeEventListener(type: channel, callback: (event: InAppBrowserEvent) => void): void; + removeEventListener(type: channel, callback: InAppBrowserEventListenerOrEventListenerObject): void; /** Closes the InAppBrowser window. */ close(): void; /** Hides the InAppBrowser window. Calling this has no effect if the InAppBrowser was already hidden. */ @@ -79,6 +79,14 @@ interface InAppBrowser extends Window { insertCSS(css: { code: string } | { file: string }, callback: () => void): void; } +type InAppBrowserEventListenerOrEventListenerObject = InAppBrowserEventListener | InAppBrowserEventListenerObject; + +type InAppBrowserEventListener = (evt: InAppBrowserEvent) => void; + +interface InAppBrowserEventListenerObject { + handleEvent(evt: InAppBrowserEvent): void; +} + interface InAppBrowserEvent extends Event { /** the eventname, either loadstart, loadstop, loaderror, or exit. */ type: string; diff --git a/types/cordova-plugin-inappbrowser/tsconfig.json b/types/cordova-plugin-inappbrowser/tsconfig.json index ff0151160c..f3d3cb59d3 100644 --- a/types/cordova-plugin-inappbrowser/tsconfig.json +++ b/types/cordova-plugin-inappbrowser/tsconfig.json @@ -5,10 +5,10 @@ "es6", "dom" ], - "noImplicitAny": false, + "noImplicitAny": true, "noImplicitThis": true, - "strictNullChecks": false, - "strictFunctionTypes": false, + "strictNullChecks": true, + "strictFunctionTypes": true, "baseUrl": "../", "typeRoots": [ "../" diff --git a/types/crypto-js/index.d.ts b/types/crypto-js/index.d.ts index c3dad4637b..c066204df2 100644 --- a/types/crypto-js/index.d.ts +++ b/types/crypto-js/index.d.ts @@ -8,7 +8,7 @@ export as namespace CryptoJS; declare var CryptoJS: CryptoJS.Hashes; declare namespace CryptoJS { - type Hash = (message: string | LibWordArray, key?: string, ...options: any[]) => WordArray; + type Hash = (message: string | LibWordArray, key?: string | WordArray, ...options: any[]) => WordArray; interface Cipher { encrypt(message: string, secretPassphrase: string | WordArray, option?: CipherOption): WordArray; decrypt(encryptedMessage: string | WordArray, secretPassphrase: string | WordArray, option?: CipherOption): DecryptedMessage; diff --git a/types/cucumber/index.d.ts b/types/cucumber/index.d.ts index d72b3ee4ac..ce2f586d9b 100644 --- a/types/cucumber/index.d.ts +++ b/types/cucumber/index.d.ts @@ -1,4 +1,4 @@ -// Type definitions for cucumber-js 2.0 +// Type definitions for cucumber-js 2.1 // Project: https://github.com/cucumber/cucumber-js // Definitions by: Abraão Alves // Jan Molak @@ -23,9 +23,7 @@ export interface TableDefinition { hashes(): Array<{ [colName: string]: string }>; } -export type StepDefinitionParam = string | number | CallbackStepDefinition | TableDefinition; - -export type StepDefinitionCode = (this: World, ...stepArgs: StepDefinitionParam[]) => PromiseLike | any | void; +export type StepDefinitionCode = (this: World, ...stepArgs: any[]) => any; export interface StepDefinitionOptions { timeout?: number; diff --git a/types/cypress/cypress-tests.ts b/types/cypress/cypress-tests.ts index 806443474a..be1b3cc959 100644 --- a/types/cypress/cypress-tests.ts +++ b/types/cypress/cypress-tests.ts @@ -10,7 +10,10 @@ cy .get('#querying') .contains('ul', 'oranges').should('have.class', 'query-list') .get('.query-button') - .contains('Save Form').should('have.class', 'btn'); + .contains('Save Form').should('have.class', 'btn') + .trigger('mousemove', {clientX: 100, clientY: 200}); + +cy.location('host'); cy .get('form') @@ -37,3 +40,5 @@ cy .spread((x , y, z) => { x + y + z; }); + +cy.log('end'); diff --git a/types/cypress/index.d.ts b/types/cypress/index.d.ts index 808c765e24..6cbc65f819 100644 --- a/types/cypress/index.d.ts +++ b/types/cypress/index.d.ts @@ -249,12 +249,13 @@ declare namespace Cypress { /** * @see https://on.cypress.io/api/location */ - location(options?: Loggable): Chainable; + location(options?: LoggableTimeoutable): Chainable; + location(key: string, options?: LoggableTimeoutable): Chainable; /** * @see https://on.cypress.io/api/log */ - log(message: string, args: any): Chainable; + log(message: string, args?: any): Chainable; /** * @see https://on.cypress.io/api/next @@ -317,9 +318,9 @@ declare namespace Cypress { /** * @see https://on.cypress.io/api/route */ - route(url: string, response?: any): Chainable; - route(method: string, url: string, response?: any): Chainable; - route(fn: () => RouteOptions | RouteOptions): Chainable; + route(url: string | RegExp, response?: any): Chainable; + route(method: string, url: string | RegExp, response?: any): Chainable; + route(fn: (() => RouteOptions) | RouteOptions): Chainable; /** * @see https://on.cypress.io/api/screenshot @@ -381,6 +382,7 @@ declare namespace Cypress { * @see https://docs.cypress.io/api/commands/trigger.html */ trigger(eventName: string, position?: PositionType, x?: number, y?: number, options?: TriggerOptions): Chainable; + trigger(eventName: string, eventObject: object): Chainable; /** * @see https://on.cypress.io/api/type diff --git a/types/d3-geo/index.d.ts b/types/d3-geo/index.d.ts index 4093b696e9..7efbb72010 100644 --- a/types/d3-geo/index.d.ts +++ b/types/d3-geo/index.d.ts @@ -36,7 +36,10 @@ export type GeoGeometryObjects = GeoJSON.GeometryObject | GeoSphere; export interface ExtendedGeometryCollection { type: string; bbox?: number[]; - crs?: GeoJSON.CoordinateReferenceSystem; + crs?: { + type: string; + properties: any; + }; geometries: GeometryType[]; } diff --git a/types/d3/v3/d3-tests.ts b/types/d3/v3/d3-tests.ts index 87b57e8261..8704448c9b 100644 --- a/types/d3/v3/d3-tests.ts +++ b/types/d3/v3/d3-tests.ts @@ -1051,7 +1051,7 @@ namespace forceCollapsable { var force = d3.layout.force() .on("tick", tick) .charge(function (d) { return d._children ? -d.size / 100 : -30; } ) - .linkDistance(function (d) { return d.target._children ? 80 : 30; } ) + .linkDistance(function (d) { return (d.target as Node)._children ? 80 : 30; } ) .size([w, h - 160]); var vis = d3.select("body").append("svg:svg") @@ -1083,10 +1083,10 @@ namespace forceCollapsable { // Enter any new links. link.enter().insert("svg:line", ".node") .attr("class", "link") - .attr("x1", function (d) { return d.source.x; } ) - .attr("y1", function (d) { return d.source.y; } ) - .attr("x2", function (d) { return d.target.x; } ) - .attr("y2", function (d) { return d.target.y; } ); + .attr("x1", function (d) { return (d.source as Node).x; } ) + .attr("y1", function (d) { return (d.source as Node).y; } ) + .attr("x2", function (d) { return (d.target as Node).x; } ) + .attr("y2", function (d) { return (d.target as Node).y; } ); // Exit any old links. link.exit().remove(); @@ -1114,10 +1114,10 @@ namespace forceCollapsable { } function tick() { - link.attr("x1", function (d) { return d.source.x; } ) - .attr("y1", function (d) { return d.source.y; } ) - .attr("x2", function (d) { return d.target.x; } ) - .attr("y2", function (d) { return d.target.y; } ); + link.attr("x1", function (d) { return (d.source as Node).x; } ) + .attr("y1", function (d) { return (d.source as Node).y; } ) + .attr("x2", function (d) { return (d.target as Node).x; } ) + .attr("y2", function (d) { return (d.target as Node).y; } ); node.attr("cx", function (d) { return d.x; } ) .attr("cy", function (d) { return d.y; } ); @@ -1738,7 +1738,7 @@ namespace forceCollapsable2 { var force = d3.layout.force() .on("tick", tick) .charge(function (d) { return d._children ? -d.size / 100 : -30; } ) - .linkDistance(function (d) { return d.target._children ? 80 : 30; } ) + .linkDistance(function (d) { return (d.target as Node)._children ? 80 : 30; } ) .size([w, h - 160]); var vis = d3.select("body").append("svg:svg") @@ -1770,10 +1770,10 @@ namespace forceCollapsable2 { // Enter any new links. link.enter().insert("svg:line", ".node") .attr("class", "link") - .attr("x1", function (d) { return d.source.x; } ) - .attr("y1", function (d) { return d.source.y; } ) - .attr("x2", function (d) { return d.target.x; } ) - .attr("y2", function (d) { return d.target.y; } ); + .attr("x1", function (d) { return (d.source as Node).x; } ) + .attr("y1", function (d) { return (d.source as Node).y; } ) + .attr("x2", function (d) { return (d.target as Node).x; } ) + .attr("y2", function (d) { return (d.target as Node).y; } ); // Exit any old links. link.exit().remove(); @@ -1801,11 +1801,11 @@ namespace forceCollapsable2 { } function tick() { - link.attr("x1", function (d) { return d.source.x; } ) - .attr("y1", function (d) { return d.source.y; } ) - .attr("x2", function (d) { return d.target.x; } ) - .attr("y2", function (d) { return d.target.y; } ); - + link.attr("x1", function (d) { return (d.source as Node).x; } ) + .attr("y1", function (d) { return (d.source as Node).y; } ) + .attr("x2", function (d) { return (d.target as Node).x; } ) + .attr("y2", function (d) { return (d.target as Node).y; } ); + node.attr("cx", function (d) { return d.x; } ) .attr("cy", function (d) { return d.y; } ); } @@ -2720,3 +2720,34 @@ function testEnterSizeEmpty() { selectionSize = newNodes.size(); } + +// Example from Matthias Jobst http://github.com/MatthiasJobst +// Checks the brush with different Axis types +class BrushAxisTest { + brush: d3.svg.Brush; + constructor() { + let scale = d3.time.scale(); + this.brush = d3.svg.brush() + .x(scale) // the x accessor accepts time scales + .y(scale); // as does y + } + brushes = () => { + let extent = this.brush.extent(); + let brush = d3.svg.brush(); + brush.x(d3.scale.linear()); // Linear scale + brush.y(d3.scale.log()); // Logarithmic scale + // Does not work: + // brush.extent(this.brush.extent()); + // From https://github.com/d3/d3-3.x-api-reference/blob/master/Ordinal-Scales.md#ordinal_rangePoints + let ordinalScale = d3.scale.ordinal() + .domain([1, 2, 3, 4]) + .rangePoints([0, 100]); + let ordinalBrush = d3.svg.brush() + .x(ordinalScale) // Ordinal scale + .y(d3.scale.linear()); + let colorScale = d3.scale.category10(); + let colorBrush = d3.svg.brush() + .x(colorScale) // Color scale + .y(d3.scale.pow()); + } +} \ No newline at end of file diff --git a/types/d3/v3/index.d.ts b/types/d3/v3/index.d.ts index 0fbc7502b0..9a2f9ae34a 100644 --- a/types/d3/v3/index.d.ts +++ b/types/d3/v3/index.d.ts @@ -1,6 +1,8 @@ // Type definitions for d3JS 3.5 // Project: http://d3js.org/ -// Definitions by: Alex Ford , Boris Yankov +// Definitions by: Alex Ford +// Boris Yankov +// Matthias Jobst // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped // Latest patch version of module validated against: 3.5.17 @@ -233,28 +235,30 @@ declare namespace d3 { * @param name the element name to append. May be prefixed (see d3.ns.prefix). * @param before the selector to determine position (e.g., ":first-child") */ - insert(name: string, before: string): Update; + // https://github.com/d3/d3-3.x-api-reference/blob/master/Selections.md#insert + insert(name: string, before?: string): Update; /** * Inserts a new child to each node in the selection. This child will inherit its parent's data (if available). Returns a fresh selection consisting of the newly-inserted children. * @param name the element name to append. May be prefixed (see d3.ns.prefix). * @param before a function to determine the node to use as the next sibling */ - insert(name: string, before: (datum: Datum, index: number, outerIndex: number) => EventTarget): Update; + // https://github.com/d3/d3-3.x-api-reference/blob/master/Selections.md#insert + insert(name: string, before?: (datum: Datum, index: number, outerIndex: number) => EventTarget): Update; /** * Inserts a new child to the end of each node in the selection by computing a new node. This child will inherit its parent's data (if available). Returns a fresh selection consisting of the newly-inserted children. * @param name the function to compute a new child * @param before the selector to determine position (e.g., ":first-child") */ - insert(name: (datum: Datum, index: number, outerIndex: number) => EventTarget, before: string): Update; + insert(name: (datum: Datum, index: number, outerIndex: number) => EventTarget, before?: string): Update; /** * Inserts a new child to the end of each node in the selection by computing a new node. This child will inherit its parent's data (if available). Returns a fresh selection consisting of the newly-inserted children. * @param name the function to compute a new child * @param before a function to determine the node to use as the next sibling */ - insert(name: (datum: Datum, index: number, outerIndex: number) => EventTarget, before: (datum: Datum, index: number, outerIndex: number) => EventTarget): Update; + insert(name: (datum: Datum, index: number, outerIndex: number) => EventTarget, before?: (datum: Datum, index: number, outerIndex: number) => EventTarget): Update; /** * Removes the elements from the DOM. They are in a detached state and may be re-added (though there is currently no dedicated API for doing so). @@ -429,7 +433,7 @@ declare namespace d3 { /** * Administrivia: JavaScript primitive types, or "things that toString() predictably". */ - export type Primitive = number | string | boolean; + export type Primitive = number | string | boolean ; /** * Administrivia: anything with a valueOf(): number method is comparable, so we allow it in numeric operations @@ -626,28 +630,28 @@ declare namespace d3 { * @param name the element name to append. May be prefixed (see d3.ns.prefix). * @param before the selector to determine position (e.g., ":first-child") */ - insert(name: string, before: string): Selection; + insert(name: string, before?: string): Selection; /** * Inserts a new child to each node in the selection. This child will inherit its parent's data (if available). Returns a fresh selection consisting of the newly-inserted children. * @param name the element name to append. May be prefixed (see d3.ns.prefix). * @param before a function to determine the node to use as the next sibling */ - insert(name: string, before: (datum: Datum, index: number, outerIndex: number) => EventTarget): Selection; + insert(name: string, before?: (datum: Datum, index: number, outerIndex: number) => EventTarget): Selection; /** * Inserts a new child to the end of each node in the selection by computing a new node. This child will inherit its parent's data (if available). Returns a fresh selection consisting of the newly-inserted children. * @param name the function to compute a new child * @param before the selector to determine position (e.g., ":first-child") */ - insert(name: (datum: Datum, index: number, outerIndex: number) => EventTarget, before: string): Selection; + insert(name: (datum: Datum, index: number, outerIndex: number) => EventTarget, before?: string): Selection; /** * Inserts a new child to the end of each node in the selection by computing a new node. This child will inherit its parent's data (if available). Returns a fresh selection consisting of the newly-inserted children. * @param name the function to compute a new child * @param before a function to determine the node to use as the next sibling */ - insert(name: (datum: Datum, index: number, outerIndex: number) => EventTarget, before: (datum: Datum, index: number, outerIndex: number) => EventTarget): Selection; + insert(name: (datum: Datum, index: number, outerIndex: number) => EventTarget, before?: (datum: Datum, index: number, outerIndex: number) => EventTarget): Selection; /** * Removes the elements from the DOM. They are in a detached state and may be re-added (though there is currently no dedicated API for doing so). @@ -928,28 +932,28 @@ declare namespace d3 { export function flush(): void; } - interface BaseEvent { - type: string; - sourceEvent?: Event; - } + interface BaseEvent { + type: string; + sourceEvent?: Event; + } - /** - * Define a D3-specific ZoomEvent per https://github.com/mbostock/d3/wiki/Zoom-Behavior#event - */ - interface ZoomEvent extends BaseEvent { - scale: number; - translate: [number, number]; - } + /** + * Define a D3-specific ZoomEvent per https://github.com/mbostock/d3/wiki/Zoom-Behavior#event + */ + interface ZoomEvent extends BaseEvent { + scale: number; + translate: [number, number]; + } - /** - * Define a D3-specific DragEvent per https://github.com/mbostock/d3/wiki/Drag-Behavior#on - */ - interface DragEvent extends BaseEvent { - x: number; - y: number; - dx: number; - dy: number; - } + /** + * Define a D3-specific DragEvent per https://github.com/mbostock/d3/wiki/Drag-Behavior#on + */ + interface DragEvent extends BaseEvent { + x: number; + y: number; + dx: number; + dy: number; + } /** * The current event's value. Use this variable in a handler registered with `selection.on`. @@ -1387,8 +1391,8 @@ declare namespace d3 { export function requote(string: string): string; export var rgb: { - new (r: number, g: number, b: number): Rgb; - new (color: string): Rgb; + new(r: number, g: number, b: number): Rgb; + new(color: string): Rgb; (r: number, g: number, b: number): Rgb; (color: string): Rgb; @@ -1408,8 +1412,8 @@ declare namespace d3 { } export var hsl: { - new (h: number, s: number, l: number): Hsl; - new (color: string): Hsl; + new(h: number, s: number, l: number): Hsl; + new(color: string): Hsl; (h: number, s: number, l: number): Hsl; (color: string): Hsl; @@ -1429,8 +1433,8 @@ declare namespace d3 { } export var hcl: { - new (h: number, c: number, l: number): Hcl; - new (color: string): Hcl; + new(h: number, c: number, l: number): Hcl; + new(color: string): Hcl; (h: number, c: number, l: number): Hcl; (color: string): Hcl; @@ -1446,8 +1450,8 @@ declare namespace d3 { } export var lab: { - new (l: number, a: number, b: number): Lab; - new (color: string): Lab; + new(l: number, a: number, b: number): Lab; + new(color: string): Lab; (l: number, a: number, b: number): Lab; (color: string): Lab; @@ -1467,7 +1471,7 @@ declare namespace d3 { export var color: { (): Color; - new (): Color; + new(): Color; }; interface Color { @@ -1681,7 +1685,7 @@ declare namespace d3 { export function category20(): Ordinal; export function category20b(): Ordinal; export function category20b(): Ordinal; - export function category20c(): Ordinal; + export function category20c(): Ordinal; export function category20c(): Ordinal; interface Ordinal { @@ -1818,10 +1822,10 @@ declare namespace d3 { export function format(specifier: string): Format; export module format { - export function multi(formats: Array<[string, (d: Date) => boolean|number]>): Format; + export function multi(formats: Array<[string, (d: Date) => boolean | number]>): Format; export function utc(specifier: string): Format; namespace utc { - export function multi(formats: Array<[string, (d: Date) => boolean|number]>): Format; + export function multi(formats: Array<[string, (d: Date) => boolean | number]>): Format; } export var iso: Format; @@ -2574,42 +2578,47 @@ declare namespace d3 { tickFormat(): (t: any) => string; tickFormat(format: (t: any) => string): Axis; - tickFormat(format:string): Axis; + tickFormat(format: string): Axis; } - export function brush(): Brush; - export function brush(): Brush; + export function brush(): Brush; + export function brush(): Brush; + export function brush(): Brush; + export function brush(): Brush; namespace brush { - interface Scale { - domain(): number[]; - domain(domain: number[]): Scale; + interface Scale { + domain(): S[]; + domain(domain: S[]): Scale; - range(): number[]; - range(range: number[]): Scale; + range(): S[]; + range(range: number[]): Scale; - invert?(y: number): number; + invert?(y: number): S; } } - interface Brush { + interface Brush { (selection: Selection): void; (selection: Transition): void; event(selection: Selection): void; event(selection: Transition): void; - x(): brush.Scale; - x(x: brush.Scale): Brush; + x(): brush.Scale; + x(x: brush.Scale): Brush; + x(x: d3.scale.Ordinal | d3.time.Scale): Brush; - y(): brush.Scale; - y(y: brush.Scale): Brush; + y(): brush.Scale; + y(y: brush.Scale): Brush; + y(x: d3.scale.Ordinal | d3.time.Scale): Brush; - extent(): [number, number] | [[number, number], [number, number]]; - extent(extent: [number, number] | [[number, number], [number, number]]): Brush; + // https://github.com/d3/d3-3.x-api-reference/blob/master/SVG-Controls.md#brush_extent + extent(): [X, X] | [Y, Y] | [[X, Y], [X, Y]] | null; + extent(extent: [X, X] | [Y, Y] | [[X, Y], [X, Y]]): Brush; clamp(): boolean | [boolean, boolean]; - clamp(clamp: boolean | [boolean, boolean]): Brush; + clamp(clamp: boolean | [boolean, boolean]): Brush; clear(): void; @@ -2620,10 +2629,10 @@ declare namespace d3 { on(type: 'brushend'): (datum: T, index: number) => void; on(type: string): (datum: T, index: number) => void; - on(type: 'brushstart', listener: (datum: T, index: number) => void): Brush; - on(type: 'brush', listener: (datum: T, index: number) => void): Brush; - on(type: 'brushend', listener: (datum: T, index: number) => void): Brush; - on(type: string, listener: (datum: T, index: number) => void): Brush; + on(type: 'brushstart', listener: (datum: T, index: number) => void): Brush; + on(type: 'brush', listener: (datum: T, index: number) => void): Brush; + on(type: 'brushend', listener: (datum: T, index: number) => void): Brush; + on(type: string, listener: (datum: T, index: number) => void): Brush; } } @@ -2759,7 +2768,7 @@ declare namespace d3 { timeFormat: { (specifier: string): time.Format; utc(specifier: string): time.Format; - multi(formats: Array<[string, (d: Date) => boolean|number]>): time.Format; + multi(formats: Array<[string, (d: Date) => boolean | number]>): time.Format; } } @@ -2874,10 +2883,12 @@ declare namespace d3 { export function force(): Force, Node>; export function force, Node extends force.Node>(): Force; + // https://github.com/d3/d3-3.x-api-reference/blob/master/Force-Layout.md#links + // Read the note at the end of the section where it talks about initial numbering namespace force { interface Link { - source: T; - target: T; + source: T | number; + target: T | number; } interface Node { diff --git a/types/datatables.net/datatables.net-tests.ts b/types/datatables.net/datatables.net-tests.ts index af722ab74f..e5cb5184fd 100644 --- a/types/datatables.net/datatables.net-tests.ts +++ b/types/datatables.net/datatables.net-tests.ts @@ -21,7 +21,13 @@ const lang: DataTables.LanguageSettings = { }, aria: { sortAscending: ": activate to sort column ascending", - sortDescending: ": activate to sort column descending" + sortDescending: ": activate to sort column descending", + paginate: { + first: "First", + last: "Last", + next: "Next", + previous: "Previous" + } } }; @@ -98,6 +104,7 @@ let col: DataTables.ColumnSettings = { orderable: true, orderData: 10, orderDataType: "dom-checkbox", + orderFixed: [[0, 'asc'], [1, 'desc']], orderSequence: ['asc', 'desc'], render: 1, searchable: true, @@ -118,6 +125,20 @@ col = { data: colDataFunc, render: colRenderFunc, }; +col = { + data: "salary", + render: $.fn.dataTable.render.number('\'', '.', 0, '$'), +}; +col = { + data: "url", + render: $.fn.dataTable.render.text(), +}; +col = { + orderFixed: { + pre: [[0, 'asc'], [1, 'desc']], + post: [[0, 'asc'], [1, 'desc']] + } +}; //#endregion "Column" @@ -135,6 +156,7 @@ let colDef: DataTables.ColumnDefsSettings = { orderable: true, orderData: 10, orderDataType: "dom-checkbox", + orderFixed: [[0, 'asc'], [1, 'desc']], orderSequence: ['asc', 'desc'], render: 1, searchable: true, @@ -353,6 +375,9 @@ let order_set = dt.order([0, "asc"]); order_set = dt.order([0, "asc"], [1, "desc"]); // TODO: Fíx that order_set = dt.order([[0, "asc"], [1, "desc"]]); +const fixed_get: DataTables.ObjectOrderFixed = dt.order.fixed(); +const fixed_set: DataTables.Api = dt.order.fixed({pre: [0, "asc"], post: [1, "desc"]}); + const orderListerner = order_set.order.listener("node", 1, () => { }); const page_get = dt.page(); @@ -791,6 +816,11 @@ dt.columns.adjust().draw(false); // adjust column sizing and redraw dt.columns().every(() => { }); dt.columns().every((colIdx, tableLoop, colLoop) => { }); +$('#example').on('column-visibility.dt', (e: object, settings: DataTables.Settings, column: number, state: boolean, recalc: boolean | undefined) => { + const widthRecalced = (recalc || recalc === undefined); + console.log(`Column ${column} has changed to ${(state ? 'visible' : 'hidden')} and width ${(widthRecalced) ? 'was' : 'was not'} recalculated.`); +}); + //#endregion "Methods-Column" //#region "Methods-Row" diff --git a/types/datatables.net/index.d.ts b/types/datatables.net/index.d.ts index 7cd4b8589b..cdddc98789 100644 --- a/types/datatables.net/index.d.ts +++ b/types/datatables.net/index.d.ts @@ -1,6 +1,9 @@ // Type definitions for JQuery DataTables 1.10 // Project: http://www.datatables.net -// Definitions by: Kiarash Ghiaseddin , Omid Rad , Armin Sander +// Definitions by: Kiarash Ghiaseddin +// Omid Rad +// Armin Sander +// Craig Boland // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped // TypeScript Version: 2.4 @@ -329,6 +332,16 @@ declare namespace DataTables { (order?: Array<(string | number)> | Array>): Api; (order: Array<(string | number)>, ...args: any[]): Api; + /** + * Get the fixed ordering that is applied to the table. If there is more than one table in the API's context, + * the ordering of the first table will be returned only (use table() if you require the ordering of a different table in the API's context). + */ + fixed(): ObjectOrderFixed; + /** + * Set the table's fixed ordering. Note this doesn't actually perform the order, but rather queues it up - use draw() to perform the ordering. + */ + fixed(order: ObjectOrderFixed): Api; + /** * Add an ordering listener to an element, for a given column. * @@ -1085,6 +1098,14 @@ declare namespace DataTables { */ isDataTable(table: string): boolean; + /** + * Helpers for `columns.render`. + * + * The options defined here can be used with the `columns.render` initialisation + * option to provide a display renderer. + */ + render: StaticRenderFunctions; + /** * Get all DataTable tables that have been initialised - optionally you can select to get only currently visible tables and / or retrieve the tables as API instances. * @@ -1125,6 +1146,42 @@ declare namespace DataTables { ext: ExtSettings; } + interface ObjectColumnRender { + display(d?: number | string | object): string | object; + } + + interface ObjectOrderFixed { + /** + * Two-element array: + * 0: Column index to order upon. + * 1: Direction so order to apply ("asc" for ascending order or "desc" for descending order). + */ + pre?: any[]; + /** + * Two-element array: + * 0: Column index to order upon. + * 1: Direction so order to apply ("asc" for ascending order or "desc" for descending order). + */ + post?: any[]; + } + + interface StaticRenderFunctions { + /** + * Will format numeric data (defined by `columns.data`) for display, retaining the original unformatted data for sorting and filtering. + * + * @param thousands Thousands grouping separator. + * @param decimal Decimal point indicator. + * @param precision Integer number of decimal points to show. + * @param prefix Prefix (optional). + * @param postfix Postfix (/suffix) (optional). + */ + number(thousands: string, decimal: string, precision: number, prefix?: string, postfix?: string): ObjectColumnRender; + /** + * Escape HTML to help prevent XSS attacks. It has no optional parameters. + */ + text(): ObjectColumnRender; + } + interface StaticUtilFunctions { /** * Escape special characters in a regular expression string. Since: 1.10.4 @@ -1563,6 +1620,15 @@ declare namespace DataTables { */ orderDataType?: string; + /** + * Ordering to always be applied to the table. Since 1.10 + * + * Array type is prefix ordering only and is a two-element array: + * 0: Column index to order upon. + * 1: Direction so order to apply ("asc" for ascending order or "desc" for descending order). + */ + orderFixed?: any[] | ObjectOrderFixed; + /** * Order direction application sequence. Since: 1.10 */ @@ -1571,7 +1637,7 @@ declare namespace DataTables { /** * Render (process) the data for use in the table. Since: 1.10 */ - render?: number | string | ObjectColumnData | FunctionColumnRender; + render?: number | string | ObjectColumnData | FunctionColumnRender | ObjectColumnRender; /** * Enable or disable filtering on the data in this column. Since: 1.10 @@ -1727,6 +1793,7 @@ declare namespace DataTables { interface LanguageAriaSettings { sortAscending: string; sortDescending: string; + paginate?: LanguagePaginateSettings; } //#endregion "language-settings" diff --git a/types/dc/index.d.ts b/types/dc/index.d.ts index 7d893baf3e..62fbd8330c 100644 --- a/types/dc/index.d.ts +++ b/types/dc/index.d.ts @@ -1,6 +1,8 @@ // Type definitions for DCJS // Project: https://github.com/dc-js/dc.js -// Definitions by: hans windhoff , matt traynham +// Definitions by: hans windhoff +// matt traynham +// matthias jobst // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped // this makes only sense together with d3 and crossfilter so you need the d3.d.ts and crossfilter.d.ts files @@ -49,8 +51,9 @@ declare namespace dc { format: Accessor; } + // http://dc-js.github.io/dc.js/docs/html/dc.units.html export interface UnitFunction { - (start: number, end: number, domain?: Array): number|Array; + (start: number|Date, end: number|Date, domain?: number|Array): number | Array; } export interface FloatPointUnits { @@ -135,12 +138,13 @@ declare namespace dc { minHeight: IGetSet; dimension: IGetSet; data: IGetSetComputed<(group: any) => Array, Array, T>; - group: IGetSet; + // http://dc-js.github.io/dc.js/docs/html/dc.baseMixin.html#group__anchor + group: IBiGetSet; ordering: IGetSet, T>; filterAll(): void; - select(selector: d3.Selection|string): d3.Selection; - selectAll(selector: d3.Selection|string): d3.Selection; - anchor(anchor: BaseMixin|d3.Selection|string, chartGroup?: string): d3.Selection; + select(selector: d3.Selection | string): d3.Selection; + selectAll(selector: d3.Selection | string): d3.Selection; + anchor(anchor: BaseMixin | d3.Selection | string, chartGroup?: string): d3.Selection; anchorName(): string; svg: IGetSet, d3.Selection>; resetSvg(): void; @@ -196,10 +200,11 @@ declare namespace dc { } export interface ColorMixin { - colors: IGetSet | Scale, T>; - ordinalColors(r: Array): void; - linearColors(r: Array): void; - colorAccessor: IGetSet, T>; + // http://dc-js.github.io/dc.js/docs/html/dc.colorMixin.html + colors: IGetSet | Scale | string, T>; + ordinalColors(r: Array): T; + linearColors(r: Array): T; + colorAccessor: IGetSet, T>; colorDomain: IGetSet, T>; calculateColorDomain(): void; getColor(datum: any, index?: number): string; @@ -291,7 +296,7 @@ declare namespace dc { dashStyle: IGetSet, LineChart>; renderArea: IGetSet; dotRadius: IGetSet; - renderDataPoints: IGetSet; + renderDataPoints: IGetSet; } export interface DataCountWidgetHTML { @@ -307,7 +312,7 @@ declare namespace dc { export interface DataTableWidget extends BaseMixin { size: IGetSet; showGroups: IGetSet; - columns: IGetSet|Columns>, DataTableWidget>; + columns: IGetSet | Columns>, DataTableWidget>; sortBy: IGetSet, DataTableWidget>; order: IGetSet<(a: any, b: any) => number, DataTableWidget>; } @@ -336,7 +341,7 @@ declare namespace dc { rightYAxis: IGetSet>; } - export interface CompositeChart extends ICompositeChart {} + export interface CompositeChart extends ICompositeChart { } export interface SeriesChart extends ICompositeChart { chart: IGetSet<(c: any) => BaseMixin, SeriesChart>; @@ -444,11 +449,16 @@ declare namespace dc { round: Round; utils: Utils; + // http://dc-js.github.io/dc.js/docs/html/core.js.html, Line 20 + version: string; + legend(): Legend; pieChart(parent: string, chartGroup?: string): PieChart; - barChart(parent: string, chartGroup?: string): BarChart; - lineChart(parent: string, chartGroup?: string): LineChart; + // http://dc-js.github.io/dc.js/docs/html/dc.barChart.html + barChart(parent: string | CompositeChart, chartGroup?: string): BarChart; + // http://dc-js.github.io/dc.js/docs/html/dc.lineChart.html + lineChart(parent: string | CompositeChart, chartGroup?: string): LineChart; dataCount(parent: string, chartGroup?: string): DataCountWidget; dataTable(parent: string, chartGroup?: string): DataTableWidget; dataGrid(parent: string, chartGroup?: string): DataGridWidget; @@ -463,5 +473,4 @@ declare namespace dc { heatMap(parent: string, chartGroup?: string): HeatMap; boxPlot(parent: string, chartGroup?: string): BoxPlot; } -} - +} \ No newline at end of file diff --git a/types/decimal.js/index.d.ts b/types/decimal.js/index.d.ts index 27f4213612..ac159029f6 100644 --- a/types/decimal.js/index.d.ts +++ b/types/decimal.js/index.d.ts @@ -642,7 +642,7 @@ declare namespace decimal { * * If a maximum denominator is not specified, or is null or undefined, the denominator will be the lowest value necessary to represent the number exactly. */ - toFraction(max_denominator?: number | string | Decimal): string[]; + toFraction(max_denominator?: number | string | Decimal): Decimal[]; toJSON(): string; diff --git a/types/defer-promise/defer-promise-tests.ts b/types/defer-promise/defer-promise-tests.ts new file mode 100644 index 0000000000..cdf80657f9 --- /dev/null +++ b/types/defer-promise/defer-promise-tests.ts @@ -0,0 +1,23 @@ +import defer = require('defer-promise'); + +// $ExpectType Deferred +const a = defer(); +// $ExpectType void +a.resolve(5); +// $ExpectError +a.resolve('foo'); +// $ExpectError +a.resolve(); + +// $ExpectType Deferred +const b = defer(); +// $ExpectType void +b.resolve(); +// $ExpectError +b.resolve(5); + +const c: DeferPromise.Deferred = defer(); +// $ExpectType void +c.resolve('foo'); +// $ExpectType Promise +c.promise; diff --git a/types/defer-promise/index.d.ts b/types/defer-promise/index.d.ts new file mode 100644 index 0000000000..8516e63b30 --- /dev/null +++ b/types/defer-promise/index.d.ts @@ -0,0 +1,21 @@ +// Type definitions for defer-promise 1.0 +// Project: https://github.com/75lb/defer-promise#readme +// Definitions by: Niklas Fiekas +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.1 + +// tslint:disable-next-line no-unnecessary-generics +declare function defer(): DeferPromise.Deferred; + +export = defer; + +declare global { + namespace DeferPromise { + interface Deferred { + promise: Promise; + resolve(value: T | PromiseLike): void; + resolve(this: Deferred): void; + reject(reason?: any): void; + } + } +} diff --git a/types/defer-promise/tsconfig.json b/types/defer-promise/tsconfig.json new file mode 100644 index 0000000000..1aaa667626 --- /dev/null +++ b/types/defer-promise/tsconfig.json @@ -0,0 +1,24 @@ +{ + "compilerOptions": { + "module": "commonjs", + "lib": [ + "es5", + "es2015.Promise" + ], + "noImplicitAny": true, + "noImplicitThis": true, + "strictNullChecks": true, + "strictFunctionTypes": true, + "baseUrl": "../", + "typeRoots": [ + "../" + ], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true + }, + "files": [ + "index.d.ts", + "defer-promise-tests.ts" + ] +} diff --git a/types/defer-promise/tslint.json b/types/defer-promise/tslint.json new file mode 100644 index 0000000000..3db14f85ea --- /dev/null +++ b/types/defer-promise/tslint.json @@ -0,0 +1 @@ +{ "extends": "dtslint/dt.json" } diff --git a/types/double-ended-queue/double-ended-queue-tests.ts b/types/double-ended-queue/double-ended-queue-tests.ts new file mode 100644 index 0000000000..d6df205a77 --- /dev/null +++ b/types/double-ended-queue/double-ended-queue-tests.ts @@ -0,0 +1,24 @@ +import * as Deque from 'double-ended-queue'; + +const a = new Deque(); // $ExpectType Deque +const b = new Deque(6); // $ExpectType Deque +const c = new Deque([1, 2, 3]); // $ExpectError +const d = new Deque([1, 2, 3]); // $ExpectType Deque + +a.length; // $ExpectType number +a.push("foo"); // $ExpectError +a.push(4, 5); // $ExpectType number +a.unshift("foo"); // $ExpectError +a.unshift(4, 5); // $ExpectType number +a.pop(); // $ExpectType number | undefined +a.pop(2); // $ExpectError +a.shift(); // $ExpectType number | undefined +a.peekBack(); // $ExpectType number | undefined +a.peekFront(); // $ExpectType number | undefined +a.toArray(); // $ExpectType number[] +a.get(); // $ExpectError +a.get(null); // $ExpectError +a.get(1); // $ExpectType number | undefined +b.get(-1); // $ExpectType string | undefined +b.clear(); // $ExpectType void +b.isEmpty(); // $ExpectType boolean diff --git a/types/double-ended-queue/index.d.ts b/types/double-ended-queue/index.d.ts new file mode 100644 index 0000000000..b9aa30de1a --- /dev/null +++ b/types/double-ended-queue/index.d.ts @@ -0,0 +1,26 @@ +// Type definitions for double-ended-queue 2.1 +// Project: https://github.com/petkaantonov/deque +// Definitions by: Dmitry +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +interface Deque { + readonly length: number; + push(...items: T[]): number; + unshift(...items: T[]): number; + pop(): T|undefined; + shift(): T|undefined; + toArray(): T[]; + peekBack(): T|undefined; + peekFront(): T|undefined; + get(index: number): T|undefined; + isEmpty(): boolean; + clear(): void; +} + +declare const Deque: { + prototype: Deque; + new (items?: ReadonlyArray): Deque; + new (capacity: number): Deque; // tslint:disable-line:no-unnecessary-generics +}; + +export = Deque; diff --git a/types/double-ended-queue/tsconfig.json b/types/double-ended-queue/tsconfig.json new file mode 100644 index 0000000000..5477379341 --- /dev/null +++ b/types/double-ended-queue/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", + "double-ended-queue-tests.ts" + ] +} diff --git a/types/double-ended-queue/tslint.json b/types/double-ended-queue/tslint.json new file mode 100644 index 0000000000..3db14f85ea --- /dev/null +++ b/types/double-ended-queue/tslint.json @@ -0,0 +1 @@ +{ "extends": "dtslint/dt.json" } diff --git a/types/draft-js/index.d.ts b/types/draft-js/index.d.ts index 3eaa05aa30..7913e81d55 100644 --- a/types/draft-js/index.d.ts +++ b/types/draft-js/index.d.ts @@ -746,7 +746,7 @@ declare namespace Draft { } class ContentState extends Record { - static createFromBlockArray(blocks: Array, entityMap: any): ContentState; + static createFromBlockArray(blocks: Array, entityMap?: any): ContentState; static createFromText(text: string, delimiter?: string): ContentState; createEntity(type: DraftEntityType, mutability: DraftEntityMutability, data?: Object): ContentState; @@ -797,7 +797,7 @@ declare namespace Draft { class CharacterMetadata { static applyStyle(record: CharacterMetadata, style: string): CharacterMetadata; static removeStyle(record: CharacterMetadata, style: string): CharacterMetadata; - static applyEntity(record: CharacterMetadata, entityKey: string): CharacterMetadata; + static applyEntity(record: CharacterMetadata, entityKey: string | null): CharacterMetadata; static applyEntity(record: CharacterMetadata): CharacterMetadata; /** * Use this function instead of the `CharacterMetadata` constructor. @@ -894,7 +894,7 @@ declare namespace Draft { static setBlockData(contentState: ContentState, selectionState: SelectionState, blockData: Immutable.Map): ContentState; static mergeBlockData(contentState: ContentState, selectionState: SelectionState, blockData: Immutable.Map): ContentState; - static applyEntity(contentState: ContentState, selectionState: SelectionState, entityKey: string): ContentState; + static applyEntity(contentState: ContentState, selectionState: SelectionState, entityKey: string | null): ContentState; } class RichTextEditorUtil { diff --git a/types/dvtng-jss/dvtng-jss-tests.ts b/types/dvtng-jss/dvtng-jss-tests.ts new file mode 100644 index 0000000000..2863bbfb66 --- /dev/null +++ b/types/dvtng-jss/dvtng-jss-tests.ts @@ -0,0 +1,16 @@ + + +jss.set('.demo', { + 'font-size': '15px', + 'color': 'red' +}); + +jss.get('.demo'); + +jss.get(); + +jss.getAll('.demo'); + +jss.remove('.demo'); + +jss.remove(); diff --git a/types/dvtng-jss/index.d.ts b/types/dvtng-jss/index.d.ts new file mode 100644 index 0000000000..18278d80d1 --- /dev/null +++ b/types/dvtng-jss/index.d.ts @@ -0,0 +1,50 @@ +// Type definitions for jss v0.6 +// Project: https://github.com/Box9/jss +// Definitions by: Valentin Robert +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +interface Properties { + [name: string]: string; +} + +interface Selectors { + [selector: string]: Properties; +} + +interface JSS { + /** + * Retrieve all rules added via JSS, organized by selectors + */ + get(): Selectors; + + /** + * Retrieve rules added via JSS for a given selector + * @param s CSS selector + */ + get(s: string): Properties; + + /** + * Retrieve all rules specified for a given selector (not necessarily added via JSS) + * @param s CSS selector + */ + getAll(s: string): Properties; + + /** + * Remove all rules added via JSS + */ + remove(): void; + + /** + * Remove all rules added via JSS for the given selector + */ + remove(s: string): void; + + /** + * Add or extend an existing rule + * @param s CSS selector + * @param p CSS properties + */ + set(s: string, p: Properties): void; +} + +declare var jss: JSS; diff --git a/types/striptags/tsconfig.json b/types/dvtng-jss/tsconfig.json similarity index 93% rename from types/striptags/tsconfig.json rename to types/dvtng-jss/tsconfig.json index 5823e343cd..3d47f98d9f 100644 --- a/types/striptags/tsconfig.json +++ b/types/dvtng-jss/tsconfig.json @@ -18,6 +18,6 @@ }, "files": [ "index.d.ts", - "striptags-tests.ts" + "dvtng-jss-tests.ts" ] -} \ No newline at end of file +} diff --git a/types/autobind-decorator/tslint.json b/types/dvtng-jss/tslint.json similarity index 100% rename from types/autobind-decorator/tslint.json rename to types/dvtng-jss/tslint.json diff --git a/types/ejs/ejs-tests.ts b/types/ejs/ejs-tests.ts index b5b46f03b5..a7b7b66944 100644 --- a/types/ejs/ejs-tests.ts +++ b/types/ejs/ejs-tests.ts @@ -1,3 +1,61 @@ +/// + import ejs = require("ejs"); -var people = ['geddy', 'neil', 'alex']; -var html = ejs.render('<%= people.join(", "); %>', { people: people }); +import { readFileSync as read } from 'fs'; +import LRU = require("lru-cache"); +import { TemplateFunction, Options } from "ejs"; + +const fileName = 'test.ejs'; +const people = ['geddy', 'neil', 'alex']; +const data = { people }; +const template = '<%= people.join(", "); %>'; +const options = { filename: fileName }; +let result: string; +let ejsFunction: TemplateFunction; + +const SimpleCallback = (err: any, html?: string) => { + if (err) { + return null; + } + return html; +}; + +result = ejs.render(template); +result = ejs.render(template, data); +result = ejs.render(template, data, options); + +result = ejs.renderFile(fileName, SimpleCallback); +result = ejs.renderFile(fileName, data, SimpleCallback); +result = ejs.renderFile(fileName, data, options, SimpleCallback); + +ejsFunction = ejs.compile(''); +ejsFunction = ejs.compile(read(fileName, "utf8")); +ejsFunction = ejs.compile(template); +ejsFunction = ejs.compile(template, options); +ejsFunction = ejs.compile(template, { cache: true, filename: fileName }); +ejsFunction = ejs.compile(template, { cache: true, filename: fileName, root: "./" }); +ejsFunction = ejs.compile(template, { context: { foo: 'FOO' } }); +ejsFunction = ejs.compile(template, { compileDebug: false }); +ejsFunction = ejs.compile(template, { client: true }); +ejsFunction = ejs.compile('<$= people.join(", "); $>', { delimiter: '$' }); +ejsFunction = ejs.compile('<%= locals.people.join(", "); %>', { _with: false }); +ejsFunction = ejs.compile('<%= locals.people.join(", "); %>', { strict: true }); +ejsFunction = ejs.compile('<%= it.people.join(", "); %>', { _with: false, localsName: "it" }); +ejsFunction = ejs.compile(template, { rmWhitespace: true }); +const customEscape = (str: string) => !str ? '' : str.toUpperCase(); +ejsFunction = ejs.compile(template, { escape: customEscape }); + +result = ejsFunction(); +result = ejsFunction({}); +result = ejsFunction(data); + +/** @see https://github.com/mde/ejs/tree/v2.5.7#custom-fileloader */ +ejs.fileLoader = (path: string) => ""; + +/** @see https://github.com/mde/ejs/tree/v2.5.7#caching */ +ejs.clearCache(); +ejs.cache = LRU(100); + +/** @see https://github.com/mde/ejs/tree/v2.5.7#custom-delimiters */ +ejs.delimiter = "%"; +delete ejs.delimiter; diff --git a/types/ejs/index.d.ts b/types/ejs/index.d.ts index a5bfb23ee9..e785f2c6ae 100644 --- a/types/ejs/index.d.ts +++ b/types/ejs/index.d.ts @@ -1,90 +1,124 @@ -// Type definitions for ejs.js v2.3.3 +// Type definitions for ejs.js 2.5 // Project: http://ejs.co/ -// Definitions by: Ben Liddicott +// Definitions by: Ben Liddicott // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.4 -declare namespace Ejs { - type Data = { [name: string]: any }; - type Dependencies = string[]; - var cache: Cache; - var localsName: string; - function resolveInclude(name: string, filename: string): string; - function compile(template: string, opts?: Options): (TemplateFunction); - function render(template: string, data?: Data, opts?: Options): string; +export interface Data { + [name: string]: any; +} +/** + * EJS template function cache. This can be a LRU object from lru-cache NPM + * module. By default, it is {@link module:utils.cache}, a simple in-process + * cache that grows continuously. + */ +export let cache: Cache; +/** + * Name of the object containing the locals. + * + * This variable is overridden by {@link Options}`.localsName` if it is not + * `undefined`. + */ +export let localsName: string; +/** + * Get the path to the included file from the parent file path and the + * specified path. + */ +export function resolveInclude(name: string, filename: string, isDir: boolean): string; +/** + * Compile the given `str` of ejs into a template function. + */ +export function compile(template: string, opts?: Options): (TemplateFunction); +/** + * Render the given `template` of ejs. + * + * If you would like to include options but not data, you need to explicitly + * call this function with `data` being an empty object or `null`. + */ +export function render(template: string, data?: Data, opts?: Options): string; - type RenderFileCallback = (err: Error, str?: string) => T; - function renderFile(path: string, cb: RenderFileCallback): T; - function renderFile(path: string, data: Data, cb: RenderFileCallback): T; - function renderFile(path: string, data: Data, opts: Options, cb: RenderFileCallback): T; +export type RenderFileCallback = (err: Error, str?: string) => T; - function clearCache(): any; +/** + * Render an EJS file at the given `path` and callback `cb(err, str)`. + * + * If you would like to include options but not data, you need to explicitly + * call this function with `data` being an empty object or `null`. + */ +export function renderFile(path: string, cb: RenderFileCallback): T; +export function renderFile(path: string, data: Data, cb: RenderFileCallback): T; +export function renderFile(path: string, data: Data, opts: Options, cb: RenderFileCallback): T; - interface TemplateFunction { - (data: Data): any; - } - interface Options { - cache?: any; - filename?: string; - context?: any; - compileDebug?: boolean; - client?: boolean; - delimiter?: string; - debug?: any; - _with?: boolean; - } - class Template { - constructor(text: string, opts: Options); - opts: Options; - templateText: string; - mode: string; - truncate: boolean; - currentLine: number; - source: string; - dependencies: Dependencies; - createRegex(): RegExp; - compile(): TemplateFunction; - generateSource(): any; - parseTemplateText(): string[]; - scanLine(line: string): any; +/** + * Clear intermediate JavaScript cache. Calls {@link Cache#reset}. + */ +export function clearCache(): void; - } - namespace Template { - interface MODES { - EVAL: string; - ESCAPED: string; - RAW: string; - COMMENT: string; - LITERAL: string; - } - } - function escapeRegexChars(s: string): string; - function escapeXML(markup: string): string; - function shallowCopy(to: T1, fro: any): T1; - interface Cache { - _data: { [name: string]: any }; - set(key: string, val: any): any; - get(key: string): any; - } - function resolve(from1: string, to: string): string; - function resolve(from1: string, from2: string, to: string): string; - function resolve(from1: string, from2: string, from3: string, to: string): string; - function resolve(from1: string, from2: string, from3: string, from4: string, to: string): string; - function resolve(from1: string, from2: string, from3: string, from4: string, from5: string, to: string): string; - function resolve(from1: string, from2: string, from3: string, from4: string, from5: string, from6: string, to: string): string; - function resolve(from1: string, from2: string, from3: string, from4: string, from5: string, from6: string, from7: string, to: string): string; - function resolve(from1: string, from2: string, from3: string, from4: string, from5: string, from6: string, from7: string, from8: string, to: string): string; - function resolve(from1: string, from2: string, from3: string, from4: string, from5: string, from6: string, from7: string, from8: string, from9: string, to: string): string; - function resolve(...args: string[]): string; - function normalize(path: string): string; - function isAbsolute(path: string): boolean; - function join(...args: string[]): string; - function relative(from: string, to: string): string; - var sep: string; - var delimiter: string; - function dirname(path: string): string; - function basename(path: string): string; - function extname(path: string): string; - function filter(xs: any, f: any): any; // TODO WHUT? +export type TemplateFunction = (data?: Data) => string; +export interface Options { + /** Compiled functions are cached, requires `filename` */ + cache?: boolean; + /** + * The name of the file being rendered. Not required if you are using `renderFile()`. + * Used by `cache` to key caches, and for includes. + */ + filename?: string; + /** Set project root for includes with an absolute path (/file.ejs). */ + root?: string; + /** Function execution context */ + context?: any; + /** When `false` no debug instrumentation is compiled */ + compileDebug?: boolean; + /** When `true`, compiles a function that can be rendered in the browser without needing to load the EJS Runtime (ejs.min.js). */ + client?: boolean; + /** Character to use with angle brackets for open/close */ + delimiter?: string; + /** Output generated function body */ + debug?: boolean; + /** When set to `true`, generated function is in strict mode */ + strict?: boolean; + /** + * Whether or not to use `with() {}` constructs. + * If `false` then the locals will be stored in the `locals` object. Set to `false` in strict mode. + */ + _with?: boolean; + /** Name to use for the object storing local variables when not using `with` Defaults to `locals` */ + localsName?: string; + /** + * Remove all safe-to-remove whitespace, including leading and trailing whitespace. + * It also enables a safer version of `-%>` line slurping for all scriptlet tags (it does not strip new lines of tags in the middle of a line). + */ + rmWhitespace?: boolean; + /** + * The escaping function used with `<%=` construct. + * It is used in rendering and is `.toString()`ed in the generation of client functions. + * (By default escapes XML). + */ + escape?(str: string): string; } -export = Ejs; +export function escapeRegexChars(s: string): string; +/** + * Escape characters reserved in XML. + * + * This is simply an export of {@link module:utils.escapeXML}. + * + * If `markup` is `undefined` or `null`, the empty string is returned. + */ +export function escapeXML(markup: string): string; +export interface Cache { + set(key: string, val: TemplateFunction): void; + get(key: string): TemplateFunction; +} +export let delimiter: string; + +/** + * Custom file loader. Useful for template preprocessing or restricting access + * to a certain part of the filesystem. + */ +export function fileLoader(filePath: string): string; + +/** + * Name for detection of EJS. + */ +export const name = "ejs"; diff --git a/types/ejs/tslint.json b/types/ejs/tslint.json index a41bf5d19a..3db14f85ea 100644 --- a/types/ejs/tslint.json +++ b/types/ejs/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/elasticsearch/index.d.ts b/types/elasticsearch/index.d.ts index 1b45a237e5..dbf836c6ae 100644 --- a/types/elasticsearch/index.d.ts +++ b/types/elasticsearch/index.d.ts @@ -137,6 +137,7 @@ export interface ShardsResponse { total: number; successful: number; failed: number; + skipped: number; } /** @@ -638,6 +639,7 @@ export interface SearchResponse { fields?: any; highlight?: any; inner_hits?: any; + sort?: string[]; }>; }; aggregations?: any; diff --git a/types/electron-spellchecker/electron-spellchecker-tests.ts b/types/electron-spellchecker/electron-spellchecker-tests.ts new file mode 100644 index 0000000000..c62b3939c9 --- /dev/null +++ b/types/electron-spellchecker/electron-spellchecker-tests.ts @@ -0,0 +1,15 @@ +import { + SpellCheckHandler, + ContextMenuListener, + ContextMenuBuilder +} from "electron-spellchecker"; + +const spellCheckHandler = new SpellCheckHandler(); +spellCheckHandler.attachToInput(); + +spellCheckHandler.switchLanguage("en-US"); + +const contextMenuBuilder = new ContextMenuBuilder(spellCheckHandler); +const contextMenuListener = new ContextMenuListener(info => { + contextMenuBuilder.showPopupMenu(info); +}); diff --git a/types/electron-spellchecker/index.d.ts b/types/electron-spellchecker/index.d.ts new file mode 100644 index 0000000000..8c02cc8794 --- /dev/null +++ b/types/electron-spellchecker/index.d.ts @@ -0,0 +1,45 @@ +// Type definitions for electron-spellchecker 1.1 +// Project: https://github.com/paulcbetts/electron-spellchecker +// Definitions by: Daniel Perez Alvarez +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +/// + +export type ContextMenuFormatter = (options: { word: string }) => string; + +export class SpellCheckHandler { + currentSpellchecker: this; + + attachToInput(): void; + autoUnloadDictionariesOnBlur(): void; + provideHintText(inputText: string): void; + switchLanguage(language: string): void; + getCorrectionsForMisspelling(misspelledWord: string): Promise; + addToDictionary(text: string): void; + + unsubscribe(): void; +} + +export class ContextMenuBuilder { + constructor( + spellCheckHandler?: SpellCheckHandler, + target?: Electron.BrowserWindow | Electron.WebviewTag | null, + debugMode?: boolean, + processMenu?: (menu: Electron.Menu) => Electron.Menu + ); + + setAlternateStringFormatter(formatter: { + [key: string]: ContextMenuFormatter; + }): void; + + showPopupMenu: (info: Electron.ContextMenuParams) => void; +} + +export class ContextMenuListener { + constructor( + handler: (info: Electron.ContextMenuParams) => void, + target?: Electron.BrowserWindow | Electron.WebviewTag | null + ); + + unsubscribe(): void; +} diff --git a/types/electron-spellchecker/package.json b/types/electron-spellchecker/package.json new file mode 100644 index 0000000000..eefa07e77a --- /dev/null +++ b/types/electron-spellchecker/package.json @@ -0,0 +1,6 @@ +{ + "private": true, + "dependencies": { + "electron": ">=1.6.10" + } +} diff --git a/types/electron-spellchecker/tsconfig.json b/types/electron-spellchecker/tsconfig.json new file mode 100644 index 0000000000..539cc30156 --- /dev/null +++ b/types/electron-spellchecker/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", + "electron-spellchecker-tests.ts" + ] +} diff --git a/types/electron-spellchecker/tslint.json b/types/electron-spellchecker/tslint.json new file mode 100644 index 0000000000..3db14f85ea --- /dev/null +++ b/types/electron-spellchecker/tslint.json @@ -0,0 +1 @@ +{ "extends": "dtslint/dt.json" } diff --git a/types/electron-winstaller/index.d.ts b/types/electron-winstaller/index.d.ts index bfc294d2a8..b5abd3c6ef 100644 --- a/types/electron-winstaller/index.d.ts +++ b/types/electron-winstaller/index.d.ts @@ -1,6 +1,6 @@ // Type definitions for electron-winstaller 2.6 // Project: https://github.com/electron/windows-installer -// Definitions by: Brendan Forster +// Definitions by: Brendan Forster , Daniel Perez Alvarez // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped export function convertVersion(version: string): string; @@ -27,13 +27,19 @@ export interface Options { * * Defaults to the `author` field from your app's package.json file when unspecified. */ - authors: string; + authors?: string; /** * The owners value for the nuget package metadata. * * Defaults to the `authors` field when unspecified. */ owners?: string; + /** + * The copyright value for the nuget package metadata. + * + * Defaults to a generated copyright with `authors` or `owners`. + */ + copyright?: string; /** * The name of your app's main `.exe` file. * diff --git a/types/ember-mocha/ember-mocha-tests.ts b/types/ember-mocha/ember-mocha-tests.ts new file mode 100644 index 0000000000..3516932eec --- /dev/null +++ b/types/ember-mocha/ember-mocha-tests.ts @@ -0,0 +1,195 @@ +import { + describeComponent, describeModel, describeModule, + setResolver, setupAcceptanceTest, setupComponentTest, + setupModelTest, setupTest +} from 'ember-mocha'; +import { context, describe, it, beforeEach, afterEach, before, after } from 'mocha'; +import chai = require('chai'); +import Ember from "ember"; +import hbs from 'htmlbars-inline-precompile'; + +describeModule('name', function() { + beforeEach(function() { + }); + + it('test', function() { + }); +}); + +describeModule('name', 'description', function() { + it('test', function() { + }); +}); + +describeModule( + 'name', + 'description', + { + needs: ['service:notifications'] + }, + function() { + } +); + +describeModule('component:x-foo', 'TestModule callbacks', { + needs: [], + + beforeSetup() { + }, + setup() { + }, + teardown() { + }, + afterTeardown() { + } +}, function() { +}); + +describeComponent('x-foo', { + integration: true +}, function() { +}); + +describeComponent('x-foo', { + unit: true, + needs: ['helper:pluralize-string'] +}, function() { +}); + +describeComponent.skip( + 'block-slot', + 'Integration: BlockSlotComponent', + { + integration: true + }, + function() { + } +); + +describeModel('user', { + needs: ['model:child'] +}, function() { +}); + +describeModule('component:x-foo', 'TestModule callbacks', function() { + before(function() { + class I18n extends Ember.Object {} + + this.skip(); + this.timeout(1000); + this.registry.register('helper:i18n', I18n); + this.registry.register('helper:i18n', I18n, { singleton: true }); + this.register('service:i18n', {}); + this.inject.service('i18n'); + this.inject.service('i18n', { as: 'i18n' }); + this.factory('object:user').create(); + }); + + after(function() { + }); + + beforeEach(function() { + }); + + afterEach(function() { + }); +}); + +describe('setupTest', function() { + setupTest(); + + setupTest('service:ajax'); + + setupTest('service:ajax', { + unit: true + }); + + setupTest('controller:sidebar', { + // Specify the other units that are required for this test. + // needs: ['controller:foo'] + }); + + setupComponentTest('gravatar-image', { + // specify the other units that are required for this test + // needs: ['component:foo', 'helper:bar'] + }); + + setupModelTest('contact', { + // Specify the other units that are required for this test. + needs: [] + }); + + const Application = Ember.Application.extend(); + + setupAcceptanceTest({ Application }); + + it('test', function() { + }); +}); + +// testing context +describe('for test suite A', function() { + context('when trying method foo', function() { + it('should test correctly', function() { + }); + }); +}); + +// if you don't have a custom resolver, do it like this: +setResolver(Ember.DefaultResolver.create()); + +it('renders', function() { + // setup the outer context + this.set('value', 'cat'); + this.on('action', function(result) { + chai.expect(result).to.equal('bar', 'The correct result was returned'); + chai.expect(this.get('value')).to.equal('cat'); + }); + + // render the component + this.render(hbs` + {{ x-foo value=value action="result" }} + `); + this.render('{{ x-foo value=value action="result" }}'); + this.render([ + '{{ x-foo value=value action="result" }}' + ]); + + chai.expect(this.$('div>.value').text()).to.equal('cat', 'The component shows the correct value'); + + this.$('button').click(); +}); + +it('renders', function() { + // creates the component instance + const subject = this.subject(); + + const subject2 = this.subject({ + item: 42 + }); + + const { inputFormat } = this.setProperties({ + inputFormat: 'M/D/YY', + outputFormat: 'MMMM D, YYYY', + date: '5/3/10' + }); + + const { inputFormat: if2, outputFormat } = this.getProperties('inputFormat', 'outputFormat'); + + const inputFormat2 = this.get('inputFormat'); + + // render the component on the page + this.render(); + chai.expect(this.$('.foo').text()).to.equal('bar'); +}); + +it('can calculate the result', function(assert) { + const subject = this.subject(); + + subject.set('value', 'foo'); + chai.assert.equal(subject.get('result'), 'bar'); +}); + +it.skip('disabled test'); + +it.skip('disabled test', function() { }); diff --git a/types/ember-mocha/index.d.ts b/types/ember-mocha/index.d.ts new file mode 100644 index 0000000000..f43982fda8 --- /dev/null +++ b/types/ember-mocha/index.d.ts @@ -0,0 +1,78 @@ +// Type definitions for ember-mocha 0.12 +// Project: https://github.com/emberjs/ember-mocha#readme +// Definitions by: Derek Wickern +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.4 + +import { TestContext, ModuleCallbacks } from "ember-test-helpers"; +import Ember from 'ember'; +import { it as mochaIt, ISuiteCallbackContext } from 'mocha'; + +// these globals are re-exported as named exports by ember-mocha +type mochaBefore = typeof before; +type mochaAfter = typeof after; +type mochaBeforeEach = typeof beforeEach; +type mochaAfterEach = typeof afterEach; +type mochaSetup = typeof setup; +type mochaTeardown = typeof teardown; +type mochaSuiteSetup = typeof suiteSetup; +type mochaSuiteTeardown = typeof suiteTeardown; + +declare module 'ember-mocha' { + interface ContextDefinitionFunction { + (name: string, description: string, callbacks: ModuleCallbacks, tests: (this: ISuiteCallbackContext) => void): void; + (name: string, description: string, tests: (this: ISuiteCallbackContext) => void): void; + (name: string, callbacks: ModuleCallbacks, tests: (this: ISuiteCallbackContext) => void): void; + (name: string, tests: (this: ISuiteCallbackContext) => void): void; + } + + interface ContextDefinition extends ContextDefinitionFunction { + only: ContextDefinitionFunction; + skip: ContextDefinitionFunction; + } + + interface SetupTest { + (name?: string, callbacks?: ModuleCallbacks): void; + (callbacks: ModuleCallbacks): void; + } + + /** @deprecated Use setupTest instead */ + export const describeModule: ContextDefinition; + + /** @deprecated Use setupComponentTest instead */ + export const describeComponent: ContextDefinition; + + /** @deprecated Use setupModelTest instead */ + export const describeModel: ContextDefinition; + + export const setupTest: SetupTest; + export const setupAcceptanceTest: SetupTest; + export const setupComponentTest: SetupTest; + export const setupModelTest: SetupTest; + + export const it: typeof mochaIt; + + /** + * Sets a Resolver globally which will be used to look up objects from each test's container. + */ + export function setResolver(resolver: Ember.Resolver): void; +} + +declare module 'mocha' { + // augment test callback context + interface ITestCallbackContext extends TestContext {} + interface IHookCallbackContext extends TestContext {} + + // re-export mocha globals as named exports + export const describe: Mocha.IContextDefinition; + export const context: Mocha.IContextDefinition; + export const it: Mocha.ITestDefinition; + export const setup: mochaSetup; + export const teardown: mochaTeardown; + export const suiteSetup: mochaSuiteSetup; + export const suiteTeardown: mochaSuiteTeardown; + export const before: mochaBefore; + export const after: mochaAfter; + export const beforeEach: mochaBeforeEach; + export const afterEach: mochaAfterEach; +} diff --git a/types/ember-mocha/tsconfig.json b/types/ember-mocha/tsconfig.json new file mode 100644 index 0000000000..e9fdedfe7f --- /dev/null +++ b/types/ember-mocha/tsconfig.json @@ -0,0 +1,21 @@ +{ + "compilerOptions": { + "module": "commonjs", + "lib": [ + "es6" + ], + "noImplicitAny": true, + "noImplicitThis": true, + "strictNullChecks": true, + "strictFunctionTypes": false, + "baseUrl": "../", + "typeRoots": ["../"], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true + }, + "files": [ + "index.d.ts", + "ember-mocha-tests.ts" + ] +} diff --git a/types/ember-mocha/tslint.json b/types/ember-mocha/tslint.json new file mode 100644 index 0000000000..aed9a80a73 --- /dev/null +++ b/types/ember-mocha/tslint.json @@ -0,0 +1,18 @@ +{ + "extends": "dtslint/dt.json", + "rules": { + "only-arrow-functions": false, + "strict-export-declare-modifiers": false, + "no-duplicate-imports": false, + "unified-signatures": false, + "no-declare-current-package": false, + + // ERROR: An interface declaring no members is equivalent to its supertype. + // -- Not true when augmenting an interface + "no-empty-interface": false, + + // ERROR: interface name must not have an "I" prefix + // -- Augmenting @types/mocha which uses "I" prefix + "interface-name": false + } +} diff --git a/types/ember-qunit/ember-qunit-tests.ts b/types/ember-qunit/ember-qunit-tests.ts new file mode 100644 index 0000000000..de22ab3d94 --- /dev/null +++ b/types/ember-qunit/ember-qunit-tests.ts @@ -0,0 +1,107 @@ +import Ember from 'ember'; +import hbs from 'htmlbars-inline-precompile'; +import { test, skip, moduleFor, moduleForModel, moduleForComponent, setResolver } from 'ember-qunit'; + +moduleForComponent('x-foo', { + integration: true +}); + +moduleForComponent('x-foo', { + unit: true, + needs: ['helper:pluralize-string'] +}); + +moduleForModel('user', { + needs: ['model:child'] +}); + +moduleFor('controller:home'); + +moduleFor('component:x-foo', 'Some description'); + +moduleFor('component:x-foo', 'TestModule callbacks', { + beforeSetup() { + }, + + beforeEach(assert) { + this.registry.register('helper:i18n', {}); + this.register('service:i18n', {}); + this.inject.service('i18n'); + this.inject.service('i18n', { as: 'i18n' }); + this.factory('object:user').create(); + assert.ok(true); + }, + + afterEach(assert) { + assert.ok(true); + }, + + afterTeardown(assert) { + assert.ok(true); + } +}); + +// if you don't have a custom resolver, do it like this: +setResolver(Ember.DefaultResolver.create()); + +test('it renders', function(assert) { + assert.expect(2); + + // setup the outer context + this.set('value', 'cat'); + this.on('action', function(result) { + assert.equal(result, 'bar', 'The correct result was returned'); + assert.equal(this.get('value'), 'cat'); + }); + + // render the component + this.render(hbs` + {{ x-foo value=value action="result" }} + `); + this.render('{{ x-foo value=value action="result" }}'); + this.render([ + '{{ x-foo value=value action="result" }}' + ]); + + assert.equal(this.$('div>.value').text(), 'cat', 'The component shows the correct value'); + + this.$('button').click(); +}); + +test('it renders', function(assert) { + assert.expect(1); + + // creates the component instance + const subject = this.subject(); + + const subject2 = this.subject({ + item: 42 + }); + + const { inputFormat } = this.setProperties({ + inputFormat: 'M/D/YY', + outputFormat: 'MMMM D, YYYY', + date: '5/3/10' + }); + + const { inputFormat: if2, outputFormat } = this.getProperties('inputFormat', 'outputFormat'); + + const inputFormat2 = this.get('inputFormat'); + + // render the component on the page + this.render(); + assert.equal(this.$('.foo').text(), 'bar'); +}); + +test('It can calculate the result', function(assert) { + assert.expect(1); + + const subject = this.subject(); + + subject.set('value', 'foo'); + assert.equal(subject.get('result'), 'bar'); +}); + +skip('disabled test'); + +skip('disabled test', function(assert) { }); diff --git a/types/ember-qunit/index.d.ts b/types/ember-qunit/index.d.ts new file mode 100644 index 0000000000..0edc5c837f --- /dev/null +++ b/types/ember-qunit/index.d.ts @@ -0,0 +1,118 @@ +// Type definitions for ember-qunit 2.2 +// Project: https://github.com/emberjs/ember-qunit#readme +// Definitions by: Derek Wickern +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.4 + +/// + +declare module 'ember-qunit' { + import Ember from 'ember'; + import { ModuleCallbacks } from "ember-test-helpers"; + + interface QUnitModuleCallbacks extends ModuleCallbacks, Hooks { + beforeSetup?(assert: Assert): void; + setup?(assert: Assert): void; + teardown?(assert: Assert): void; + afterTeardown?(assert: Assert): void; + } + + /** + * @param fullName The full name of the unit, ie controller:application, route:index. + * @param description The description of the module + */ + export function moduleFor(fullName: string, description: string, callbacks?: QUnitModuleCallbacks): void; + export function moduleFor(fullName: string, callbacks?: QUnitModuleCallbacks): void; + + /** + * @param fullName the short name of the component that you'd use in a template, ie x-foo, ic-tabs, etc. + * @param description The description of the module + */ + export function moduleForComponent(fullName: string, description: string, callbacks?: QUnitModuleCallbacks): void; + export function moduleForComponent(fullName: string, callbacks?: QUnitModuleCallbacks): void; + + /** + * @param fullName the short name of the model you'd use in store operations ie user, assignmentGroup, etc. + * @param description The description of the module + */ + export function moduleForModel(fullName: string, description: string, callbacks?: QUnitModuleCallbacks): void; + export function moduleForModel(fullName: string, callbacks?: QUnitModuleCallbacks): void; + + /** + * Sets a Resolver globally which will be used to look up objects from each test's container. + */ + export function setResolver(resolver: Ember.Resolver): void; + + export class QUnitAdapter extends Ember.Test.Adapter {} + + export { module, test, skip, only, todo } from 'qunit'; +} + +declare module 'qunit' { + import { TestContext } from "ember-test-helpers"; + + export const module: typeof QUnit.module; + + /** + * Add a test to run. + * + * Add a test to run using `QUnit.test()`. + * + * The `assert` argument to the callback contains all of QUnit's assertion + * methods. Use this argument to call your test assertions. + * + * `QUnit.test()` can automatically handle the asynchronous resolution of a + * Promise on your behalf if you return a thenable Promise as the result of + * your callback function. + * + * @param name Title of unit being tested + * @param callback Function to close over assertions + */ + export function test(name: string, callback: (this: TestContext, assert: Assert) => void): void; + + /** + * Adds a test to exclusively run, preventing all other tests from running. + * + * Use this method to focus your test suite on a specific test. QUnit.only + * will cause any other tests in your suite to be ignored. + * + * Note, that if more than one QUnit.only is present only the first instance + * will run. + * + * This is an alternative to filtering tests to run in the HTML reporter. It + * is especially useful when you use a console reporter or in a codebase + * with a large set of long running tests. + * + * @param name Title of unit being tested + * @param callback Function to close over assertions + */ + export function only(name: string, callback: (this: TestContext, assert: Assert) => void): void; + + /** + * Use this method to test a unit of code which is still under development (in a “todo” state). + * The test will pass as long as one failing assertion is present. + * + * If all assertions pass, then the test will fail signaling that `QUnit.todo` should + * be replaced by `QUnit.test`. + * + * @param name Title of unit being tested + * @param callback Function to close over assertions + */ + export function todo(name: string, callback: (this: TestContext, assert: Assert) => void): void; + + /** + * Adds a test like object to be skipped. + * + * Use this method to replace QUnit.test() instead of commenting out entire + * tests. + * + * This test's prototype will be listed on the suite as a skipped test, + * ignoring the callback argument and the respective global and module's + * hooks. + * + * @param Title of unit being tested + */ + export const skip: typeof QUnit.skip; + + export default QUnit; +} diff --git a/types/ember-qunit/tsconfig.json b/types/ember-qunit/tsconfig.json new file mode 100644 index 0000000000..845f5b1023 --- /dev/null +++ b/types/ember-qunit/tsconfig.json @@ -0,0 +1,21 @@ +{ + "compilerOptions": { + "module": "commonjs", + "lib": [ + "es6" + ], + "noImplicitAny": true, + "noImplicitThis": true, + "strictNullChecks": true, + "strictFunctionTypes": false, + "baseUrl": "../", + "typeRoots": ["../"], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true + }, + "files": [ + "index.d.ts", + "ember-qunit-tests.ts" + ] +} diff --git a/types/ember-qunit/tslint.json b/types/ember-qunit/tslint.json new file mode 100644 index 0000000000..5070b08af9 --- /dev/null +++ b/types/ember-qunit/tslint.json @@ -0,0 +1,9 @@ +{ + "extends": "dtslint/dt.json", + "rules": { + "only-arrow-functions": false, + "strict-export-declare-modifiers": false, + "no-duplicate-imports": false, + "no-declare-current-package": false + } +} diff --git a/types/ember-test-helpers/ember-test-helpers-tests.ts b/types/ember-test-helpers/ember-test-helpers-tests.ts new file mode 100644 index 0000000000..f21d554cfa --- /dev/null +++ b/types/ember-test-helpers/ember-test-helpers-tests.ts @@ -0,0 +1,25 @@ +/// +import { ModuleCallbacks, TestModule } from "ember-test-helpers"; +import wait from 'ember-test-helpers/wait'; +import hasEmberVersion from 'ember-test-helpers/has-ember-version'; + +function moduleFor(name: string, description: string, callbacks: ModuleCallbacks) { + const module = new TestModule(name, description, callbacks); + + QUnit.module(module.name, { + beforeEach() { + module.setup(); + }, + afterEach() { + module.teardown(); + } + }); +} + +async function testWait() { + await wait(); +} + +if (hasEmberVersion(2, 10)) { + // ... +} diff --git a/types/ember-test-helpers/index.d.ts b/types/ember-test-helpers/index.d.ts new file mode 100644 index 0000000000..26591d7d23 --- /dev/null +++ b/types/ember-test-helpers/index.d.ts @@ -0,0 +1,95 @@ +// Type definitions for ember-test-helpers 0.6 +// Project: https://github.com/emberjs/ember-test-helpers#readme +// Definitions by: Derek Wickern +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.4 + +/// + +declare module 'ember-test-helpers' { + import Ember from 'ember'; + import DS from 'ember-data'; + import { TemplateFactory } from 'htmlbars-inline-precompile'; + import RSVP from "rsvp"; + + interface ModuleCallbacks { + integration?: boolean; + unit?: boolean; + needs?: string[]; + + beforeSetup?(assert?: any): void; + setup?(assert?: any): void; + teardown?(assert?: any): void; + afterTeardown?(assert?: any): void; + + [key: string]: any; + } + + interface TestContext { + get(key: string): any; + getProperties(...keys: K[]): Pick; + set(key: string, value: V): V; + setProperties

(hash: P): P; + on(actionName: string, handler: (this: TestContext, ...args: any[]) => any): void; + send(actionName: string): void; + $: JQueryStatic; + subject(options?: {}): any; + render(template?: string | string[] | TemplateFactory): void; + clearRender(): void; + registry: Ember.Registry; + container: Ember.Container; + dispatcher: Ember.EventDispatcher; + application: Ember.Application; + store: DS.Store; + register(fullName: string, factory: any): void; + factory(fullName: string): any; + inject: { + controller(name: string, options?: { as: string }): any; + service(name: string, options?: { as: string }): any; + }; + } + + class TestModule { + constructor(name: string, callbacks?: ModuleCallbacks); + constructor(name: string, description?: string, callbacks?: ModuleCallbacks); + + name: string; + subjectName: string; + description: string; + isIntegration: boolean; + callbacks: ModuleCallbacks; + context: TestContext; + resolver: Ember.Resolver; + + setup(assert?: any): RSVP.Promise; + teardown(assert?: any): RSVP.Promise; + getContext(): TestContext; + setContext(context: TestContext): void; + } + + class TestModuleForAcceptance extends TestModule {} + class TestModuleForIntegration extends TestModule {} + class TestModuleForComponent extends TestModule {} + class TestModuleForModel extends TestModule {} + + function getContext(): TestContext | undefined; + function setContext(context: TestContext): void; + function unsetContext(): void; + function setResolver(resolver: Ember.Resolver): void; +} + +declare module 'ember-test-helpers/wait' { + import RSVP from "rsvp"; + + interface WaitOptions { + waitForTimers?: boolean; + waitForAJAX?: boolean; + waitForWaiters?: boolean; + } + + export default function wait(options?: WaitOptions): RSVP.Promise; +} + +declare module 'ember-test-helpers/has-ember-version' { + export default function hasEmberVersion(major: number, minor: number): boolean; +} diff --git a/types/ember-test-helpers/tsconfig.json b/types/ember-test-helpers/tsconfig.json new file mode 100644 index 0000000000..dc9c583d1c --- /dev/null +++ b/types/ember-test-helpers/tsconfig.json @@ -0,0 +1,22 @@ +{ + "compilerOptions": { + "module": "commonjs", + "lib": [ + "es6", + "dom" + ], + "noImplicitAny": true, + "noImplicitThis": true, + "strictNullChecks": true, + "strictFunctionTypes": false, + "baseUrl": "../", + "typeRoots": ["../"], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true + }, + "files": [ + "index.d.ts", + "ember-test-helpers-tests.ts" + ] +} diff --git a/types/ember-test-helpers/tslint.json b/types/ember-test-helpers/tslint.json new file mode 100644 index 0000000000..659431c9ea --- /dev/null +++ b/types/ember-test-helpers/tslint.json @@ -0,0 +1,8 @@ +{ + "extends": "dtslint/dt.json", + "rules": { + "strict-export-declare-modifiers": false, + "no-duplicate-imports": false, + "no-declare-current-package": false + } +} diff --git a/types/ember/index.d.ts b/types/ember/index.d.ts index adef4e70c2..7839a3021c 100755 --- a/types/ember/index.d.ts +++ b/types/ember/index.d.ts @@ -300,7 +300,7 @@ declare module 'ember' { /** * Given a fullName return a corresponding instance. */ - lookup(fullName: string, options: {}): any; + lookup(fullName: string, options?: {}): any; } const _ContainerProxyMixin: Mixin<_ContainerProxyMixin>; @@ -2097,7 +2097,15 @@ declare module 'ember' { options?: { path?: string; resetNamespace?: boolean }, callback?: (this: RouterDSL) => void ): void; - mount(name: string): void; + mount( + name: string, + options?: { + as?: string, + path?: string, + resetNamespace?: boolean, + engineInfo?: any + } + ): void; } class Service extends Object {} /** diff --git a/types/ember/test/router.ts b/types/ember/test/router.ts index a4aa89af1a..9ec79ce281 100755 --- a/types/ember/test/router.ts +++ b/types/ember/test/router.ts @@ -20,4 +20,5 @@ AppRouter.map(function() { }); this.route('not-found', { path: '/*path' }); this.mount('my-engine'); + this.mount('my-engine', { as: 'some-other-engine', path: '/some-other-engine'}); }); diff --git a/types/enigma.js/README.md b/types/enigma.js/README.md new file mode 100644 index 0000000000..4370bff4cb --- /dev/null +++ b/types/enigma.js/README.md @@ -0,0 +1,36 @@ +# Installation +`npm install --save @types/enigma.js` + +# Summary +This package contains type definitions for enigma.js (https://github.com/qlik-oss/enigma.js). + +# Example + +`npm install --save enigma.js` + +`npm install --save bluebird` + +```js +import * as enigma from "enigma.js"; +import * as blubird from "bluebird"; + +let qixSchema = require("./node_modules/enigma.js/schemas/12.20.0.json"); + +let enigmaConfig: enigmaJS.IConfig = { + Promise: blubird, + schema: qixSchema, + url: "ws://localhost:4848/" +}; + +let session = enigma.create(enigmaConfig); + +session.on("traffic:sent", data => console.log("sent:", data)); + +session.open() + .then((global: EngineAPI.IGlobal) => { + return global.EngineVersion(); + }) + .then((version) => { + console.log(version); + }); +``` diff --git a/types/enigma.js/index.d.ts b/types/enigma.js/index.d.ts index 38fc18da16..f691e69b2b 100644 --- a/types/enigma.js/index.d.ts +++ b/types/enigma.js/index.d.ts @@ -38,7 +38,7 @@ declare namespace enigmaJS { /** * mixin.extend is an object containing methods to extend the generated API with. These method names cannot already exist or enigma.js will throw an error. */ - extend?: [any]; + extend?: any; /** * mixin.override is an object containing methods that overrides existing API methods. @@ -46,7 +46,35 @@ declare namespace enigmaJS { * Be careful when overriding, you may break expected behaviors in other mixins or your application. * base is a reference to the previous mixin method, can be used to invoke the mixin chain before this mixin method. */ - override?: [any]; + override?: any; + } + + interface IResponseInterceptors { + /** + * This method is invoked when a previous interceptor has rejected the promise, use this to handle for example errors before they are sent into mixins. + * @param session refers to the session executing the interceptor. + * @param request is the JSON-RPC request resulting in this error. You may use .retry() to retry sending it to QIX Engine. + * @param error is whatever the previous interceptor rejected with. + */ + onRejected?(session: ISession, request: any, error: any): Promise; + + /** + * This method is invoked when a promise has been successfully resolved, use this to modify the result or reject the promise chain before it is sent to mixins. + * @param session refers to the session executing the interceptor. + * @param request is the JSON-RPC request resulting in this error. You may use .retry() to retry sending it to QIX Engine. + * @param error is whatever the previous interceptor resolved with. + */ + onFulfilled?(session: ISession, request: any, result: any): Promise; + } + + interface IRequestInterceptors { + /** + * This method is invoked when a request is about to be sent to QIX Engine. + * @param session refers to the session executing the interceptor. + * @param request is the JSON-RPC request resulting in this error. You may use .retry() to retry sending it to QIX Engine. + * @returns request the new request + */ + onFulfilled?(session: ISession, request: any, result: any): any; } interface IProtocol { @@ -83,13 +111,19 @@ declare namespace enigmaJS { * See Mixins section for more information how each entry in this array should look like. * Mixins are applied in the array order. */ - mixins?: [any]; + mixins?: IMixin[]; /** - * Interceptors for augmenting responses before they are passed into mixins and end-users. + * Interceptors for augmenting requests before they are sent to QIX Engine. * See Interceptors section for more information how each entry in this array should look like. * Interceptors are applied in the array order. */ - interceptors?: [any]; + requestInterceptors?: IRequestInterceptors[]; + /** + * Interceptors for augmenting responses before they are sent to QIX Engine. + * See Interceptors section for more information how each entry in this array should look like. + * Interceptors are applied in the array order. + */ + responseInterceptors?: IResponseInterceptors[]; /** * An object containing additional JSON-RPC request parameters. * protocol.delta : Set to false to disable the use of the bandwidth-reducing delta protocol. @@ -148,7 +182,7 @@ declare namespace enigmaJS { * @param event - Event that triggers the function * @param func - Called function */ - on(event: "opened" | "close" | "suspended" | "resumed" | string, func: any): void; + on(event: "opened" | "closed" | "suspended" | "resumed" | string, func: any): void; } interface IGeneratedAPI { diff --git a/types/event-kit/index.d.ts b/types/event-kit/index.d.ts index 01b68e8f26..2208ffaae3 100644 --- a/types/event-kit/index.d.ts +++ b/types/event-kit/index.d.ts @@ -2,7 +2,7 @@ // Project: https://github.com/atom/event-kit // Definitions by: GlenCFL // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -// TypeScript Version: 2.2 +// TypeScript Version: 2.3 export interface DisposableLike { dispose(): void; @@ -64,21 +64,12 @@ export class CompositeDisposable implements DisposableLike { clear(): void; } -/** - * Allows you to strongly type event emissions across your codebase. Additional - * key:value pairings merged into this interface will result in emissions under - * the value of each key being templated by the type of the associated value. - */ -export interface Emissions { - // tslint:disable-next-line:no-any - [key: string]: any; -} - /** * Utility class to be used when implementing event-based APIs that allows * for handlers registered via ::on to be invoked with calls to ::emit. */ -export class Emitter implements DisposableLike { +// tslint:disable-next-line:no-any +export class Emitter implements DisposableLike { disposed: boolean; /** Construct an emitter. */ diff --git a/types/events/events-tests.ts b/types/events/events-tests.ts new file mode 100644 index 0000000000..ccf89c1402 --- /dev/null +++ b/types/events/events-tests.ts @@ -0,0 +1,60 @@ +import { EventEmitter } from 'events'; + +const emitter = new EventEmitter(); +const listener = () => { + console.log('once'); +}; +const listener1 = () => { + console.log('listener1'); +}; +const listener2 = () => { + console.log('listener2'); +}; +const listener3 = (arg1: string) => { + console.log('listener3', arg1); +}; +const listener4 = () => { + console.log('type of number'); +}; + +emitter.setMaxListeners(100); + +emitter.addListener('send', listener1); + +emitter.on('send', listener2); + +emitter.on('send', listener3); + +emitter.once('send', listener); + +emitter.once(1, listener4); + +emitter.listeners('send'); +emitter.listenerCount('send'); + +EventEmitter.defaultMaxListeners = 100; +console.log(`count(static): ${EventEmitter.listenerCount(emitter, 'send')}`); +console.log(`ncount: ${emitter.listenerCount('send')}`); + +setTimeout(() => { + console.log('\n'); + emitter.emit('send'); +}, 1000); + +setTimeout(() => { + console.log('\n'); + emitter.emit('send'); + emitter.removeListener('send', listener2); +}, 2000); + +setTimeout(() => { + console.log('\n'); + emitter.emit('send', 'params1'); + emitter.removeAllListeners('send'); +}, 3000); + +setTimeout(() => { + console.log('\n'); + emitter.emit(1); + emitter.emit('send'); +}, 3000); diff --git a/types/events/index.d.ts b/types/events/index.d.ts new file mode 100644 index 0000000000..85ce0a7b0e --- /dev/null +++ b/types/events/index.d.ts @@ -0,0 +1,21 @@ +// Type definitions for events 1.1 +// Project: https://github.com/Gozala/events +// Definitions by: Yasunori Ohoka +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +export type Listener = (...args: any[]) => void; + +export class EventEmitter { + static listenerCount(emitter: EventEmitter, type: string | number): number; + static defaultMaxListeners: number; + + setMaxListeners(n: number): this; + emit(type: string | number, ...args: any[]): boolean; + addListener(type: string | number, listener: Listener): this; + on(type: string | number, listener: Listener): this; + once(type: string | number, listener: Listener): this; + removeListener(type: string | number, listener: Listener): this; + removeAllListeners(type: string | number): this; + listeners(type: string | number): Listener[]; + listenerCount(type: string | number): number; +} diff --git a/types/events/tsconfig.json b/types/events/tsconfig.json new file mode 100644 index 0000000000..f43a926ad8 --- /dev/null +++ b/types/events/tsconfig.json @@ -0,0 +1,25 @@ +{ + "compilerOptions": { + "module": "commonjs", + "target": "es6", + "lib": [ + "es6", + "dom" + ], + "noImplicitAny": true, + "noImplicitThis": true, + "strictNullChecks": true, + "strictFunctionTypes": true, + "baseUrl": "../", + "typeRoots": [ + "../" + ], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true + }, + "files": [ + "index.d.ts", + "events-tests.ts" + ] +} diff --git a/types/events/tslint.json b/types/events/tslint.json new file mode 100644 index 0000000000..3db14f85ea --- /dev/null +++ b/types/events/tslint.json @@ -0,0 +1 @@ +{ "extends": "dtslint/dt.json" } diff --git a/types/express-promise-router/express-promise-router-tests.ts b/types/express-promise-router/express-promise-router-tests.ts new file mode 100644 index 0000000000..42e0cdf570 --- /dev/null +++ b/types/express-promise-router/express-promise-router-tests.ts @@ -0,0 +1,12 @@ +import Router = require("express-promise-router"); + +const router = Router(); + +router.get("/", (req, res) => { + // equivalent to calling next() + return Promise.resolve('next'); +}); + +router.post("/", async (req, res) => { + // ... +}); diff --git a/types/express-promise-router/index.d.ts b/types/express-promise-router/index.d.ts new file mode 100644 index 0000000000..507f6d0e40 --- /dev/null +++ b/types/express-promise-router/index.d.ts @@ -0,0 +1,32 @@ +// Type definitions for express-promise-router 2.0 +// Project: https://github.com/express-promise-router/express-promise-router +// Definitions by: Anjun Wang +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.3 + +/* =================== USAGE =================== +import Router = require('express-promise-router'); + +const router = Router(); + +router.get('/', (req, res) => { + // equivalent to calling next() + return Promise.resolve('next'); +}) + +router.post('/', async (req, res) => { + // ... +}) + +export default router; + =============================================== */ + +import { Router } from "express"; + +/** + * A simple wrapper for Express 4's Router that allows middleware to return + * promises. If the promise is rejected, `express-promise-router` will call next + * with the reason + */ +declare const PromiseRouter: typeof Router; +export = PromiseRouter; diff --git a/types/express-promise-router/tsconfig.json b/types/express-promise-router/tsconfig.json new file mode 100644 index 0000000000..1f33dd7104 --- /dev/null +++ b/types/express-promise-router/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", + "express-promise-router-tests.ts" + ] +} diff --git a/types/express-promise-router/tslint.json b/types/express-promise-router/tslint.json new file mode 100644 index 0000000000..3db14f85ea --- /dev/null +++ b/types/express-promise-router/tslint.json @@ -0,0 +1 @@ +{ "extends": "dtslint/dt.json" } diff --git a/types/express-rate-limit/express-rate-limit-tests.ts b/types/express-rate-limit/express-rate-limit-tests.ts index 677c46254b..6be714f3bf 100644 --- a/types/express-rate-limit/express-rate-limit-tests.ts +++ b/types/express-rate-limit/express-rate-limit-tests.ts @@ -21,7 +21,7 @@ const callbackWithFewerParams = new RateLimit({ class SomeStore implements RateLimit.Store { incr(key: string, cb: RateLimit.StoreIncrementCallback) { } - resetAll() { } + decrement(key: string) { } resetKey(key: string) { } } diff --git a/types/express-rate-limit/index.d.ts b/types/express-rate-limit/index.d.ts index a46e0ed6cc..32799cc842 100644 --- a/types/express-rate-limit/index.d.ts +++ b/types/express-rate-limit/index.d.ts @@ -11,7 +11,7 @@ declare namespace RateLimit { interface Store { incr(key: string, cb: StoreIncrementCallback): void; - resetAll(): void; + decrement(key: string): void; resetKey(key: string): void; } @@ -24,6 +24,7 @@ declare namespace RateLimit { max?: number; message?: string; skip?(req: express.Request, res: express.Response): boolean; + skipFailedRequests?: boolean; statusCode?: number; store?: Store; onLimitReached?(req: express.Request, res: express.Response, optionsUsed: Options): void; diff --git a/types/fb/index.d.ts b/types/fb/index.d.ts index a968d9f3c0..d48aedee8a 100644 --- a/types/fb/index.d.ts +++ b/types/fb/index.d.ts @@ -83,12 +83,20 @@ interface FeedDialogParams { ref?: any; } -declare type FBUIParams = ShareDialogParams - | PageTabDialogParams - | RequestsDialogParams - | SendDialogParams - | PayDialogParams - | FeedDialogParams; +interface LiveDialogParams { + redirect_uri?: string; + method: string; + display: string; + phase: string; + broadcast_data?: LiveDialogResponse; +} + +interface LiveDialogResponse { + id: string; + stream_url: string; + secure_stream_url: string; + status: string; +} interface FBLoginOptions{ auth_type?: string; @@ -201,8 +209,14 @@ interface FBSDK{ api(path: string, params: any, callback: (response: any) => void): void; api(path: string, method: ApiMethod, params: any, callback: (response: any) => void): void; - /* This method is used to trigger different forms of Facebook created UI dialogs. */ - ui(params : FBUIParams, handler : (fbResponseObject : Object) => any) : void; + /* These methods are used to trigger different forms of Facebook-created UI dialogs. */ + ui(params : ShareDialogParams, handler : (fbResponseObject : Object) => any) : void; + ui(params : PageTabDialogParams, handler : (fbResponseObject : Object) => any) : void; + ui(params : RequestsDialogParams, handler : (fbResponseObject : Object) => any) : void; + ui(params : SendDialogParams, handler : (fbResponseObject : Object) => any) : void; + ui(params : PayDialogParams, handler : (fbResponseObject : Object) => any) : void; + ui(params : FeedDialogParams, handler : (fbResponseObject : Object) => any) : void; + ui(params : LiveDialogParams, handler : (fbResponseObject : LiveDialogResponse) => any) : void; /* Allows you to determine if a user is logged in to Facebook and has authenticated your app */ getLoginStatus(handler : (fbResponseObject : FB.LoginStatusResponse) => any, force?: Boolean) : void; diff --git a/types/firefox-webext-browser/firefox-webext-browser-tests.ts b/types/firefox-webext-browser/firefox-webext-browser-tests.ts new file mode 100644 index 0000000000..01d9cf9f3d --- /dev/null +++ b/types/firefox-webext-browser/firefox-webext-browser-tests.ts @@ -0,0 +1,10 @@ +browser.nonexistentNS; // $ExpectError +browser.nonexistentNS.unknownMethod(); // $ExpectError + +// Test that out overwritten things at least worked +browser.runtime.getManifest(); // $ExpectType WebExtensionManifest +browser.test; // $ExpectError +browser.manifest; // $ExpectError +browser._manifest; // $ExpectType typeof _manifest +browser._manifest.WebExtensionLangpackManifest; // $ExpectError +browser._manifest.NativeManifest; // $ExpectError diff --git a/types/firefox-webext-browser/index.d.ts b/types/firefox-webext-browser/index.d.ts new file mode 100644 index 0000000000..326346be82 --- /dev/null +++ b/types/firefox-webext-browser/index.d.ts @@ -0,0 +1,3148 @@ +// Type definitions for WebExtension Development in FireFox 58.0 +// Project: https://developer.mozilla.org/en-US/Add-ons/WebExtensions +// Definitions by: Jacob Bom +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.4 +// Generated using script at github.com/bomjacob/definitelytyped-firefox-webext-browser + +interface WebExtEventListener any> { + addListener: (callback: T) => void; + removeListener: (listener: T) => void; + hasListener: (listener: T) => boolean; +} + +interface Window { + browser: typeof browser; +} + +declare namespace browser.alarms { + /* alarms types */ + interface Alarm { + name: string; + scheduledTime: number; + periodInMinutes?: number; + } + + /* alarms functions */ + function create(alarmInfo: { + when?: number; + delayInMinutes?: number; + periodInMinutes?: number; + }): void; + function create(name: string, alarmInfo: { + when?: number; + delayInMinutes?: number; + periodInMinutes?: number; + }): void; + + function get(name?: string): Promise; + + function getAll(): Promise; + + function clear(name?: string): Promise; + + function clearAll(): Promise; + + /* alarms events */ + const onAlarm: WebExtEventListener<(name: Alarm) => void>; +} + +declare namespace browser._manifest { + /* _manifest types */ + type OptionalPermission = _OptionalPermission; + + type Permission = string | OptionalPermission | _Permission; + + interface ProtocolHandler { + name: string; + protocol: string | _ProtocolHandlerProtocol; + uriTemplate: ExtensionURL | HttpURL; + } + + interface WebExtensionManifest { + protocol_handlers?: ProtocolHandler[]; + default_locale?: string; + manifest_version: number; + minimum_chrome_version?: string; + minimum_opera_version?: string; + applications?: { + gecko?: FirefoxSpecificProperties; + }; + browser_specific_settings?: { + gecko?: FirefoxSpecificProperties; + }; + name: string; + short_name?: string; + description?: string; + author?: string; + version: string; + homepage_url?: string; + icons?: { + [key: number]: string; + }; + incognito?: _WebExtensionManifestIncognito; + background?: { + page: ExtensionURL; + persistent?: PersistentBackgroundProperty; + } | { + scripts: ExtensionURL[]; + persistent?: PersistentBackgroundProperty; + }; + options_ui?: { + page: ExtensionURL; + browser_style?: boolean; + chrome_style?: boolean; + open_in_tab?: boolean; + }; + content_scripts?: ContentScript[]; + content_security_policy?: string; + permissions?: PermissionOrOrigin[]; + optional_permissions?: OptionalPermissionOrOrigin[]; + web_accessible_resources?: string[]; + developer?: { + name?: string; + url?: string; + }; + theme?: ThemeType; + browser_action?: { + default_title?: string; + default_icon?: IconPath; + theme_icons?: ThemeIcons[]; + default_popup?: string; + browser_style?: boolean; + default_area?: _WebExtensionManifestBrowserActionDefaultArea; + }; + chrome_settings_overrides?: { + homepage?: string; + search_provider?: { + name: string; + keyword?: string; + search_url: string; + favicon_url?: string; + suggest_url?: string; + instant_url?: string; + image_url?: string; + search_url_post_params?: string; + instant_url_post_params?: string; + image_url_post_params?: string; + alternate_urls?: string[]; + prepopulated_id?: number; + is_default?: boolean; + }; + }; + commands?: { + suggested_key?: { + default?: KeyName; + mac?: KeyName; + linux?: KeyName; + windows?: KeyName; + chromeos?: string; + android?: string; + ios?: string; + additionalProperties?: string; + }; + description?: string; + }; + devtools_page?: ExtensionURL; + omnibox?: { + keyword: string; + }; + page_action?: { + default_title?: string; + default_icon?: IconPath; + default_popup?: string; + browser_style?: boolean; + }; + sidebar_action?: { + default_title?: string; + default_icon?: IconPath; + browser_style?: boolean; + default_panel: string; + }; + chrome_url_overrides?: { + newtab?: ExtensionURL; + bookmarks?: ExtensionURL; + history?: ExtensionURL; + }; + } + + interface ThemeIcons { + light: ExtensionURL; + dark: ExtensionURL; + size: number; + } + + type OptionalPermissionOrOrigin = OptionalPermission | MatchPattern; + + type PermissionOrOrigin = Permission | MatchPattern; + + type HttpURL = string; + + type ExtensionURL = string; + + type ImageDataOrExtensionURL = string; + + type ExtensionID = string; + + interface FirefoxSpecificProperties { + id?: ExtensionID; + update_url?: string; + strict_min_version?: string; + strict_max_version?: string; + } + + type MatchPattern = string | _MatchPattern; + + type MatchPatternInternal = string | _MatchPatternInternal; + + interface ContentScript { + matches: MatchPattern[]; + exclude_matches?: MatchPattern[]; + include_globs?: string[]; + exclude_globs?: string[]; + css?: ExtensionURL[]; + js?: ExtensionURL[]; + all_frames?: boolean; + match_about_blank?: boolean; + run_at?: extensionTypes.RunAt; + } + + type IconPath = { + [key: number]: ExtensionURL; + } | ExtensionURL; + + type IconImageData = { + [key: number]: ImageData; + } | ImageData; + + type ImageData = any; + + type UnrecognizedProperty = any; + + type PersistentBackgroundProperty = boolean; + + interface ThemeType { + images?: { + additional_backgrounds?: ImageDataOrExtensionURL[]; + headerURL?: ImageDataOrExtensionURL; + theme_frame?: ImageDataOrExtensionURL; + }; + colors?: { + accentcolor?: string; + frame?: number[]; + tab_text?: number[]; + textcolor?: string; + toolbar?: string; + toolbar_text?: string; + bookmark_text?: string; + toolbar_field?: string; + toolbar_field_text?: string; + toolbar_top_separator?: string; + toolbar_bottom_separator?: string; + toolbar_vertical_separator?: string; + }; + icons?: { + back?: ExtensionURL; + forward?: ExtensionURL; + reload?: ExtensionURL; + stop?: ExtensionURL; + bookmark_star?: ExtensionURL; + bookmark_menu?: ExtensionURL; + downloads?: ExtensionURL; + home?: ExtensionURL; + app_menu?: ExtensionURL; + cut?: ExtensionURL; + copy?: ExtensionURL; + paste?: ExtensionURL; + new_window?: ExtensionURL; + new_private_window?: ExtensionURL; + save_page?: ExtensionURL; + print?: ExtensionURL; + history?: ExtensionURL; + full_screen?: ExtensionURL; + find?: ExtensionURL; + options?: ExtensionURL; + addons?: ExtensionURL; + developer?: ExtensionURL; + synced_tabs?: ExtensionURL; + open_file?: ExtensionURL; + sidebars?: ExtensionURL; + subscribe?: ExtensionURL; + text_encoding?: ExtensionURL; + email_link?: ExtensionURL; + forget?: ExtensionURL; + pocket?: ExtensionURL; + getmsg?: ExtensionURL; + newmsg?: ExtensionURL; + address?: ExtensionURL; + reply?: ExtensionURL; + replyall?: ExtensionURL; + replylist?: ExtensionURL; + forwarding?: ExtensionURL; + delete?: ExtensionURL; + junk?: ExtensionURL; + file?: ExtensionURL; + nextUnread?: ExtensionURL; + prevUnread?: ExtensionURL; + mark?: ExtensionURL; + tag?: ExtensionURL; + compact?: ExtensionURL; + archive?: ExtensionURL; + chat?: ExtensionURL; + nextMsg?: ExtensionURL; + prevMsg?: ExtensionURL; + QFB?: ExtensionURL; + conversation?: ExtensionURL; + newcard?: ExtensionURL; + newlist?: ExtensionURL; + editcard?: ExtensionURL; + newim?: ExtensionURL; + send?: ExtensionURL; + spelling?: ExtensionURL; + attach?: ExtensionURL; + security?: ExtensionURL; + save?: ExtensionURL; + quote?: ExtensionURL; + buddy?: ExtensionURL; + join_chat?: ExtensionURL; + chat_accounts?: ExtensionURL; + calendar?: ExtensionURL; + tasks?: ExtensionURL; + synchronize?: ExtensionURL; + newevent?: ExtensionURL; + newtask?: ExtensionURL; + editevent?: ExtensionURL; + today?: ExtensionURL; + category?: ExtensionURL; + complete?: ExtensionURL; + priority?: ExtensionURL; + saveandclose?: ExtensionURL; + attendees?: ExtensionURL; + privacy?: ExtensionURL; + status?: ExtensionURL; + freebusy?: ExtensionURL; + timezones?: ExtensionURL; + }; + properties?: { + additional_backgrounds_alignment?: _ThemeTypeAdditionalBackgroundsAlignment[]; + additional_backgrounds_tiling?: _ThemeTypeAdditionalBackgroundsTiling[]; + }; + } + + type KeyName = string; + + enum _OptionalPermission { + browserSettings = "browserSettings", + cookies = "cookies", + clipboardRead = "clipboardRead", + clipboardWrite = "clipboardWrite", + geolocation = "geolocation", + idle = "idle", + notifications = "notifications", + topSites = "topSites", + webNavigation = "webNavigation", + webRequest = "webRequest", + webRequestBlocking = "webRequestBlocking", + bookmarks = "bookmarks", + find = "find", + history = "history", + activeTab = "activeTab", + tabs = "tabs" + } + + enum _Permission { + contextualIdentities = "contextualIdentities", + downloads = "downloads", + downloadsopen = "downloads.open", + identity = "identity", + management = "management", + alarms = "alarms", + mozillaAddons = "mozillaAddons", + storage = "storage", + unlimitedStorage = "unlimitedStorage", + privacy = "privacy", + proxy = "proxy", + nativeMessaging = "nativeMessaging", + theme = "theme", + browsingData = "browsingData", + devtools = "devtools", + geckoProfiler = "geckoProfiler", + menus = "menus", + contextMenus = "contextMenus", + pkcs11 = "pkcs11", + sessions = "sessions" + } + + enum _ProtocolHandlerProtocol { + bitcoin = "bitcoin", + geo = "geo", + gopher = "gopher", + im = "im", + irc = "irc", + ircs = "ircs", + magnet = "magnet", + mailto = "mailto", + mms = "mms", + news = "news", + nntp = "nntp", + sip = "sip", + sms = "sms", + smsto = "smsto", + ssh = "ssh", + tel = "tel", + urn = "urn", + webcal = "webcal", + wtai = "wtai", + xmpp = "xmpp" + } + + enum _WebExtensionManifestIncognito { + spanning = "spanning" + } + + enum _WebExtensionManifestBrowserActionDefaultArea { + navbar = "navbar", + menupanel = "menupanel", + tabstrip = "tabstrip", + personaltoolbar = "personaltoolbar" + } + + enum _MatchPattern { + all_urls = "" + } + + enum _MatchPatternInternal { + all_urls = "" + } + + enum _ThemeTypeAdditionalBackgroundsAlignment { + bottom = "bottom", + center = "center", + left = "left", + right = "right", + top = "top", + centerbottom = "center bottom", + centercenter = "center center", + centertop = "center top", + leftbottom = "left bottom", + leftcenter = "left center", + lefttop = "left top", + rightbottom = "right bottom", + rightcenter = "right center", + righttop = "right top" + } + + enum _ThemeTypeAdditionalBackgroundsTiling { + norepeat = "no-repeat", + repeat = "repeat", + repeatx = "repeat-x", + repeaty = "repeat-y" + } +} + +declare namespace browser.browserSettings { + /* browserSettings types */ + enum ImageAnimationBehavior { + normal = "normal", + none = "none", + once = "once" + } + + /* browserSettings properties */ + const allowPopupsForUserEvents: types.Setting; + + const cacheEnabled: types.Setting; + + const homepageOverride: types.Setting; + + const imageAnimationBehavior: types.Setting; + + const newTabPageOverride: types.Setting; + + const webNotificationsDisabled: types.Setting; +} + +declare namespace browser.clipboard { + type ArrayBuffer = any; + + enum _SetImageData { + jpeg = "jpeg", + png = "png" + } + + /* clipboard functions */ + function setImageData(imageData: ArrayBuffer, imageType: _SetImageData): void; +} + +declare namespace browser.contextualIdentities { + /* contextualIdentities types */ + interface ContextualIdentity { + name: string; + icon: string; + iconUrl: string; + color: string; + colorCode: string; + cookieStoreId: string; + } + + /* contextualIdentities functions */ + function get(cookieStoreId: string): void; + + function query(details: { + name?: string; + }): void; + + function create(details: { + name: string; + color: string; + icon: string; + }): void; + + function update(cookieStoreId: string, details: { + name?: string; + color?: string; + icon?: string; + }): void; + + function remove(cookieStoreId: string): void; + + /* contextualIdentities events */ + const onUpdated: WebExtEventListener<(changeInfo: { + contextualIdentity: ContextualIdentity; + }) => void>; + + const onCreated: WebExtEventListener<(changeInfo: { + contextualIdentity: ContextualIdentity; + }) => void>; + + const onRemoved: WebExtEventListener<(changeInfo: { + contextualIdentity: ContextualIdentity; + }) => void>; +} + +declare namespace browser.cookies { + /* cookies types */ + interface Cookie { + name: string; + value: string; + domain: string; + hostOnly: boolean; + path: string; + secure: boolean; + httpOnly: boolean; + session: boolean; + expirationDate?: number; + storeId: string; + } + + interface CookieStore { + id: string; + tabIds: number[]; + incognito: boolean; + } + + enum OnChangedCause { + evicted = "evicted", + expired = "expired", + explicit = "explicit", + expired_overwrite = "expired_overwrite", + overwrite = "overwrite" + } + + /* cookies functions */ + function get(details: { + url: string; + name: string; + storeId?: string; + }): Promise; + + function getAll(details: { + url?: string; + name?: string; + domain?: string; + path?: string; + secure?: boolean; + session?: boolean; + storeId?: string; + }): Promise; + + function set(details: { + url: string; + name?: string; + value?: string; + domain?: string; + path?: string; + secure?: boolean; + httpOnly?: boolean; + expirationDate?: number; + storeId?: string; + }): Promise; + + function remove(details: { + url: string; + name: string; + storeId?: string; + }): Promise<{ + url: string; + name: string; + storeId: string; + }>; + + function getAllCookieStores(): Promise; + + /* cookies events */ + const onChanged: WebExtEventListener<(changeInfo: { + removed: boolean; + cookie: Cookie; + cause: OnChangedCause; + }) => void>; +} + +declare namespace browser.downloads { + /* downloads types */ + enum FilenameConflictAction { + uniquify = "uniquify", + overwrite = "overwrite", + prompt = "prompt" + } + + enum InterruptReason { + FILE_FAILED = "FILE_FAILED", + FILE_ACCESS_DENIED = "FILE_ACCESS_DENIED", + FILE_NO_SPACE = "FILE_NO_SPACE", + FILE_NAME_TOO_LONG = "FILE_NAME_TOO_LONG", + FILE_TOO_LARGE = "FILE_TOO_LARGE", + FILE_VIRUS_INFECTED = "FILE_VIRUS_INFECTED", + FILE_TRANSIENT_ERROR = "FILE_TRANSIENT_ERROR", + FILE_BLOCKED = "FILE_BLOCKED", + FILE_SECURITY_CHECK_FAILED = "FILE_SECURITY_CHECK_FAILED", + FILE_TOO_SHORT = "FILE_TOO_SHORT", + NETWORK_FAILED = "NETWORK_FAILED", + NETWORK_TIMEOUT = "NETWORK_TIMEOUT", + NETWORK_DISCONNECTED = "NETWORK_DISCONNECTED", + NETWORK_SERVER_DOWN = "NETWORK_SERVER_DOWN", + NETWORK_INVALID_REQUEST = "NETWORK_INVALID_REQUEST", + SERVER_FAILED = "SERVER_FAILED", + SERVER_NO_RANGE = "SERVER_NO_RANGE", + SERVER_BAD_CONTENT = "SERVER_BAD_CONTENT", + SERVER_UNAUTHORIZED = "SERVER_UNAUTHORIZED", + SERVER_CERT_PROBLEM = "SERVER_CERT_PROBLEM", + SERVER_FORBIDDEN = "SERVER_FORBIDDEN", + USER_CANCELED = "USER_CANCELED", + USER_SHUTDOWN = "USER_SHUTDOWN", + CRASH = "CRASH" + } + + enum DangerType { + file = "file", + url = "url", + content = "content", + uncommon = "uncommon", + host = "host", + unwanted = "unwanted", + safe = "safe", + accepted = "accepted" + } + + enum State { + in_progress = "in_progress", + interrupted = "interrupted", + complete = "complete" + } + + interface DownloadItem { + id: number; + url: string; + referrer?: string; + filename: string; + incognito: boolean; + danger: DangerType; + mime: string; + startTime: string; + endTime?: string; + estimatedEndTime?: string; + state: State; + paused: boolean; + canResume: boolean; + error?: InterruptReason; + bytesReceived: number; + totalBytes: number; + fileSize: number; + exists: boolean; + byExtensionId?: string; + byExtensionName?: string; + } + + interface StringDelta { + current?: string; + previous?: string; + } + + interface DoubleDelta { + current?: number; + previous?: number; + } + + interface BooleanDelta { + current?: boolean; + previous?: boolean; + } + + type DownloadTime = string | extensionTypes.Date; + + interface DownloadQuery { + query?: string[]; + startedBefore?: DownloadTime; + startedAfter?: DownloadTime; + endedBefore?: DownloadTime; + endedAfter?: DownloadTime; + totalBytesGreater?: number; + totalBytesLess?: number; + filenameRegex?: string; + urlRegex?: string; + limit?: number; + orderBy?: string[]; + id?: number; + url?: string; + filename?: string; + danger?: DangerType; + mime?: string; + startTime?: string; + endTime?: string; + state?: State; + paused?: boolean; + error?: InterruptReason; + bytesReceived?: number; + totalBytes?: number; + fileSize?: number; + exists?: boolean; + } + + enum _DownloadMethod { + GET = "GET", + POST = "POST" + } + + /* downloads functions */ + function download(options: { + url: string; + filename?: string; + incognito?: boolean; + conflictAction?: FilenameConflictAction; + saveAs?: boolean; + method?: _DownloadMethod; + headers?: Array<{ + name: string; + value: string; + }>; + body?: string; + }): Promise; + + function search(query: DownloadQuery): Promise; + + function pause(downloadId: number): Promise; + + function resume(downloadId: number): Promise; + + function cancel(downloadId: number): Promise; + + function getFileIcon(downloadId: number, options?: { + size?: number; + }): Promise; + + function open(downloadId: number): Promise; + + function show(downloadId: number): Promise; + + function showDefaultFolder(): void; + + function erase(query: DownloadQuery): Promise; + + function removeFile(downloadId: number): Promise; + + const acceptDanger: ((downloadId: number) => void) | undefined; + + const drag: ((downloadId: number) => void) | undefined; + + const setShelfEnabled: ((enabled: boolean) => void) | undefined; + + /* downloads events */ + const onCreated: WebExtEventListener<(downloadItem: DownloadItem) => void>; + + const onErased: WebExtEventListener<(downloadId: number) => void>; + + const onChanged: WebExtEventListener<(downloadDelta: { + id: number; + url?: StringDelta; + filename?: StringDelta; + danger?: StringDelta; + mime?: StringDelta; + startTime?: StringDelta; + endTime?: StringDelta; + state?: StringDelta; + canResume?: BooleanDelta; + paused?: BooleanDelta; + error?: StringDelta; + totalBytes?: DoubleDelta; + fileSize?: DoubleDelta; + exists?: BooleanDelta; + }) => void>; +} + +declare namespace browser.events { + /* events types */ + interface Rule { + id?: string; + tags?: string[]; + conditions: any[]; + actions: any[]; + priority?: number; + } + + class Event { + addListener(): void; + + removeListener(): void; + + hasListener(): boolean; + + hasListeners(): boolean; + + addRules?(eventName: string, webViewInstanceId: number, rules: Rule[]): void; + + getRules?(eventName: string, webViewInstanceId: number, ruleIdentifiers?: string[]): void; + + removeRules?(eventName: string, webViewInstanceId: number, ruleIdentifiers?: string[]): void; + } + + interface UrlFilter { + hostContains?: string; + hostEquals?: string; + hostPrefix?: string; + hostSuffix?: string; + pathContains?: string; + pathEquals?: string; + pathPrefix?: string; + pathSuffix?: string; + queryContains?: string; + queryEquals?: string; + queryPrefix?: string; + querySuffix?: string; + urlContains?: string; + urlEquals?: string; + urlMatches?: string; + originAndPathMatches?: string; + urlPrefix?: string; + urlSuffix?: string; + schemes?: string[]; + ports?: Array; + } +} + +declare namespace browser.extension { + /* extension types */ + enum ViewType { + tab = "tab", + popup = "popup", + sidebar = "sidebar" + } + + /* extension properties */ + const lastError: { + message: string; + } | undefined; + + const inIncognitoContext: boolean | undefined; + + /* extension functions */ + function getURL(path: string): string; + + function getViews(fetchProperties?: { + type?: ViewType; + windowId?: number; + tabId?: number; + }): Window[]; + + function getBackgroundPage(): Window; + + function isAllowedIncognitoAccess(): Promise; + + function isAllowedFileSchemeAccess(): Promise; + + const setUpdateUrlData: ((data: string) => void) | undefined; + + /* extension events */ + const onRequest: WebExtEventListener<(request: any, sender: runtime.MessageSender, sendResponse: () => void) => void> + | WebExtEventListener<(sender: runtime.MessageSender, sendResponse: () => void) => void> | undefined; + + const onRequestExternal: WebExtEventListener<(request: any, sender: runtime.MessageSender, sendResponse: () => void) => void> + | WebExtEventListener<(sender: runtime.MessageSender, sendResponse: () => void) => void> | undefined; +} + +declare namespace browser.extensionTypes { + /* extensionTypes types */ + enum ImageFormat { + jpeg = "jpeg", + png = "png" + } + + interface ImageDetails { + format?: ImageFormat; + quality?: number; + } + + enum RunAt { + document_start = "document_start", + document_end = "document_end", + document_idle = "document_idle" + } + + enum CSSOrigin { + user = "user", + author = "author" + } + + interface InjectDetails { + code?: string; + file?: string; + allFrames?: boolean; + matchAboutBlank?: boolean; + frameId?: number; + runAt?: RunAt; + cssOrigin?: CSSOrigin; + } + + type Date = string | number | object/*Date*/; +} + +declare namespace browser.i18n { + /* i18n types */ + type LanguageCode = string; + + /* i18n functions */ + function getAcceptLanguages(): Promise; + + function getMessage(messageName: string, substitutions?: any): string; + + function getUILanguage(): string; + + function detectLanguage(text: string): Promise<{ + isReliable: boolean; + languages: Array<{ + language: LanguageCode; + percentage: number; + }>; + }>; +} + +declare namespace browser.identity { + /* identity types */ + interface AccountInfo { + id: string; + } + + /* identity functions */ + const getAccounts: (() => Promise) | undefined; + + const getAuthToken: ((details?: { + interactive?: boolean; + account?: AccountInfo; + scopes?: string[]; + }) => Promise) | undefined; + + const getProfileUserInfo: (() => Promise<{ + email: string; + id: string; + }>) | undefined; + + const removeCachedAuthToken: ((details: { + token: string; + }) => Promise<{ + email: string; + id: string; + }>) | undefined; + + function launchWebAuthFlow(details: { + url: string; + interactive?: boolean; + }): Promise; + + function getRedirectURL(path?: string): string; + + /* identity events */ + const onSignInChanged: WebExtEventListener<(account: AccountInfo, signedIn: boolean) => void> | undefined; +} + +declare namespace browser.idle { + /* idle types */ + enum IdleState { + active = "active", + idle = "idle" + } + + /* idle functions */ + function queryState(detectionIntervalInSeconds: number): Promise; + + function setDetectionInterval(intervalInSeconds: number): void; + + /* idle events */ + const onStateChanged: WebExtEventListener<(newState: IdleState) => void>; +} + +declare namespace browser.management { + /* management types */ + interface IconInfo { + size: number; + url: string; + } + + enum ExtensionDisabledReason { + unknown = "unknown", + permissions_increase = "permissions_increase" + } + + enum ExtensionType { + extension = "extension", + theme = "theme" + } + + enum ExtensionInstallType { + development = "development", + normal = "normal", + sideload = "sideload", + other = "other" + } + + interface ExtensionInfo { + id: string; + name: string; + shortName?: string; + description: string; + version: string; + versionName?: string; + mayDisable: boolean; + enabled: boolean; + disabledReason?: ExtensionDisabledReason; + type: ExtensionType; + homepageUrl?: string; + updateUrl?: string; + optionsUrl: string; + icons?: IconInfo[]; + permissions?: string[]; + hostPermissions?: string[]; + installType: ExtensionInstallType; + } + + /* management functions */ + function getAll(): Promise; + + function get(id: _manifest.ExtensionID): Promise; + + function getSelf(): Promise; + + function uninstallSelf(options?: { + showConfirmDialog?: boolean; + dialogMessage?: string; + }): Promise; + + function setEnabled(id: string, enabled: boolean): Promise; + + /* management events */ + const onDisabled: WebExtEventListener<(info: ExtensionInfo) => void>; + + const onEnabled: WebExtEventListener<(info: ExtensionInfo) => void>; + + const onInstalled: WebExtEventListener<(info: ExtensionInfo) => void>; + + const onUninstalled: WebExtEventListener<(info: ExtensionInfo) => void>; +} + +declare namespace browser.notifications { + /* notifications types */ + enum TemplateType { + basic = "basic", + image = "image", + list = "list", + progress = "progress" + } + + enum PermissionLevel { + granted = "granted", + denied = "denied" + } + + interface NotificationItem { + title: string; + message: string; + } + + interface CreateNotificationOptions { + type: TemplateType; + iconUrl?: string; + appIconMaskUrl?: string; + title: string; + message: string; + contextMessage?: string; + priority?: number; + eventTime?: number; + buttons?: Array<{ + title: string; + iconUrl?: string; + }>; + imageUrl?: string; + items?: NotificationItem[]; + progress?: number; + isClickable?: boolean; + } + + interface UpdateNotificationOptions { + type?: TemplateType; + iconUrl?: string; + appIconMaskUrl?: string; + title?: string; + message?: string; + contextMessage?: string; + priority?: number; + eventTime?: number; + buttons?: Array<{ + title: string; + iconUrl?: string; + }>; + imageUrl?: string; + items?: NotificationItem[]; + progress?: number; + isClickable?: boolean; + } + + /* notifications functions */ + function create(options: CreateNotificationOptions): Promise; + function create(notificationId: string, options: CreateNotificationOptions): Promise; + + const update: ((notificationId: string, options: UpdateNotificationOptions) => Promise) | undefined; + + function clear(notificationId: string): Promise; + + function getAll(): Promise; + + const getPermissionLevel: (() => Promise) | undefined; + + /* notifications events */ + const onClosed: WebExtEventListener<(notificationId: string, byUser: boolean) => void>; + + const onClicked: WebExtEventListener<(notificationId: string) => void>; + + const onButtonClicked: WebExtEventListener<(notificationId: string, buttonIndex: number) => void>; + + const onPermissionLevelChanged: WebExtEventListener<(level: PermissionLevel) => void> | undefined; + + const onShowSettings: WebExtEventListener<() => void> | undefined; + + const onShown: WebExtEventListener<(notificationId: string) => void>; +} + +declare namespace browser.permissions { + /* permissions types */ + interface Permissions { + permissions?: _manifest.OptionalPermission[]; + origins?: _manifest.MatchPattern[]; + } + + interface AnyPermissions { + permissions?: _manifest.Permission[]; + origins?: _manifest.MatchPatternInternal[]; + } + + /* permissions functions */ + function getAll(): Promise; + + function contains(permissions: AnyPermissions): Promise; + + function request(permissions: Permissions): Promise; + + function remove(permissions: Permissions): Promise; + + /* permissions events */ + const onAdded: WebExtEventListener<(permissions: Permissions) => void> | undefined; + + const onRemoved: WebExtEventListener<(permissions: Permissions) => void> | undefined; +} + +declare namespace browser.privacy { +} + +declare namespace browser.privacy.network { + /* privacy.network types */ + enum IPHandlingPolicy { + default = "default", + default_public_and_private_interfaces = "default_public_and_private_interfaces", + default_public_interface_only = "default_public_interface_only", + disable_non_proxied_udp = "disable_non_proxied_udp" + } + + /* privacy.network properties */ + const networkPredictionEnabled: types.Setting; + + const peerConnectionEnabled: types.Setting; + + const webRTCIPHandlingPolicy: types.Setting; +} + +declare namespace browser.privacy.services { + /* privacy.services properties */ + const passwordSavingEnabled: types.Setting; +} + +declare namespace browser.privacy.websites { + /* privacy.websites types */ + enum TrackingProtectionModeOption { + always = "always", + never = "never", + private_browsing = "private_browsing" + } + + /* privacy.websites properties */ + const thirdPartyCookiesAllowed: types.Setting | undefined; + + const hyperlinkAuditingEnabled: types.Setting; + + const referrersEnabled: types.Setting; + + const resistFingerprinting: types.Setting; + + const firstPartyIsolate: types.Setting; + + const protectedContentEnabled: types.Setting | undefined; + + const trackingProtectionMode: types.Setting; +} + +declare namespace browser.proxy { + /* proxy functions */ + function register(url: string): void; + + function unregister(): void; + + function registerProxyScript(url: string): void; + + /* proxy events */ + const onProxyError: WebExtEventListener<(error: object) => void>; +} + +declare namespace browser.runtime { + /* runtime types */ + interface Port { + name: string; + disconnect: () => void; + onDisconnect: events.Event; + onMessage: events.Event; + postMessage: () => void; + sender?: MessageSender; + } + + interface MessageSender { + tab?: tabs.Tab; + frameId?: number; + id?: string; + url?: string; + tlsChannelId?: string; + } + + enum PlatformOs { + mac = "mac", + win = "win", + android = "android", + cros = "cros", + linux = "linux", + openbsd = "openbsd" + } + + enum PlatformArch { + arm = "arm", + x8632 = "x86-32", + x8664 = "x86-64" + } + + interface PlatformInfo { + os: PlatformOs; + arch: PlatformArch; + nacl_arch?: PlatformNaclArch; + } + + interface BrowserInfo { + name: string; + vendor: string; + version: string; + buildID: string; + } + + enum RequestUpdateCheckStatus { + throttled = "throttled", + no_update = "no_update", + update_available = "update_available" + } + + enum OnInstalledReason { + install = "install", + update = "update", + browser_update = "browser_update" + } + + enum OnRestartRequiredReason { + app_update = "app_update", + os_update = "os_update", + periodic = "periodic" + } + + type PlatformNaclArch = any; + + /* runtime properties */ + const lastError: { + message?: string; + } | undefined; + + const id: string; + + /* runtime functions */ + function getBackgroundPage(): Promise; + + function openOptionsPage(): Promise; + + function getManifest(): _manifest.WebExtensionManifest; + + function getURL(path: string): string; + + function setUninstallURL(url: string): Promise; + + function reload(): void; + + const requestUpdateCheck: (() => Promise) | undefined; + + const restart: (() => void) | undefined; + + function connect(connectInfo?: { + name?: string; + includeTlsChannelId?: boolean; + }): Port; + function connect(extensionId: string, connectInfo?: { + name?: string; + includeTlsChannelId?: boolean; + }): Port; + + function connectNative(application: string): Port; + + function sendMessage(message: any, options?: { + includeTlsChannelId?: boolean; + toProxyScript?: boolean; + }, responseCallback?: (response: any) => void): void; + function sendMessage(extensionId: string, message: any, options: { + includeTlsChannelId?: boolean; + toProxyScript?: boolean; + }, responseCallback?: (response: any) => void): void; + + function sendNativeMessage(application: string, message: any, responseCallback?: (response: any) => void): void; + + function getBrowserInfo(): Promise; + + function getPlatformInfo(): Promise; + + const getPackageDirectoryEntry: (() => Promise) | undefined; + + /* runtime events */ + const onStartup: WebExtEventListener<() => void>; + + const onInstalled: WebExtEventListener<(details: { + reason: OnInstalledReason; + previousVersion?: string; + temporary: boolean; + id?: string; + }) => void>; + + const onSuspend: WebExtEventListener<() => void> | undefined; + + const onSuspendCanceled: WebExtEventListener<() => void> | undefined; + + const onUpdateAvailable: WebExtEventListener<(details: { + version: string; + }) => void>; + + const onBrowserUpdateAvailable: WebExtEventListener<() => void> | undefined; + + const onConnect: WebExtEventListener<(port: Port) => void>; + + const onConnectExternal: WebExtEventListener<(port: Port) => void>; + + const onMessage: WebExtEventListener<(message: any, sender: MessageSender, sendResponse: () => void) => boolean> + | WebExtEventListener<(sender: MessageSender, sendResponse: () => void) => boolean>; + + const onMessageExternal: WebExtEventListener<(message: any, sender: MessageSender, sendResponse: () => void) => boolean> + | WebExtEventListener<(sender: MessageSender, sendResponse: () => void) => boolean>; + + const onRestartRequired: WebExtEventListener<(reason: OnRestartRequiredReason) => void> | undefined; +} + +declare namespace browser.storage { + /* storage types */ + interface StorageChange { + oldValue?: any; + newValue?: any; + } + + class StorageArea { + get(keys?: string | string[] | object): Promise; + + getBytesInUse?(keys?: string | string[]): Promise; + + set(items: any): Promise; + + remove(keys: string | string[]): Promise; + + clear(): Promise; + } + + /* storage properties */ + const sync: StorageArea; + + const local: StorageArea; + + const managed: StorageArea; + + /* storage events */ + const onChanged: WebExtEventListener<(changes: StorageChange, areaName: string) => void>; +} + +declare namespace browser.theme { + /* theme types */ + interface ThemeUpdateInfo { + theme: object; + windowId?: number; + } + + /* theme functions */ + function getCurrent(windowId?: number): void; + + function update(details: _manifest.ThemeType): void; + function update(windowId: number, details: _manifest.ThemeType): void; + + function reset(windowId?: number): void; + + /* theme events */ + const onUpdated: WebExtEventListener<(updateInfo: ThemeUpdateInfo) => void>; +} + +declare namespace browser.topSites { + /* topSites types */ + interface MostVisitedURL { + url: string; + title?: string; + } + + /* topSites functions */ + function get(options?: { + providers?: string[]; + }): Promise; +} + +declare namespace browser.types { + /* types types */ + enum SettingScope { + regular = "regular", + regular_only = "regular_only", + incognito_persistent = "incognito_persistent", + incognito_session_only = "incognito_session_only" + } + + enum LevelOfControl { + not_controllable = "not_controllable", + controlled_by_other_extensions = "controlled_by_other_extensions", + controllable_by_this_extension = "controllable_by_this_extension", + controlled_by_this_extension = "controlled_by_this_extension" + } + + class Setting { + get(details: { + incognito?: boolean; + }): Promise<{ + value: any; + levelOfControl: LevelOfControl; + incognitoSpecific?: boolean; + }>; + + set(details: { + value: any; + scope?: SettingScope; + }): Promise; + + clear(details: { + scope?: SettingScope; + }): Promise; + + onChange: WebExtEventListener<(details: { + value: any; + levelOfControl: LevelOfControl; + incognitoSpecific?: boolean; + }) => void>; + } +} + +declare namespace browser.webNavigation { + /* webNavigation types */ + enum TransitionType { + link = "link", + typed = "typed", + auto_bookmark = "auto_bookmark", + auto_subframe = "auto_subframe", + manual_subframe = "manual_subframe", + generated = "generated", + start_page = "start_page", + form_submit = "form_submit", + reload = "reload", + keyword = "keyword", + keyword_generated = "keyword_generated" + } + + enum TransitionQualifier { + client_redirect = "client_redirect", + server_redirect = "server_redirect", + forward_back = "forward_back", + from_address_bar = "from_address_bar" + } + + interface EventUrlFilters { + url: events.UrlFilter[]; + } + + /* webNavigation functions */ + function getFrame(details: { + tabId: number; + processId?: number; + frameId: number; + }): Promise<{ + errorOccurred?: boolean; + url: string; + tabId: number; + frameId: number; + parentFrameId: number; + }>; + + function getAllFrames(details: { + tabId: number; + }): Promise>; + + /* webNavigation events */ + const onBeforeNavigate: WebExtEventListener<(details: { + tabId: number; + url: string; + processId?: number; + frameId: number; + parentFrameId: number; + timeStamp: number; + }) => void>; + + const onCommitted: WebExtEventListener<(details: { + tabId: number; + url: string; + processId?: number; + frameId: number; + transitionType?: TransitionType; + transitionQualifiers?: TransitionQualifier[]; + timeStamp: number; + }) => void>; + + const onDOMContentLoaded: WebExtEventListener<(details: { + tabId: number; + url: string; + processId?: number; + frameId: number; + timeStamp: number; + }) => void>; + + const onCompleted: WebExtEventListener<(details: { + tabId: number; + url: string; + processId?: number; + frameId: number; + timeStamp: number; + }) => void>; + + const onErrorOccurred: WebExtEventListener<(details: { + tabId: number; + url: string; + processId?: number; + frameId: number; + error?: string; + timeStamp: number; + }) => void>; + + const onCreatedNavigationTarget: WebExtEventListener<(details: { + sourceTabId: number; + sourceProcessId: number; + sourceFrameId: number; + url: string; + tabId: number; + timeStamp: number; + }) => void>; + + const onReferenceFragmentUpdated: WebExtEventListener<(details: { + tabId: number; + url: string; + processId?: number; + frameId: number; + transitionType?: TransitionType; + transitionQualifiers?: TransitionQualifier[]; + timeStamp: number; + }) => void>; + + const onTabReplaced: WebExtEventListener<(details: { + replacedTabId: number; + tabId: number; + timeStamp: number; + }) => void>; + + const onHistoryStateUpdated: WebExtEventListener<(details: { + tabId: number; + url: string; + processId?: number; + frameId: number; + transitionType?: TransitionType; + transitionQualifiers?: TransitionQualifier[]; + timeStamp: number; + }) => void>; +} + +declare namespace browser.webRequest { + /* webRequest types */ + enum ResourceType { + main_frame = "main_frame", + sub_frame = "sub_frame", + stylesheet = "stylesheet", + script = "script", + image = "image", + object = "object", + object_subrequest = "object_subrequest", + xmlhttprequest = "xmlhttprequest", + xbl = "xbl", + xslt = "xslt", + ping = "ping", + beacon = "beacon", + xml_dtd = "xml_dtd", + font = "font", + media = "media", + websocket = "websocket", + csp_report = "csp_report", + imageset = "imageset", + web_manifest = "web_manifest", + other = "other" + } + + enum OnBeforeRequestOptions { + blocking = "blocking", + requestBody = "requestBody" + } + + enum OnBeforeSendHeadersOptions { + requestHeaders = "requestHeaders", + blocking = "blocking" + } + + enum OnSendHeadersOptions { + requestHeaders = "requestHeaders" + } + + enum OnHeadersReceivedOptions { + blocking = "blocking", + responseHeaders = "responseHeaders" + } + + enum OnAuthRequiredOptions { + responseHeaders = "responseHeaders", + blocking = "blocking", + asyncBlocking = "asyncBlocking" + } + + enum OnResponseStartedOptions { + responseHeaders = "responseHeaders" + } + + enum OnBeforeRedirectOptions { + responseHeaders = "responseHeaders" + } + + enum OnCompletedOptions { + responseHeaders = "responseHeaders" + } + + interface RequestFilter { + urls: string[]; + types?: ResourceType[]; + tabId?: number; + windowId?: number; + } + + type HttpHeaders = Array<{ + name: string; + value?: string; + binaryValue?: number[]; + }>; + + interface BlockingResponse { + cancel?: boolean; + redirectUrl?: string; + requestHeaders?: HttpHeaders; + responseHeaders?: HttpHeaders; + authCredentials?: { + username: string; + password: string; + }; + } + + interface UploadData { + bytes?: any; + file?: string; + } + + /* webRequest properties */ + const MAX_HANDLER_BEHAVIOR_CHANGED_CALLS_PER_10_MINUTES: number; + + /* webRequest functions */ + function handlerBehaviorChanged(): Promise; + + function filterResponseData(requestId: string): object/*StreamFilter*/; + + /* webRequest events */ + const onBeforeRequest: WebExtEventListener<(details: { + requestId: string; + url: string; + method: string; + frameId: number; + parentFrameId: number; + originUrl?: string; + documentUrl?: string; + requestBody?: { + error?: string; + formData?: object; + raw?: UploadData[]; + }; + tabId: number; + type: ResourceType; + timeStamp: number; + }) => BlockingResponse>; + + const onBeforeSendHeaders: WebExtEventListener<(details: { + requestId: string; + url: string; + method: string; + frameId: number; + parentFrameId: number; + originUrl?: string; + documentUrl?: string; + tabId: number; + type: ResourceType; + timeStamp: number; + requestHeaders?: HttpHeaders; + }) => BlockingResponse>; + + const onSendHeaders: WebExtEventListener<(details: { + requestId: string; + url: string; + method: string; + frameId: number; + parentFrameId: number; + originUrl?: string; + documentUrl?: string; + tabId: number; + type: ResourceType; + timeStamp: number; + requestHeaders?: HttpHeaders; + }) => void>; + + const onHeadersReceived: WebExtEventListener<(details: { + requestId: string; + url: string; + method: string; + frameId: number; + parentFrameId: number; + originUrl?: string; + documentUrl?: string; + tabId: number; + type: ResourceType; + timeStamp: number; + statusLine: string; + responseHeaders?: HttpHeaders; + statusCode: number; + }) => BlockingResponse>; + + const onAuthRequired: WebExtEventListener<(details: { + requestId: string; + url: string; + method: string; + frameId: number; + parentFrameId: number; + originUrl?: string; + documentUrl?: string; + tabId: number; + type: ResourceType; + timeStamp: number; + scheme: string; + realm?: string; + challenger: { + host: string; + port: number; + }; + isProxy: boolean; + responseHeaders?: HttpHeaders; + statusLine: string; + statusCode: number; + }) => BlockingResponse>; + + const onResponseStarted: WebExtEventListener<(details: { + requestId: string; + url: string; + method: string; + frameId: number; + parentFrameId: number; + originUrl?: string; + documentUrl?: string; + tabId: number; + type: ResourceType; + timeStamp: number; + ip?: string; + fromCache: boolean; + statusCode: number; + responseHeaders?: HttpHeaders; + statusLine: string; + }) => void>; + + const onBeforeRedirect: WebExtEventListener<(details: { + requestId: string; + url: string; + method: string; + frameId: number; + parentFrameId: number; + originUrl?: string; + documentUrl?: string; + tabId: number; + type: ResourceType; + timeStamp: number; + ip?: string; + fromCache: boolean; + statusCode: number; + redirectUrl: string; + responseHeaders?: HttpHeaders; + statusLine: string; + }) => void>; + + const onCompleted: WebExtEventListener<(details: { + requestId: string; + url: string; + method: string; + frameId: number; + parentFrameId: number; + originUrl?: string; + documentUrl?: string; + tabId: number; + type: ResourceType; + timeStamp: number; + ip?: string; + fromCache: boolean; + statusCode: number; + responseHeaders?: HttpHeaders; + statusLine: string; + }) => void>; + + const onErrorOccurred: WebExtEventListener<(details: { + requestId: string; + url: string; + method: string; + frameId: number; + parentFrameId: number; + originUrl?: string; + documentUrl?: string; + tabId: number; + type: ResourceType; + timeStamp: number; + ip?: string; + fromCache: boolean; + error: string; + }) => void>; +} + +declare namespace browser.bookmarks { + /* bookmarks types */ + enum BookmarkTreeNodeUnmodifiable { + managed = "managed" + } + + enum BookmarkTreeNodeType { + bookmark = "bookmark", + folder = "folder", + separator = "separator" + } + + interface BookmarkTreeNode { + id: string; + parentId?: string; + index?: number; + url?: string; + title: string; + dateAdded?: number; + dateGroupModified?: number; + unmodifiable?: BookmarkTreeNodeUnmodifiable; + type?: BookmarkTreeNodeType; + children?: BookmarkTreeNode[]; + } + + interface CreateDetails { + parentId?: string; + index?: number; + title?: string; + url?: string; + type?: BookmarkTreeNodeType; + } + + export {_import as import}; + + export {_export as export}; + + /* bookmarks functions */ + function get(idOrIdList: string | string[]): Promise; + + function getChildren(id: string): Promise; + + function getRecent(numberOfItems: number): Promise; + + function getTree(): Promise; + + function getSubTree(id: string): Promise; + + function search(query: string | { + query?: string; + url?: string; + title?: string; + }): Promise; + + function create(bookmark: CreateDetails): Promise; + + function move(id: string, destination: { + parentId?: string; + index?: number; + }): Promise; + + function update(id: string, changes: { + title?: string; + url?: string; + }): Promise; + + function remove(id: string): Promise; + + function removeTree(id: string): Promise; + + const _import: (() => Promise) | undefined; + + const _export: (() => Promise) | undefined; + + /* bookmarks events */ + const onCreated: WebExtEventListener<(id: string, bookmark: BookmarkTreeNode) => void>; + + const onRemoved: WebExtEventListener<(id: string, removeInfo: { + parentId: string; + index: number; + node: BookmarkTreeNode; + }) => void>; + + const onChanged: WebExtEventListener<(id: string, changeInfo: { + title: string; + url?: string; + }) => void>; + + const onMoved: WebExtEventListener<(id: string, moveInfo: { + parentId: string; + index: number; + oldParentId: string; + oldIndex: number; + }) => void>; + + const onChildrenReordered: WebExtEventListener<(id: string, reorderInfo: { + childIds: string[]; + }) => void> | undefined; + + const onImportBegan: WebExtEventListener<() => void> | undefined; + + const onImportEnded: WebExtEventListener<() => void> | undefined; +} + +declare namespace browser.browserAction { + /* browserAction types */ + type ColorArray = [number, number, number, number]; + + type ImageDataType = object/*ImageData*/; + + /* browserAction functions */ + function setTitle(details: { + title: string; + tabId?: number; + }): Promise; + + function getTitle(details: { + tabId?: number; + }): Promise; + + function setIcon(details: { + imageData?: ImageDataType | { + [key: number]: ImageDataType; + }; + path?: string | { + [key: number]: string; + }; + tabId?: number; + }): Promise; + + function setPopup(details: { + tabId?: number; + popup: string; + }): Promise; + + function getPopup(details: { + tabId?: number; + }): Promise; + + function setBadgeText(details: { + text: string; + tabId?: number; + }): Promise; + + function getBadgeText(details: { + tabId?: number; + }): Promise; + + function setBadgeBackgroundColor(details: { + color: string | ColorArray; + tabId?: number; + }): Promise; + + function getBadgeBackgroundColor(details: { + tabId?: number; + }): Promise; + + function enable(tabId?: number): Promise; + + function disable(tabId?: number): Promise; + + function openPopup(): void; + + /* browserAction events */ + const onClicked: WebExtEventListener<(tab: tabs.Tab) => void>; +} + +declare namespace browser.browsingData { + /* browsingData types */ + interface RemovalOptions { + since?: extensionTypes.Date; + hostnames?: string[]; + originTypes?: { + unprotectedWeb?: boolean; + protectedWeb?: boolean; + extension?: boolean; + }; + } + + interface DataTypeSet { + cache?: boolean; + cookies?: boolean; + downloads?: boolean; + formData?: boolean; + history?: boolean; + indexedDB?: boolean; + localStorage?: boolean; + serverBoundCertificates?: boolean; + passwords?: boolean; + pluginData?: boolean; + serviceWorkers?: boolean; + } + + /* browsingData functions */ + function settings(): Promise<{ + options: RemovalOptions; + dataToRemove: DataTypeSet; + dataRemovalPermitted: DataTypeSet; + }>; + + function remove(options: RemovalOptions, dataToRemove: DataTypeSet): Promise; + + const removeAppcache: ((options: RemovalOptions) => Promise) | undefined; + + function removeCache(options: RemovalOptions): Promise; + + function removeCookies(options: RemovalOptions): Promise; + + function removeDownloads(options: RemovalOptions): Promise; + + const removeFileSystems: ((options: RemovalOptions) => Promise) | undefined; + + function removeFormData(options: RemovalOptions): Promise; + + function removeHistory(options: RemovalOptions): Promise; + + const removeIndexedDB: ((options: RemovalOptions) => Promise) | undefined; + + function removeLocalStorage(options: RemovalOptions): Promise; + + function removePluginData(options: RemovalOptions): Promise; + + function removePasswords(options: RemovalOptions): Promise; + + const removeWebSQL: ((options: RemovalOptions) => Promise) | undefined; +} + +declare namespace browser.commands { + /* commands types */ + interface Command { + name?: string; + description?: string; + shortcut?: string; + } + + /* commands functions */ + function getAll(): Promise; + + /* commands events */ + const onCommand: WebExtEventListener<(command: string) => void>; +} + +declare namespace browser.devtools { +} + +declare namespace browser.devtools.inspectedWindow { + /* devtools.inspectedWindow types */ + class Resource { + url: string; + + getContent?(): Promise; + + setContent?(content: string, commit: boolean): Promise; + } + + /* devtools.inspectedWindow properties */ + const tabId: number; + + /* devtools.inspectedWindow functions */ + function eval(expression: string, options?: { + frameURL?: string; + useContentScriptContext?: boolean; + contextSecurityOrigin?: string; + }): Promise; + + function reload(reloadOptions?: { + ignoreCache?: boolean; + userAgent?: string; + injectedScript?: string; + preprocessorScript?: string; + }): void; + + const getResources: (() => Promise) | undefined; + + /* devtools.inspectedWindow events */ + const onResourceAdded: WebExtEventListener<(resource: Resource) => void> | undefined; + + const onResourceContentCommitted: WebExtEventListener<(resource: Resource, content: string) => void> | undefined; +} + +declare namespace browser.devtools.network { + /* devtools.network types */ + class Request { + getContent(): Promise; + } + + /* devtools.network functions */ + const getHAR: (() => Promise) | undefined; + + /* devtools.network events */ + const onRequestFinished: WebExtEventListener<(request: Request) => void> | undefined; + + const onNavigated: WebExtEventListener<(url: string) => void>; +} + +declare namespace browser.devtools.panels { + /* devtools.panels types */ + class ElementsPanel { + createSidebarPane(title: string): Promise; + + onSelectionChanged: WebExtEventListener<() => void>; + } + + class SourcesPanel { + createSidebarPane?(title: string): void; + + onSelectionChanged: WebExtEventListener<() => void>; + } + + class ExtensionPanel { + createStatusBarButton?(iconPath: string, tooltipText: string, disabled: boolean): Button; + + onSearch: WebExtEventListener<(action: string, queryString?: string) => void>; + onShown: WebExtEventListener<(window: object/*global*/) => void>; + onHidden: WebExtEventListener<() => void>; + } + + class ExtensionSidebarPane { + setHeight?(height: string): void; + + setExpression(expression: string, rootTitle?: string): Promise; + + setObject(jsonObject: string, rootTitle?: string): Promise; + + setPage?(path: string): void; + + onShown: WebExtEventListener<(window: object/*global*/) => void>; + onHidden: WebExtEventListener<() => void>; + } + + class Button { + update?(tooltipText?: string, disabled?: boolean): void; + update?(disabled?: boolean): void; + update?(iconPath: string, tooltipText: string, disabled?: boolean): void; + + onClicked: WebExtEventListener<() => void>; + } + + /* devtools.panels properties */ + const elements: ElementsPanel; + + const sources: SourcesPanel; + + const themeName: string; + + /* devtools.panels functions */ + function create(title: string, iconPath: string, pagePath: string): Promise; + + const setOpenResourceHandler: (() => Promise) | undefined; + + const openResource: ((url: string, lineNumber: number) => Promise) | undefined; + + /* devtools.panels events */ + const onThemeChanged: WebExtEventListener<(themeName: string) => void>; +} + +declare namespace browser.find { + /* find functions */ + function find(queryphrase: string, params?: { + tabId?: number; + caseSensitive?: boolean; + entireWord?: boolean; + includeRectData?: boolean; + includeRangeData?: boolean; + }): void; + + function highlightResults(params?: { + rangeIndex?: number; + tabId?: number; + noScroll?: boolean; + }): void; + + function removeHighlighting(tabId?: number): void; +} + +declare namespace browser.geckoProfiler { + /* geckoProfiler types */ + enum ProfilerFeature { + java = "java", + js = "js", + leaf = "leaf", + mainthreadio = "mainthreadio", + memory = "memory", + privacy = "privacy", + restyle = "restyle", + stackwalk = "stackwalk", + tasktracer = "tasktracer", + threads = "threads" + } + + /* geckoProfiler functions */ + function start(settings: { + bufferSize: number; + interval: number; + features: ProfilerFeature[]; + threads?: string[]; + }): void; + + function stop(): void; + + function pause(): void; + + function resume(): void; + + function getProfile(): void; + + function getProfileAsArrayBuffer(): void; + + function getSymbols(debugName: string, breakpadId: string): void; + + /* geckoProfiler events */ + const onRunning: WebExtEventListener<(isRunning: boolean) => void>; +} + +declare namespace browser.history { + /* history types */ + enum TransitionType { + link = "link", + typed = "typed", + auto_bookmark = "auto_bookmark", + auto_subframe = "auto_subframe", + manual_subframe = "manual_subframe", + generated = "generated", + auto_toplevel = "auto_toplevel", + form_submit = "form_submit", + reload = "reload", + keyword = "keyword", + keyword_generated = "keyword_generated" + } + + interface HistoryItem { + id: string; + url?: string; + title?: string; + lastVisitTime?: number; + visitCount?: number; + typedCount?: number; + } + + interface VisitItem { + id: string; + visitId: string; + visitTime?: number; + referringVisitId: string; + transition: TransitionType; + } + + /* history functions */ + function search(query: { + text: string; + startTime?: extensionTypes.Date; + endTime?: extensionTypes.Date; + maxResults?: number; + }): Promise; + + function getVisits(details: { + url: string; + }): Promise; + + function addUrl(details: { + url: string; + title?: string; + transition?: TransitionType; + visitTime?: extensionTypes.Date; + }): Promise; + + function deleteUrl(details: { + url: string; + }): Promise; + + function deleteRange(range: { + startTime: extensionTypes.Date; + endTime: extensionTypes.Date; + }): Promise; + + function deleteAll(): Promise; + + /* history events */ + const onVisited: WebExtEventListener<(result: HistoryItem) => void>; + + const onVisitRemoved: WebExtEventListener<(removed: { + allHistory: boolean; + urls: string[]; + }) => void>; + + const onTitleChanged: WebExtEventListener<(changed: { + url: string; + title: string; + }) => void>; +} + +declare namespace browser.contextMenus { + /* contextMenus types */ + enum ContextType { + all = "all", + page = "page", + frame = "frame", + selection = "selection", + link = "link", + editable = "editable", + password = "password", + image = "image", + video = "video", + audio = "audio", + launcher = "launcher", + browser_action = "browser_action", + page_action = "page_action", + tab = "tab" + } + + enum ItemType { + normal = "normal", + checkbox = "checkbox", + radio = "radio", + separator = "separator" + } + + interface OnClickData { + menuItemId: number | string; + parentMenuItemId?: number | string; + mediaType?: string; + linkText?: string; + linkUrl?: string; + srcUrl?: string; + pageUrl?: string; + frameUrl?: string; + selectionText?: string; + editable: boolean; + wasChecked?: boolean; + checked?: boolean; + modifiers: _OnClickDataModifiers[]; + } + + enum _OnClickDataModifiers { + Shift = "Shift", + Alt = "Alt", + Command = "Command", + Ctrl = "Ctrl", + MacCtrl = "MacCtrl" + } + + /* contextMenus properties */ + const ACTION_MENU_TOP_LEVEL_LIMIT: number; + + /* contextMenus functions */ + function create(createProperties: { + type?: ItemType; + id?: string; + icons?: { + [key: number]: string; + }; + title?: string; + checked?: boolean; + contexts?: ContextType[]; + onclick?: (info: menusInternal.OnClickData, tab: tabs.Tab) => void; + parentId?: number | string; + documentUrlPatterns?: string[]; + targetUrlPatterns?: string[]; + enabled?: boolean; + command?: string; + }): number | string; + + function update(id: number | string, updateProperties: { + type?: ItemType; + title?: string; + checked?: boolean; + contexts?: ContextType[]; + onclick?: (info: menusInternal.OnClickData, tab: tabs.Tab) => void; + parentId?: number | string; + documentUrlPatterns?: string[]; + targetUrlPatterns?: string[]; + enabled?: boolean; + }): Promise; + + function remove(menuItemId: number | string): Promise; + + function removeAll(): Promise; + + /* contextMenus events */ + const onClicked: WebExtEventListener<(info: OnClickData, tab?: tabs.Tab) => void>; +} + +declare namespace browser.menus { + /* menus types */ + enum ContextType { + all = "all", + page = "page", + frame = "frame", + selection = "selection", + link = "link", + editable = "editable", + password = "password", + image = "image", + video = "video", + audio = "audio", + launcher = "launcher", + browser_action = "browser_action", + page_action = "page_action", + tab = "tab", + tools_menu = "tools_menu" + } + + enum ItemType { + normal = "normal", + checkbox = "checkbox", + radio = "radio", + separator = "separator" + } + + interface OnClickData { + menuItemId: number | string; + parentMenuItemId?: number | string; + mediaType?: string; + linkText?: string; + linkUrl?: string; + srcUrl?: string; + pageUrl?: string; + frameUrl?: string; + selectionText?: string; + editable: boolean; + wasChecked?: boolean; + checked?: boolean; + modifiers: _OnClickDataModifiers[]; + } + + enum _OnClickDataModifiers { + Shift = "Shift", + Alt = "Alt", + Command = "Command", + Ctrl = "Ctrl", + MacCtrl = "MacCtrl" + } + + /* menus properties */ + const ACTION_MENU_TOP_LEVEL_LIMIT: number; + + /* menus functions */ + function create(createProperties: { + type?: ItemType; + id?: string; + icons?: { + [key: number]: string; + }; + title?: string; + checked?: boolean; + contexts?: ContextType[]; + onclick?: (info: menusInternal.OnClickData, tab: tabs.Tab) => void; + parentId?: number | string; + documentUrlPatterns?: string[]; + targetUrlPatterns?: string[]; + enabled?: boolean; + command?: string; + }): number | string; + + function update(id: number | string, updateProperties: { + type?: ItemType; + title?: string; + checked?: boolean; + contexts?: ContextType[]; + onclick?: (info: menusInternal.OnClickData, tab: tabs.Tab) => void; + parentId?: number | string; + documentUrlPatterns?: string[]; + targetUrlPatterns?: string[]; + enabled?: boolean; + }): Promise; + + function remove(menuItemId: number | string): Promise; + + function removeAll(): Promise; + + /* menus events */ + const onClicked: WebExtEventListener<(info: OnClickData, tab?: tabs.Tab) => void>; +} + +declare namespace browser.menusInternal { + /* menusInternal types */ + interface OnClickData { + menuItemId: number | string; + parentMenuItemId?: number | string; + mediaType?: string; + linkUrl?: string; + srcUrl?: string; + pageUrl?: string; + frameUrl?: string; + selectionText?: string; + editable: boolean; + wasChecked?: boolean; + checked?: boolean; + } +} + +declare namespace browser.omnibox { + /* omnibox types */ + enum DescriptionStyleType { + url = "url", + match = "match", + dim = "dim" + } + + enum OnInputEnteredDisposition { + currentTab = "currentTab", + newForegroundTab = "newForegroundTab", + newBackgroundTab = "newBackgroundTab" + } + + interface SuggestResult { + content: string; + description: string; + descriptionStyles?: Array<{ + offset: number; + type: DescriptionStyleType; + length?: number; + }>; + descriptionStylesRaw?: Array<{ + offset: number; + type: number; + }>; + } + + interface DefaultSuggestResult { + description: string; + descriptionStyles?: Array<{ + offset: number; + type: DescriptionStyleType; + length?: number; + }>; + descriptionStylesRaw?: Array<{ + offset: number; + type: number; + }>; + } + + /* omnibox functions */ + function setDefaultSuggestion(suggestion: DefaultSuggestResult): void; + + /* omnibox events */ + const onInputStarted: WebExtEventListener<() => void>; + + const onInputChanged: WebExtEventListener<(text: string, suggest: (suggestResults: SuggestResult[]) => void) => void>; + + const onInputEntered: WebExtEventListener<(text: string, disposition: OnInputEnteredDisposition) => void>; + + const onInputCancelled: WebExtEventListener<() => void>; +} + +declare namespace browser.pageAction { + /* pageAction types */ + type ImageDataType = object/*ImageData*/; + + /* pageAction functions */ + function show(tabId: number): Promise; + + function hide(tabId: number): Promise; + + function setTitle(details: { + tabId: number; + title: string; + }): void; + + function getTitle(details: { + tabId: number; + }): Promise; + + function setIcon(details: { + tabId: number; + imageData?: ImageDataType | { + [key: number]: ImageDataType; + }; + path?: string | { + [key: number]: string; + }; + }): Promise; + + function setPopup(details: { + tabId: number; + popup: string; + }): void; + + function getPopup(details: { + tabId: number; + }): Promise; + + function openPopup(): void; + + /* pageAction events */ + const onClicked: WebExtEventListener<(tab: tabs.Tab) => void>; +} + +declare namespace browser.pkcs11 { + /* pkcs11 functions */ + function isModuleInstalled(name: string): void; + + function installModule(name: string, flags?: number): void; + + function uninstallModule(name: string): void; + + function getModuleSlots(name: string): void; +} + +declare namespace browser.sessions { + /* sessions types */ + interface Filter { + maxResults?: number; + } + + interface Session { + lastModified: number; + tab?: tabs.Tab; + window?: windows.Window; + } + + interface Device { + info: string; + deviceName: string; + sessions: Session[]; + } + + /* sessions properties */ + const MAX_SESSION_RESULTS: number; + + /* sessions functions */ + function forgetClosedTab(windowId: number, sessionId: string): void; + + function forgetClosedWindow(sessionId: string): void; + + function getRecentlyClosed(filter?: Filter): Promise; + + const getDevices: ((filter?: Filter) => Promise) | undefined; + + function restore(sessionId?: string): Promise; + + function setTabValue(tabId: number, key: string, value: any): void; + + function getTabValue(tabId: number, key: string): void; + + function removeTabValue(tabId: number, key: string): void; + + function setWindowValue(windowId: number, key: string, value: any): void; + + function getWindowValue(windowId: number, key: string): void; + + function removeWindowValue(windowId: number, key: string): void; + + /* sessions events */ + const onChanged: WebExtEventListener<() => void>; +} + +declare namespace browser.sidebarAction { + /* sidebarAction types */ + type ImageDataType = object/*ImageData*/; + + /* sidebarAction functions */ + function setTitle(details: { + title: string; + tabId?: number; + }): void; + + function getTitle(details: { + tabId?: number; + }): void; + + function setIcon(details: { + imageData?: ImageDataType | { + [key: number]: ImageDataType; + }; + path?: string; + tabId?: number; + }): void; + + function setPanel(details: { + tabId?: number; + panel: string; + }): void; + + function getPanel(details: { + tabId?: number; + }): void; + + function open(): void; + + function close(): void; +} + +declare namespace browser.tabs { + /* tabs types */ + enum MutedInfoReason { + user = "user", + capture = "capture", + extension = "extension" + } + + interface MutedInfo { + muted: boolean; + reason?: MutedInfoReason; + extensionId?: string; + } + + interface Tab { + id?: number; + index: number; + windowId?: number; + openerTabId?: number; + selected?: boolean; + highlighted: boolean; + active: boolean; + pinned: boolean; + lastAccessed?: number; + audible?: boolean; + mutedInfo?: MutedInfo; + url?: string; + title?: string; + favIconUrl?: string; + status?: string; + discarded?: boolean; + incognito: boolean; + width?: number; + height?: number; + sessionId?: string; + cookieStoreId?: string; + isArticle?: boolean; + isInReaderMode?: boolean; + } + + enum ZoomSettingsMode { + automatic = "automatic", + manual = "manual", + disabled = "disabled" + } + + enum ZoomSettingsScope { + perorigin = "per-origin", + pertab = "per-tab" + } + + interface ZoomSettings { + mode?: ZoomSettingsMode; + scope?: ZoomSettingsScope; + defaultZoomFactor?: number; + } + + interface PageSettings { + orientation?: number; + scaling?: number; + shrinkToFit?: boolean; + showBackgroundColors?: boolean; + showBackgroundImages?: boolean; + paperSizeUnit?: number; + paperWidth?: number; + paperHeight?: number; + headerLeft?: string; + headerCenter?: string; + headerRight?: string; + footerLeft?: string; + footerCenter?: string; + footerRight?: string; + marginLeft?: number; + marginRight?: number; + marginTop?: number; + marginBottom?: number; + } + + enum TabStatus { + loading = "loading", + complete = "complete" + } + + enum WindowType { + normal = "normal", + popup = "popup", + panel = "panel", + app = "app", + devtools = "devtools" + } + + /* tabs properties */ + const TAB_ID_NONE: number; + + /* tabs functions */ + function get(tabId: number): Promise; + + function getCurrent(): Promise; + + function connect(tabId: number, connectInfo?: { + name?: string; + frameId?: number; + }): runtime.Port; + + const sendRequest: ((tabId: number, request: any, responseCallback?: (response: any) => void) => void) | undefined; + + function sendMessage(tabId: number, message: any, options: { + frameId?: number; + }, responseCallback?: (response: any) => void): void; + + const getSelected: ((windowId?: number) => Promise) | undefined; + + const getAllInWindow: ((windowId?: number) => Promise) | undefined; + + function create(createProperties: { + windowId?: number; + index?: number; + url?: string; + active?: boolean; + selected?: boolean; + pinned?: boolean; + openerTabId?: number; + cookieStoreId?: string; + openInReaderMode?: boolean; + }): Promise; + + function duplicate(tabId: number): Promise; + + function query(queryInfo: { + active?: boolean; + pinned?: boolean; + audible?: boolean; + muted?: boolean; + highlighted?: boolean; + currentWindow?: boolean; + lastFocusedWindow?: boolean; + status?: TabStatus; + discarded?: boolean; + title?: string; + url?: string | string[]; + windowId?: number; + windowType?: WindowType; + index?: number; + cookieStoreId?: string; + openerTabId?: number; + }): Promise; + + const highlight: ((highlightInfo: { + windowId?: number; + tabs: number[] | number; + }) => Promise) | undefined; + + function update(updateProperties: { + url?: string; + active?: boolean; + highlighted?: boolean; + selected?: boolean; + pinned?: boolean; + muted?: boolean; + openerTabId?: number; + loadReplace?: boolean; + }): Promise; + function update(tabId: number, updateProperties: { + url?: string; + active?: boolean; + highlighted?: boolean; + selected?: boolean; + pinned?: boolean; + muted?: boolean; + openerTabId?: number; + loadReplace?: boolean; + }): Promise; + + function move(tabIds: number | number[], moveProperties: { + windowId?: number; + index: number; + }): Promise; + + function reload(reloadProperties?: { + bypassCache?: boolean; + }): Promise; + function reload(tabId: number, reloadProperties?: { + bypassCache?: boolean; + }): Promise; + + function remove(tabIds: number | number[]): Promise; + + function discard(tabIds: number | number[]): void; + + function detectLanguage(tabId?: number): Promise; + + function toggleReaderMode(tabId?: number): void; + + function captureVisibleTab(options?: extensionTypes.ImageDetails): Promise; + function captureVisibleTab(windowId: number, options?: extensionTypes.ImageDetails): Promise; + + function executeScript(details: extensionTypes.InjectDetails): Promise; + function executeScript(tabId: number, details: extensionTypes.InjectDetails): Promise; + + function insertCSS(details: extensionTypes.InjectDetails): Promise; + function insertCSS(tabId: number, details: extensionTypes.InjectDetails): Promise; + + function removeCSS(details: extensionTypes.InjectDetails): Promise; + function removeCSS(tabId: number, details: extensionTypes.InjectDetails): Promise; + + function setZoom(zoomFactor: number): Promise; + function setZoom(tabId: number, zoomFactor: number): Promise; + + function getZoom(tabId?: number): Promise; + + function setZoomSettings(zoomSettings: ZoomSettings): Promise; + function setZoomSettings(tabId: number, zoomSettings: ZoomSettings): Promise; + + function getZoomSettings(tabId?: number): Promise; + + function print(): void; + + function printPreview(): Promise; + + function saveAsPDF(pageSettings: PageSettings): Promise; + + /* tabs events */ + const onCreated: WebExtEventListener<(tab: Tab) => void>; + + const onUpdated: WebExtEventListener<(tabId: number, changeInfo: { + status: string; + discarded?: boolean; + url?: string; + pinned?: boolean; + audible?: boolean; + mutedInfo?: MutedInfo; + favIconUrl?: string; + }, tab: Tab) => void>; + + const onMoved: WebExtEventListener<(tabId: number, moveInfo: { + windowId: number; + fromIndex: number; + toIndex: number; + }) => void>; + + const onSelectionChanged: WebExtEventListener<(tabId: number, selectInfo: { + windowId: number; + }) => void> | undefined; + + const onActiveChanged: WebExtEventListener<(tabId: number, selectInfo: { + windowId: number; + }) => void> | undefined; + + const onActivated: WebExtEventListener<(activeInfo: { + tabId: number; + windowId: number; + }) => void>; + + const onHighlightChanged: WebExtEventListener<(selectInfo: { + windowId: number; + tabIds: number[]; + }) => void> | undefined; + + const onHighlighted: WebExtEventListener<(highlightInfo: { + windowId: number; + tabIds: number[]; + }) => void>; + + const onDetached: WebExtEventListener<(tabId: number, detachInfo: { + oldWindowId: number; + oldPosition: number; + }) => void>; + + const onAttached: WebExtEventListener<(tabId: number, attachInfo: { + newWindowId: number; + newPosition: number; + }) => void>; + + const onRemoved: WebExtEventListener<(tabId: number, removeInfo: { + windowId: number; + isWindowClosing: boolean; + }) => void>; + + const onReplaced: WebExtEventListener<(addedTabId: number, removedTabId: number) => void>; + + const onZoomChange: WebExtEventListener<(ZoomChangeInfo: { + tabId: number; + oldZoomFactor: number; + newZoomFactor: number; + zoomSettings: ZoomSettings; + }) => void>; +} + +declare namespace browser.windows { + /* windows types */ + enum WindowType { + normal = "normal", + popup = "popup", + panel = "panel", + app = "app", + devtools = "devtools" + } + + enum WindowState { + normal = "normal", + minimized = "minimized", + maximized = "maximized", + fullscreen = "fullscreen", + docked = "docked" + } + + interface Window { + id?: number; + focused: boolean; + top?: number; + left?: number; + width?: number; + height?: number; + tabs?: tabs.Tab[]; + incognito: boolean; + type?: WindowType; + state?: WindowState; + alwaysOnTop: boolean; + sessionId?: string; + title?: string; + } + + enum CreateType { + normal = "normal", + popup = "popup", + panel = "panel", + detached_panel = "detached_panel" + } + + /* windows properties */ + const WINDOW_ID_NONE: number; + + const WINDOW_ID_CURRENT: number; + + /* windows functions */ + function get(windowId: number, getInfo?: { + populate?: boolean; + windowTypes?: WindowType[]; + }): Promise; + + function getCurrent(getInfo?: { + populate?: boolean; + windowTypes?: WindowType[]; + }): Promise; + + function getLastFocused(getInfo?: { + populate?: boolean; + windowTypes?: WindowType[]; + }): Promise; + + function getAll(getInfo?: { + populate?: boolean; + windowTypes?: WindowType[]; + }): Promise; + + function create(createData?: { + url?: string | string[]; + tabId?: number; + left?: number; + top?: number; + width?: number; + height?: number; + focused?: boolean; + incognito?: boolean; + type?: CreateType; + state?: WindowState; + allowScriptsToClose?: boolean; + titlePreface?: string; + }): Promise; + + function update(windowId: number, updateInfo: { + left?: number; + top?: number; + width?: number; + height?: number; + focused?: boolean; + drawAttention?: boolean; + state?: WindowState; + titlePreface?: string; + }): Promise; + + function remove(windowId: number): Promise; + + /* windows events */ + const onCreated: WebExtEventListener<(window: Window) => void>; + + const onRemoved: WebExtEventListener<(windowId: number) => void>; + + const onFocusChanged: WebExtEventListener<(windowId: number) => void>; +} diff --git a/types/firefox-webext-browser/tsconfig.json b/types/firefox-webext-browser/tsconfig.json new file mode 100644 index 0000000000..202f6824d1 --- /dev/null +++ b/types/firefox-webext-browser/tsconfig.json @@ -0,0 +1,24 @@ +{ + "compilerOptions": { + "module": "commonjs", + "lib": [ + "es6", + "dom" + ], + "noImplicitAny": true, + "noImplicitThis": true, + "strictNullChecks": true, + "strictFunctionTypes": true, + "baseUrl": "../", + "typeRoots": [ + "../" + ], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true + }, + "files": [ + "index.d.ts", + "firefox-webext-browser-tests.ts" + ] +} diff --git a/types/firefox-webext-browser/tslint.json b/types/firefox-webext-browser/tslint.json new file mode 100644 index 0000000000..c94feb08d9 --- /dev/null +++ b/types/firefox-webext-browser/tslint.json @@ -0,0 +1,8 @@ +{ + "extends": "dtslint/dt.json", + "rules": { + "no-mergeable-namespace": false, + "unified-signatures": false, + "no-unnecessary-qualifier": false + } +} diff --git a/types/first-mate/index.d.ts b/types/first-mate/index.d.ts index c7df2365c3..2fcc7141cb 100644 --- a/types/first-mate/index.d.ts +++ b/types/first-mate/index.d.ts @@ -2,7 +2,7 @@ // Project: https://github.com/atom/first-mate/ // Definitions by: GlenCFL // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -// TypeScript Version: 2.2 +// TypeScript Version: 2.3 import { Disposable } from "event-kit"; diff --git a/types/fixed-data-table-2/fixed-data-table-2-tests.tsx b/types/fixed-data-table-2/fixed-data-table-2-tests.tsx new file mode 100644 index 0000000000..3b34d6a44a --- /dev/null +++ b/types/fixed-data-table-2/fixed-data-table-2-tests.tsx @@ -0,0 +1,196 @@ +/** + * The tests are based on tests from types/fixed-data-table + */ + +import * as React from "react"; +import { Table, Cell, Column, CellProps } from "fixed-data-table-2"; + +// create your Table +class MyTable1 extends React.Component { + render() { + return ( + + // add columns +
+ ); + } +} + +// create your Columns +class MyTable2 extends React.Component { + render() { + return ( + + Basic content} + width={200} + /> +
+ ); + } +} + +// provide Custom Data +interface MyTable3State { + myTableData: Array<{ name: string }>; +} + +class MyTable3 extends React.Component<{}, MyTable3State> { + constructor(props: {}) { + super(props); + + this.state = { + myTableData: [ + { name: "Rylan" }, + { name: "Amelia" }, + { name: "Estevan" }, + { name: "Florence" }, + { name: "Tressa" }, + ] + }; + } + + render() { + return ( + + Name} + cell={(props) => ( + + {this.state.myTableData[props.rowIndex].name} + + )} + width={200} + /> +
+ ); + } +} + +// Create Reusable Cells +interface RowData { + [field: string]: string; +} + +interface MyCellProps extends CellProps { + field: string; + myData: RowData[]; +} + +class MyTextCell extends React.Component { + render() { + const { rowIndex, field, myData } = this.props; + + return ( + + {myData[rowIndex!][field]} + + ); + } +} + +class MyLinkCell extends React.Component { + render() { + const { rowIndex, field, myData } = this.props; + const link: string = myData[rowIndex!][field]; + + return ( + + {link} + + ); + } +} + +interface MyTable4State { + tableData: RowData[]; +} + +class MyTable4 extends React.Component<{}, MyTable4State> { + constructor(props: {}) { + super(props); + this.state = { + tableData: [ + { name: "Rylan", email: "Angelita_Weimann42@gmail.com" }, + { name: "Amelia", email: "Dexter.Trantow57@hotmail.com" }, + { name: "Estevan", email: "Aimee7@hotmail.com" }, + { name: "Florence", email: "Jarrod.Bernier13@yahoo.com" }, + { name: "Tressa", email: "Yadira1@hotmail.com" } + ] + }; + } + + render() { + return ( + + { + ["name", "email"].map(field => + {field}} + cell={ + + } + width={200} /> + ) + } +
+ ); + } +} + +// Listen for events +class MyTable5 extends React.Component { + render() { + return ( + { }} + onScrollEnd={(x: number, y: number) => { }} + onContentHeightChange={(newHeight: number) => { }} + onRowClick={(event: React.SyntheticEvent
, rowIndex: number) => { }} + onRowDoubleClick={(event: React.SyntheticEvent
, rowIndex: number) => { }} + onRowMouseDown={(event: React.SyntheticEvent
, rowIndex: number) => { }} + onRowMouseEnter={(event: React.SyntheticEvent
, rowIndex: number) => { }} + onRowMouseLeave={(event: React.SyntheticEvent
, rowIndex: number) => { }} + onColumnResizeEndCallback={(newColumnWidth: number, columnKey: string) => { }}> + // add columns +
+ ); + } +} diff --git a/types/fixed-data-table-2/index.d.ts b/types/fixed-data-table-2/index.d.ts new file mode 100644 index 0000000000..a39397a228 --- /dev/null +++ b/types/fixed-data-table-2/index.d.ts @@ -0,0 +1,677 @@ +// Type definitions for fixed-data-table-2 0.8 +// Project: https://github.com/schrodinger/fixed-data-table-2 +// Definitions by: Ilya Petukhov +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.3 + +import * as React from "react"; + +export as namespace FixedDataTable; + +export interface RowProps { + /** the row index */ + rowIndex: number; + + /** supplied from the Table or rowHeightGetter */ + height: number; + + /** supplied from the Table */ + width: number; +} + +export interface ColumnReorderEndEvent { + /** the column before the new location of this one */ + columnBefore?: string; + + /** the column after the new location of this one */ + columnAfter?: string; + + /** the column key that was just reordered */ + reorderColumn: string; +} + +export type ElementOrFunc

= string | React.ReactElement | ((props: P) => (string | React.ReactElement)); + +export type TableRowEventHandler = (event: React.SyntheticEvent, rowIndex: number) => void; + +/** + * Data grid component with fixed or scrollable header and columns. + * + * The layout of the data table is as follows: + * + * ``` + * +---------------------------------------------------+ + * | Fixed Column Group | Scrollable Column Group | + * | Header | Header | + * | | | + * +---------------------------------------------------+ + * | | | + * | Fixed Header Columns | Scrollable Header Columns | + * | | | + * +-----------------------+---------------------------+ + * | | | + * | Fixed Body Columns | Scrollable Body Columns | + * | | | + * +-----------------------+---------------------------+ + * | | | + * | Fixed Footer Columns | Scrollable Footer Columns | + * | | | + * +-----------------------+---------------------------+ + * ``` + * + * - Fixed Column Group Header: These are the headers for a group + * of columns if included in the table that do not scroll + * vertically or horizontally. + * + * - Scrollable Column Group Header: The header for a group of columns + * that do not move while scrolling vertically, but move horizontally + * with the horizontal scrolling. + * + * - Fixed Header Columns: The header columns that do not move while scrolling + * vertically or horizontally. + * + * - Scrollable Header Columns: The header columns that do not move + * while scrolling vertically, but move horizontally with the horizontal + * scrolling. + * + * - Fixed Body Columns: The body columns that do not move while scrolling + * horizontally, but move vertically with the vertical scrolling. + * + * - Scrollable Body Columns: The body columns that move while scrolling + * vertically or horizontally. + */ +export interface TableProps extends React.ClassAttributes
{ + /** + * Pixel width of table. If all columns do not fit, + * a horizontal scrollbar will appear. + */ + width: number; + + /** + * Pixel height of table. If all rows do not fit, + * a vertical scrollbar will appear. + * + * Either `height` or `maxHeight` must be specified. + */ + height?: number; + + /** + * Class name to be passed into parent container + */ + className?: string; + + /** + * Maximum pixel height of table. If all rows do not fit, + * a vertical scrollbar will appear. + * + * Either `height` or `maxHeight` must be specified. + */ + maxHeight?: number; + + /** + * Pixel height of table's owner, this is used in a managed scrolling + * situation when you want to slide the table up from below the fold + * without having to constantly update the height on every scroll tick. + * Instead, vary this property on scroll. By using `ownerHeight`, we + * over-render the table while making sure the footer and horizontal + * scrollbar of the table are visible when the current space for the table + * in view is smaller than the final, over-flowing height of table. It + * allows us to avoid resizing and reflowing table when it is moving in the + * view. + * + * This is used if `ownerHeight < height` (or `maxHeight`). + */ + ownerHeight?: number; + + overflowX?: 'hidden' | 'auto'; + overflowY?: 'hidden' | 'auto'; + + /** + * Boolean flag indicating of touch scrolling should be enabled + * This feature is current in beta and may have bugs + */ + touchScrollEnabled?: boolean; + + /** Boolean flags to control if scrolling with keys is enabled */ + keyboardScrollEnabled?: boolean; + /** Boolean flags to control if scrolling with keys is enabled */ + keyboardPageEnabled?: boolean; + + /** Hide the scrollbar but still enable scroll functionality */ + showScrollbarX?: boolean; + /** Hide the scrollbar but still enable scroll functionality */ + showScrollbarY?: boolean; + + /** + * Callback when horizontally scrolling the grid. + * + * Return false to stop propagation. + */ + onHorizontalScroll?: (scrollPos: number) => boolean; + + /** + * Callback when vertically scrolling the grid. + * + * Return false to stop propagation. + */ + onVerticalScroll?: (scrollPos: number) => boolean; + + /** + * Number of rows in the table. + */ + rowsCount: number; + + /** + * Pixel height of rows unless `rowHeightGetter` is specified and returns + * different value. + */ + rowHeight: number; + + /** + * If specified, `rowHeightGetter(index)` is called for each row and the + * returned value overrides `rowHeight` for particular row. + */ + rowHeightGetter?: (index: number) => number; + + /** + * Pixel height of sub-row unless `subRowHeightGetter` is specified and returns + * different value. Defaults to 0 and no sub-row being displayed. + */ + subRowHeight?: number; + + /** + * If specified, `subRowHeightGetter(index)` is called for each row and the + * returned value overrides `subRowHeight` for particular row. + */ + subRowHeightGetter?: (index: number) => number; + + /** + * The row expanded for table row. + * This can either be a React element, or a function that generates + * a React Element. By default, the React element passed in can expect to + * receive the following props: + * + * ``` + * props: { + * rowIndex; number // (the row index) + * height: number // (supplied from the Table or rowHeightGetter) + * width: number // (supplied from the Table) + * } + * ``` + * + * Because you are passing in your own React element, you can feel free to + * pass in whatever props you may want or need. + * + * If you pass in a function, you will receive the same props object as the + * first argument. + */ + rowExpanded?: ElementOrFunc; + + /** + * To get any additional CSS classes that should be added to a row, + * `rowClassNameGetter(index)` is called. + */ + rowClassNameGetter?: (index: number) => string; + + /** + * If specified, `rowKeyGetter(index)` is called for each row and the + * returned value overrides `key` for the particular row. + */ + rowKeyGetter?: (index: number) => string; + + /** + * Pixel height of the column group header. + */ + groupHeaderHeight?: number; + + /** + * Pixel height of header. + */ + headerHeight: number; + + /** + * Pixel height of fixedDataTableCellGroupLayout/cellGroupWrapper. + * Default is headerHeight and groupHeaderHeight. + * + * This can be used with CSS to make a header cell span both the group & normal header row. + * Setting this to a value larger than height will cause the content to + * overflow the height. This is useful when adding a 2nd table as the group + * header and vertically merging the 2 headers when a column is not part + * of a group. Here are the necessary CSS changes: + * + * Both headers: + * - cellGroupWrapper needs overflow-x: hidden and pointer-events: none + * - cellGroup needs pointer-events: auto to reenable them on child els + * Group header: + * - Layout/main needs overflow: visible and a higher z-index + * - CellLayout/main needs overflow-y: visible + * - cellGroup needs overflow: visible + */ + cellGroupWrapperHeight?: number; + + /** + * Pixel height of footer. + */ + footerHeight?: number; + + /** + * Value of horizontal scroll. + */ + scrollLeft?: number; + + /** + * Index of column to scroll to. + */ + scrollToColumn?: number; + + /** + * Value of vertical scroll. + */ + scrollTop?: number; + + /** + * Index of row to scroll to. + */ + scrollToRow?: number; + + /** + * Callback that is called when scrolling starts with current horizontal + * and vertical scroll values. + */ + onScrollStart?: (x: number, y: number) => void; + + /** + * Callback that is called when scrolling ends or stops with new horizontal + * and vertical scroll values. + */ + onScrollEnd?: (x: number, y: number) => void; + + /** + * If enabled scroll events will not be propagated outside of the table. + */ + stopScrollPropagation?: boolean; + + /** + * Callback that is called when `rowHeightGetter` returns a different height + * for a row than the `rowHeight` prop. This is necessary because initially + * table estimates heights of some parts of the content. + */ + onContentHeightChange?: (newHeight: number) => void; + + /** + * Callback that is called when a row is clicked. + */ + onRowClick?: TableRowEventHandler; + + /** + * Callback that is called when a row is double clicked. + */ + onRowDoubleClick?: TableRowEventHandler; + + /** + * Callback that is called when a mouse-down event happens on a row. + */ + onRowMouseDown?: TableRowEventHandler; + + /** + * Callback that is called when a mouse-up event happens on a row. + */ + onRowMouseUp?: TableRowEventHandler; + + /** + * Callback that is called when a mouse-enter event happens on a row. + */ + onRowMouseEnter?: TableRowEventHandler; + + /** + * Callback that is called when a mouse-leave event happens on a row. + */ + onRowMouseLeave?: TableRowEventHandler; + + /** + * Callback that is called when a touch-start event happens on a row. + */ + onRowTouchStart?: TableRowEventHandler; + + /** + * Callback that is called when a touch-end event happens on a row. + */ + onRowTouchEnd?: TableRowEventHandler; + + /** + * Callback that is called when a touch-move event happens on a row. + */ + onRowTouchMove?: TableRowEventHandler; + + /** + * Callback that is called when resizer has been released + * and column needs to be updated. + * + * Required if the isResizable property is true on any column. + * + * ``` + * function( + * newColumnWidth: number, + * columnKey: string, + * ) + * ``` + */ + onColumnResizeEndCallback?: (newColumnWidth: number, columnKey: string) => void; + + /** + * Callback that is called when reordering has been completed + * and columns need to be updated. + * + * ``` + * function( + * event { + * columnBefore: string|undefined, // the column before the new location of this one + * columnAfter: string|undefined, // the column after the new location of this one + * reorderColumn: string, // the column key that was just reordered + * } + * ) + * ``` + */ + onColumnReorderEndCallback?: (event: ColumnReorderEndEvent) => void; + + /** + * Whether a column is currently being resized. + */ + isColumnResizing?: boolean; + + /** + * Whether columns are currently being reordered. + */ + isColumnReordering?: boolean; + + /** + * The number of rows outside the viewport to prerender. Defaults to roughly + * half of the number of visible rows. + */ + bufferRowCount?: number; +} + +export class Table extends React.Component { +} + +export interface ColumnHeaderProps { + columnKey?: string; + + /** supplied from the Table or rowHeightGetter */ + height: number; + + /** supplied from the Column */ + width: number; +} + +export interface ColumnCellProps extends ColumnHeaderProps { + /** the row index of the cell */ + rowIndex: number; +} + +/** + * Component that defines the attributes of table column. + */ +export interface ColumnProps extends React.ClassAttributes { + /** + * The horizontal alignment of the table cell content. + */ + align?: 'left' | 'center' | 'right'; + + /** + * Controls if the column is fixed when scrolling in the X axis. + * + * defaultValue: false + */ + fixed?: boolean; + + /** + * Controls if the column is fixed to the right side of the table + * when scrolling in the X axis. + * + * defaultValue: false + */ + fixedRight?: boolean; + + /** + * The header cell for this column. + * This can either be a string a React element, or a function that generates + * a React Element. Passing in a string will render a default header cell + * with that string. By default, the React element passed in can expect to + * receive the following props: + * + * ``` + * props: { + * columnKey: string // (of the column, if given) + * height: number // (supplied from the Table or rowHeightGetter) + * width: number // (supplied from the Column) + * } + * ``` + * + * Because you are passing in your own React element, you can feel free to + * pass in whatever props you may want or need. + * + * If you pass in a function, you will receive the same props object as the + * first argument. + */ + header?: ElementOrFunc; + + /** + * This is the body cell that will be cloned for this column. + * This can either be a string a React element, or a function that generates + * a React Element. Passing in a string will render a default header cell + * with that string. By default, the React element passed in can expect to + * receive the following props: + * + * ``` + * props: { + * rowIndex; number // (the row index of the cell) + * columnKey: string // (of the column, if given) + * height: number // (supplied from the Table or rowHeightGetter) + * width: number // (supplied from the Column) + * } + * ``` + * + * Because you are passing in your own React element, you can feel free to + * pass in whatever props you may want or need. + * + * If you pass in a function, you will receive the same props object as the + * first argument. + */ + cell?: ElementOrFunc; + + /** + * This is the footer cell for this column. + * This can either be a string a React element, or a function that generates + * a React Element. Passing in a string will render a default header cell + * with that string. By default, the React element passed in can expect to + * receive the following props: + * + * ``` + * props: { + * columnKey: string // (of the column, if given) + * height: number // (supplied from the Table or rowHeightGetter) + * width: number // (supplied from the Column) + * } + * ``` + * + * Because you are passing in your own React element, you can feel free to + * pass in whatever props you may want or need. + * + * If you pass in a function, you will receive the same props object as the + * first argument. + */ + footer?: ElementOrFunc; + + /** + * This is used to uniquely identify the column, and is not required unless + * you a resizing columns. This will be the key given in the + * `onColumnResizeEndCallback` on the Table. + */ + columnKey?: string | number; + + /** + * The pixel width of the column. + */ + width: number; + + /** + * If this is a resizable column this is its minimum pixel width. + */ + minWidth?: number; + + /** + * If this is a resizable column this is its maximum pixel width. + */ + maxWidth?: number; + + /** + * The grow factor relative to other columns. Same as the flex-grow API + * from http://www.w3.org/TR/css3-flexbox/. Basically, take any available + * extra width and distribute it proportionally according to all columns' + * flexGrow values. Defaults to zero (no-flexing). + */ + flexGrow?: number; + + /** + * Whether the column can be resized with the + * FixedDataTableColumnResizeHandle. Please note that if a column + * has a flex grow, once you resize the column this will be set to 0. + * + * This property only provides the UI for the column resizing. If this + * is set to true, you will need to set the onColumnResizeEndCallback table + * property and render your columns appropriately. + */ + isResizable?: boolean; + + /** + * Whether the column can be dragged to reorder. + */ + isReorderable?: boolean; + + /** + * Whether cells in this column can be removed from document when outside + * of viewport as a result of horizontal scrolling. + * Setting this property to true allows the table to not render cells in + * particular column that are outside of viewport for visible rows. This + * allows to create table with many columns and not have vertical scrolling + * performance drop. + * Setting the property to false will keep previous behaviour and keep + * cell rendered if the row it belongs to is visible. + * + * defaultValue: false + */ + allowCellsRecycling?: boolean; + + /** + * Flag to enable performance check when rendering. Stops the component from + * rendering if none of it's passed in props have changed + */ + pureRendering?: boolean; +} + +export class Column extends React.Component { +} + +export interface ColumnGroupHeaderProps { + /* supplied from the groupHeaderHeight */ + height: number; + + /* supplied from the Column */ + width: number; +} + +/** + * Component that defines the attributes of a table column group. + */ +export interface ColumnGroupProps extends React.ClassAttributes { + /** + * The horizontal alignment of the table cell content. + */ + align?: 'left' | 'center' | 'right'; + + /** + * Controls if the column group is fixed when scrolling in the X axis. + * + * defaultValue: false + */ + fixed?: boolean; + + /** + * This is the header cell for this column group. + * This can either be a string or a React element. Passing in a string + * will render a default footer cell with that string. By default, the React + * element passed in can expect to receive the following props: + * + * ``` + * props: { + * height: number // (supplied from the groupHeaderHeight) + * width: number // (supplied from the Column) + * } + * ``` + * + * Because you are passing in your own React element, you can feel free to + * pass in whatever props you may want or need. + * + * You can also pass in a function that returns a react elemnt, with the + * props object above passed in as the first parameter. + */ + header?: string | React.ReactElement | ((props: ColumnGroupHeaderProps) => (string | React.ReactElement)); +} + +export class ColumnGroup extends React.Component { +} + +/** + * Component that handles default cell layout and styling. + * + * All props unless specified below will be set onto the top level `div` + * rendered by the cell. + * + * Example usage via from a `Column`: + * ``` + * const MyColumn = ( + * ( + * + * Cell number: {rowIndex} + * + * )} + * width={100} + * /> + * ); + * ``` + */ +export interface CellProps extends React.HTMLAttributes { + /** + * Outer height of the cell. + */ + height?: number; + + /** + * Outer width of the cell. + */ + width?: number; + + /** + * Optional prop that if specified on the `Column` will be passed to the + * cell. It can be used to uniquely identify which column is the cell is in. + */ + columnKey?: string | number; + + /** + * Optional prop that represents the rows index in the table. + * For the 'cell' prop of a Column, this parameter will exist for any + * cell in a row with a positive index. + * + * Below that entry point the user is welcome to consume or + * pass the prop through at their discretion. + */ + rowIndex?: number; +} + +export class Cell extends React.Component { +} diff --git a/types/fixed-data-table-2/tsconfig.json b/types/fixed-data-table-2/tsconfig.json new file mode 100644 index 0000000000..c548d5c369 --- /dev/null +++ b/types/fixed-data-table-2/tsconfig.json @@ -0,0 +1,22 @@ +{ + "files": [ + "index.d.ts", + "fixed-data-table-2-tests.tsx" + ], + "compilerOptions": { + "module": "commonjs", + "lib": ["es6", "dom"], + "jsx":"preserve", + "noImplicitAny": true, + "noImplicitThis": true, + "strictNullChecks": true, + "strictFunctionTypes": true, + "baseUrl": "../", + "typeRoots": [ + "../" + ], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true + } +} diff --git a/types/fixed-data-table-2/tslint.json b/types/fixed-data-table-2/tslint.json new file mode 100644 index 0000000000..e60c15844f --- /dev/null +++ b/types/fixed-data-table-2/tslint.json @@ -0,0 +1,3 @@ +{ + "extends": "dtslint/dt.json" +} \ No newline at end of file diff --git a/types/flot/index.d.ts b/types/flot/index.d.ts index 84ab0daeb8..a75142b49e 100644 --- a/types/flot/index.d.ts +++ b/types/flot/index.d.ts @@ -1,6 +1,8 @@ // Type definitions for Flot // Project: http://www.flotcharts.org/ -// Definitions by: Matt Burland , Timo Mühlbach +// Definitions by: Matt Burland +// Timo Mühlbach +// Ariel Kuechler // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped // TypeScript Version: 2.3 @@ -120,6 +122,10 @@ declare namespace jquery.flot { tickLength?: number; alignTicksWithAxis?: number; + + timezone?: string; // "browser" or timezone (only makes sense for mode: "time") + timeformat?: string; // null or format string + twelveHourClock?: boolean; } interface seriesTypeBase { diff --git a/types/format-duration/format-duration-tests.ts b/types/format-duration/format-duration-tests.ts new file mode 100644 index 0000000000..4a08b33119 --- /dev/null +++ b/types/format-duration/format-duration-tests.ts @@ -0,0 +1,5 @@ +import formatDuration = require("format-duration"); + +const milliseconds = 12345; + +const duration: string = formatDuration(milliseconds); diff --git a/types/format-duration/index.d.ts b/types/format-duration/index.d.ts new file mode 100644 index 0000000000..06682200b2 --- /dev/null +++ b/types/format-duration/index.d.ts @@ -0,0 +1,8 @@ +// Type definitions for format-duration 1.0 +// Project: https://github.com/ungoldman/format-duration +// Definitions by: Giles Roadnight +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +declare function formatDuration(ms: number): string; + +export = formatDuration; diff --git a/types/format-duration/tsconfig.json b/types/format-duration/tsconfig.json new file mode 100644 index 0000000000..f17a4f7c6c --- /dev/null +++ b/types/format-duration/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", + "format-duration-tests.ts" + ] +} diff --git a/types/format-duration/tslint.json b/types/format-duration/tslint.json new file mode 100644 index 0000000000..3db14f85ea --- /dev/null +++ b/types/format-duration/tslint.json @@ -0,0 +1 @@ +{ "extends": "dtslint/dt.json" } diff --git a/types/fs-extra-promise/tsconfig.json b/types/fs-extra-promise/tsconfig.json index e0f6cc3450..4a4fc0f60b 100644 --- a/types/fs-extra-promise/tsconfig.json +++ b/types/fs-extra-promise/tsconfig.json @@ -12,6 +12,11 @@ "typeRoots": [ "../" ], + "paths": { + "fs-extra": [ + "fs-extra/v4" + ] + }, "types": [], "noEmit": true, "forceConsistentCasingInFileNames": true diff --git a/types/fs-extra/fs-extra-tests.ts b/types/fs-extra/fs-extra-tests.ts index 1af094260d..50d594e1a4 100644 --- a/types/fs-extra/fs-extra-tests.ts +++ b/types/fs-extra/fs-extra-tests.ts @@ -52,17 +52,9 @@ fs.copy(src, dest, }, errorCallback ); -fs.copy(src, dest, - { - overwrite: true, - preserveTimestamps: true, - filter: /.*/ - }, - errorCallback -); + fs.copySync(src, dest); fs.copySync(src, dest, { filter: (src: string, dest: string) => false }); -fs.copySync(src, dest, { filter: /.*/ }); fs.copySync(src, dest, { overwrite: true, @@ -70,13 +62,7 @@ fs.copySync(src, dest, filter: (src: string, dest: string) => false } ); -fs.copySync(src, dest, - { - overwrite: true, - preserveTimestamps: true, - filter: /.*/ - } -); + fs.createFile(file).then(() => { // stub }); diff --git a/types/fs-extra/index.d.ts b/types/fs-extra/index.d.ts index 82bd401c39..f556afa82f 100644 --- a/types/fs-extra/index.d.ts +++ b/types/fs-extra/index.d.ts @@ -1,4 +1,4 @@ -// Type definitions for fs-extra 4.0 +// Type definitions for fs-extra 5.0 // Project: https://github.com/jprichardson/node-fs-extra // Definitions by: Alan Agius , // midknight41 , @@ -254,7 +254,7 @@ export interface PathEntryStream { read(): PathEntry | null; } -export type CopyFilter = ((src: string, dest: string) => boolean) | RegExp; +export type CopyFilter = (src: string, dest: string) => boolean; export type SymlinkType = "dir" | "file"; @@ -289,7 +289,7 @@ export interface WriteFileOptions { export interface WriteOptions extends WriteFileOptions { fs?: object; replacer?: any; - spaces?: number; + spaces?: number | string; } export interface ReadResult { diff --git a/types/fs-extra/v4/fs-extra-tests.ts b/types/fs-extra/v4/fs-extra-tests.ts new file mode 100644 index 0000000000..1af094260d --- /dev/null +++ b/types/fs-extra/v4/fs-extra-tests.ts @@ -0,0 +1,230 @@ +import * as fs from "fs-extra"; +import * as Path from "path"; + +const len = 2; +const src = ""; +const dest = ""; +const file = ""; +const dir = ""; +const path = ""; +const data = ""; +const uid = 0; +const gid = 0; +const fd = 0; +const modeNum = 0; +const modeStr = ""; +const object = {}; +const errorCallback = (err: Error) => { }; +const readOptions: fs.ReadOptions = { + reviver: {} +}; +const writeOptions: fs.WriteOptions = { + replacer: {} +}; + +fs.moveSync(src, dest, {}); +fs.move(src, dest, {}).then(() => { + // stub +}); +fs.move(src, dest).then(() => { + // stub +}); +fs.move(src, dest, {}, () => { + // stub +}); +fs.move(src, dest, () => { + // stub +}); + +fs.copy(src, dest).then(() => { + // stub +}); +fs.copy(src, dest, { overwrite: true }).then(() => { + // stub +}); +fs.copy(src, dest, errorCallback); +fs.copy(src, dest, { filter: (src: string, dest: string) => false }, errorCallback); +fs.copy(src, dest, + { + overwrite: true, + preserveTimestamps: true, + filter: (src: string, dest: string) => false + }, + errorCallback +); +fs.copy(src, dest, + { + overwrite: true, + preserveTimestamps: true, + filter: /.*/ + }, + errorCallback +); +fs.copySync(src, dest); +fs.copySync(src, dest, { filter: (src: string, dest: string) => false }); +fs.copySync(src, dest, { filter: /.*/ }); +fs.copySync(src, dest, + { + overwrite: true, + preserveTimestamps: true, + filter: (src: string, dest: string) => false + } +); +fs.copySync(src, dest, + { + overwrite: true, + preserveTimestamps: true, + filter: /.*/ + } +); +fs.createFile(file).then(() => { + // stub +}); +fs.createFile(file, errorCallback); +fs.createFileSync(file); + +fs.mkdirs(dir).then(() => { + // stub +}); +fs.mkdirp(dir).then(() => { + // stub +}); +fs.mkdirs(dir, errorCallback); +fs.mkdirsSync(dir); +fs.mkdirp(dir, errorCallback); +fs.mkdirpSync(dir); + +fs.outputFile(file, data).then(() => { + // stub +}); +fs.outputFile(file, data, errorCallback); +fs.outputFileSync(file, data); + +fs.outputJson(file, data, { + spaces: 2 +}).then(() => { + // stub +}); +fs.outputJson(file, data, { + spaces: 2 +}, errorCallback); +fs.outputJSON(file, data, errorCallback); +fs.outputJSON(file, data).then(() => { + // stub +}); + +fs.outputJsonSync(file, data); +fs.outputJSONSync(file, data); + +fs.readJson(file).then(() => { + // stub +}); + +fs.readJson(file, readOptions).then(() => { + // stub +}); +fs.readJson(file, (error: Error, jsonObject: any) => { }); +fs.readJson(file, readOptions, (error: Error, jsonObject: any) => { }); +fs.readJSON(file, (error: Error, jsonObject: any) => { }); +fs.readJSON(file, readOptions, (error: Error, jsonObject: any) => { }); + +fs.readJsonSync(file, readOptions); +fs.readJSONSync(file, readOptions); + +fs.remove(dir, errorCallback); +fs.remove(dir).then(() => { + // stub +}); +fs.removeSync(dir); + +fs.writeJson(file, object).then(() => { + // stub +}); +fs.writeJSON(file, object).then(() => { + // stub +}); +fs.writeJson(file, object, errorCallback); +fs.writeJson(file, object, writeOptions, errorCallback); +fs.writeJSON(file, object, errorCallback); +fs.writeJSON(file, object, writeOptions, errorCallback); +fs.writeJson(file, object, writeOptions).then(() => { + // stub +}); +fs.writeJSON(file, object, writeOptions).then(() => { + // stub +}); +fs.writeJsonSync(file, object, writeOptions); +fs.writeJSONSync(file, object, writeOptions); + +fs.ensureDir(path).then(() => { + // stub +}); +fs.ensureDir(path, errorCallback); +fs.ensureDirSync(path); + +fs.ensureFile(path).then(() => { + // stub +}); +fs.ensureFile(path, errorCallback); +fs.ensureFileSync(path); +fs.ensureLink(path, path).then(() => { + // stub +}); +fs.ensureLink(path, path, errorCallback); +fs.ensureLinkSync(path, path); +fs.ensureSymlink(path, path, "file").then(() => { + // stub +}); +fs.ensureSymlink(path, path, errorCallback); +fs.ensureSymlinkSync(path, path); +fs.emptyDir(path).then(() => { + // stub +}); +fs.emptyDir(path, errorCallback); +fs.emptyDirSync(path); +fs.pathExists(path).then((_exist: boolean) => { + // stub +}); +fs.pathExists(path, (_err: Error, _exists: boolean) => { }); +const x: boolean = fs.pathExistsSync(path); + +fs.rename(src, dest, errorCallback); +fs.renameSync(src, dest); +fs.truncate(path, len, errorCallback); +fs.truncateSync(path, len); +fs.chown(path, uid, gid, errorCallback); +fs.chownSync(path, uid, gid); +fs.fchown(fd, uid, gid, errorCallback); +fs.fchownSync(fd, uid, gid); +fs.lchown(path, uid, gid, errorCallback); +fs.lchownSync(path, uid, gid); +fs.chmod(path, modeNum, errorCallback); +fs.chmod(path, modeStr, errorCallback); +fs.chmodSync(path, modeNum); +fs.chmodSync(path, modeStr); +fs.fchmod(fd, modeNum, errorCallback); +fs.fchmod(fd, modeStr, errorCallback); +fs.fchmodSync(fd, modeNum); +fs.fchmodSync(fd, modeStr); +fs.lchmod(path, modeStr, errorCallback); +fs.lchmod(path, modeNum, errorCallback); +fs.lchmodSync(path, modeNum); +fs.lchmodSync(path, modeStr); +fs.statSync(path); +fs.lstatSync(path); + +fs.read(0, new Buffer(""), 0, 0, null).then(x => { + const a = x.buffer; + const b = x.bytesRead; +}); + +fs.write(0, new Buffer(""), 0, 0, null).then(x => { + const a = x.buffer; + const b = x.bytesWritten; +}); + +// $ExpectType Promise +fs.writeFile("foo.txt", "i am foo", { encoding: "utf-8" }); + +// $ExpectType Promise +fs.mkdtemp("foo"); diff --git a/types/fs-extra/v4/index.d.ts b/types/fs-extra/v4/index.d.ts new file mode 100644 index 0000000000..575df86b4d --- /dev/null +++ b/types/fs-extra/v4/index.d.ts @@ -0,0 +1,303 @@ +// Type definitions for fs-extra 4.0 +// Project: https://github.com/jprichardson/node-fs-extra +// Definitions by: Alan Agius , +// midknight41 , +// Brendan Forster , +// Mees van Dijk +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.2 + +/// + +import { Stats } from "fs"; + +export * from "fs"; + +export function copy(src: string, dest: string, options?: CopyOptions): Promise; +export function copy(src: string, dest: string, callback: (err: Error) => void): void; +export function copy(src: string, dest: string, options: CopyOptions, callback: (err: Error) => void): void; +export function copySync(src: string, dest: string, options?: CopyOptions): void; + +export function move(src: string, dest: string, options?: MoveOptions): Promise; +export function move(src: string, dest: string, callback: (err: Error) => void): void; +export function move(src: string, dest: string, options: MoveOptions, callback: (err: Error) => void): void; +export function moveSync(src: string, dest: string, options?: MoveOptions): void; + +export function createFile(file: string): Promise; +export function createFile(file: string, callback: (err: Error) => void): void; +export function createFileSync(file: string): void; + +export function ensureDir(path: string): Promise; +export function ensureDir(path: string, callback: (err: Error) => void): void; +export function ensureDirSync(path: string): void; + +export function mkdirs(dir: string): Promise; +export function mkdirs(dir: string, callback: (err: Error) => void): void; +export function mkdirp(dir: string): Promise; +export function mkdirp(dir: string, callback: (err: Error) => void): void; +export function mkdirsSync(dir: string): void; +export function mkdirpSync(dir: string): void; + +export function outputFile(file: string, data: any, options?: WriteFileOptions | string): Promise; +export function outputFile(file: string, data: any, callback: (err: Error) => void): void; +export function outputFile(file: string, data: any, options: WriteFileOptions | string, callback: (err: Error) => void): void; +export function outputFileSync(file: string, data: any, options?: WriteFileOptions | string): void; + +export function readJson(file: string, options?: ReadOptions): Promise; +export function readJson(file: string, callback: (err: Error, jsonObject: any) => void): void; +export function readJson(file: string, options: ReadOptions, callback: (err: Error, jsonObject: any) => void): void; +export function readJSON(file: string, options?: ReadOptions): Promise; +export function readJSON(file: string, callback: (err: Error, jsonObject: any) => void): void; +export function readJSON(file: string, options: ReadOptions, callback: (err: Error, jsonObject: any) => void): void; + +export function readJsonSync(file: string, options?: ReadOptions): any; +export function readJSONSync(file: string, options?: ReadOptions): any; + +export function remove(dir: string): Promise; +export function remove(dir: string, callback: (err: Error) => void): void; +export function removeSync(dir: string): void; + +export function outputJSON(file: string, data: any, options?: WriteOptions): Promise; +export function outputJSON(file: string, data: any, options: WriteOptions, callback: (err: Error) => void): void; +export function outputJSON(file: string, data: any, callback: (err: Error) => void): void; +export function outputJson(file: string, data: any, options?: WriteOptions): Promise; +export function outputJson(file: string, data: any, options: WriteOptions, callback: (err: Error) => void): void; +export function outputJson(file: string, data: any, callback: (err: Error) => void): void; +export function outputJsonSync(file: string, data: any, options?: WriteOptions): void; +export function outputJSONSync(file: string, data: any, options?: WriteOptions): void; + +export function writeJSON(file: string, object: any, options?: WriteOptions): Promise; +export function writeJSON(file: string, object: any, callback: (err: Error) => void): void; +export function writeJSON(file: string, object: any, options: WriteOptions, callback: (err: Error) => void): void; +export function writeJson(file: string, object: any, options?: WriteOptions): Promise; +export function writeJson(file: string, object: any, callback: (err: Error) => void): void; +export function writeJson(file: string, object: any, options: WriteOptions, callback: (err: Error) => void): void; + +export function writeJsonSync(file: string, object: any, options?: WriteOptions): void; +export function writeJSONSync(file: string, object: any, options?: WriteOptions): void; + +export function ensureFile(path: string): Promise; +export function ensureFile(path: string, callback: (err: Error) => void): void; +export function ensureFileSync(path: string): void; + +export function ensureLink(src: string, dest: string): Promise; +export function ensureLink(src: string, dest: string, callback: (err: Error) => void): void; +export function ensureLinkSync(src: string, dest: string): void; + +export function ensureSymlink(src: string, dest: string, type?: SymlinkType): Promise; +export function ensureSymlink(src: string, dest: string, type: SymlinkType, callback: (err: Error) => void): void; +export function ensureSymlink(src: string, dest: string, callback: (err: Error) => void): void; +export function ensureSymlinkSync(src: string, dest: string, type?: SymlinkType): void; + +export function emptyDir(path: string): Promise; +export function emptyDir(path: string, callback: (err: Error) => void): void; +export function emptyDirSync(path: string): void; + +export function pathExists(path: string): Promise; +export function pathExists(path: string, callback: (err: Error, exists: boolean) => void): void; +export function pathExistsSync(path: string): boolean; + +// fs async methods +// copied from https://github.com/DefinitelyTyped/DefinitelyTyped/blob/master/types/node/v6/index.d.ts + +export function access(path: string | Buffer, callback: (err: NodeJS.ErrnoException) => void): void; +export function access(path: string | Buffer, mode: number, callback: (err: NodeJS.ErrnoException) => void): void; +export function access(path: string | Buffer, mode?: number): Promise; + +export function appendFile(file: string | Buffer | number, data: any, options: { encoding?: string; mode?: number | string; flag?: string; }, + callback: (err: NodeJS.ErrnoException) => void): void; +export function appendFile(file: string | Buffer | number, data: any, callback: (err: NodeJS.ErrnoException) => void): void; +export function appendFile(file: string | Buffer | number, data: any, options?: { encoding?: string; mode?: number | string; flag?: string; }): Promise; + +export function chmod(path: string | Buffer, mode: string | number, callback: (err: NodeJS.ErrnoException) => void): void; +export function chmod(path: string | Buffer, mode: string | number): Promise; + +export function chown(path: string | Buffer, uid: number, gid: number): Promise; +export function chown(path: string | Buffer, uid: number, gid: number, callback: (err: NodeJS.ErrnoException) => void): void; + +export function close(fd: number, callback: (err: NodeJS.ErrnoException) => void): void; +export function close(fd: number): Promise; + +export function fchmod(fd: number, mode: string | number, callback: (err: NodeJS.ErrnoException) => void): void; +export function fchmod(fd: number, mode: string | number): Promise; + +export function fchown(fd: number, uid: number, gid: number, callback: (err: NodeJS.ErrnoException) => void): void; +export function fchown(fd: number, uid: number, gid: number): Promise; + +export function fdatasync(fd: number, callback: () => void): void; +export function fdatasync(fd: number): Promise; + +export function fstat(fd: number, callback: (err: NodeJS.ErrnoException, stats: Stats) => any): void; +export function fstat(fd: number): Promise; + +export function fsync(fd: number, callback: (err: NodeJS.ErrnoException) => void): void; +export function fsync(fd: number): Promise; + +export function ftruncate(fd: number, callback: (err: NodeJS.ErrnoException) => void): void; +export function ftruncate(fd: number, len: number, callback: (err: NodeJS.ErrnoException) => void): void; +export function ftruncate(fd: number, len?: number): Promise; + +export function futimes(fd: number, atime: number, mtime: number, callback: (err: NodeJS.ErrnoException) => void): void; +export function futimes(fd: number, atime: Date, mtime: Date, callback: (err: NodeJS.ErrnoException) => void): void; +export function futimes(fd: number, atime: number, mtime: number): Promise; +export function futimes(fd: number, atime: Date, mtime: Date): Promise; + +export function lchown(path: string | Buffer, uid: number, gid: number, callback: (err: NodeJS.ErrnoException) => void): void; +export function lchown(path: string | Buffer, uid: number, gid: number): Promise; + +export function link(srcpath: string | Buffer, dstpath: string | Buffer, callback: (err: NodeJS.ErrnoException) => void): void; +export function link(srcpath: string | Buffer, dstpath: string | Buffer): Promise; + +export function lstat(path: string | Buffer, callback: (err: NodeJS.ErrnoException, stats: Stats) => any): void; +export function lstat(path: string | Buffer): Promise; + +/** + * Asynchronous mkdir - creates the directory specified in {path}. Parameter {mode} defaults to 0777. + * + * @param callback No arguments other than a possible exception are given to the completion callback. + */ +export function mkdir(path: string | Buffer, callback: (err: NodeJS.ErrnoException) => void): void; +/** + * Asynchronous mkdir - creates the directory specified in {path}. Parameter {mode} defaults to 0777. + * + * @param callback No arguments other than a possible exception are given to the completion callback. + */ +export function mkdir(path: string | Buffer, mode: number | string, callback: (err: NodeJS.ErrnoException) => void): void; +export function mkdir(path: string | Buffer): Promise; + +export function open(path: string | Buffer, flags: string | number, callback: (err: NodeJS.ErrnoException, fd: number) => void): void; +export function open(path: string | Buffer, flags: string | number, mode: number, callback: (err: NodeJS.ErrnoException, fd: number) => void): void; +export function open(path: string | Buffer, flags: string | number, mode?: number): Promise; + +export function read(fd: number, buffer: Buffer, offset: number, length: number, position: number | null, + callback: (err: NodeJS.ErrnoException, bytesRead: number, buffer: Buffer) => void): void; +export function read(fd: number, buffer: Buffer, offset: number, length: number, position: number | null): Promise; + +export function readFile(file: string | Buffer | number, callback: (err: NodeJS.ErrnoException, data: Buffer) => void): void; +export function readFile(file: string | Buffer | number, encoding: string, callback: (err: NodeJS.ErrnoException, data: string) => void): void; +export function readFile(file: string | Buffer | number, options: { flag?: string; } | { encoding: string; flag?: string; }, callback: (err: NodeJS.ErrnoException, data: Buffer) => void): void; +export function readFile(file: string | Buffer | number, options: { flag?: string; } | { encoding: string; flag?: string; }): Promise; +// tslint:disable-next-line:unified-signatures +export function readFile(file: string | Buffer | number, encoding: string): Promise; +export function readFile(file: string | Buffer | number): Promise; + +export function readdir(path: string | Buffer, callback: (err: NodeJS.ErrnoException, files: string[]) => void): void; +export function readdir(path: string | Buffer): Promise; + +export function readlink(path: string | Buffer, callback: (err: NodeJS.ErrnoException, linkString: string) => any): void; +export function readlink(path: string | Buffer): Promise; + +export function realpath(path: string | Buffer, callback: (err: NodeJS.ErrnoException, resolvedPath: string) => any): void; +export function realpath(path: string | Buffer, cache: { [path: string]: string }, callback: (err: NodeJS.ErrnoException, resolvedPath: string) => any): void; +export function realpath(path: string | Buffer, cache?: { [path: string]: string }): Promise; + +export function rename(oldPath: string, newPath: string, callback: (err: NodeJS.ErrnoException) => void): void; +export function rename(oldPath: string, newPath: string): Promise; + +/** + * Asynchronous rmdir - removes the directory specified in {path} + * + * @param callback No arguments other than a possible exception are given to the completion callback. + */ +export function rmdir(path: string | Buffer, callback: (err: NodeJS.ErrnoException) => void): void; +export function rmdir(path: string | Buffer): Promise; + +export function stat(path: string | Buffer, callback: (err: NodeJS.ErrnoException, stats: Stats) => any): void; +export function stat(path: string | Buffer): Promise; + +export function symlink(srcpath: string | Buffer, dstpath: string | Buffer, type: string, callback: (err: NodeJS.ErrnoException) => void): void; +export function symlink(srcpath: string | Buffer, dstpath: string | Buffer, type?: string): Promise; + +export function truncate(path: string | Buffer, callback: (err: NodeJS.ErrnoException) => void): void; +export function truncate(path: string | Buffer, len: number, callback: (err: NodeJS.ErrnoException) => void): void; +export function truncate(path: string | Buffer, len?: number): Promise; + +/** + * Asynchronous unlink - deletes the file specified in {path} + * + * @param callback No arguments other than a possible exception are given to the completion callback. + */ +export function unlink(path: string | Buffer, callback: (err: NodeJS.ErrnoException) => void): void; +export function unlink(path: string | Buffer): Promise; + +export function utimes(path: string | Buffer, atime: number, mtime: number, callback: (err: NodeJS.ErrnoException) => void): void; +export function utimes(path: string | Buffer, atime: Date, mtime: Date, callback: (err: NodeJS.ErrnoException) => void): void; +export function utimes(path: string | Buffer, atime: number, mtime: number): Promise; +export function utimes(path: string | Buffer, atime: Date, mtime: Date): Promise; + +export function write(fd: number, buffer: Buffer, offset: number, length: number, position: number | null, callback: (err: NodeJS.ErrnoException, written: number, buffer: Buffer) => void): void; +export function write(fd: number, buffer: Buffer, offset: number, length: number, callback: (err: NodeJS.ErrnoException, written: number, buffer: Buffer) => void): void; +export function write(fd: number, data: any, callback: (err: NodeJS.ErrnoException, written: number, str: string) => void): void; +export function write(fd: number, data: any, offset: number, callback: (err: NodeJS.ErrnoException, written: number, str: string) => void): void; +export function write(fd: number, data: any, offset: number, encoding: string, callback: (err: NodeJS.ErrnoException, written: number, str: string) => void): void; +export function write(fd: number, buffer: Buffer, offset: number, length: number, position?: number | null): Promise; +export function write(fd: number, data: any, offset: number, encoding?: string): Promise; + +export function writeFile(file: string | Buffer | number, data: any, callback: (err: NodeJS.ErrnoException) => void): void; +export function writeFile(file: string | Buffer | number, data: any, options?: WriteFileOptions | string): Promise; +export function writeFile(file: string | Buffer | number, data: any, options: WriteFileOptions | string, callback: (err: NodeJS.ErrnoException) => void): void; + +/** + * Asynchronous mkdtemp - Creates a unique temporary directory. Generates six random characters to be appended behind a required prefix to create a unique temporary directory. + * + * @param callback The created folder path is passed as a string to the callback's second parameter. + */ +export function mkdtemp(prefix: string): Promise; +export function mkdtemp(prefix: string, callback: (err: NodeJS.ErrnoException, folder: string) => void): void; + +export interface PathEntry { + path: string; + stats: Stats; +} + +export interface PathEntryStream { + read(): PathEntry | null; +} + +export type CopyFilter = ((src: string, dest: string) => boolean) | RegExp; + +export type SymlinkType = "dir" | "file"; + +export interface CopyOptions { + dereference?: boolean; + overwrite?: boolean; + preserveTimestamps?: boolean; + errorOnExist?: boolean; + filter?: CopyFilter; + recursive?: boolean; +} + +export interface MoveOptions { + overwrite?: boolean; + limit?: number; +} + +export interface ReadOptions { + throws?: boolean; + fs?: object; + reviver?: any; + encoding?: string; + flag?: string; +} + +export interface WriteFileOptions { + encoding?: string; + flag?: string; + mode?: number; +} + +export interface WriteOptions extends WriteFileOptions { + fs?: object; + replacer?: any; + spaces?: number | string; +} + +export interface ReadResult { + bytesRead: number; + buffer: Buffer; +} + +export interface WriteResult { + bytesWritten: number; + buffer: Buffer; +} diff --git a/types/fs-extra/v4/tsconfig.json b/types/fs-extra/v4/tsconfig.json new file mode 100644 index 0000000000..80435f4ede --- /dev/null +++ b/types/fs-extra/v4/tsconfig.json @@ -0,0 +1,28 @@ +{ + "compilerOptions": { + "module": "commonjs", + "lib": [ + "es6" + ], + "noImplicitAny": true, + "noImplicitThis": true, + "strictNullChecks": true, + "strictFunctionTypes": false, + "baseUrl": "../../", + "typeRoots": [ + "../../" + ], + "paths": { + "fs-extra": [ + "fs-extra/v4" + ] + }, + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true + }, + "files": [ + "index.d.ts", + "fs-extra-tests.ts" + ] +} \ No newline at end of file diff --git a/types/fs-extra/v4/tslint.json b/types/fs-extra/v4/tslint.json new file mode 100644 index 0000000000..d88586e5bd --- /dev/null +++ b/types/fs-extra/v4/tslint.json @@ -0,0 +1,3 @@ +{ + "extends": "dtslint/dt.json" +} diff --git a/types/fs-plus/fs-plus-tests.ts b/types/fs-plus/fs-plus-tests.ts new file mode 100644 index 0000000000..92ae917266 --- /dev/null +++ b/types/fs-plus/fs-plus-tests.ts @@ -0,0 +1,151 @@ +import * as path from "path"; +import * as fs from "fs-plus"; + +const homeDir = fs.getHomeDirectory(); + +console.log(fs.absolute("~") === fs.realpathSync(homeDir)); +console.log( + fs.absolute(path.join("~", "does", "not", "exist")) === + path.join(homeDir, "does", "not", "exist") +); + +console.log(fs.normalize("~/foo") === path.join(homeDir, "foo")); + +console.log(fs.tildify(homeDir) === "~"); + +console.log( + fs.getAppDataDirectory() === + path.join(fs.getHomeDirectory(), "Library", "Application Support") +); + +console.log(fs.isAbsolute("/a/b/c")); + +console.log(fs.existsSync("/a/b/c")); + +console.log(fs.isDirectorySync("/a/b/c")); + +fs.isDirectory("a/b/c", result => { + console.log(result); +}); + +console.log(fs.isFileSync("/a/b/c")); + +console.log(fs.isSymbolicLinkSync("/a/b/c")); + +fs.isSymbolicLink("a/b/c", result => { + console.log(result); +}); + +console.log(fs.isExecutableSync("/a/b/c")); + +console.log(fs.getSizeSync("/a/b/c") === -1); + +console.log(fs.listSync("/a/b").indexOf("c") === 0); +console.log(fs.listSync("/a/b", [".ts", ".tsx"]).indexOf("c.tsx") === 0); + +fs.list("/a/b", (err, result) => { + if (err) { + console.error(err); + return; + } + console.log(result.indexOf("c") === 0); +}); +fs.list("/a/b", [".ts", ".tsx"], (err, result) => { + if (err) { + console.error(err); + return; + } + console.log(result.indexOf("c.tsx") === 0); +}); + +console.log(fs.listTreeSync("/a/b").indexOf("c") === 0); + +fs.moveSync("/a/b", "a/c"); + +fs.move("/a/b", "a/c", err => { + console.log(err); +}); + +fs.removeSync("/a/b"); + +fs.remove("/a/b", err => { + console.log(err); +}); + +fs.writeFileSync("a/b/c", "data"); +fs.writeFileSync("a/b/c", "data", "utf8"); +fs.writeFileSync("a/b/c", "data", { encoding: "utf8" }); + +fs.writeFile("a/b/c", "data", err => { + console.log(err); +}); +fs.writeFile("a/b/c", "data", "utf8", err => { + console.log(err); +}); +fs.writeFile("a/b/c", "data", { encoding: "utf8" }, err => { + console.log(err); +}); + +fs.copySync("/a/b", "a/c"); + +fs.copy("/a/b", "a/c", err => { + console.log(err); +}); + +fs.copyFileSync("/a/b", "a/c"); +fs.copyFileSync("/a/b", "a/c", 32 * 1024); + +fs.makeTreeSync("/a/b"); + +fs.makeTree("/a/b", err => { + console.log(err); +}); + +fs.traverseTreeSync( + "a/b/c", + file => { + console.log("file", file); + }, + dir => { + console.log("directory", dir); + return true; + } +); + +fs.traverseTree( + "a/b/c", + file => { + console.log("file", file); + }, + dir => { + console.log("directory", dir); + }, + err => { + console.error(err); + } +); + +console.log(fs.md5ForPath("a/b/c")); + +console.log(fs.resolve("a/b/c", "sample.js")); +console.log(fs.resolve("a/b/c", "sample", [".js"])); + +console.log(fs.resolveOnLoadPath("sample.js")); +console.log(fs.resolveOnLoadPath("sample", [".js"])); + +console.log(fs.resolveExtension("a/b/c", [".js"])); + +console.log(fs.isCompressedExtension(".tar.gz")); + +console.log(fs.isImageExtension(".jpg")); + +console.log(fs.isPdfExtension(".pdf")); + +console.log(fs.isBinaryExtension(".exe")); + +console.log(fs.isReadmePath("a/b/README.md")); + +console.log(fs.isMarkdownExtension(".md")); + +console.log(fs.isCaseInsensitive()); +console.log(fs.isCaseSensitive()); diff --git a/types/fs-plus/index.d.ts b/types/fs-plus/index.d.ts new file mode 100644 index 0000000000..0151de2c73 --- /dev/null +++ b/types/fs-plus/index.d.ts @@ -0,0 +1,305 @@ +// Type definitions for fs-plus 3.0 +// Project: https://github.com/atom/fs-plus +// Definitions by: Daniel Perez Alvarez +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.1 + +/// + +import { Stats } from "fs"; + +export * from "fs"; + +/** + * Returns the absolute path to the home directory. + */ +export function getHomeDirectory(): string; + +/** + * Make the given path absolute by resolving it against the current working directory. + */ +export function absolute(relativePath: string): string; + +/** + * Normalize the given path treating a leading `~` segment as referring to the home directory. This method does not query the filesystem. + */ +export function normalize(pathToNormalize: string): string; + +/** + * Convert an absolute path to tilde path for Linux and macOS. + */ +export function tildify(pathToTildify: string): string; + +/** + * Get path to store application specific data. + * + * * Mac: `~/Library/Application Support/` + * * Win: `%AppData%` + * * Linux: `/var/lib` + */ +export function getAppDataDirectory(): string; + +/** + * Returns true if the given path is absolute. + */ +export function isAbsolute(pathToCheck: string): boolean; + +/** + * Returns true if a file or folder at the specified path exists. + */ +export function existsSync(pathToCheck: string): boolean; + +/** + * Returns true if the given path exists and is a directory. + */ +export function isDirectorySync(directoryPath: string): boolean; + +/** + * Asynchronously checks that the given path exists and is a directory. + */ +export function isDirectory( + directoryPath: string, + callback: (result: boolean) => void +): void; + +/** + * Returns true if the specified path exists and is a file. + */ +export function isFileSync(filePath: string): boolean; + +/** + * Returns true if the specified path is a symbolic link. + */ +export function isSymbolicLinkSync(symlinkPath: string): boolean; + +/** + * Calls back with true if the specified path is a symbolic link. + */ +export function isSymbolicLink( + symlinkPath: string, + callback: (result: boolean) => void +): void; + +/** + * Returns true if the specified path is executable. + */ +export function isExecutableSync(pathToCheck: string): boolean; + +/** + * Returns the size of the specified path. + */ +export function getSizeSync(pathToCheck: string): number; + +/** + * Returns an Array with the paths of the files and directories contained within the directory path. It is not recursive. + */ +export function listSync(rootPath: string, extensions?: string[]): string[]; + +/** + * Asynchronously lists the files and directories in the given path. The listing is not recursive. + */ +export function list( + rootPath: string, + callback: (err: Error, result: string[]) => void +): void; + +/** + * Asynchronously lists the files and directories in the given path. The listing is not recursive. + */ +export function list( + rootPath: string, + extensions: string[], + callback: (err: Error, result: string[]) => void +): void; + +/** + * Get all paths under the given path. + */ +export function listTreeSync(rootPath: string): string[]; + +/** + * Moves the source file or directory to the target. + */ +export function moveSync(source: string, target: string): void; + +/** + * Asynchronously moves the source file or directory to the target. + */ +export function move( + source: string, + target: string, + callback: (err: Error) => void +): void; + +/** + * Removes the file or directory at the given path. + */ +export function removeSync(pathToRemove: string): void; + +/** + * Asynchronously removes the file or directory at the given path. + */ +export function remove( + pathToRemove: string, + callback: (err: Error) => void +): void; + +/** + * Open, write, flush, and close a file, writing the given content synchronously. + */ +export function writeFileSync( + filePath: string, + content: string, + options?: + | { encoding?: string | null; mode?: number | string; flag?: string } + | string + | null +): void; + +/** + * Open, write, flush, and close a file, writing the given content asynchronously. + */ +export function writeFile( + filePath: string, + content: any, + callback: (err: any) => void +): void; + +/** + * Open, write, flush, and close a file, writing the given content asynchronously. + */ +export function writeFile( + filePath: string, + content: any, + options: + | { encoding?: string | null; mode?: number | string; flag?: string } + | string + | undefined + | null, + callback: (err: any) => void +): void; + +/** + * Copies the given path. + */ +export function copySync(source: string, target: string): void; + +/** + * Asynchronously copies the given path. + */ +export function copy( + source: string, + target: string, + callback: (err: any) => void +): void; + +/** + * Copies the given path synchronously, buffering reads and writes to keep memory footprint to a minimum. If the destination directory doesn't exist, it creates it. + */ +export function copyFileSync( + source: string, + target: string, + bufferSize?: number +): void; + +/** + * Create a directory at the specified path including any missing parent directories. + */ +export function makeTreeSync(directoryPath: string): void; + +/** + * Asynchronously create a directory at the specified path including any missing parent directories. + */ +export function makeTree( + directoryPath: string, + callback: (err: any) => void +): void; + +/** + * Recursively walk the given path and execute the given functions. + */ +export function traverseTreeSync( + rootPath: string, + onFile: (file: string) => void, + onDirectory: (dir: string) => boolean | void +): void; + +/** + * Asynchronously walk the given path and execute the given functions. + */ +export function traverseTree( + rootPath: string, + onFile: (file: string) => void, + onDirectory: (dir: string) => boolean | void, + onDone: (err: any) => void +): void; + +/** + * Hashes the contents of the given file. + */ +export function md5ForPath(pathToDigest: string): string; + +/** + * Finds a relative path among the given array of paths. + */ +export function resolve( + loadPath: string, + pathToResolve: string, + extensions?: string[] +): string | undefined; + +/** + * Finds a relative path using Node's module paths as load paths. + */ +export function resolveOnLoadPath( + pathToResolve: string, + extensions?: string[] +): string | undefined; + +/** + * Finds the first file in the given path which matches the extension in the order given. + */ +export function resolveExtension( + pathToResolve: string, + extensions: string[] +): string | undefined; + +/** + * Returns true for extensions associated with compressed files. + */ +export function isCompressedExtension(ext: string): boolean; + +/** + * Returns true for extensions associated with image files. + */ +export function isImageExtension(ext: string): boolean; + +/** + * Returns true for extensions associated with PDF files. + */ +export function isPdfExtension(ext: string): boolean; + +/** + * Returns true for extensions associated with binary files. + */ +export function isBinaryExtension(ext: string): boolean; + +/** + * Returns true for files named similarily to `README`. + */ +export function isReadmePath(readmePath: string): boolean; + +/** + * Returns true for extensions associated with Markdown files. + */ +export function isMarkdownExtension(ext: string): boolean; + +/** + * Is the filesystem case insensitive? + */ +export function isCaseInsensitive(): boolean; + +/** + * Is the filesystem case sensitive? + */ +export function isCaseSensitive(): boolean; diff --git a/types/fs-plus/tsconfig.json b/types/fs-plus/tsconfig.json new file mode 100644 index 0000000000..1ab0098d52 --- /dev/null +++ b/types/fs-plus/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", + "fs-plus-tests.ts" + ] +} diff --git a/types/fs-plus/tslint.json b/types/fs-plus/tslint.json new file mode 100644 index 0000000000..3db14f85ea --- /dev/null +++ b/types/fs-plus/tslint.json @@ -0,0 +1 @@ +{ "extends": "dtslint/dt.json" } diff --git a/types/fullcalendar/index.d.ts b/types/fullcalendar/index.d.ts index 196de10898..3d5ff28f12 100644 --- a/types/fullcalendar/index.d.ts +++ b/types/fullcalendar/index.d.ts @@ -995,7 +995,7 @@ declare global { /** * Immediately switches to a different view. */ - fullCalendar(method: 'changeView', viewName: string): void; + fullCalendar(method: 'changeView', viewName: string, dateOrRange?: moment.Moment | Date | string | TimeRange): void; /** * Moves the calendar one step back (either by a month, week, or day). diff --git a/types/fuzzaldrin/fuzzaldrin-tests.ts b/types/fuzzaldrin/fuzzaldrin-tests.ts new file mode 100644 index 0000000000..90ec26e3e0 --- /dev/null +++ b/types/fuzzaldrin/fuzzaldrin-tests.ts @@ -0,0 +1,20 @@ +import { match, filter, score } from 'fuzzaldrin'; + +let number = 0; +const string = '' as string; +let strings: string[] = []; +let objects: Array<{name: string, speed: number}> = []; + +strings = filter(strings, string); +strings = filter(strings, string, {maxResults: number}); +objects = filter(objects, string, {key: 'name'}); +objects = filter(objects, string, {key: 'name', maxResults: number}); + +number = score(string, string); + +match(string, string); + +// These should be type errors! Uncomment to verify. +// objects = filter(objects, string); +// objects = filter(objects, string, {key: 'speed'}); +// strings = filter(strings, string, {key: 'speed'}); diff --git a/types/fuzzaldrin/index.d.ts b/types/fuzzaldrin/index.d.ts index 1e1427c08f..ca9a64e819 100644 --- a/types/fuzzaldrin/index.d.ts +++ b/types/fuzzaldrin/index.d.ts @@ -2,7 +2,9 @@ // Project: https://github.com/atom/fuzzaldrin // Definitions by: Mohamed Hegazy // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.1 -export function filter(candidates: T[], query: string, options?: { key?: string, maxResults?: number }): T[]; +export function filter(candidates: string[], query: string, options?: {maxResults?: number}): string[]; +export function filter(candidates: T[], query: string & T[K], options: {key: K, maxResults?: number}): T[]; export function match(string: string, query: string): any; export function score(string: string, query: string): number; diff --git a/types/fuzzaldrin/tsconfig.json b/types/fuzzaldrin/tsconfig.json index abf333c6bf..2e1263faf8 100644 --- a/types/fuzzaldrin/tsconfig.json +++ b/types/fuzzaldrin/tsconfig.json @@ -17,6 +17,7 @@ "forceConsistentCasingInFileNames": true }, "files": [ - "index.d.ts" + "index.d.ts", + "fuzzaldrin-tests.ts" ] -} \ No newline at end of file +} diff --git a/types/fuzzyset.js/fuzzyset.js-tests.ts b/types/fuzzyset.js/fuzzyset.js-tests.ts new file mode 100644 index 0000000000..97a0d45008 --- /dev/null +++ b/types/fuzzyset.js/fuzzyset.js-tests.ts @@ -0,0 +1,10 @@ +import FuzzySet = require('fuzzyset.js'); + +const fuzzyset: FuzzySet = FuzzySet(['coucou', 'foo', 'bar', 'toto']); +const results = fuzzyset.get('foo'); + +fuzzyset.length(); + +fuzzyset.isEmpty(); + +fuzzyset.values(); diff --git a/types/fuzzyset.js/index.d.ts b/types/fuzzyset.js/index.d.ts new file mode 100644 index 0000000000..04914683bc --- /dev/null +++ b/types/fuzzyset.js/index.d.ts @@ -0,0 +1,23 @@ +// Type definitions for fuzzyset.js 0.0 +// Project: https://github.com/Glench/fuzzyset.js +// Definitions by: Louis Grignon +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.3 + +interface FuzzySet { + get(candidate: string, defaultValue?: T, minScore?: number): Array<[number, string]> | T | null; + add(value: string): boolean; + length(): number; + isEmpty(): boolean; + values(): string[]; +} + +declare function FuzzySet( + source: string[], + useLevenshtein?: boolean, + gramSizeLower?: number, + gramSizeUpper?: number, +): FuzzySet; + +export = FuzzySet; +export as namespace FuzzySet; diff --git a/types/fuzzyset.js/tsconfig.json b/types/fuzzyset.js/tsconfig.json new file mode 100644 index 0000000000..a1eeb06b97 --- /dev/null +++ b/types/fuzzyset.js/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", + "fuzzyset.js-tests.ts" + ] +} diff --git a/types/fuzzyset.js/tslint.json b/types/fuzzyset.js/tslint.json new file mode 100644 index 0000000000..3db14f85ea --- /dev/null +++ b/types/fuzzyset.js/tslint.json @@ -0,0 +1 @@ +{ "extends": "dtslint/dt.json" } diff --git a/types/gapi.youtube/index.d.ts b/types/gapi.youtube/index.d.ts index b09779cdb3..bf2aebaf3a 100644 --- a/types/gapi.youtube/index.d.ts +++ b/types/gapi.youtube/index.d.ts @@ -778,7 +778,7 @@ interface GoogleApiYouTubeActivityResource { /** * A map of thumbnail images associated with the resource that is primarily associated with the activity. */ - thumbnails: GoogleApiYouTubeThumbnailItemResource[]; + thumbnails: GoogleApiYouTubeThumbnailResource; /** * Channel title for the channel responsible for this activity */ @@ -1082,7 +1082,7 @@ interface GoogleApiYouTubeChannelResource { /** * A map of thumbnail images associated with the channel. For each object in the map, the key is the name of the thumbnail image, and the value is an object that contains other information about the thumbnail. */ - thumbnails: GoogleApiYouTubeThumbnailItemResource[]; + thumbnails: GoogleApiYouTubeThumbnailResource; } /** * The contentDetails object encapsulates information about the channels content. @@ -1526,7 +1526,7 @@ interface GoogleApiYouTubePlaylistItemResource { /** * A map of thumbnail images associated with the playlist item. For each object in the map, the key is the name of the thumbnail image, and the value is an object that contains other information about the thumbnail. */ - thumbnails: GoogleApiYouTubeThumbnailItemResource[]; + thumbnails: GoogleApiYouTubeThumbnailResource; /** * The channel title of the channel that the playlist item belongs to. */ @@ -1713,7 +1713,7 @@ interface GoogleApiYouTubeSearchResource { /** * A map of thumbnail images associated with the search result. For each object in the map, the key is the name of the thumbnail image, and the value is an object that contains other information about the thumbnail. */ - thumbnails: GoogleApiYouTubeThumbnailItemResource[]; + thumbnails: GoogleApiYouTubeThumbnailResource; /** * The title of the channel that published the resource that the search result identifies. */ @@ -1774,7 +1774,7 @@ interface GoogleApiYouTubeSubscriptionResource { /** * A map of thumbnail images associated with the subscription. For each object in the map, the key is the name of the thumbnail image, and the value is an object that contains other information about the thumbnail. */ - thumbnails: GoogleApiYouTubeThumbnailItemResource[]; + thumbnails: GoogleApiYouTubeThumbnailResource; } /** * @@ -1796,7 +1796,7 @@ interface GoogleApiYouTubeSubscriptionResource { title: string; description: string; channelId: string; - thumbnails: GoogleApiYouTubeThumbnailItemResource[]; + thumbnails: GoogleApiYouTubeThumbnailResource; } } @@ -1902,7 +1902,7 @@ interface GoogleApiYouTubeVideoResource { /** * A map of thumbnail images associated with the video. For each object in the map, the key is the name of the thumbnail image, and the value is an object that contains other information about the thumbnail. */ - thumbnails: GoogleApiYouTubeThumbnailItemResource[]; + thumbnails: GoogleApiYouTubeThumbnailResource; /** * Channel title for the channel that the video belongs to. */ diff --git a/types/gifffer/gifffer-tests.ts b/types/gifffer/gifffer-tests.ts new file mode 100644 index 0000000000..b069e0020c --- /dev/null +++ b/types/gifffer/gifffer-tests.ts @@ -0,0 +1,28 @@ +import Gifffer from 'gifffer'; + +let gifs: HTMLButtonElement[]; + +gifs = Gifffer({ + playButtonStyles: { + width: '60px', + height: '60px', + 'border-radius': '30px', + background: 'rgba(0, 0, 0, 0.3)', + position: 'absolute', + top: '50%', + left: '50%', + margin: '-30px 0 0 -30px' + }, + playButtonIconStyles: { + width: '0', + height: '0', + 'border-top': '14px solid transparent', + 'border-bottom': '14px solid transparent', + 'border-left': '14px solid rgba(0, 0, 0, 0.5)', + position: 'absolute', + left: '26px', + top: '16px' + } +}); + +gifs[0].click(); diff --git a/types/gifffer/index.d.ts b/types/gifffer/index.d.ts new file mode 100644 index 0000000000..ac0f7663cc --- /dev/null +++ b/types/gifffer/index.d.ts @@ -0,0 +1,17 @@ +// Type definitions for gifffer 1.5 +// Project: https://github.com/krasimir/gifffer#readme +// Definitions by: William Lohan +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +/** + * @see {@link https://github.com/krasimir/gifffer#styling|Styling} + */ +export interface GiffferOptions { + playButtonStyles: { [style: string]: string; }; + playButtonIconStyles: { [style: string]: string; }; +} + +/** + * @see {@link https://github.com/krasimir/gifffer#usage|Usage} + */ +export default function Gifffer(options?: GiffferOptions): HTMLButtonElement[]; diff --git a/types/gifffer/tsconfig.json b/types/gifffer/tsconfig.json new file mode 100644 index 0000000000..273e998048 --- /dev/null +++ b/types/gifffer/tsconfig.json @@ -0,0 +1,24 @@ +{ + "compilerOptions": { + "module": "commonjs", + "lib": [ + "es6", + "dom" + ], + "noImplicitAny": true, + "noImplicitThis": true, + "strictNullChecks": true, + "strictFunctionTypes": true, + "baseUrl": "../", + "typeRoots": [ + "../" + ], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true + }, + "files": [ + "index.d.ts", + "gifffer-tests.ts" + ] +} diff --git a/types/gifffer/tslint.json b/types/gifffer/tslint.json new file mode 100644 index 0000000000..3db14f85ea --- /dev/null +++ b/types/gifffer/tslint.json @@ -0,0 +1 @@ +{ "extends": "dtslint/dt.json" } diff --git a/types/glob-stream/glob-stream-tests.ts b/types/glob-stream/glob-stream-tests.ts index 617246799c..ca436746cc 100644 --- a/types/glob-stream/glob-stream-tests.ts +++ b/types/glob-stream/glob-stream-tests.ts @@ -2,9 +2,24 @@ import gs = require('glob-stream'); var read: NodeJS.ReadableStream; -read = gs.create('xx'); -read = gs.create('xx', {}); -read = gs.create(['xx'], {}); -read = gs.create(['xx'], {cwd: 'xx'}); -read = gs.create(['xx'], {base: 'xx'}); -read = gs.create(['xx'], {cwdbase: true}); +// Types +var strPredicate: gs.UniqueByStringPredicate = 'base'; +var fnPredicate: gs.UniqueByFunctionPredicate = (entry) => entry.path; + +// Base cases +read = gs('xx'); +read = gs('xx', {}); +read = gs(['xx'], {}); + +// Package options +read = gs(['xx'], { allowEmpty: true }); +read = gs(['xx'], { base: 'xx' }); +read = gs(['xx'], { cwdbase: true }); +read = gs(['xx'], { uniqueBy: 'path' }); +read = gs(['xx'], { uniqueBy: 'base' }); +read = gs(['xx'], { uniqueBy: 'cwd' }); +read = gs(['xx'], { uniqueBy: (entry: gs.Entry) => entry.path }); + +// Glob options +read = gs(['xx'], { root: 'root' }); +read = gs(['xx'], { debug: true }); diff --git a/types/glob-stream/index.d.ts b/types/glob-stream/index.d.ts index 36a5d9fb92..d9d9c6d7c6 100644 --- a/types/glob-stream/index.d.ts +++ b/types/glob-stream/index.d.ts @@ -1,6 +1,7 @@ -// Type definitions for glob-stream v3.1.12 +// Type definitions for glob-stream v6.1.0 // Project: https://github.com/wearefractal/glob-stream // Definitions by: Bart van der Schoor +// mrmlnc // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped /// @@ -8,17 +9,40 @@ import glob = require('glob'); -export interface Options extends glob.IOptions { - cwd?: string; - base?: string; - cwdbase?: boolean; +declare function GlobStream(glob: string | string[]): NodeJS.ReadableStream; +declare function GlobStream(glob: string | string[], options: GlobStream.Options): NodeJS.ReadableStream; + +declare namespace GlobStream { + export interface Entry { + cwd: string; + base: string; + path: string; + } + + export type UniqueByStringPredicate = 'cwd' | 'base' | 'path'; + export type UniqueByFunctionPredicate = (entry: Entry) => string; + + export interface Options extends glob.IOptions { + /** + * Whether or not to error upon an empty singular glob. + */ + allowEmpty?: boolean; + /** + * The absolute segment of the glob path that isn't a glob. This value is attached + * to each globobject and is useful for relative pathing. + */ + base?: string; + /** + * Whether or not the `cwd` and `base` should be the same. + */ + cwdbase?: boolean; + /** + * Filters stream to remove duplicates based on the string property name or the result of function. + * When using a function, the function receives the streamed + * data (objects containing `cwd`, `base`, `path` properties) to compare against. + */ + uniqueBy?: UniqueByStringPredicate | UniqueByFunctionPredicate; + } } -export interface Element { - cwd: string; - base: string; - path: string; -} - -export declare function create(glob: string, opts?: Options): NodeJS.ReadableStream; -export declare function create(globs: string[], opts?: Options): NodeJS.ReadableStream; +export = GlobStream; diff --git a/types/glob/glob-tests.ts b/types/glob/glob-tests.ts index dcc72341cc..e0f612e682 100644 --- a/types/glob/glob-tests.ts +++ b/types/glob/glob-tests.ts @@ -1,22 +1,30 @@ import glob = require("glob"); -var Glob = glob.Glob; +const Glob = glob.Glob; -(()=> { - var pattern = "test/a/**/[cg]/../[cg]"; +(() => { + const pattern = "test/a/**/[cg]/../[cg]"; console.log(pattern); - var mg = new Glob(pattern, {mark: true, sync: true}, function (er, matches) { - console.log("matches", matches) + const mg = new Glob(pattern, {mark: true, sync: true}, (er, matches) => { + if (er) { + console.error(er); + return; + } + console.log("matches", matches); }); - console.log("after") + console.log("after"); })(); -(()=> { - var pattern = "{./*/*,/*,/usr/local/*}"; +(() => { + const pattern = "{./*/*,/*,/usr/local/*}"; console.log(pattern); - var mg = new Glob(pattern, {mark: true}, function (er, matches) { - console.log("matches", matches) + const mg = new Glob(pattern, {mark: true}, (er, matches) => { + if (er) { + console.error(er); + return; + } + console.log("matches", matches); }); - console.log("after") + console.log("after"); })(); diff --git a/types/glob/index.d.ts b/types/glob/index.d.ts index c7c6ffc601..f7628d5ab7 100644 --- a/types/glob/index.d.ts +++ b/types/glob/index.d.ts @@ -1,11 +1,10 @@ -// Type definitions for Glob 5.0.10 +// Type definitions for Glob 5.0 // Project: https://github.com/isaacs/node-glob // Definitions by: vvakame // voy // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped /// -/// import events = require("events"); import fs = require('fs'); @@ -19,8 +18,8 @@ declare namespace G { function hasMagic(pattern: string, options?: IOptions): boolean; - var Glob: IGlobStatic; - var GlobSync: IGlobSyncStatic; + let Glob: IGlobStatic; + let GlobSync: IGlobSyncStatic; interface IOptions extends minimatch.IOptions { cwd?: string; @@ -63,7 +62,7 @@ declare namespace G { } interface IGlobSyncStatic { - new (pattern: string, options?: IOptions): IGlobBase + new (pattern: string, options?: IOptions): IGlobBase; prototype: IGlobBase; } diff --git a/types/glob/tslint.json b/types/glob/tslint.json index a41bf5d19a..2c7c1bed53 100644 --- a/types/glob/tslint.json +++ b/types/glob/tslint.json @@ -1,79 +1,6 @@ { "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 + "interface-name": false } } diff --git a/types/google-cloud__storage/index.d.ts b/types/google-cloud__storage/index.d.ts index 544f2e095f..a614ea4982 100644 --- a/types/google-cloud__storage/index.d.ts +++ b/types/google-cloud__storage/index.d.ts @@ -153,6 +153,7 @@ declare namespace Storage { interface FileMetadata { contentType?: string; metadata?: CustomFileMetadata; + cacheControl?: string; } /** diff --git a/types/graphql/type/definition.d.ts b/types/graphql/type/definition.d.ts index 7f84c875fb..52df7bd46c 100644 --- a/types/graphql/type/definition.d.ts +++ b/types/graphql/type/definition.d.ts @@ -455,6 +455,7 @@ export class GraphQLEnumType { constructor(config: GraphQLEnumTypeConfig); getValues(): GraphQLEnumValue[]; getValue(name: string): GraphQLEnumValue; + isValidValue(value: any): boolean; serialize(value: any): string; parseValue(value: any): any; parseLiteral(valueNode: ValueNode): any; diff --git a/types/gridstack/index.d.ts b/types/gridstack/index.d.ts index 20f01186c6..ec7899217c 100644 --- a/types/gridstack/index.d.ts +++ b/types/gridstack/index.d.ts @@ -321,7 +321,7 @@ interface IGridstackOptions { /** * if true widgets could be removed by dragging outside of the grid. It could also be a jQuery selector string, */ - removable?: boolean; + removable?: boolean | string; /** * time in milliseconds before widget is being removed while dragging outside of the grid. (default: 2000) */ diff --git a/types/hapi-auth-basic/hapi-auth-basic-tests.ts b/types/hapi-auth-basic/hapi-auth-basic-tests.ts index 7f78fe9f65..1a7192af6f 100644 --- a/types/hapi-auth-basic/hapi-auth-basic-tests.ts +++ b/types/hapi-auth-basic/hapi-auth-basic-tests.ts @@ -22,21 +22,22 @@ const users: {[index: string]: User} = { } }; -const validate: Basic.ValidateFunc = function (request, username, password, callback) { +const validate: Basic.Validate = async (request, username, password, h) => { const user = users[username]; if (!user) { - return callback(null, false); + return { isValid: false, credentials: null }; } - Bcrypt.compare(password, user.password, (err, isValid) => { + let isValid = await Bcrypt.compare(password, user.password) - callback(err, isValid, { id: user.id, name: user.name }); - }); + return { isValid, credentials: { id: user.id, name: user.name } }; }; -server.register(Basic, (err) => { +server.register(Basic).then(() => { + + server.auth.strategy('simple', 'basic', { validate }); + server.auth.default('simple'); - server.auth.strategy('simple', 'basic', { validateFunc: validate }); server.route({ method: 'GET', path: '/', config: { auth: 'simple' } }); }); diff --git a/types/hapi-auth-basic/index.d.ts b/types/hapi-auth-basic/index.d.ts index 54d463c2b3..ddf05c348a 100644 --- a/types/hapi-auth-basic/index.d.ts +++ b/types/hapi-auth-basic/index.d.ts @@ -1,18 +1,24 @@ -// Type definitions for hapi 4.2 +// Type definitions for hapi-bauth-basic 5.0.0 // Project: https://github.com/hapijs/hapi-auth-basic // Definitions by: AJP +// Rodrigo Saboya // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped // TypeScript Version: 2.4 import * as Hapi from 'hapi'; declare namespace Basic { - interface ValidateFuncCallback { - (err: Error | null, isValid: boolean, userCredentials?: any): void; + interface ValidateCustomResponse { + response: any, } - interface ValidateFunc { - (request: Hapi.Request, username: string, password: string, callback: ValidateFuncCallback): void; + interface ValidateResponse { + isValid: boolean, + credentials?: any, + } + + interface Validate { + (request: Hapi.Request, username: string, password: string, h: object): Promise; } } diff --git a/types/heatmap.js/heatmap.js-tests.ts b/types/heatmap.js/heatmap.js-tests.ts index c2f2d34c16..af0c021b3f 100644 --- a/types/heatmap.js/heatmap.js-tests.ts +++ b/types/heatmap.js/heatmap.js-tests.ts @@ -1,42 +1,271 @@ +declare const container: HTMLElement; +// -- h337.HeatmapConfiguration -- -var baseLayer = L.tileLayer( - 'http://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png', { - attribution: 'Map data © OpenStreetMap contributors, CC-BY-SA, Imagery © CloudMade', - maxZoom: 18 - }); +{ + const config: h337.HeatmapConfiguration = { container }; + config; // $ExpectType HeatmapConfiguration<"value", "x", "y"> +} -var testData: HeatmapData = { - max: 8, - data: [ - { - lat: 24.6408, - lng:46.7728, - count: 3 - }, { - lat: 50.75, - lng: -1.55, - count: 1 +{ + const config: h337.HeatmapConfiguration = { + container, + xField: 'x', + yField: 'y', + valueField: 'value', + }; +} + +{ + // $ExpectError + const config: h337.HeatmapConfiguration = { + container, + valueField: 'foo', + }; +} + +{ + const config: h337.HeatmapConfiguration<'foo'> = { + container, + valueField: 'foo', + }; + config; // $ExpectType HeatmapConfiguration<"foo", "x", "y"> +} + +// -- h337.create -- + +{ + // $ExpectType Heatmap<"value", "x", "y"> + h337.create({ container }); + + // $ExpectType Heatmap<"count", "xPos", "yPos"> + h337.create<"count", "xPos", "yPos">({ + container, + valueField: "count", + xField: "xPos", + yField: "yPos", + }); + + const config: h337.HeatmapConfiguration<"count", "xPos", "yPos"> = { + container, + valueField: "count", + xField: "xPos", + yField: "yPos", + }; + // $ExpectType Heatmap<"count", "xPos", "yPos"> + h337.create(config); +} + +// -- Heatmap#addData -- + +{ + const heatmap = h337.create({ container }); + + // $ExpectType Heatmap<"value", "x", "y"> + heatmap.addData({ x: 1, y: 1, value: 5 }); + + heatmap.addData([ + { x: 1, y: 1, value: 1 }, + { x: 2, y: 2, value: 2 }, + ]); + + heatmap.addData({ x: null, y: 1, value: 1 }); // $ExpectError + heatmap.addData({ x: 1, y: null, value: 1 }); // $ExpectError + heatmap.addData({ x: 1, y: 1, value: null }); // $ExpectError + heatmap.addData({ y: 1, value: 1 }); // $ExpectError + heatmap.addData({ x: 1, value: 1 }); // $ExpectError + heatmap.addData({ x: 1, y: 1, }); // $ExpectError +} + +{ + const heatmap = h337.create<"count", "xPos", "yPos">({ + container, + xField: "xPos", + yField: "yPos", + valueField: "count", + }); + + // $ExpectType Heatmap<"count", "xPos", "yPos"> + heatmap.addData({ xPos: 1, yPos: 1, count: 5 }); + + heatmap.addData([ + { xPos: 1, yPos: 1, count: 1 }, + { xPos: 2, yPos: 2, count: 2 }, + ]); + + heatmap.addData({ xPos: null, yPos: 1, count: 1 }); // $ExpectError + heatmap.addData({ xPos: 1, yPos: null, count: 1 }); // $ExpectError + heatmap.addData({ xPos: 1, yPos: 1, count: null }); // $ExpectError + heatmap.addData({ yPos: 1, count: 1 }); // $ExpectError + heatmap.addData({ xPos: 1, count: 1 }); // $ExpectError + heatmap.addData({ xPos: 1, yPos: 1, }); // $ExpectError +} + +// -- Heatmap#setData -- + +{ + const validData: ReadonlyArray = + [{ x: 1, y: 2, value: 1 }]; + + const heatmap = h337.create({ container }); + heatmap.setData({ max: 5, data: validData }); // $ExpectError + heatmap.setData({ min: 5, data: validData }); // $ExpectError + + // $ExpectType Heatmap<"value", "x", "y"> + heatmap.setData({ + min: 0, + max: 1, + data: validData + }); + + heatmap.setData({ // $ExpectError + min: 0, + max: 1, + data: [{ xPos: 1, yPos: 2, value: 5 }] + }); +} + +{ + const validData: ReadonlyArray> = + [{ xPos: 1, yPos: 2, count: 1 }]; + + const heatmap = h337.create<"count", "xPos", "yPos">({ container }); + heatmap.setData({ max: 5, data: validData }); // $ExpectError + heatmap.setData({ min: 5, data: validData }); // $ExpectError + + // $ExpectType Heatmap<"count", "xPos", "yPos"> + heatmap.setData({ + min: 0, + max: 1, + data: validData + }); + + heatmap.setData({ // $ExpectError + min: 0, + max: 1, + data: [{ x: 1, y: 2, value: 5 }] + }); +} + +// -- Heatmap#setDataMax / Heatmap#setDataMin -- + +{ + const heatmap = h337.create({ container }); + + // $ExpectType Heatmap<"value", "x", "y"> + heatmap.setDataMax(500); + heatmap.setDataMax(null); // $ExpectError + heatmap.setDataMax(); // $ExpectError + + heatmap.setDataMin(500); + heatmap.setDataMin(null); // $ExpectError + heatmap.setDataMin(); // $ExpectError +} + +// -- Heatmap#configure -- + +{ + const heatmap = h337.create({ container }); + + // $ExpectType Heatmap<"value", "x", "y"> + heatmap.configure({ container }); + + const nextHeatmap = heatmap.configure<"count", "xPos", "yPos">({ + container, + valueField: "count", + xField: "xPos", + yField: "yPos" + }); + + nextHeatmap; // $ExpectType Heatmap<"count", "xPos", "yPos"> + + // $ExpectType Heatmap<"count", "xPos", "yPos"> + nextHeatmap.configure({ container }); +} + +// -- Heatmap#getValueAt -- + +{ + // $ExpectType number + h337.create({ container }).getValueAt({ x: 0, y: 1 }); + + // $ExpectType number + h337.create<"foo", "bar", "baz">({ container }).getValueAt({ x: 0, y: 1 }); +} + +// -- Heatmap#getData -- + +{ + // $ExpectType HeatmapData + h337.create({ container }).getData(); + + // $ExpectType HeatmapData + h337.create<"foo", "bar", "baz">({ container }).getData(); +} + +// -- Heatmap#getDataURL -- + +{ + // $ExpectType string + h337.create({ container }).getDataURL(); +} + +// -- Heatmap#repaint -- +{ + // $ExpectType Heatmap<"value", "x", "y"> + h337.create({ container }).repaint(); + + // $ExpectType Heatmap<"foo", "bar", "baz"> + h337.create<"foo", "bar", "baz">({ container }).repaint(); +} + +// -- Leaflet plugin -- + +{ + const baseLayer = L.tileLayer( + 'http://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png', { + // tslint:disable-next-line max-line-length + attribution: 'Map data © OpenStreetMap contributors, CC-BY-SA, Imagery © CloudMade', + maxZoom: 18 } - ] -}; + ); -var config : HeatmapConfiguration = { - radius: 2, - maxOpacity: .8, - scaleRadius: true, - useLocalExtrema: true, - latField: 'lat', - lngField: 'lng', - valueField: 'count' -}; + const testData: h337.HeatmapData> = { + min: 1, + max: 3, + data: [ + { + lat: 24.6408, + lng: 46.7728, + count: 3 + }, { + lat: 50.75, + lng: -1.55, + count: 1 + } + ] + }; -var heatmapLayer = new HeatmapOverlay(config); + const config: h337.HeatmapOverlayConfiguration<'count'> = { + radius: 2, + maxOpacity: .8, + scaleRadius: true, + useLocalExtrema: true, + latField: 'lat', + lngField: 'lng', + valueField: 'count' + }; + config; // $ExpectType HeatmapOverlayConfiguration<"count", "lat", "lng"> -var map = new L.Map('map-canvas', { - center: new L.LatLng(25.6586, -80.3568), - zoom: 4, - layers: [baseLayer, heatmapLayer] -}); + const heatmapLayer = new HeatmapOverlay(config); + heatmapLayer; // $ExpectType HeatmapOverlay<"count", "lat", "lng"> -heatmapLayer.setData(testData); + const map = new L.Map('map-canvas', { + center: new L.LatLng(25.6586, -80.3568), + zoom: 4, + layers: [baseLayer, heatmapLayer] + }); + + // $ExpectType void + heatmapLayer.setData(testData); +} diff --git a/types/heatmap.js/index.d.ts b/types/heatmap.js/index.d.ts index e6c0a4aec1..265f17f5fb 100644 --- a/types/heatmap.js/index.d.ts +++ b/types/heatmap.js/index.d.ts @@ -1,143 +1,390 @@ -// Type definitions for heatmap.js v2.0 +// Type definitions for heatmap.js 2.0 // Project: https://github.com/pa7/heatmap.js/ // Definitions by: Yang Guan +// Rhys van der Waerden // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -// TypeScript Version: 2.3 +// TypeScript Version: 2.4 + +export as namespace h337; + +/** + * Create a heatmap instance. A Heatmap can be customized with the configObject. + * + * @example + * + * // create configuration object + * var config = { + * container: document.getElementById('heatmapContainer'), + * radius: 10, + * maxOpacity: .5, + * minOpacity: 0, + * blur: .75 + * }; + * // create heatmap with configuration + * var heatmapInstance = h337.create(config); + * + * @example + * + * // create configuration object + * var config = { + * container: document.getElementById('heatmapContainer'), + * radius: 10, + * maxOpacity: .5, + * minOpacity: 0, + * blur: .75, + * gradient: { + * // enter n keys between 0 and 1 here + * // for gradient color customization + * '.5': 'blue', + * '.8': 'red', + * '.95': 'white' + * } + * }; + * var heatmapInstance = h337.create(config); + */ +export function create< + V extends string = 'value', + X extends string = 'x', + Y extends string = 'y' +>( + configObject: HeatmapConfiguration +): Heatmap; + +export function register(pluginKey: string, plugin: any): void; + +/** + * Heatmap instances are returned by h337.create. A heatmap instance has its own + * internal datastore and renderer where you can manipulate data. As a result + * the heatmap gets updated (either partially or completely, depending on + * whether it's necessary). + */ +export class Heatmap { + /** + * Use this functionality only for adding datapoints on the fly, not for data + * initialization! heatmapInstance.addData adds a single or multiple + * datapoints to the heatmap's datastore. + * + * @example + * + * var dataPoint = { + * x: 5, // x coordinate of the datapoint, a number + * y: 5, // y coordinate of the datapoint, a number + * value: 100 // the value at datapoint(x, y) + * }; + * heatmapInstance.addData(dataPoint); + * + * @example + * + * // for data initialization use setData!! + * var dataPoints = [dataPoint, dataPoint, dataPoint, dataPoint]; + * heatmapInstance.addData(dataPoints); + */ + addData(dataPoint: DataPoint | ReadonlyArray>): this; + + /** + * Initialize a heatmap instance with the given dataset. Removes all + * previously existing points from the heatmap instance and re-initializes + * the datastore. + * + * @example + * + * var data = { + * max: 100, + * min: 0, + * data: [ + * dataPoint, dataPoint, dataPoint, dataPoint + * ] + * }; + * heatmapInstance.setData(data); + */ + setData(data: HeatmapData>): this; + + /** + * Changes the upper bound of your dataset and triggers a complete + * rerendering. + * + * @example + * + * heatmapInstance.setDataMax(200); + * // setting the maximum value triggers a complete rerendering of the heatmap + * heatmapInstance.setDataMax(100); + */ + setDataMax(number: number): this; + + /** + * Changes the lower bound of your dataset and triggers a complete + * rerendering. + * + * @example + * + * heatmapInstance.setDataMin(10); + * // setting the minimum value triggers a complete rerendering of the heatmap + * heatmapInstance.setDataMin(0); + */ + setDataMin(number: number): this; + + /** + * Reconfigures a heatmap instance after it has been initialized. Triggers a + * complete rerendering. + * + * NOTE: This returns a reference to itself, but also offers an opportunity + * to change the `xField`, `yField` and `valueField` options, which can + * change the type of the `Heatmap` instance. + * + * @example + * + * var nuConfig = { + * radius: 10, + * maxOpacity: .5, + * minOpacity: 0, + * blur: .75 + * }; + * heatmapInstance.configure(nuConfig); + */ + configure< + Vn extends string = V, + Xn extends string = X, + Yn extends string = Y + >(configObject: HeatmapConfiguration): Heatmap; + + /** + * Returns value at datapoint position. + * + * The returned value is an interpolated value based on the gradient blending + * if point is not in store. + * + * @example + * + * heatmapInstance.addData({ x: 10, y: 10, value: 100}); + * // get the value at x=10, y=10 + * heatmapInstance.getValueAt({ x: 10, y: 10 }); // returns 100 + */ + getValueAt(point: { x: number, y: number }): number; + + /** + * Returns a persistable and reimportable (with setData) JSON object. + * + * @example + * + * var currentData = heatmapInstance.getData(); + * // now let's create a new instance and set the data + * var heatmap2 = h337.create(config); + * heatmap2.setData(currentData); // now both heatmap instances have the same content + */ + getData(): HeatmapData; + + /** + * Returns dataURL string. + * + * The returned value is the base64 encoded dataURL of the heatmap instance. + * + * @example + * + * heatmapInstance.getDataURL(); // data:image/png;base64... + * // ready for saving locally or on the server + */ + getDataURL(): string; + + /** + * Repaints the whole heatmap canvas. + */ + repaint(): this; +} + +export interface BaseHeatmapConfiguration { + /** + * A background color string in form of hexcode, color name, or rgb(a) + */ + backgroundColor?: string; + + /** + * The blur factor that will be applied to all datapoints. The higher the + * blur factor is, the smoother the gradients will be + * Default value: 0.85 + */ + blur?: number; + + /** + * An object that represents the gradient. + * Syntax: {[key: number in range [0,1]]: color} + */ + gradient?: { [key: string]: string }; + + /** + * The maximal opacity the highest value in the heatmap will have. (will be + * overridden if opacity set) + * Default value: 0.6 + */ + maxOpacity?: number; + + /** + * The minimum opacity the lowest value in the heatmap will have (will be + * overridden if opacity set) + */ + minOpacity?: number; + + /** + * A global opacity for the whole heatmap. This overrides maxOpacity and + * minOpacity if set + * Default value: 0.6 + */ + opacity?: number; + + /** + * The radius each datapoint will have (if not specified on the datapoint + * itself) + */ + radius?: number; + + /** + * Scales the radius based on map zoom. + */ + scaleRadius?: boolean; + + /** + * The property name of the value/weight in a datapoint + * Default value: 'value' + */ + valueField?: V; + + /** + * Pass a callback to receive extrema change updates. Useful for DOM + * legends. + */ + onExtremaChange?: () => void; + + /** + * Indicate whether the heatmap should use a global extrema or a local + * extrema (the maximum and minimum of the currently displayed viewport) + */ + useLocalExtrema?: boolean; +} + +/** + * Configuration object of a heatmap + */ +export interface HeatmapConfiguration< + V extends string = 'value', + X extends string = 'x', + Y extends string = 'y', +> extends BaseHeatmapConfiguration { + /** + * A DOM node where the heatmap canvas should be appended (heatmap will adapt to + * the node's size) + */ + container: HTMLElement; + + /** + * The property name of your x coordinate in a datapoint + * Default value: 'x' + */ + xField?: X; + + /** + * The property name of your y coordinate in a datapoint + * Default value: 'y' + */ + yField?: Y; +} + +export interface HeatmapOverlayConfiguration< + V extends string = 'value', + TLat extends string = 'lat', + TLong extends string = 'lng', +> extends BaseHeatmapConfiguration { + /** + * The property name of your latitude coordinate in a datapoint + * Default value: 'x' + */ + latField?: TLat; + + /** + * The property name of your longitude coordinate in a datapoint + * Default value: 'y' + */ + lngField?: TLong; +} + +/** + * A single data point on a heatmap. The interface of the data point can be + * overridden by providing alternative values for `xKey` and `yKey` in the + * config object. + */ +export type DataPoint< + V extends string = 'value', + X extends string = 'x', + Y extends string = 'y', +> = Record; + +/** + * Type of data returned by `Heatmap#hello`, which ignores custom `xField`, + * `yField` and `valueField`. + */ +export interface DataCircle { + x: number; + y: number; + value: number; + radius: number; +} + +/** + * An object representing the set of data points on a heatmap + */ +export interface HeatmapData { + /** + * An array of data points + */ + data: ReadonlyArray; + + /** + * Max value of the valueField + */ + max: number; + + /** + * Min value of the valueField + */ + min: number; +} + +// -- Leaflet plugin -- import * as Leaflet from "leaflet"; declare global { - /* - * Configuration object of a heatmap - */ - interface HeatmapConfiguration { - - /* - * A background color string in form of hexcode, color name, or rgb(a) - */ - backgroundColor?: string; - - /* - * The blur factor that will be applied to all datapoints. The higher the - * blur factor is, the smoother the gradients will be - * Default value: 0.85 - */ - blur?: number; - - /* - * An object that represents the gradient - */ - gradient?: any; - - /* - * The property name of your latitude coordinate in a datapoint - * Default value: 'x' - */ - latField?: string; - - /* - * The property name of your longitude coordinate in a datapoint - * Default value: 'y' - */ - lngField?: string; - - /* - * The maximal opacity the highest value in the heatmap will have. (will be - * overridden if opacity set) - * Default value: 0.6 - */ - maxOpacity?: number; - - /* - * The minimum opacity the lowest value in the heatmap will have (will be - * overridden if opacity set) - */ - minOpacity?: number; - - /* - * A global opacity for the whole heatmap. This overrides maxOpacity and - * minOpacity if set - */ - opacity?: number; - - /* - * The radius each datapoint will have (if not specified on the datapoint - * itself) - */ - radius?: number; + /** + * The overlay layer to be added onto leaflet map + */ + class HeatmapOverlay< + V extends string, + TLat extends string, + TLng extends string + > implements Leaflet.ILayer { + /** + * Initialization function + */ + constructor(configuration: HeatmapOverlayConfiguration); /** - * Scales the radius based on map zoom. + * Initialize a heatmap instance with the given dataset */ - scaleRadius?: boolean; + setData(data: HeatmapData>): void; - /* - * Indicate whether the heatmap should use a global extrema or a local - * extrema (the maximum and minimum of the currently displayed viewport) - */ - useLocalExtrema?: boolean; + /** + * Experimential... not ready. + */ + addData(data: DataPoint | ReadonlyArray>): void; - /* - * The property name of the value/weight in a datapoint - * Default value: 'value' - */ - valueField?: string; - } - - /* - * A single data point on a heatmap. The keys are specified by - * HeatmapConfig.latField, HeatmapConfig.lngField and HeatmapConfig.valueField - */ - interface HeatmapDataPoint { - [index: string]: number; - } - - /* - * An object representing the set of data points on a heatmap - */ - interface HeatmapData { - - /* - * An array of HeatmapDataPoints - */ - data: HeatmapDataPoint[]; - - /* - * Max value of the valueField - */ - max?: number; - - /* - * Min value of the valueField - */ - min?: number; - } - - /* - * The overlay layer to be added onto leaflet map - */ - class HeatmapOverlay { - - /* - * Initialization function - */ - constructor(configuration: HeatmapConfiguration) - - /* - * Create DOM elements for an overlay, adding them to map panes and puts - * listeners on relevant map events - */ + /** + * Create DOM elements for an overlay, adding them to map panes and puts + * listeners on relevant map events + */ onAdd(map: Leaflet.Map): void; - /* - * Remove the overlay's elements from the DOM and remove listeners - * previously added by onAdd() - */ + /** + * Remove the overlay's elements from the DOM and remove listeners + * previously added by onAdd() + */ onRemove(map: Leaflet.Map): void; - - /* - * Initialize a heatmap instance with the given dataset - */ - setData(data: HeatmapData): void; } } diff --git a/types/heatmap.js/tsconfig.json b/types/heatmap.js/tsconfig.json index 06fa28716f..2e22853a34 100644 --- a/types/heatmap.js/tsconfig.json +++ b/types/heatmap.js/tsconfig.json @@ -7,7 +7,7 @@ ], "noImplicitAny": true, "noImplicitThis": true, - "strictNullChecks": false, + "strictNullChecks": true, "strictFunctionTypes": true, "baseUrl": "../", "typeRoots": [ diff --git a/types/heatmap.js/tslint.json b/types/heatmap.js/tslint.json index a41bf5d19a..f93cf8562a 100644 --- a/types/heatmap.js/tslint.json +++ b/types/heatmap.js/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/homeworks/homeworks-tests.ts b/types/homeworks/homeworks-tests.ts index 16bce6d106..5c41b7fffc 100644 --- a/types/homeworks/homeworks-tests.ts +++ b/types/homeworks/homeworks-tests.ts @@ -1,33 +1,38 @@ const element: JQuery = $('#element'); const target: JQuery = $('#target'); +homeworks.disableHook(); + element.checkbox({ - /* Empty options */ -}).bind('change', (event: HomeWorksEventObject) => { - /* HomeWorks native event */ -}); + /* Empty options */ +}) + .on('change', (event: JQuery.Event) => { + /* HomeWorks native event */ + }); element.converter({ - /* Empty options */ + /* Empty options */ }); element.dropdown({ - /* Empty options */ + /* Empty options */ }); const dropdownHandlerTarget: JQuery = element.addHandler(target); element.input({ - /* Empty options */ -}).bind('change', (event: HomeWorksEventObject) => { - /* HomeWorks native event */ -}); + /* Empty options */ +}) + .on('change', (event: JQuery.Event) => { + /* HomeWorks native event */ + }); element.modal({ - /* Any options */ -}).each(() => { - /* Chaining */ -}); + /* Any options */ +}) + .each(() => { + /* Chaining */ + }); element.modal('show'); element.modal('hide'); element.modal('open'); @@ -35,59 +40,70 @@ element.modal('close'); notification('title', 'content', 'url', 'success'); -element.ripple({ - /* Object options */ -}); -element.start({ - x: 1, - y: 2 -}); +element + .ripple({ + /* Object options */ + }) + .on('start', (event: homeworks.RippleEvent) => { + }); + +element + .start({ + x: 1, + y: 2 + }); element.spinner({ - type: 'any', - empty: 'any' -}).bind('change', (event: HomeWorksEventObject) => { - /* HomeWorks native event */ -}); - -element.step('method'); -element.step({ - active: 0 -}).bind('move', (event: HomeWorksStepEventObject) => { - /* HomeWorks step event */ -}); + type: 'any', + empty: 'any' +}) + .on('change', (event: JQuery.Event) => { + /* HomeWorks native event */ + }); element.tab('method'); element.tab({ - active: 0 -}).bind('move', (event: HomeWorksTabEventObject) => { - /* HomeWorks step event */ -}); + active: 0 +}) + .on('move', (event: homeworks.TabEvent) => { + /* HomeWorks step event */ + }); + +element.step('method'); +element.step({ + active: 0 +}) + .on('move', (event: homeworks.StepEvent) => { + /* HomeWorks step event */ + }); toast('hello homeworks'); toast({ - message: 'hello homeworks' + message: 'hello homeworks' }); -element.toggle({ - placeholder: 'placeholder' -}).bind('change', (event: HomeWorksEventObject) => { - /* HomeWorks native event */ -}); +element + .toggle({ + placeholder: 'placeholder' + }) + .on('change', (event: JQuery.Event) => { + /* HomeWorks native event */ + }); -element.upload({ - url: 'url', - type: 'type', - data: {}, - dest: 'dest', - isBtn: true, - beforeStart() { - }, - complete(data: any) { - }, - success(data?: any, state?: any, xhr?: any) { - }, - error(xhr?: any, state?: any, error?: any) { - }, - extensions: 'any' -}); +element + .upload({ + url: 'url', + type: 'type', + data: {}, + dest: 'dest', + isBtn: true, + beforeStart() { + }, + complete(data: any) { + }, + success(data?: any, state?: any, xhr?: any) { + }, + error(xhr?: any, state?: any, error?: any) { + }, + extensions: 'any' + }); diff --git a/types/homeworks/index.d.ts b/types/homeworks/index.d.ts index 4449483d35..7a25666659 100644 --- a/types/homeworks/index.d.ts +++ b/types/homeworks/index.d.ts @@ -6,208 +6,242 @@ /// -/** - * * [MAIN] - * @ EVENT - * - */ +type _NativeEvent = Event; -declare interface HomeWorksEventObject { - element: JQuery; - value: string; - checked?: boolean; -} +interface JQuery { + /** + * jQuery homeworks chaining functions + */ -declare interface JQuery { + /** + * @since 1.0.0 + */ bind(eventType: string, handler: (...parameters: any[]) => void): JQuery; + /** + * @since 1.0.0 + */ knock(): JQuery; -} - -/** - * * [COMPONENT] - * @ CHECKBOX - * - */ -interface CheckboxOptions { -} - -declare interface JQuery { - checkbox(options?: CheckboxOptions): JQuery; -} - -/** - * * [COMPONENT] - * @ CONVERTER - * - */ - -interface ConverterOptions { -} - -declare interface JQuery { - converter(options?: ConverterOptions): JQuery; -} - -/** - * * [COMPONENT] - * @ DROPDOIWN - * - */ - -interface DropdownOptions { -} - -declare interface JQuery { - dropdown(options?: DropdownOptions): JQuery; - addHandler(target: JQuery): JQuery; -} - -/** - * * [COMPONENT] - * @ INPUT - * - */ - -interface InputOptions { -} - -declare interface JQuery { - input(options?: InputOptions): JQuery; -} - -/** - * * [COMPONENT] - * @ MODAL - * - */ - -declare interface JQuery { - modal(options?: any): JQuery; - modal(method?: string, options?: any): JQuery; -} - -/** - * * [COMPONENT] - * @ NOTIFICATION - * - */ - -declare function notification(title: string, content: string, url: string, status?: string): void; - -/** - * * [COMPONENT] - * @ RIPPLE - * - */ - -interface RippleStartOptions { - x: number; - y: number; -} - -declare interface JQuery { + /** + * @since 1.0.0 + */ + checkbox(options?: homeworks.CheckboxOptions): JQuery; + /** + * @since 1.0.0 + */ + converter(options?: homeworks.ConverterOptions): JQuery; + /** + * @since 1.0.0 + */ + spinner(options?: homeworks.SpinnerOptions): JQuery; + /** + * @since 1.0.0 + */ + dropdown(options?: homeworks.DropdownOptions): JQuery; + /** + * @since 1.0.0 + */ ripple(options?: any): JQuery; - start(options?: RippleStartOptions): JQuery; -} - -/** - * * [COMPONENT] - * @ SPINNER - * - */ - -interface SpinnerOptions { - type?: any; - empty?: any; -} - -declare interface JQuery { - spinner(options?: SpinnerOptions): JQuery; -} - -/** - * * [COMPONENT] - * @ STEP - * - */ - -interface StepOptions { - active?: number; -} - -declare interface JQuery { - step(method?: string): JQuery; - step(options?: StepOptions): JQuery; -} - -declare interface HomeWorksStepEventObject { - header: JQuery[]; - index: number; - length: number; -} - -/** - * * [COMPONENT] - * @ TAB - * - */ - -interface TabOptions { - active?: number; -} - -declare interface JQuery { + /** + * @since 1.0.0 + */ + input(options?: homeworks.InputOptions): JQuery; + /** + * @since 1.0.0 + */ + modal(options?: any): JQuery; + /** + * @since 1.0.0 + */ + modal(method?: string, options?: any): JQuery; + /** + * @since 1.0.0 + */ tab(method?: string): JQuery; - tab(options?: TabOptions): JQuery; -} + /** + * @since 1.0.0 + */ + tab(options?: homeworks.TabOptions): JQuery; + /** + * @since 1.0.0 + */ + step(method?: string): JQuery; + /** + * @since 1.0.0 + */ + step(options?: homeworks.StepOptions): JQuery; + /** + * @since 1.0.0 + */ + toggle(options: homeworks.ToggleOptions): JQuery; + /** + * @since 1.0.0 + */ + upload(options?: homeworks.UploadOptions): JQuery; + /** + * @since 1.0.0 + * @summary dropdown method + */ + addHandler(target: JQuery): JQuery; + /** + * @since 1.0.0 + * @summary ripple method + */ + start(event?: homeworks.RippleEvent): JQuery; -declare interface HomeWorksTabEventObject { - header: JQuery[]; - index: number; - length: number; + /** + * jQuery homeworks events + */ + + /** + * @since 1.0.44 + */ + on(event: homeworks.TabMoveEventType, handler: JQuery.EventHandlerBase): JQuery; + /** + * @since 1.0.44 + */ + on(event: homeworks.StepMoveEventType, handler: JQuery.EventHandlerBase): JQuery; + /** + * @since 1.0.44 + */ + on(event: homeworks.RippleStartEventType, handler: JQuery.EventHandlerBase): JQuery; } /** - * * [COMPONENT] - * @ TOAST - * + * @since 1.0.44 */ +declare function notification( + title: string, + content: string, + url: string, + status?: string): void; +/** + * @since 1.0.44 + */ declare function toast(message: any): void; -/** - * * [COMPONENT] - * @ TOGGLE - * - */ +declare namespace homeworks { + /** + * @since 1.0.0 + */ + interface CheckboxOptions { + } -interface ToggleOptions { - placeholder?: string; -} - -declare interface JQuery { - toggle(options: ToggleOptions): JQuery; -} - -/** - * * [COMPONENT] - * @ UPLOAD - * - */ - -interface UploadOptions { - url: string; - type?: string; - data?: any; - dest?: string; - isBtn?: boolean; - beforeStart?: () => void; - complete?: (data?: any) => void; - success?: (data?: any, state?: any, xhr?: any) => void; - error?: (xhr?: any, state?: any, error?: any) => void; - extensions?: any; -} - -declare interface JQuery { - upload(options?: UploadOptions): JQuery; + /** + * @since 1.0.0 + */ + interface ConverterOptions { + } + + /** + * @since 1.0.0 + */ + interface DropdownOptions { + } + + /** + * @since 1.0.0 + */ + interface InputOptions { + } + + /** + * @since 1.0.0 + */ + interface ToggleOptions { + placeholder?: string; + } + + /** + * @since 1.0.0 + */ + interface UploadOptions { + url: string; + type?: string; + data?: any; + dest?: string; + isBtn?: boolean; + beforeStart?: () => void; + complete?: (data?: any) => void; + success?: (data?: any, state?: any, xhr?: any) => void; + error?: (xhr?: any, state?: any, error?: any) => void; + extensions?: any; + } + + /** + * @since 1.0.0 + */ + interface SpinnerOptions { + type?: any; + empty?: any; + } + + /** + * @since 1.0.0 + */ + interface StepOptions { + active?: number; + } + + /** + * @since 1.0.0 + */ + interface TabOptions { + active?: number; + } + + /** + * @since 1.0.44 + */ + interface Event { + element: JQuery; + value: string | string[] | number; + checked?: boolean; + } + + /** + * @since 1.0.44 + */ + interface StepEvent { + header: JQuery[]; + index: number; + length: number; + } + + /** + * @since 1.0.44 + */ + interface TabEvent { + header: JQuery[]; + index: number; + length: number; + } + + /** + * @since 1.0.44 + */ + interface RippleEvent { + x: number; + y: number; + } + + /** + * @since 1.0.0 + */ + type TabMoveEventType = 'move'; + + /** + * @since 1.0.0 + */ + type StepMoveEventType = 'move'; + + /** + * @since 1.0.0 + */ + type RippleStartEventType = 'start'; + + /** + * @since 1.0.44 + */ + function disableHook(): void; } diff --git a/types/http-context/http-context-tests.ts b/types/http-context/http-context-tests.ts index 1542f50e1e..629f09ece3 100644 --- a/types/http-context/http-context-tests.ts +++ b/types/http-context/http-context-tests.ts @@ -9,7 +9,7 @@ let header: http.IncomingHttpHeaders = context.header; header = context.headers; header = request.header; header = request.headers; -const headerString: string | string[] = header['Content-Type']; +const headerString: string | string[] | undefined = header['Content-Type']; let url: string = context.url; url = request.url; diff --git a/types/ignore-styles/ignore-styles-tests.ts b/types/ignore-styles/ignore-styles-tests.ts new file mode 100644 index 0000000000..1a7dbc74c1 --- /dev/null +++ b/types/ignore-styles/ignore-styles-tests.ts @@ -0,0 +1,15 @@ +import register, { DEFAULT_EXTENSIONS, oldHandlers, noOp, restore } from 'ignore-styles'; + +register(['.css'], (module, filename) => {}); // $ExpectType void +register(['.css']); // $ExpectType void +register(undefined, (module, filename) => {}); // $ExpectType void +register([1], (module, filename) => {}); // $ExpectError +register(['.css'], 1); // $ExpectError + +DEFAULT_EXTENSIONS[0]; // $ExpectType string + +oldHandlers['.css']; // $ExpectType Handler + +noOp(); // $ExpectType void + +restore(); // $ExpectType void diff --git a/types/ignore-styles/index.d.ts b/types/ignore-styles/index.d.ts new file mode 100644 index 0000000000..2eab90b591 --- /dev/null +++ b/types/ignore-styles/index.d.ts @@ -0,0 +1,24 @@ +// Type definitions for ignore-styles 5.0 +// Project: https://github.com/bkonkle/ignore-styles +// Definitions by: Taiju Muto +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.4 + +/// + +export type Handler = (m: NodeModule, filename: string) => any; + +export const DEFAULT_EXTENSIONS: string[]; + +export let oldHandlers: { + [ext: string]: Handler +}; + +export function noOp(): void; + +export function restore(): void; + +export default function register( + extensions?: string[], + handler?: Handler +): void; diff --git a/types/ignore-styles/tsconfig.json b/types/ignore-styles/tsconfig.json new file mode 100644 index 0000000000..aed3487cf4 --- /dev/null +++ b/types/ignore-styles/tsconfig.json @@ -0,0 +1,23 @@ +{ + "compilerOptions": { + "module": "commonjs", + "lib": [ + "es6" + ], + "noImplicitAny": true, + "noImplicitThis": true, + "strictFunctionTypes": true, + "strictNullChecks": true, + "baseUrl": "../", + "typeRoots": [ + "../" + ], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true + }, + "files": [ + "index.d.ts", + "ignore-styles-tests.ts" + ] +} diff --git a/types/ignore-styles/tslint.json b/types/ignore-styles/tslint.json new file mode 100644 index 0000000000..3db14f85ea --- /dev/null +++ b/types/ignore-styles/tslint.json @@ -0,0 +1 @@ +{ "extends": "dtslint/dt.json" } diff --git a/types/inquirer/index.d.ts b/types/inquirer/index.d.ts index 2a0b9f60f4..32c54fa99e 100644 --- a/types/inquirer/index.d.ts +++ b/types/inquirer/index.d.ts @@ -2,6 +2,7 @@ // Project: https://github.com/SBoudrias/Inquirer.js // Definitions by: Qubo // Parvez +// Jouderian // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped /// @@ -115,6 +116,14 @@ declare namespace inquirer { * Add a mask when password will entered */ mask?: string; + /** + * Change the default prefix message. + */ + prefix?: string; + /** + * Change the default suffix message. + */ + suffix?: string; } /** diff --git a/types/inquirer/inquirer-tests.ts b/types/inquirer/inquirer-tests.ts index d3591b13d2..4a43dcc98e 100644 --- a/types/inquirer/inquirer-tests.ts +++ b/types/inquirer/inquirer-tests.ts @@ -151,13 +151,15 @@ var questions = [ { type: "input", name: "first_name", - message: "What's your first name" + message: "What's your first name", + prefix: "1 - ", }, { type: "input", name: "last_name", message: "What's your last name", - default: function () { return "Doe"; } + default: function () { return "Doe"; }, + suffix: "!!" }, { type: "input", diff --git a/types/ioredis/index.d.ts b/types/ioredis/index.d.ts index ec1dbe3512..ff2810ebd4 100644 --- a/types/ioredis/index.d.ts +++ b/types/ioredis/index.d.ts @@ -5,6 +5,7 @@ // Yoga Aliarham // Ebrahim // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.3 /* =================== USAGE =================== import * as Redis from "ioredis"; @@ -13,6 +14,8 @@ /// +import Promise = require('bluebird'); + interface RedisStatic { new(port?: number, host?: string, options?: IORedis.RedisOptions): IORedis.Redis; new(host?: string, options?: IORedis.RedisOptions): IORedis.Redis; @@ -78,9 +81,9 @@ declare namespace IORedis { strlen(key: string, callback: (err: Error, res: number) => void): void; strlen(key: string): Promise; - del(key: string, ...keys: string[]): any; + del(...keys: string[]): any; - exists(key: string, ...keys: string[]): any; + exists(...keys: string[]): any; setbit(key: string, offset: number, value: any, callback: (err: Error, res: number) => void): void; setbit(key: string, offset: number, value: any): Promise; @@ -103,11 +106,11 @@ declare namespace IORedis { decr(key: string, callback: (err: Error, res: number) => void): void; decr(key: string): Promise; - mget(key: string, ...keys: string[]): any; + mget(...keys: string[]): any; - rpush(key: string, value: any, ...values: string[]): any; + rpush(key: string, ...values: any[]): any; - lpush(key: string, value: any, ...values: string[]): any; + lpush(key: string, ...values: any[]): any; rpushx(key: string, value: any, callback: (err: Error, res: number) => void): void; rpushx(key: string, value: any): Promise; @@ -124,9 +127,9 @@ declare namespace IORedis { lpop(key: string, callback: (err: Error, res: string) => void): void; lpop(key: string): Promise; - brpop(key: string, ...keys: string[]): any; + brpop(...keys: string[]): any; - blpop(key: string, ...keys: string[]): any; + blpop(...keys: string[]): any; brpoplpush(source: string, destination: string, timeout: number, callback: (err: Error, res: any) => void): void; brpoplpush(source: string, destination: string, timeout: number): Promise; @@ -173,17 +176,17 @@ declare namespace IORedis { srandmember(key: string, count: number, callback: (err: Error, res: any) => void): void; srandmember(key: string, count?: number): Promise; - sinter(key: string, ...keys: string[]): any; + sinter(...keys: string[]): any; - sinterstore(destination: string, key: string, ...keys: string[]): any; + sinterstore(destination: string, ...keys: string[]): any; - sunion(key: string, ...keys: string[]): any; + sunion(...keys: string[]): any; - sunionstore(destination: string, key: string, ...keys: string[]): any; + sunionstore(destination: string, ...keys: string[]): any; - sdiff(key: string, ...keys: string[]): any; + sdiff(...keys: string[]): any; - sdiffstore(destination: string, key: string, ...keys: string[]): any; + sdiffstore(destination: string, ...keys: string[]): any; smembers(key: string, callback: (err: Error, res: any) => void): void; smembers(key: string): Promise; @@ -193,10 +196,10 @@ declare namespace IORedis { zincrby(key: string, increment: number, member: string, callback: (err: Error, res: any) => void): void; zincrby(key: string, increment: number, member: string): Promise; - zrem(key: string, member: string, ...members: any[]): any; + zrem(key: string, ...members: any[]): any; - zremrangebyscore(key: string, min: number, max: number, callback: (err: Error, res: any) => void): void; - zremrangebyscore(key: string, min: number, max: number): Promise; + zremrangebyscore(key: string, min: number | string, max: number | string, callback: (err: Error, res: any) => void): void; + zremrangebyscore(key: string, min: number | string, max: number | string): Promise; zremrangebyrank(key: string, start: number, stop: number, callback: (err: Error, res: any) => void): void; zremrangebyrank(key: string, start: number, stop: number): Promise; @@ -213,12 +216,12 @@ declare namespace IORedis { zrevrange(key: string, start: number, stop: number, withScores: "WITHSCORES", callback: (err: Error, res: any) => void): void; zrevrange(key: string, start: number, stop: number, withScores?: "WITHSCORES"): Promise; - zrangebyscore(key: string, min: number, max: number, ...args: string[]): any; + zrangebyscore(key: string, min: number | string, max: number | string, ...args: string[]): any; - zrevrangebyscore(key: string, max: number, min: number, ...args: string[]): any; + zrevrangebyscore(key: string, max: number | string, min: number | string, ...args: string[]): any; - zcount(key: string, min: number, max: number, callback: (err: Error, res: number) => void): void; - zcount(key: string, min: number, max: number): Promise; + zcount(key: string, min: number | string, max: number | string, callback: (err: Error, res: number) => void): void; + zcount(key: string, min: number | string, max: number | string): Promise; zcard(key: string, callback: (err: Error, res: number) => void): void; zcard(key: string): Promise; @@ -241,9 +244,11 @@ declare namespace IORedis { hget(key: string, field: string, callback: (err: Error, res: string) => void): void; hget(key: string, field: string): Promise; - hmset(key: string, field: string, value: any, ...args: string[]): any; + hmset(key: string, field: string, value: any, ...args: string[]): Promise<0 | 1>; + hmset(key: string, data: any, callback: (err: Error, res: 0 | 1) => void): void; + hmset(key: string, data: any): Promise<0 | 1>; - hmget(key: string, field: string, ...fields: string[]): any; + hmget(key: string, ...fields: string[]): any; hincrby(key: string, field: string, increment: number, callback: (err: Error, res: number) => void): void; hincrby(key: string, field: string, increment: number): Promise; @@ -251,7 +256,7 @@ declare namespace IORedis { hincrbyfloat(key: string, field: string, increment: number, callback: (err: Error, res: number) => void): void; hincrbyfloat(key: string, field: string, increment: number): Promise; - hdel(key: string, field: string, ...fields: string[]): any; + hdel(key: string, ...fields: string[]): any; hlen(key: string, callback: (err: Error, res: number) => void): void; hlen(key: string): Promise; @@ -388,18 +393,18 @@ declare namespace IORedis { config(...args: any[]): any; - subscribe(channel: string, ...channels: any[]): any; + subscribe(...channels: any[]): any; unsubscribe(...channels: string[]): any; - psubscribe(pattern: string, ...patterns: string[]): any; + psubscribe(...patterns: string[]): any; punsubscribe(...patterns: string[]): any; publish(channel: string, message: string, callback: (err: Error, res: number) => void): void; publish(channel: string, message: string): Promise; - watch(key: string, ...keys: string[]): any; + watch(...keys: string[]): any; unwatch(callback: (err: Error, res: string) => void): void; unwatch(): Promise; @@ -432,11 +437,11 @@ declare namespace IORedis { zscan(key: string, cursor: number, ...args: any[]): any; - pfmerge(destkey: string, sourcekey: string, ...sourcekeys: string[]): any; + pfmerge(destkey: string, ...sourcekeys: string[]): any; - pfadd(key: string, element: string, ...elements: string[]): any; + pfadd(key: string, ...elements: string[]): any; - pfcount(key: string, ...keys: string[]): any; + pfcount(...keys: string[]): any; pipeline(commands?: string[][]): Pipeline; @@ -464,9 +469,9 @@ declare namespace IORedis { strlen(key: string, callback?: (err: Error, res: number) => void): Pipeline; - del(key: string, ...keys: string[]): Pipeline; + del(...keys: string[]): Pipeline; - exists(key: string, ...keys: string[]): Pipeline; + exists(...keys: string[]): Pipeline; setbit(key: string, offset: number, value: any, callback?: (err: Error, res: number) => void): Pipeline; @@ -482,11 +487,11 @@ declare namespace IORedis { decr(key: string, callback?: (err: Error, res: number) => void): Pipeline; - mget(key: string, ...keys: string[]): Pipeline; + mget(...keys: string[]): Pipeline; - rpush(key: string, value: any, ...values: string[]): Pipeline; + rpush(key: string, ...values: any[]): Pipeline; - lpush(key: string, value: any, ...values: string[]): Pipeline; + lpush(key: string, ...values: any[]): Pipeline; rpushx(key: string, value: any, callback?: (err: Error, res: number) => void): Pipeline; @@ -498,9 +503,9 @@ declare namespace IORedis { lpop(key: string, callback?: (err: Error, res: string) => void): Pipeline; - brpop(key: string, ...keys: string[]): Pipeline; + brpop(...keys: string[]): Pipeline; - blpop(key: string, ...keys: string[]): Pipeline; + blpop(...keys: string[]): Pipeline; brpoplpush(source: string, destination: string, timeout: number, callback?: (err: Error, res: any) => void): Pipeline; @@ -534,17 +539,17 @@ declare namespace IORedis { srandmember(key: string, callback?: (err: Error, res: any) => void): Pipeline; srandmember(key: string, count: number, callback?: (err: Error, res: any) => void): Pipeline; - sinter(key: string, ...keys: string[]): Pipeline; + sinter(...keys: string[]): Pipeline; - sinterstore(destination: string, key: string, ...keys: string[]): Pipeline; + sinterstore(destination: string, ...keys: string[]): Pipeline; - sunion(key: string, ...keys: string[]): Pipeline; + sunion(...keys: string[]): Pipeline; - sunionstore(destination: string, key: string, ...keys: string[]): Pipeline; + sunionstore(destination: string, ...keys: string[]): Pipeline; - sdiff(key: string, ...keys: string[]): Pipeline; + sdiff(...keys: string[]): Pipeline; - sdiffstore(destination: string, key: string, ...keys: string[]): Pipeline; + sdiffstore(destination: string, ...keys: string[]): Pipeline; smembers(key: string, callback?: (err: Error, res: any) => void): Pipeline; @@ -552,9 +557,9 @@ declare namespace IORedis { zincrby(key: string, increment: number, member: string, callback?: (err: Error, res: any) => void): Pipeline; - zrem(key: string, member: string, ...members: any[]): Pipeline; + zrem(key: string, ...members: any[]): Pipeline; - zremrangebyscore(key: string, min: number, max: number, callback?: (err: Error, res: any) => void): Pipeline; + zremrangebyscore(key: string, min: number | string, max: number | string, callback?: (err: Error, res: any) => void): Pipeline; zremrangebyrank(key: string, start: number, stop: number, callback?: (err: Error, res: any) => void): Pipeline; @@ -568,11 +573,11 @@ declare namespace IORedis { zrevrange(key: string, start: number, stop: number, callback?: (err: Error, res: any) => void): Pipeline; zrevrange(key: string, start: number, stop: number, withScores: "WITHSCORES", callback?: (err: Error, res: any) => void): Pipeline; - zrangebyscore(key: string, min: number, max: number, ...args: string[]): Pipeline; + zrangebyscore(key: string, min: number | string, max: number | string, ...args: string[]): Pipeline; - zrevrangebyscore(key: string, max: number, min: number, ...args: string[]): Pipeline; + zrevrangebyscore(key: string, max: number | string, min: number | string, ...args: string[]): Pipeline; - zcount(key: string, min: number, max: number, callback?: (err: Error, res: number) => void): Pipeline; + zcount(key: string, min: number | string, max: number | string, callback?: (err: Error, res: number) => void): Pipeline; zcard(key: string, callback?: (err: Error, res: number) => void): Pipeline; @@ -590,13 +595,13 @@ declare namespace IORedis { hmset(key: string, field: string, value: any, ...args: string[]): Pipeline; - hmget(key: string, field: string, ...fields: string[]): Pipeline; + hmget(key: string, ...fields: string[]): Pipeline; hincrby(key: string, field: string, increment: number, callback?: (err: Error, res: number) => void): Pipeline; hincrbyfloat(key: string, field: string, increment: number, callback?: (err: Error, res: number) => void): Pipeline; - hdel(key: string, field: string, ...fields: string[]): Pipeline; + hdel(key: string, ...fields: string[]): Pipeline; hlen(key: string, callback?: (err: Error, res: number) => void): Pipeline; @@ -692,17 +697,17 @@ declare namespace IORedis { config(...args: any[]): Pipeline; - subscribe(channel: string, ...channels: any[]): Pipeline; + subscribe(...channels: any[]): Pipeline; unsubscribe(...channels: string[]): Pipeline; - psubscribe(pattern: string, ...patterns: string[]): Pipeline; + psubscribe(...patterns: string[]): Pipeline; punsubscribe(...patterns: string[]): Pipeline; publish(channel: string, message: string, callback?: (err: Error, res: number) => void): Pipeline; - watch(key: string, ...keys: string[]): Pipeline; + watch(...keys: string[]): Pipeline; unwatch(callback?: (err: Error, res: string) => void): Pipeline; @@ -732,11 +737,11 @@ declare namespace IORedis { zscan(key: string, cursor: number, ...args: any[]): Pipeline; - pfmerge(destkey: string, sourcekey: string, ...sourcekeys: string[]): Pipeline; + pfmerge(destkey: string, ...sourcekeys: string[]): Pipeline; - pfadd(key: string, element: string, ...elements: string[]): Pipeline; + pfadd(key: string, ...elements: string[]): Pipeline; - pfcount(key: string, ...keys: string[]): Pipeline; + pfcount(...keys: string[]): Pipeline; } interface Cluster extends NodeJS.EventEmitter, Commander { diff --git a/types/ioredis/ioredis-tests.ts b/types/ioredis/ioredis-tests.ts index 02b62def62..99c7efada3 100644 --- a/types/ioredis/ioredis-tests.ts +++ b/types/ioredis/ioredis-tests.ts @@ -104,3 +104,6 @@ redis.multi([ ]).exec((err, results) => { // results = [[null, 'OK'], [null, 'bar']] }); + +const keys = [ 'foo', 'bar' ]; +redis.mget(...keys); diff --git a/types/is/index.d.ts b/types/is/index.d.ts index 3c0e279eea..b61bd6deee 100644 --- a/types/is/index.d.ts +++ b/types/is/index.d.ts @@ -1320,4 +1320,8 @@ declare var is: Is; declare module 'is' { export = is; -} \ No newline at end of file +} + +declare module 'is_js' { + export = is; +} diff --git a/types/joi/index.d.ts b/types/joi/index.d.ts index 6dbc08245a..7a41f238de 100644 --- a/types/joi/index.d.ts +++ b/types/joi/index.d.ts @@ -8,6 +8,7 @@ // Rytis Alekna // Pavel Ivanov // Youngrok Kim +// Dan Kraus // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped // TypeScript Version: 2.4 @@ -15,7 +16,7 @@ export type Types = 'any' | 'alternatives' | 'array' | 'boolean' | 'binary' | 'date' | 'function' | 'lazy' | 'number' | 'object' | 'string'; -export type LanguageOptions = string | false | null | { +export type LanguageOptions = string | boolean | null | { [key: string]: LanguageOptions; }; @@ -127,6 +128,13 @@ export interface UriOptions { scheme?: string | RegExp | Array; } +export interface Base64Options { + /** + * optional parameter defaulting to true which will require = padding if true or make padding optional if false + */ + paddingRequired?: boolean; +} + export interface WhenOptions { /** * the required condition joi type. @@ -520,6 +528,12 @@ export interface StringSchema extends AnySchema { */ normalize(form?: 'NFC' | 'NFD' | 'NFKC' | 'NFKD'): this; + /** + * Requires the string value to be a valid base64 string; does not check the decoded value. + * @param options - optional settings: The unicode normalization options to use. Valid values: NFC [default], NFD, NFKC, NFKD + */ + base64(options?: Base64Options): this; + /** * Requires the number to be a credit card number (Using Lunh Algorithm). */ @@ -1057,7 +1071,7 @@ export function reach(schema: ObjectSchema, path: string): T; /** * Creates a new Joi instance customized with the extension(s) you provide included. */ -export function extend(extention: Extension): any; +export function extend(extension: Extension|Extension[], ...extensions: (Extension|Extension[])[]): any; // --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- diff --git a/types/joi/joi-tests.ts b/types/joi/joi-tests.ts index 96d91a72b9..6d2d12efb6 100644 --- a/types/joi/joi-tests.ts +++ b/types/joi/joi-tests.ts @@ -2,50 +2,50 @@ import Joi = require('joi'); // --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- -var x: any = null; -var value: any = null; -var num: number = 0; -var str: string = ''; -var bool: boolean = false; -var exp: RegExp = null; -var obj: object = null; -var date: Date = null; -var err: Error = null; -var func: Function = null; +let x: any = null; +let value: any = null; +let num: number = 0; +let str: string = ''; +let bool: boolean = false; +let exp: RegExp = null; +let obj: object = null; +let date: Date = null; +let err: Error = null; +let func: Function = null; -var anyArr: any[] = []; -var numArr: number[] = []; -var strArr: string[] = []; -var boolArr: boolean[] = []; -var expArr: RegExp[] = []; -var objArr: object[] = []; -var errArr: Error[] = []; -var funcArr: Function[] = []; +let anyArr: any[] = []; +let numArr: number[] = []; +let strArr: string[] = []; +let boolArr: boolean[] = []; +let expArr: RegExp[] = []; +let objArr: object[] = []; +let errArr: Error[] = []; +let funcArr: Function[] = []; // --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- -var schema: Joi.Schema = null; -var schemaLike: Joi.SchemaLike = null; +let schema: Joi.Schema = null; +let schemaLike: Joi.SchemaLike = null; -var anySchema: Joi.AnySchema = null; -var numSchema: Joi.NumberSchema = null; -var strSchema: Joi.StringSchema = null; -var arrSchema: Joi.ArraySchema = null; -var boolSchema: Joi.BooleanSchema = null; -var binSchema: Joi.BinarySchema = null; -var dateSchema: Joi.DateSchema = null; -var funcSchema: Joi.FunctionSchema = null; -var objSchema: Joi.ObjectSchema = null; -var altSchema: Joi.AlternativesSchema = null; +let anySchema: Joi.AnySchema = null; +let numSchema: Joi.NumberSchema = null; +let strSchema: Joi.StringSchema = null; +let arrSchema: Joi.ArraySchema = null; +let boolSchema: Joi.BooleanSchema = null; +let binSchema: Joi.BinarySchema = null; +let dateSchema: Joi.DateSchema = null; +let funcSchema: Joi.FunctionSchema = null; +let objSchema: Joi.ObjectSchema = null; +let altSchema: Joi.AlternativesSchema = null; -var schemaArr: Joi.Schema[] = []; +let schemaArr: Joi.Schema[] = []; -var ref: Joi.Reference = null; -var description: Joi.Description = null; +let ref: Joi.Reference = null; +let description: Joi.Description = null; // --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- -var validOpts: Joi.ValidationOptions = null; +let validOpts: Joi.ValidationOptions = null; validOpts = { abortEarly: bool }; validOpts = { convert: bool }; @@ -77,7 +77,7 @@ validOpts = { // --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- -var renOpts: Joi.RenameOptions = null; +let renOpts: Joi.RenameOptions = null; renOpts = { alias: bool }; renOpts = { multiple: bool }; @@ -86,7 +86,7 @@ renOpts = { ignoreUndefined: bool }; // --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- -var emailOpts: Joi.EmailOptions = null; +let emailOpts: Joi.EmailOptions = null; emailOpts = { errorLevel: num }; emailOpts = { errorLevel: bool }; @@ -96,7 +96,7 @@ emailOpts = { minDomainAtoms: num }; // --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- -var ipOpts: Joi.IpOptions = null; +let ipOpts: Joi.IpOptions = null; ipOpts = { version: str }; ipOpts = { version: strArr }; @@ -104,7 +104,7 @@ ipOpts = { cidr: str }; // --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- -var uriOpts: Joi.UriOptions = null; +let uriOpts: Joi.UriOptions = null; uriOpts = { scheme: str }; uriOpts = { scheme: exp }; @@ -113,7 +113,13 @@ uriOpts = { scheme: expArr }; // --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- -var whenOpts: Joi.WhenOptions = null; +let base64Opts: Joi.Base64Options = null; + +base64Opts = { paddingRequired: bool }; + +// --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- + +let whenOpts: Joi.WhenOptions = null; whenOpts = { is: x }; whenOpts = { is: schema, then: schema }; @@ -122,16 +128,16 @@ whenOpts = { is: schemaLike, then: schemaLike, otherwise: schemaLike }; // --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- -var refOpts: Joi.ReferenceOptions = null; +let refOpts: Joi.ReferenceOptions = null; refOpts = { separator: str }; refOpts = { contextPrefix: str }; // --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- -var validErr: Joi.ValidationError = null; -var validErrItem: Joi.ValidationErrorItem; -var validErrFunc: Joi.ValidationErrorFunction; +let validErr: Joi.ValidationError = null; +let validErrItem: Joi.ValidationErrorItem; +let validErrFunc: Joi.ValidationErrorFunction; validErrItem = { message: str, @@ -176,7 +182,7 @@ anySchema = objSchema; // --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- -var schemaMap: Joi.SchemaMap = null; +let schemaMap: Joi.SchemaMap = null; schemaMap = { a: numSchema, @@ -765,7 +771,7 @@ strSchema = strSchema.ip(ipOpts); strSchema = strSchema.uri(); strSchema = strSchema.uri(uriOpts); strSchema = strSchema.guid(); -strSchema = strSchema.guid({ version: ['uuidv1', 'uuidv2', 'uuidv3', 'uuidv4', 'uuidv5'] }); +strSchema = strSchema.guid({ version: ['uuidv1', 'uuidv2', 'uuidv3', 'uuidv4', 'uuidv5'] } as Joi.GuidOptions); strSchema = strSchema.guid({ version: 'uuidv4' }); strSchema = strSchema.hex(); strSchema = strSchema.hostname(); @@ -777,6 +783,8 @@ strSchema = strSchema.truncate(); strSchema = strSchema.truncate(false); strSchema = strSchema.normalize(); strSchema = strSchema.normalize('NFKC'); +strSchema = strSchema.base64(); +strSchema = strSchema.base64(base64Opts); namespace common { strSchema = strSchema.allow(x); @@ -962,6 +970,12 @@ const Joi3 = Joi.extend({ ], }); +const Joi4 = Joi.extend([{ name: '', base: schema }, { name: '', base: schema }]); + +const Joi5 = Joi.extend({ name: '', base: schema }, { name: '', base: schema }); + +const Joi6 = Joi.extend({ name: '', base: schema }, [{ name: '', base: schema }, { name: '', base: schema }]); + // --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- const defaultsJoi = Joi.defaults((schema) => { diff --git a/types/joi/v10/index.d.ts b/types/joi/v10/index.d.ts index 372975ed9e..9270c411aa 100644 --- a/types/joi/v10/index.d.ts +++ b/types/joi/v10/index.d.ts @@ -15,7 +15,7 @@ export type Types = 'any' | 'alternatives' | 'array' | 'boolean' | 'binary' | 'date' | 'function' | 'lazy' | 'number' | 'object' | 'string'; -export type LanguageOptions = string | false | null | { +export type LanguageOptions = string | boolean | null | { [key: string]: LanguageOptions; }; diff --git a/types/joi/v10/joi-tests.ts b/types/joi/v10/joi-tests.ts index 226abb3a7f..bfc6268ef7 100644 --- a/types/joi/v10/joi-tests.ts +++ b/types/joi/v10/joi-tests.ts @@ -765,7 +765,7 @@ strSchema = strSchema.ip(ipOpts); strSchema = strSchema.uri(); strSchema = strSchema.uri(uriOpts); strSchema = strSchema.guid(); -strSchema = strSchema.guid({ version: ['uuidv1', 'uuidv2', 'uuidv3', 'uuidv4', 'uuidv5'] }); +strSchema = strSchema.guid({ version: ['uuidv1', 'uuidv2', 'uuidv3', 'uuidv4', 'uuidv5'] } as Joi.GuidOptions); strSchema = strSchema.guid({ version: 'uuidv4' }); strSchema = strSchema.hex(); strSchema = strSchema.hostname(); diff --git a/types/commander/tslint.json b/types/joi/v10/tslint.json similarity index 100% rename from types/commander/tslint.json rename to types/joi/v10/tslint.json diff --git a/types/jquery-jcrop/index.d.ts b/types/jquery-jcrop/index.d.ts new file mode 100644 index 0000000000..af2afaf9d7 --- /dev/null +++ b/types/jquery-jcrop/index.d.ts @@ -0,0 +1,106 @@ +// Type definitions for jcrop 2.0 +// Project: https://github.com/tapmodo/Jcrop/ +// Definitions by: Joe Skeen +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.3 +/// + +declare namespace JQuery.Jcrop { + interface Options { + /** Aspect ratio of w/h (e.g. 1 for square) */ + aspectRatio?: number; + /** Minimum width/height, use 0 for unbounded dimension; [width, height] */ + minSize?: [number, number]; + /** Maximum width/height, use 0 for unbounded dimension; [width, height] */ + maxSize?: [number, number]; + minSelect?: [number, number]; + /** Set an initial selection area; [x, y, x2, y2] */ + setSelect?: [number, number, number, number]; + + /** Set color of background container @default 'black' */ + bgColor?: string; + /** Opacity of outer image when cropping; between 0 and 1 @default .6 */ + bgOpacity?: number; + baseClass?: string; + addClass?: string; + bgFade?: boolean; + borderOpacity?: number; + handleOpacity?: number; + handleSize?: number | null; + + /** Called when selection is completed */ + onSelect?: JCropEventHandler; + /** Called when the selection is moving */ + onChange?: JCropEventHandler; + /** Called when double-clicked */ + onDblClick?: JCropEventHandler; + /** Called when the selection is released */ + onRelease?: JCropEventHandler; + + /** Maximum width of cropping area @default 0 (no limit) */ + boxWidth?: number; + /** Maximum height of cropping area @default 0 (no limit) */ + boxHeight?: number; + boundary?: number; + fadeTime?: number; + animationDelay?: number; + swingSpeed?: number; + + /** Specify the true size of the image */ + trueSize?: [number, number]; + + // Basic Settings + allowSelect?: boolean; + allowMove?: boolean; + allowResize?: boolean; + + trackDocument?: boolean; + + keySupport?: boolean; + createHandles?: Array; + createDragbars?: CardinalDirection[]; + createBorders?: CardinalDirection[]; + drawBorders?: boolean; + dragEdges?: boolean; + fixedSupport?: boolean; + touchSupport?: boolean | null; + shade?: boolean | null; + } + + type CardinalDirection = 'n' | 's' | 'e' | 'w'; + type IntermediateDirection = 'nw' | 'ne' | 'se' | 'sw'; + type JCropEventHandler = (c: SelectionInfo) => void; + interface SelectionInfo { + x: number; + y: number; + x2: number; + y2: number; + w: number; + h: number; + } + + interface Api { + /** Set selection, format: [ x,y,x2,y2 ] */ + setSelect: (selection: [number, number, number, number]) => void; + /** Animate selection to new selection, format: [ x,y,x2,y2 ] */ + animateTo: (selection: [number, number, number, number]) => void; + /** Release current selection */ + release: () => void; + + /** Query current selection values (true size) */ + tellSelect: () => SelectionInfo; + /** Query current selection values (interface) */ + tellScaled: () => SelectionInfo; + + /** Disables Jcrop interactivity */ + disable: () => void; + /** Enables Jcrop interactivity */ + enable: () => void; + /** Remove Jcrop entirely */ + remove: () => void; + } +} + +interface JQuery { + Jcrop(options?: JQuery.Jcrop.Options, callback?: (this: JQuery.Jcrop.Api) => void): JQuery; +} diff --git a/types/jquery-jcrop/jquery-jcrop-tests.ts b/types/jquery-jcrop/jquery-jcrop-tests.ts new file mode 100644 index 0000000000..f5fb25f39c --- /dev/null +++ b/types/jquery-jcrop/jquery-jcrop-tests.ts @@ -0,0 +1,54 @@ +jQuery(($) => { + $('#target').Jcrop(); +}); + +function showCoords(c: { x: number, y: number, x2: number; y2: number; w: number; h: number; }) { + // variables can be accessed here as + // c.x, c.y, c.x2, c.y2, c.w, c.h +} + +jQuery(($) => { + $('#target').Jcrop({ + onSelect: showCoords, + onChange: showCoords + }); +}); + +jQuery(($) => { + $('#target').Jcrop({ + onSelect: showCoords, + bgColor: 'black', + bgOpacity: .4, + setSelect: [100, 100, 50, 50], + aspectRatio: 16 / 9 + }); +}); + +let jcrop_api; +$('#target').Jcrop({}, function() { + jcrop_api = this; +}); + +jQuery(($) => { + let jcrop_api: JQuery.Jcrop.Api; + + $('#target').Jcrop({ + bgColor: 'red' + }, function() { + jcrop_api = this; + }); + + $('#animbutton').click((e) => { + jcrop_api.animateTo([120, 120, 80, 80]); + return false; + }); + + $('#delselect').click((e) => { + jcrop_api.release(); + return false; + }); +}); + +(() => { + $('#cropbox').Jcrop({ boxWidth: 450, boxHeight: 400 }); +}); diff --git a/types/jquery-jcrop/tsconfig.json b/types/jquery-jcrop/tsconfig.json new file mode 100644 index 0000000000..add23691c0 --- /dev/null +++ b/types/jquery-jcrop/tsconfig.json @@ -0,0 +1,24 @@ +{ + "compilerOptions": { + "module": "commonjs", + "lib": [ + "es6", + "dom" + ], + "noImplicitAny": true, + "noImplicitThis": true, + "strictNullChecks": true, + "strictFunctionTypes": true, + "baseUrl": "../", + "typeRoots": [ + "../" + ], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true + }, + "files": [ + "index.d.ts", + "jquery-jcrop-tests.ts" + ] +} \ No newline at end of file diff --git a/types/jquery-jcrop/tslint.json b/types/jquery-jcrop/tslint.json new file mode 100644 index 0000000000..d88586e5bd --- /dev/null +++ b/types/jquery-jcrop/tslint.json @@ -0,0 +1,3 @@ +{ + "extends": "dtslint/dt.json" +} diff --git a/types/jquery-notifier/index.d.ts b/types/jquery-notifier/index.d.ts new file mode 100644 index 0000000000..bf9d0ff93b --- /dev/null +++ b/types/jquery-notifier/index.d.ts @@ -0,0 +1,18 @@ +// Type definitions for notifier 1.0 +// Project: https://github.com/allipierre/jquery-notifier +// Definitions by: Alli Pierre Yotti +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +declare namespace notifier { + /** + * notifier.show(title, msg, type, icon, timeout); + * {title} title + * {msg} msg + * {type} type + * {icon} icon + * {timeout} timeout + */ + function show(title: string, msg: string, type: string, icon: string, timeout?: number): string | number; + + function hide(notificationId: string | number): boolean; +} diff --git a/types/jquery-notifier/jquery-notifier-tests.ts b/types/jquery-notifier/jquery-notifier-tests.ts new file mode 100644 index 0000000000..18804758be --- /dev/null +++ b/types/jquery-notifier/jquery-notifier-tests.ts @@ -0,0 +1,31 @@ +notifier.show('Hello!', 'I am a default notification.', '', '', 0); +notifier.show('Reminder!', 'You have a meeting at 10:30 AM.', '', '', 0); +notifier.show('Well Done!', 'You just submit your resume successfuly.', '', '', 0); +notifier.show('Warning!', 'The data presented here can be change.', '', '', 0); +notifier.show('Sorry!', 'Could not complete your transaction.', '', '', 0); + +notifier.show('Default!', 'I am a default notification.', '', 'img/clock-48.png', 0); +notifier.show('Reminder!', 'You have a meeting at 10:30 AM.', '', 'img/survey-48.png', 0); +notifier.show('Well Done!', 'You just submit your resume successfuly.', '', 'img/ok-48.png', 0); +notifier.show('Warning!', 'The data presented here can be change.', '', 'img/medium_priority-48.png', 0); +notifier.show('Sorry!', 'Could not complete your transaction.', '', 'img/high_priority-48.png', 0); + +notifier.show('Default!', 'I am a default notification.', '', 'img/clock-48.png', 4000); +notifier.show('Reminder!', 'You have a meeting at 10:30 AM.', '', 'img/survey-48.png', 4000); +notifier.show('Well Done!', 'You just submit your resume successfuly.', '', 'img/ok-48.png', 4000); +notifier.show('Warning!', 'The data presented here can be change.', '', 'img/medium_priority-48.png', 4000); +notifier.show('Sorry!', 'Could not complete your transaction.', '', 'img/high_priority-48.png', 4000); + +let notificationId: string | number; + +let showNotification = () => { + notificationId = notifier.show('Reminder!', 'You have a meeting at 10:30 AM.', '', 'img/survey-48.png', 4000); +}; + +let hideNotification = () => { + notifier.hide(notificationId); +}; + +document.querySelector('#btn-nt-show').addEventListener('click', showNotification); + +document.querySelector('#btn-nt-hide').addEventListener('click', hideNotification); diff --git a/types/autobind-decorator/tsconfig.json b/types/jquery-notifier/tsconfig.json similarity index 82% rename from types/autobind-decorator/tsconfig.json rename to types/jquery-notifier/tsconfig.json index 0b05ea04fb..b2178bf718 100644 --- a/types/autobind-decorator/tsconfig.json +++ b/types/jquery-notifier/tsconfig.json @@ -1,7 +1,6 @@ { "compilerOptions": { "module": "commonjs", - "target": "es6", "lib": [ "es6", "dom" @@ -11,7 +10,6 @@ "strictNullChecks": false, "strictFunctionTypes": true, "baseUrl": "../", - "experimentalDecorators": true, "typeRoots": [ "../" ], @@ -21,6 +19,6 @@ }, "files": [ "index.d.ts", - "autobind-decorator-tests.ts" + "jquery-notifier-tests.ts" ] -} \ No newline at end of file +} diff --git a/types/jquery-notifier/tslint.json b/types/jquery-notifier/tslint.json new file mode 100644 index 0000000000..3db14f85ea --- /dev/null +++ b/types/jquery-notifier/tslint.json @@ -0,0 +1 @@ +{ "extends": "dtslint/dt.json" } diff --git a/types/jquery.bootstrap.wizard/index.d.ts b/types/jquery.bootstrap.wizard/index.d.ts index 465d7cd095..a84c9ca4c4 100644 --- a/types/jquery.bootstrap.wizard/index.d.ts +++ b/types/jquery.bootstrap.wizard/index.d.ts @@ -1,6 +1,7 @@ // Type definitions for twitter-bootstrap-wizard // Project: https://github.com/VinceG/twitter-bootstrap-wizard // Definitions by: Blake Niemyjski +// Dennis Åhlin // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped // TypeScript Version: 2.3 @@ -41,6 +42,11 @@ interface Wizard { } interface JQuery { + bootstrapWizard(method: 'next' | 'previous' | 'first' | 'last' | 'back' | 'finish'): void; + bootstrapWizard(method: 'currentIndex' | 'navigationLength'): number; + bootstrapWizard(method: 'show', indexOrId: number | string): void; + bootstrapWizard(method: 'enable' | 'disable' | 'display' | 'hide', index: number): void; + bootstrapWizard(method: 'remove', index: number, removeTabPane?: boolean): void; bootstrapWizard(options?: WizardOptions): Wizard; } diff --git a/types/jquery.fancytree/index.d.ts b/types/jquery.fancytree/index.d.ts index 34d90d9e8f..9c793a2c19 100644 --- a/types/jquery.fancytree/index.d.ts +++ b/types/jquery.fancytree/index.d.ts @@ -2,6 +2,7 @@ // Project: https://github.com/mar10/fancytree // Definitions by: Peter Palotas // Mahdi Abedi +// Nitecube // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped // TypeScript Version: 2.3 @@ -93,6 +94,12 @@ declare namespace Fancytree { */ findNextNode(match: (node: FancytreeNode) => boolean, startNode?: FancytreeNode): FancytreeNode; + /** Find all nodes that matches condition. + * + * @returns array of nodes (may be empty) + */ + findAll(match: string|((node: FancytreeNode) => boolean|undefined)): FancytreeNode[]; + /** Generate INPUT elements that can be submitted with html forms. In selectMode 3 only the topmost selected nodes are considered. */ generateFormElements(selected?: boolean, active?: boolean): void; @@ -283,6 +290,11 @@ declare namespace Fancytree { addChildren(child: Fancytree.NodeData, insertBefore?: number): FancytreeNode; + /** Add class to node's span tag and to .extraClasses. + * @param className class name + */ + addClass(className: string): void; + /** Append or prepend a node, or append a child node. This a convenience function that calls addChildren() * * @param mode 'before', 'after', 'firstChild', or 'child' ('over' is a synonym for 'child') (default='child') @@ -508,6 +520,11 @@ declare namespace Fancytree { */ removeChildren(): void; + /** Remove class from node's span tag and .extraClasses. + * @param className class name + */ + removeClass(className: string): void; + /** This method renders and updates all HTML markup that is required to display this node in its current state. * * @param force re-render, even if html markup was already created @@ -594,6 +611,13 @@ declare namespace Fancytree { */ toDict(recursive?: boolean, callback?: (dict: NodeData) => void): NodeData; + /** Set, clear, or toggle class of node's span tag and .extraClasses. + * @param {string} className class name (separate multiple classes by space) + * @param {boolean} [flag] true/false to add/remove class. If omitted, class is toggled. + * @return true if a class was added + */ + toggleClass(className: string, flag?: boolean): boolean; + /** Flip expanded status. */ toggleExpanded(): void; @@ -747,7 +771,7 @@ declare namespace Fancytree { /** Scroll node into visible area, when focused by keyboard (default: false). */ autoScroll?: boolean; /** Display checkboxes to allow selection (default: false) */ - checkbox?: boolean; + checkbox?: boolean|string|((event: JQueryEventObject, data: EventData) => boolean); /** Defines what happens, when the user click a folder node. (default: activate_dblclick_expands) */ clickFolderMode?: FancytreeClickFolderMode; /** 0..2 (null: use global setting $.ui.fancytree.debugInfo) */ @@ -792,13 +816,20 @@ declare namespace Fancytree { titlesTabbable?: boolean; /** Animation options, false:off (default: { effect: "blind", options: {direction: "vertical", scale: "box"}, duration: 200 }) */ toggleEffect?: JQueryUI.EffectOptions; + + /** (dynamic Option)Prevent (de-)selection using mouse or keyboard. */ + unselectable?: boolean|((event: JQueryEventObject, data: Fancytree.EventData) => boolean|undefined); + /** (dynamic Option)Ignore this node when calculating the partsel status of parent nodes in selectMode 3 propagation. */ + unselectableIgnore?: boolean|((event: JQueryEventObject, data: Fancytree.EventData) => boolean|undefined); + /** (dynamic Option)Use this as constant selected value (overriding selectMode 3 propagation). */ + unselectableStatus?: boolean|((event: JQueryEventObject, data: Fancytree.EventData) => boolean|undefined); } /** Data object passed to FancytreeNode() constructor. Note: typically these attributes are accessed by meber methods, e.g. `node.isExpanded()` and `node.setSelected(false)`. */ interface NodeData { /** node text (may contain HTML tags) */ title: string; - icon?: string; + icon?: boolean|string; /** unique key for this node (auto-generated if omitted) */ key?: string; /** (reserved) */ @@ -820,6 +851,21 @@ declare namespace Fancytree { extraClasses?: string; /** all properties from will be copied to `node.data` */ data?: Object; + + /** Will be added as title attribute of the node's icon span,thus enabling a tooltip. */ + iconTooltip?: string; + + /** If set, make this node a status node. Values: 'error', 'loading', 'nodata', 'paging'. */ + statusNodeType?: string; + + /** Made available as node.type. */ + type?: string; + + /** Ignore this node when calculating the partsel status of parent nodes in selectMode 3 propagation. */ + unselectableIgnore?: boolean; + + /** Use this as constant selected value(overriding selectMode 3 propagation). */ + unselectableStatus?: boolean; } /** Data object similar to NodeData, but with additional options. diff --git a/types/jquery.fancytree/jquery.fancytree-tests.ts b/types/jquery.fancytree/jquery.fancytree-tests.ts index 4fa52c790a..de1489de42 100644 --- a/types/jquery.fancytree/jquery.fancytree-tests.ts +++ b/types/jquery.fancytree/jquery.fancytree-tests.ts @@ -13,7 +13,8 @@ $("#tree").fancytree({ { title: "Folder 2", key: "2", folder: true, children: [ { title: "Node 2.1", key: "3" }, - { title: "Node 2.2", key: "4" } + { title: "Node 2.2", key: "4" }, + { title: "NOde 2.3", key: "5", icon: "./icon.svg", checkbox: "radio"} ] } ] @@ -24,7 +25,7 @@ $("#tree").fancytree({ click: (ev: JQueryEventObject, node: Fancytree.EventData) => { return true; }, - checkbox: true, + checkbox: "radio",//boolean or "radio" expand: () => { console.log("expanded"); }, @@ -38,8 +39,14 @@ $("#tree").fancytree({ if (data.node.isFolder()) { return false; } + }, + unselectable: function (event, data) { + return true; + }, + unselectableIgnore: false, + unselectableStatus: function (event, data) { + return false; } - }); //$("#tree").fancytree(); @@ -91,3 +98,26 @@ alert("We have " + tree.count() + " nodes."); // Use the API node.setTitle("New title"); + +// add/remove/toggle class +activeNode.addClass("test-class"); +activeNode.removeClass("test-class"); +activeNode.toggleClass("test-class"); +activeNode.toggleClass("test-class", true); + +// Fancytree.findAll() +var nodes: Fancytree.FancytreeNode[]; +nodes = tree.findAll((node) => { + return true; +}); +nodes = tree.findAll("Node"); + +node.addChildren({ + title: "New Node", + key: "15", + type: "book", + iconTooltip: "Icon toolip", + statusNodeType: "loading", + unselectableIgnore: true, + unselectableStatus: false, +}, 0); \ No newline at end of file diff --git a/types/jquery.tooltipster/index.d.ts b/types/jquery.tooltipster/index.d.ts deleted file mode 100644 index 44536908ff..0000000000 --- a/types/jquery.tooltipster/index.d.ts +++ /dev/null @@ -1,285 +0,0 @@ -// Type definitions for jQuery Tooltipster 3.3.0 -// Project: https://github.com/iamceege/tooltipster -// Definitions by: Patrick Magee , -// Dmitry Pesterev , -// Leonard Thieu , -// Jan Hirzel -// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -// TypeScript Version: 2.3 - -/// - -interface JQueryTooltipsterOptions { - /** - * Determines how the tooltip will animate in and out. Feel free to modify or create custom transitions in the tooltipster.css file. In IE9 and 8, all animations default to a JavaScript generated, fade animation. Default: 'fade' - * fade, grow, swing, slide, fall - */ - animation?: string; - /** - * Adds the "speech bubble arrow" to the tooltip. Default: true - */ - arrow?: boolean; - /** - * Select a specific color for the "speech bubble arrow". Default: will inherit the tooltip's background color - * hex code / rgb - */ - arrowColor?: string; - /** - * If autoClose is set to false, the tooltip will never close unless you call the 'close' method yourself. Default: true - */ - autoClose?: boolean; - /** - * If set, this will override the content of the tooltip. Default: null - * @type string, jQuery object - */ - content?: string | JQuery; - /** - * If the content of the tooltip is provided as a string, it is displayed as plain text by default. If this content should actually be interpreted as HTML, set this option to true. Default: false - */ - contentAsHTML?: boolean; - /** - * If you provide a jQuery object to the 'content' option, this sets if it is a clone of this object that should actually be used. Default: true - */ - contentCloning?: boolean; - /** - * Tooltipster logs notices into the console when you're doing something you ideally shouldn't be doing. Set to false to disable logging. Default: true - */ - debug?: boolean; - /** - * Delay how long it takes (in milliseconds) for the tooltip to start animating in. Default: 200 - */ - delay?: number; - /** - * Set a minimum width for the tooltip. Default: 0 (auto width) - */ - minWidth?: number; - /** - * Set a max width for the tooltip. If the tooltip ends up being smaller than the set max width, the tooltip's width will be set automatically. Default: 0 (no max width) - */ - maxWidth?: number; - /** - * Create a custom function to be fired only once at instantiation. If the function returns a value, this value will become the content of the tooltip. See the advanced section to learn more. Default: function(origin, content) {} - */ - functionInit?: (origin: JQuery, content: string) => void | string; - /** - * Create a custom function to be fired before the tooltip opens. This function may prevent or hold off the opening. See the advanced section to learn more. Default: function(origin, continueTooltip) { continueTooltip(); } - */ - functionBefore?: (origin: JQuery, continueTooltip: Function) => void; - /** - * Create a custom function to be fired when the tooltip and its contents have been added to the DOM. Default: function(origin, tooltip) {} - */ - functionReady?: (origin: JQuery, tooltip: JQuery) => void; - /** - * Create a custom function to be fired once the tooltip has been closed and removed from the DOM. Default: function(origin) {} - */ - functionAfter?: (origin: JQuery) => void; - /** - * If true, the tooltip will close if its origin is clicked. This option only applies when 'trigger' is 'hover' and 'autoClose' is false. Default: false - */ - hideOnClick?: boolean; - /** - * If using the iconDesktop or iconTouch options, this sets the content for your icon. Default: '(?)' - * @type string, jQuery object - */ - icon?: string | JQuery; - /** - * If you provide a jQuery object to the 'icon' option, this sets if it is a clone of this object that should actually be used. Default: true - */ - iconCloning?: boolean; - /** - * Generate an icon next to your content that is responsible for activating the tooltip on non-touch devices. Default: false - */ - iconDesktop?: boolean; - /** - * If using the iconDesktop or iconTouch options, this sets the class on the icon (used to style the icon). Default: 'tooltipster-icon' - */ - iconTheme?: string; - /** - * Generate an icon next to your content that is responsible for activating the tooltip on touch devices (tablets, phones, etc). Default: false - */ - iconTouch?: boolean; - /** - * Give users the possibility to interact with the tooltip. Unless autoClose is set to false, the tooltip will still close if the user moves away from or clicks out of the tooltip. Default: false - */ - interactive?: boolean; - /** - * If the tooltip is interactive and activated by a hover event, set the amount of time (milliseconds) allowed for a user to hover off of the tooltip activator (origin) on to the tooltip itself - keeping the tooltip from closing. Default: 350 - */ - interactiveTolerance?: number; - /** - * Allows you to put multiple tooltips on a single element. Read further instructions down this page. Default: false - */ - multiple?: boolean; - /** - * Offsets the tooltip (in pixels) farther left/right from the origin. Default: 0 - */ - offsetX?: number; - /** - * Offsets the tooltip (in pixels) farther up/down from the origin. Default: 0 - */ - offsetY?: number; - /** - * If true, only one tooltip will be allowed to be active at a time. Non-autoclosing tooltips will not be closed though. Default: false - */ - onlyOne?: boolean; - /** - * Set the position of the tooltip. Default: 'top' - * right, left, top, top-right, top-left, bottom, bottom-right, bottom-left - */ - position?: string; - /** - * Will reposition the tooltip if the origin moves. As this option may have an impact on performance, we suggest you enable it only if you need to. Default: false - */ - positionTracker?: boolean; - /** - * Called after the tooltip has been repositioned by the position tracker (if enabled). Default: A function that will close the tooltip if the trigger is 'hover' and autoClose is false. - */ - positionTrackerCallback?: (origin: JQuery) => void; - /** - * Specify if a TITLE attribute should be restored on the HTML element after a call to the 'destroy' method. This attribute may be omitted, or be restored with the value that existed before Tooltipster was initialized, or be restored with the stringified value of the current content. Note: in case of multiple tooltips on a single element, only the last destroyed tooltip may trigger a restoration. Default: 'current' - */ - restoration?: string; - /** - * Sets the side of the tooltip. The value may one of the following: 'top', 'bottom', 'left', 'right'. It may also be an array containing one or more of these values. When using an array, the order of values is taken into account as order of fallbacks and the absence of a side disables it (see the sides section). Default: ['top', 'bottom', 'right', 'left'] - */ - side?: string | string[]; - /** - * Set the speed of the animation. Default: 350 - */ - speed?: number; - /** - * How long the tooltip should be allowed to live before closing. Default: 0 (disabled) - */ - timer?: number; - /** - * Set the theme used for your tooltip. Default: 'tooltipster-default' - */ - theme?: string; - /** - * If set to false, tooltips will not show on pure-touch devices, unless you open them yourself with the 'show' method. Touch gestures on devices which also have a mouse will still open the tooltips though. Default: true - */ - touchDevices?: boolean; - /** - * Set how tooltips should be activated and closed. See the advanced section to learn how to build custom triggers. Default: 'hover' - * hover, click, custom - */ - trigger?: string; - /** - * If a tooltip is open while its content is updated, play a subtle animation when the content changes. Default: true - */ - updateAnimation?: boolean; -} - -interface JQuery { - - /** - * Show a tooltip (the 'callback' argument is optional) - * @param methodName show - * @param callback Function for call back - */ - tooltipster(methodName: "show", callback?: Function): JQuery; - - /** - * Hide a tooltip (the 'callback' argument is optional) - * @param methodName hide - * @param callback Function for call back - */ - tooltipster(methodName: "hide", callback?: Function): JQuery; - - /** - * Update tooltip content - * @param methodName content - * @param newContent New content - */ - tooltipster(methodName: "content", newContent: string): JQuery; - - /** - * Update tooltip content - * @param methodName option - * @param optionName Option name - */ - tooltipster(methodName: "option", optionName: string): JQuery; - - /** - * Set the value of an option (use at your own risk, we do not provide support for issues you may encounter when using this method) - * @param methodName option - * @param optionName Option name - * @param optionValue New vale for option - */ - tooltipster(methodName: "option", optionName: string, optionValue: string): JQuery; - - - /** - * Temporarily disable a tooltip from being able to open - * @param methodName disable - */ - tooltipster(methodName: "disable"): JQuery; - - /** - * Temporarily disable a tooltip from being able to open - * @param methodName enable - */ - tooltipster(methodName: "enable"): JQuery; - - /** - * Hide and destroy tooltip functionality - * @param methodName destroy - */ - tooltipster(methodName: "destroy"): JQuery; - - /** - * Return a tooltip's current content (if selector contains multiple origins, only the value of the first will be returned) - * @param methodName content - */ - tooltipster(methodName: "content"): string; - - /** - * Reposition and resize the tooltip - * @param methodName reposition - */ - tooltipster(methodName: "reposition"): JQuery; - - /** - * Return the HTML root element of the tooltip - * @param methodName elementTooltip - */ - tooltipster(methodName: "elementTooltip"): JQuery; - - /** - * Return the HTML root element of the icon if there is one, 'undefined' otherwise - * @param methodName elementIcon - */ - tooltipster(methodName: "elementIcon"): JQuery; - - /** - * Change default options for all future instances - * @param methodName setDefaults - * @param {object} options The options that should be made defaults - */ - tooltipster(methodName: 'setDefaults', options: JQueryTooltipsterOptions): JQuery; - - /** - * Generics - */ - tooltipster(methodName: string, optionName: string, optionValue?: string): JQuery; - tooltipster(methodName: string): JQuery | string; - - /** - * Creates a new tooltip with the specified, or default, options. - * @param options The options - * @example - * $('.tooltip').tooltipster({ - * animation: 'fade', - * delay: 200, - * theme: 'tooltipster-default', - * touchDevices: false, - * trigger: 'hover' - * }); - */ - tooltipster(options?: JQueryTooltipsterOptions): JQuery; - - /** - * Initiate the Tooltipster plugin - */ - tooltipster(): JQuery; -} diff --git a/types/jquery.tooltipster/jquery.tooltipster-tests.ts b/types/jquery.tooltipster/jquery.tooltipster-tests.ts deleted file mode 100644 index 3d48c29bcc..0000000000 --- a/types/jquery.tooltipster/jquery.tooltipster-tests.ts +++ /dev/null @@ -1,202 +0,0 @@ - - -// Type definition tests for jQuery Tooltipster 3.3.0 -// Project: https://github.com/iamceege/tooltipster -// Definitions by: Patrick Magee , Dmitry Pesterev -// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -// Tests taken from the getting started section of the Tooltipster website - -$(document).ready(function () { - - $('.tooltip').tooltipster(); - - $('#my-tooltip').tooltipster({ - content: $(' This text is in bold case !') - }); - - $('#my-tooltip').tooltipster({ - content: 'string test' - }); -}); - - -$(document).ready(function () { - $('.tooltip').tooltipster({ - contentAsHTML: true - }); -}); - -$('.tooltip').tooltipster({ - theme: 'tooltipster-noir' -}); - -$('.tooltip').tooltipster({ - animation: 'fade', - delay: 200, - theme: 'tooltipster-default', - touchDevices: false, - trigger: 'hover' -}); - -$.fn.tooltipster('setDefaults', { - position: 'bottom' -}); - -var myNewContent = ''; - -function callback(): void { - -} - -// temporarily disable a tooltip from being able to open -$('.tooltip').tooltipster('disable'); - -// if a tooltip was disabled from opening, reenable its previous functionality -$('.tooltip').tooltipster('enable'); - -// hide and destroy tooltip functionality -$('.tooltip').tooltipster('destroy'); - -// return a tooltip's current content (if selector contains multiple origins, only the value of the first will be returned) -$('.tooltip').tooltipster('content'); - -// update tooltip content -$('.tooltip').tooltipster('content', myNewContent); - -//update option -$('.tooltip').tooltipster('option', 'delay', '200'); - -// reposition and resize the tooltip -$('.tooltip').tooltipster('reposition'); - -// return the HTML root element of the tooltip -$('.tooltip').tooltipster('elementTooltip'); - -// return the HTML root element of the icon if there is one, 'undefined' otherwise -$('.tooltip').tooltipster('elementIcon'); - -$('.tooltip').tooltipster({ - content: 'Loading...', - functionBefore: function (origin, continueTooltip) { - - // we'll make this function asynchronous and allow the tooltip to go ahead and show the loading notification while fetching our data - continueTooltip(); - - // next, we want to check if our data has already been cached - if (origin.data('ajax') !== 'cached') { - $.ajax({ - type: 'POST', - url: 'example.php', - success: function (data) { - // update our tooltip content with our returned data and cache it - origin.tooltipster('content', data).data('ajax', 'cached'); - } - }); - } - } -}); - - - -$('.tooltip').tooltipster({ - content: 'Loading...', - functionBefore: (origin, continueTooltip) => { - - // we'll make this function asynchronous and allow the tooltip to go ahead and show the loading notification while fetching our data - continueTooltip(); - - // next, we want to check if our data has already been cached - if (origin.data('ajax') !== 'cached') { - $.ajax({ - type: 'POST', - url: 'example.php', - success: function (data) { - // update our tooltip content with our returned data and cache it - origin.tooltipster('content', data).data('ajax', 'cached'); - } - }); - } - } -}); - -$('.tooltip').tooltipster({ - functionInit: function (origin, content) { - - if (content === 'This is bad content') { - - // when the request has finished loading, we will change the tooltip's content - $.ajax({ - type: 'POST', - url: 'example.php', - success: function (data) { - origin.tooltipster('content', 'New content has been loaded : ' + data); - } - }); - - // this returned string will overwrite the content of the tooltip for the time being - return 'Wait while we load new content...'; - } - else { - // return nothing : the initialization continues normally with its content unchanged. - } - } -}); - -$('.tooltip').tooltipster({ - functionInit: (origin, content) => { - - if (content === 'This is bad content') { - - // when the request has finished loading, we will change the tooltip's content - $.ajax({ - type: 'POST', - url: 'example.php', - success: function (data) { - origin.tooltipster('content', 'New content has been loaded : ' + data); - } - }); - - // this returned string will overwrite the content of the tooltip for the time being - return 'Wait while we load new content...'; - } - else { - // return nothing : the initialization continues normally with its content unchanged. - } - } -}); - -$(document).ready(function () { - - // first on page load, initiate the Tooltipster plugin - $('.tooltip').tooltipster(); - - $('.tooltip').tooltipster({ - contentAsHTML: true - }); - - $('.tooltip').tooltipster({ - content: $(' This text is in bold case !') - }); - - // then immediately show the tooltip - $('#example').tooltipster('show'); - - // as soon as a key is pressed on the keyboard, hide the tooltip. - $(window).keypress(function () { - $('#example').tooltipster('hide'); - }); - - $('#example').tooltipster('show', function () { - alert('The tooltip is now fully open. The content is: ' + this.tooltipster('content')); - }); - - $('#example').tooltipster('show', () => { - alert('The tooltip is now fully open. The content is: ' + this.tooltipster('content')); - }); - - $(window).keypress(function () { - $('#example').tooltipster('hide', function () { - alert('The tooltip is now fully closed'); - }); - }); -}); diff --git a/types/jquery.tooltipster/tslint.json b/types/jquery.tooltipster/tslint.json deleted file mode 100644 index a41bf5d19a..0000000000 --- a/types/jquery.tooltipster/tslint.json +++ /dev/null @@ -1,79 +0,0 @@ -{ - "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 - } -} diff --git a/types/jquery/index.d.ts b/types/jquery/index.d.ts index ef3d33a09e..9c635a747b 100644 --- a/types/jquery/index.d.ts +++ b/types/jquery/index.d.ts @@ -5405,6 +5405,14 @@ declare namespace JQuery { * A string containing the URL to which the request is sent. */ url?: string; + /** + * A pre-request callback function that can be used to modify the jqXHR (in jQuery 1.4.x, + * XMLHTTPRequest) object before it is sent. Use this to set custom headers, etc. The jqXHR and + * settings objects are passed as arguments. This is an Ajax Event. Returning false in the beforeSend + * function will cancel the request. As of jQuery 1.5, the beforeSend option will be called regardless + * of the type of request. + */ + beforeSend?(this: TContext, jqXHR: jqXHR, settings: AjaxSettings): false | void; } interface UrlAjaxSettings extends Ajax.AjaxSettingsBase { @@ -5412,6 +5420,14 @@ declare namespace JQuery { * A string containing the URL to which the request is sent. */ url: string; + /** + * A pre-request callback function that can be used to modify the jqXHR (in jQuery 1.4.x, + * XMLHTTPRequest) object before it is sent. Use this to set custom headers, etc. The jqXHR and + * settings objects are passed as arguments. This is an Ajax Event. Returning false in the beforeSend + * function will cancel the request. As of jQuery 1.5, the beforeSend option will be called regardless + * of the type of request. + */ + beforeSend?(this: TContext, jqXHR: jqXHR, settings: UrlAjaxSettings): false | void; } namespace Ajax { diff --git a/types/jquery/jquery-tests.ts b/types/jquery/jquery-tests.ts index 6cb790f408..338509a37a 100644 --- a/types/jquery/jquery-tests.ts +++ b/types/jquery/jquery-tests.ts @@ -1,5 +1,3 @@ -// tslint:disable:interface-name - function JQueryStatic() { function type_assertion() { const $Canvas = $ as JQueryStatic; @@ -6195,7 +6193,7 @@ function JQuery_AjaxSettings() { this; // $ExpectType jqXHR jqXHR; - // $ExpectType AjaxSettingsBase + // $ExpectType AjaxSettings settings; }, cache: false, @@ -6305,7 +6303,7 @@ function JQuery_AjaxSettings() { this; // $ExpectType jqXHR jqXHR; - // $ExpectType AjaxSettingsBase + // $ExpectType AjaxSettings settings; return false; diff --git a/types/jquery/test/example-tests.ts b/types/jquery/test/example-tests.ts index f32a2c3723..728a42b3d6 100644 --- a/types/jquery/test/example-tests.ts +++ b/types/jquery/test/example-tests.ts @@ -1,5 +1,3 @@ -/* tslint:disable:no-arg object-literal-shorthand one-variable-per-declaration only-arrow-functions prefer-const prefer-for-of triple-equals no-var */ - function examples() { function add_0() { $('div').css('border', '2px solid red') diff --git a/types/jquery/test/longdesc-tests.ts b/types/jquery/test/longdesc-tests.ts index bf63445c16..23ff500d24 100644 --- a/types/jquery/test/longdesc-tests.ts +++ b/types/jquery/test/longdesc-tests.ts @@ -1,5 +1,3 @@ -/* tslint:disable:object-literal-key-quotes object-literal-shorthand one-variable-per-declaration only-arrow-functions prefer-const prefer-for-of triple-equals no-var */ - function longdesc() { function add_0() { $('p').add('div').addClass('widget'); diff --git a/types/jquery/tslint.json b/types/jquery/tslint.json index 24680d3efb..dea67c016f 100644 --- a/types/jquery/tslint.json +++ b/types/jquery/tslint.json @@ -5,7 +5,9 @@ "await-promise": false, "ban-types": false, "callable-types": false, + "interface-name": false, "no-any-union": false, + "no-arg": false, "no-boolean-literal-compare": false, "no-declare-current-package": false, "no-empty-interface": false, @@ -14,12 +16,20 @@ "no-unnecessary-generics": false, "no-unnecessary-qualifier": false, "no-unnecessary-type-assertion": false, + "no-var": false, "no-var-keyword": false, + "object-literal-key-quotes": false, + "object-literal-shorthand": false, + "one-variable-per-declaration": false, + "only-arrow-functions": false, "prefer-conditional-expression": false, + "prefer-const": false, + "prefer-for-of": false, "prefer-switch": false, "prefer-template": false, "space-before-function-paren": false, "space-within-parens": false, + "triple-equals": false, "use-default-type-parameter": false } } diff --git a/types/jschannel/index.d.ts b/types/jschannel/index.d.ts new file mode 100644 index 0000000000..42145531ea --- /dev/null +++ b/types/jschannel/index.d.ts @@ -0,0 +1,46 @@ +// Type definitions for jschannel 1.0 +// Project: https://github.com/yochannah/jschannel +// Definitions by: Yitzchok Gottlieb +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.4 + +export as namespace Channel; + +export function build(config: ChannelConfiguration): MessagingChannel; + +export interface MessagingChannel { + unbind: (method: string, doNotPublish?: boolean) => boolean; + bind: (method: string, callback?: (transaction: MessageTransaction, params: any) => void, doNotPublish?: boolean) => MessagingChannel; + call: (message: Message) => void; + notify: (message: Message) => void; + destroy: () => void; +} + +export interface Message { + method: string; + success?: (result: any) => void; + params?: any; + timeout?: number; + error?: (error: any, message: string) => void; +} + +export interface ChannelConfiguration { + window: any; + origin: string; + scope: string; + debugOutput?: boolean; + postMessageObserver?: (origin: string, message: Message) => void; + gotMessageObserver?: (origin: string, message: Message) => void; + onReady?: (channel: MessagingChannel) => void; + reconnect?: boolean; + publish?: boolean; + remote?: string | ReadonlyArray; +} + +export interface MessageTransaction { + delayReturn: (delay: boolean) => boolean; + complete: (result: any) => void; + error: (error: any, message: string) => void; + invoke: (callbackName: string, params: any) => void; + completed: () => boolean; +} diff --git a/types/jschannel/jschannel-tests.ts b/types/jschannel/jschannel-tests.ts new file mode 100644 index 0000000000..eabd150bf2 --- /dev/null +++ b/types/jschannel/jschannel-tests.ts @@ -0,0 +1,3 @@ +import { build } from 'jschannel'; + +build({ window: null, origin: "*", scope: "testScope"}); diff --git a/types/jschannel/tsconfig.json b/types/jschannel/tsconfig.json new file mode 100644 index 0000000000..83727a281c --- /dev/null +++ b/types/jschannel/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", + "jschannel-tests.ts" + ] +} diff --git a/types/jschannel/tslint.json b/types/jschannel/tslint.json new file mode 100644 index 0000000000..3db14f85ea --- /dev/null +++ b/types/jschannel/tslint.json @@ -0,0 +1 @@ +{ "extends": "dtslint/dt.json" } diff --git a/types/json-schema/index.d.ts b/types/json-schema/index.d.ts index 016db75a25..7f02b671a0 100644 --- a/types/json-schema/index.d.ts +++ b/types/json-schema/index.d.ts @@ -1,10 +1,10 @@ -// Type definitions for json-schema 4.0 +// Type definitions for json-schema 4.0 and 6.0 // Project: https://www.npmjs.com/package/json-schema -// Definitions by: Boris Cherny +// Definitions by: Boris Cherny , Cyrille Tuzi // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped // TypeScript Version: 2.2 -/// +/* JSON Schema 4 */ /** * @see https://tools.ietf.org/html/draft-zyp-json-schema-03#section-5.1 @@ -198,3 +198,276 @@ export interface JSONSchema4 { */ [k: string]: any } + +/* JSON Schema 6 */ + +export type JSONSchema6TypeName = 'string' | 'number' | 'integer' | 'boolean' | 'object' | 'array' | 'null' | 'any' + +export type JSONSchema6Type = any[] | boolean | number | null | object | string + +/** + * JSON Schema V6 + * @see https://tools.ietf.org/html/draft-wright-json-schema-validation-01 + */ +export interface JSONSchema6 { + $id?: string + $ref?: string + $schema?: 'http://json-schema.org/schema#' | 'http://json-schema.org/hyper-schema#' | + 'http://json-schema.org/draft-06/schema#' | 'http://json-schema.org/draft-06/hyper-schema#' + + /** + * Must be strictly greater than 0. + * A numeric instance is valid only if division by this keyword's value results in an integer. + * @see https://tools.ietf.org/html/draft-wright-json-schema-validation-01#section-6.1 + */ + multipleOf?: number + + /** + * Representing an inclusive upper limit for a numeric instance. + * This keyword validates only if the instance is less than or exactly equal to "maximum". + * @see https://tools.ietf.org/html/draft-wright-json-schema-validation-01#section-6.2 + */ + maximum?: number + + /** + * Representing an exclusive upper limit for a numeric instance. + * This keyword validates only if the instance is strictly less than (not equal to) to "exclusiveMaximum". + * @see https://tools.ietf.org/html/draft-wright-json-schema-validation-01#section-6.3 + */ + exclusiveMaximum?: number + + /** + * Representing an inclusive lower limit for a numeric instance. + * This keyword validates only if the instance is greater than or exactly equal to "minimum". + * @see https://tools.ietf.org/html/draft-wright-json-schema-validation-01#section-6.4 + */ + minimum?: number + + /** + * Representing an exclusive lower limit for a numeric instance. + * This keyword validates only if the instance is strictly greater than (not equal to) to "exclusiveMinimum". + * @see https://tools.ietf.org/html/draft-wright-json-schema-validation-01#section-6.5 + */ + exclusiveMinimum?: number + + /** + * Must be a non-negative integer. + * A string instance is valid against this keyword if its length is less than, or equal to, the value of this keyword. + * @see https://tools.ietf.org/html/draft-wright-json-schema-validation-01#section-6.6 + */ + maxLength?: number + + /** + * Must be a non-negative integer. + * A string instance is valid against this keyword if its length is greater than, or equal to, the value of this keyword. + * Omitting this keyword has the same behavior as a value of 0. + * @see https://tools.ietf.org/html/draft-wright-json-schema-validation-01#section-6.7 + */ + minLength?: number + + /** + * Should be a valid regular expression, according to the ECMA 262 regular expression dialect. + * @see https://tools.ietf.org/html/draft-wright-json-schema-validation-01#section-6.8 + */ + pattern?: string + + /** + * This keyword determines how child instances validate for arrays, and does not directly validate the immediate instance itself. + * Omitting this keyword has the same behavior as an empty schema. + * @see https://tools.ietf.org/html/draft-wright-json-schema-validation-01#section-6.9 + */ + items?: boolean | JSONSchema6 | JSONSchema6[] + + /** + * This keyword determines how child instances validate for arrays, and does not directly validate the immediate instance itself. + * If "items" is an array of schemas, validation succeeds if every instance element + * at a position greater than the size of "items" validates against "additionalItems". + * Otherwise, "additionalItems" MUST be ignored, as the "items" schema + * (possibly the default value of an empty schema) is applied to all elements. + * Omitting this keyword has the same behavior as an empty schema. + * @see https://tools.ietf.org/html/draft-wright-json-schema-validation-01#section-6.10 + */ + additionalItems?: boolean | JSONSchema6 + + /** + * Must be a non-negative integer. + * An array instance is valid against "maxItems" if its size is less than, or equal to, the value of this keyword. + * @see https://tools.ietf.org/html/draft-wright-json-schema-validation-01#section-6.11 + */ + maxItems?: number + + /** + * Must be a non-negative integer. + * An array instance is valid against "maxItems" if its size is greater than, or equal to, the value of this keyword. + * Omitting this keyword has the same behavior as a value of 0. + * @see https://tools.ietf.org/html/draft-wright-json-schema-validation-01#section-6.12 + */ + minItems?: number + + /** + * If this keyword has boolean value false, the instance validates successfully. + * If it has boolean value true, the instance validates successfully if all of its elements are unique. + * Omitting this keyword has the same behavior as a value of false. + * @see https://tools.ietf.org/html/draft-wright-json-schema-validation-01#section-6.13 + */ + uniqueItems?: boolean + + /** + * An array instance is valid against "contains" if at least one of its elements is valid against the given schema. + * @see https://tools.ietf.org/html/draft-wright-json-schema-validation-01#section-6.14 + */ + contains?: boolean | JSONSchema6 + + /** + * Must be a non-negative integer. + * An object instance is valid against "maxProperties" if its number of properties is less than, or equal to, the value of this keyword. + * @see https://tools.ietf.org/html/draft-wright-json-schema-validation-01#section-6.15 + */ + maxProperties?: number + + /** + * Must be a non-negative integer. + * An object instance is valid against "maxProperties" if its number of properties is greater than, + * or equal to, the value of this keyword. + * Omitting this keyword has the same behavior as a value of 0. + * @see https://tools.ietf.org/html/draft-wright-json-schema-validation-01#section-6.16 + */ + minProperties?: number + + /** + * Elements of this array must be unique. + * An object instance is valid against this keyword if every item in the array is the name of a property in the instance. + * Omitting this keyword has the same behavior as an empty array. + * + * @see https://tools.ietf.org/html/draft-wright-json-schema-validation-01#section-6.17 + */ + required?: string[] + + /** + * This keyword determines how child instances validate for objects, and does not directly validate the immediate instance itself. + * Validation succeeds if, for each name that appears in both the instance and as a name within this keyword's value, + * the child instance for that name successfully validates against the corresponding schema. + * Omitting this keyword has the same behavior as an empty object. + * @see https://tools.ietf.org/html/draft-wright-json-schema-validation-01#section-6.18 + */ + properties?: { + [k: string]: boolean | JSONSchema6 + } + + /** + * This attribute is an object that defines the schema for a set of property names of an object instance. + * The name of each property of this attribute's object is a regular expression pattern in the ECMA 262, while the value is a schema. + * If the pattern matches the name of a property on the instance object, the value of the instance's property + * MUST be valid against the pattern name's schema value. + * Omitting this keyword has the same behavior as an empty object. + * @see https://tools.ietf.org/html/draft-wright-json-schema-validation-01#section-6.19 + */ + patternProperties?: { + [k: string]: boolean | JSONSchema6 + } + + /** + * This attribute defines a schema for all properties that are not explicitly defined in an object type definition. + * If specified, the value MUST be a schema or a boolean. + * If false is provided, no additional properties are allowed beyond the properties defined in the schema. + * The default value is an empty schema which allows any value for additional properties. + * @see https://tools.ietf.org/html/draft-wright-json-schema-validation-01#section-6.20 + */ + additionalProperties?: boolean | JSONSchema6 + + /** + * This keyword specifies rules that are evaluated if the instance is an object and contains a certain property. + * Each property specifies a dependency. + * If the dependency value is an array, each element in the array must be unique. + * Omitting this keyword has the same behavior as an empty object. + * @see https://tools.ietf.org/html/draft-wright-json-schema-validation-01#section-6.21 + */ + dependencies?: { + [k: string]: boolean | JSONSchema6 | string[] + } + + /** + * Takes a schema which validates the names of all properties rather than their values. + * Note the property name that the schema is testing will always be a string. + * Omitting this keyword has the same behavior as an empty schema. + * @see https://tools.ietf.org/html/draft-wright-json-schema-validation-01#section-6.22 + */ + propertyNames?: boolean | JSONSchema6 + + /** + * This provides an enumeration of all possible values that are valid + * for the instance property. This MUST be an array, and each item in + * the array represents a possible value for the instance value. If + * this attribute is defined, the instance value MUST be one of the + * values in the array in order for the schema to be valid. + * + * @see https://tools.ietf.org/html/draft-wright-json-schema-validation-01#section-6.23 + */ + enum?: JSONSchema6Type[] + + /** + * More readible form of a one-element "enum" + * @see https://tools.ietf.org/html/draft-wright-json-schema-validation-01#section-6.24 + */ + const?: JSONSchema6Type + + /** + * A single type, or a union of simple types + * @see https://tools.ietf.org/html/draft-wright-json-schema-validation-01#section-6.25 + */ + type?: JSONSchema6TypeName | JSONSchema6TypeName[] + + /** + * @see https://tools.ietf.org/html/draft-wright-json-schema-validation-01#section-6.26 + */ + allOf?: JSONSchema6[] + + /** + * @see https://tools.ietf.org/html/draft-wright-json-schema-validation-01#section-6.27 + */ + anyOf?: JSONSchema6[] + + /** + * @see https://tools.ietf.org/html/draft-wright-json-schema-validation-01#section-6.28 + */ + oneOf?: JSONSchema6[] + + /** + * @see https://tools.ietf.org/html/draft-wright-json-schema-validation-01#section-6.29 + */ + not?: boolean | JSONSchema6 + + /** + * @see https://tools.ietf.org/html/draft-wright-json-schema-validation-01#section-7.1 + */ + definitions?: { + [k: string]: boolean | JSONSchema6 + } + + /** + * This attribute is a string that provides a short description of the instance property. + * + * @see https://tools.ietf.org/html/draft-wright-json-schema-validation-01#section-7.2 + */ + title?: string + + /** + * This attribute is a string that provides a full description of the of purpose the instance property. + * + * @see https://tools.ietf.org/html/draft-wright-json-schema-validation-01#section-7.2 + */ + description?: string + + /** + * This keyword can be used to supply a default JSON value associated with a particular schema. + * It is RECOMMENDED that a default value be valid against the associated schema. + * @see https://tools.ietf.org/html/draft-wright-json-schema-validation-01#section-7.3 + */ + default?: JSONSchema6Type + + /** + * Array of examples with no validation effect the value of "default" is usable as an example without repeating it under this keyword + * @see https://tools.ietf.org/html/draft-wright-json-schema-validation-01#section-7.4 + */ + examples?: JSONSchema6Type[] +} diff --git a/types/json-schema/json-schema-tests.ts b/types/json-schema/json-schema-tests.ts index 58264668b0..0fd15f5de9 100644 --- a/types/json-schema/json-schema-tests.ts +++ b/types/json-schema/json-schema-tests.ts @@ -1,4 +1,6 @@ -import { JSONSchema4, JSONSchema4Type, JSONSchema4TypeName } from 'json-schema' +import { JSONSchema4, JSONSchema4Type, JSONSchema4TypeName, JSONSchema6, JSONSchema6Type, JSONSchema6TypeName } from 'json-schema' + +/* JSON Schema 4 */ // SimpleType () => { @@ -56,7 +58,7 @@ import { JSONSchema4, JSONSchema4Type, JSONSchema4TypeName } from 'json-schema' baz: { type: 'integer' } }, enum: ['foo', 42], - type: ['string', 'array'], + type: 'string', allOf: [{}], anyOf: [{}], oneOf: [{}], @@ -65,3 +67,73 @@ import { JSONSchema4, JSONSchema4Type, JSONSchema4TypeName } from 'json-schema' bar: 4 } } + +/* JSON Schema 6 */ + +// SimpleType +() => { + const a: JSONSchema6TypeName = 'string' + const b: JSONSchema6TypeName = 'null' + const c: JSONSchema6TypeName = 'any' +} + +// Type +() => { + const a: JSONSchema6Type = 'foo' + const b: JSONSchema6Type = null + const c: JSONSchema6Type = [1, 2] +} + +// JSONSchema4 +() => { + const a: JSONSchema6 = {} + const b: JSONSchema6 = { + $id: 'foo', + $ref: 'foo/bar', + $schema: 'http://json-schema.org/schema#', + title: 'foo', + description: 'bar', + default: 42, + multipleOf: 3, + maximum: 4, + exclusiveMaximum: 4, + minimum: 5, + exclusiveMinimum: 5, + maxLength: 6, + minLength: 7, + pattern: 'baz', + additionalItems: true, + items: [ + { items: [{ minLength: 4 }] } + ], + maxItems: 4, + minItems: 5, + uniqueItems: true, + maxProperties: 10, + minProperties: 11, + required: ['foo', 'bar'], + additionalProperties: false, + definitions: { + foo: { type: 'string' } + }, + properties: { + bar: { type: 'boolean' } + }, + patternProperties: { + foo: { type: 'integer' } + }, + dependencies: { + baz: { type: 'integer' } + }, + enum: ['foo', 42], + type: 'string', + allOf: [{}], + anyOf: [{}], + oneOf: [{}], + not: {}, + const: 'foo', + contains: {}, + examples: [{}], + propertyNames: {} + } +} diff --git a/types/jsonstream/index.d.ts b/types/jsonstream/index.d.ts index cf0f0fdd43..3e9bdd4b12 100644 --- a/types/jsonstream/index.d.ts +++ b/types/jsonstream/index.d.ts @@ -14,7 +14,25 @@ export interface Options { export declare function parse(pattern: any): NodeJS.ReadWriteStream; export declare function parse(patterns: any[]): NodeJS.ReadWriteStream; + +/** + * Create a writable stream. + * you may pass in custom open, close, and seperator strings. But, by default, + * JSONStream.stringify() will create an array, + * (with default options open='[\n', sep='\n,\n', close='\n]\n') + */ export declare function stringify(): NodeJS.ReadWriteStream; + +/** If you call JSONStream.stringify(false) the elements will only be seperated by a newline. */ +export declare function stringify(newlineOnly: NewlineOnlyIndicator): NodeJS.ReadWriteStream; +type NewlineOnlyIndicator = false + +/** + * Create a writable stream. + * you may pass in custom open, close, and seperator strings. But, by default, + * JSONStream.stringify() will create an array, + * (with default options open='[\n', sep='\n,\n', close='\n]\n') + */ export declare function stringify(open: string, sep: string, close: string): NodeJS.ReadWriteStream; export declare function stringifyObject(): NodeJS.ReadWriteStream; diff --git a/types/jsonstream/jsonstream-tests.ts b/types/jsonstream/jsonstream-tests.ts index d42ab0d845..68c8e858ac 100644 --- a/types/jsonstream/jsonstream-tests.ts +++ b/types/jsonstream/jsonstream-tests.ts @@ -8,6 +8,7 @@ read = read.pipe(json.parse('*')); read = read.pipe(json.parse(['foo/*', 'bar/*'])); read = json.stringify(); +read = json.stringify(false); read = json.stringify('{', ',', '}'); read = json.stringifyObject(); diff --git a/types/jsonwebtoken/index.d.ts b/types/jsonwebtoken/index.d.ts index 335a6f52b7..26e223df53 100644 --- a/types/jsonwebtoken/index.d.ts +++ b/types/jsonwebtoken/index.d.ts @@ -1,6 +1,8 @@ -// Type definitions for jsonwebtoken 7.2.0 +// Type definitions for jsonwebtoken 7.2.1 // Project: https://github.com/auth0/node-jsonwebtoken -// Definitions by: Maxime LUCE , Daniel Heim +// Definitions by: Maxime LUCE , +// Daniel Heim , +// Brice BERNARD // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped // TypeScript Version: 2.2 @@ -51,17 +53,17 @@ export interface SignOptions { noTimestamp?: boolean; header?: object; encoding?: string; - } export interface VerifyOptions { algorithms?: string[]; audience?: string | string[]; + clockTimestamp?: number; clockTolerance?: number; issuer?: string | string[]; ignoreExpiration?: boolean; ignoreNotBefore?: boolean; - jwtId?: string; + jwtid?: string; subject?: string; /** *@deprecated @@ -76,14 +78,17 @@ export interface DecodeOptions { } export interface VerifyCallback { - (err: JsonWebTokenError | NotBeforeError | TokenExpiredError, decoded: object | string): void; + ( + err: JsonWebTokenError | NotBeforeError | TokenExpiredError, + decoded: object | string, + ): void; } export interface SignCallback { (err: Error, encoded: string): void; } -export type Secret = string | Buffer | {key: string, passphrase: string} +export type Secret = string | Buffer | { key: string; passphrase: string }; /** * Synchronously sign the given payload into a JSON Web Token string @@ -92,7 +97,11 @@ export type Secret = string | Buffer | {key: string, passphrase: string} * @param {SignOptions} [options] - Options for the signature * @returns {String} The JSON Web Token string */ -export declare function sign(payload: string | Buffer | object, secretOrPrivateKey: Secret, options?: SignOptions): string; +export declare function sign( + payload: string | Buffer | object, + secretOrPrivateKey: Secret, + options?: SignOptions, +): string; /** * Sign the given payload into a JSON Web Token string @@ -101,8 +110,17 @@ export declare function sign(payload: string | Buffer | object, secretOrPrivateK * @param {SignOptions} [options] - Options for the signature * @param {Function} callback - Callback to get the encoded token on */ -export declare function sign(payload: string | Buffer | object, secretOrPrivateKey: Secret, callback: SignCallback): void; -export declare function sign(payload: string | Buffer | object, secretOrPrivateKey: Secret, options: SignOptions, callback: SignCallback): void; +export declare function sign( + payload: string | Buffer | object, + secretOrPrivateKey: Secret, + callback: SignCallback, +): void; +export declare function sign( + payload: string | Buffer | object, + secretOrPrivateKey: Secret, + options: SignOptions, + callback: SignCallback, +): void; /** * Synchronously verify given token using a secret or a public key to get a decoded token @@ -111,8 +129,15 @@ export declare function sign(payload: string | Buffer | object, secretOrPrivateK * @param {VerifyOptions} [options] - Options for the verification * @returns The decoded token. */ -declare function verify(token: string, secretOrPublicKey: string | Buffer): object | string; -declare function verify(token: string, secretOrPublicKey: string | Buffer, options?: VerifyOptions): object | string; +declare function verify( + token: string, + secretOrPublicKey: string | Buffer, +): object | string; +declare function verify( + token: string, + secretOrPublicKey: string | Buffer, + options?: VerifyOptions, +): object | string; /** * Asynchronously verify given token using a secret or a public key to get a decoded token @@ -121,8 +146,17 @@ declare function verify(token: string, secretOrPublicKey: string | Buffer, optio * @param {VerifyOptions} [options] - Options for the verification * @param {Function} callback - Callback to get the decoded token on */ -declare function verify(token: string, secretOrPublicKey: string | Buffer, callback?: VerifyCallback): void; -declare function verify(token: string, secretOrPublicKey: string | Buffer, options?: VerifyOptions, callback?: VerifyCallback): void; +declare function verify( + token: string, + secretOrPublicKey: string | Buffer, + callback?: VerifyCallback, +): void; +declare function verify( + token: string, + secretOrPublicKey: string | Buffer, + options?: VerifyOptions, + callback?: VerifyCallback, +): void; /** * Returns the decoded payload without verifying if the signature is valid. @@ -130,4 +164,7 @@ declare function verify(token: string, secretOrPublicKey: string | Buffer, optio * @param {DecodeOptions} [options] - Options for decoding * @returns {Object} The decoded Token */ -declare function decode(token: string, options?: DecodeOptions): null | object | string; +declare function decode( + token: string, + options?: DecodeOptions, +): null | object | string; diff --git a/types/jsonwebtoken/jsonwebtoken-tests.ts b/types/jsonwebtoken/jsonwebtoken-tests.ts index 9e495d31cb..0b04c23e63 100644 --- a/types/jsonwebtoken/jsonwebtoken-tests.ts +++ b/types/jsonwebtoken/jsonwebtoken-tests.ts @@ -57,6 +57,13 @@ jwt.verify(token, 'shhhhh', function(err, decoded) { console.log(result.foo) // bar }); +// use external time for verifying +jwt.verify(token, 'shhhhh', { clockTimestamp: 1 }, function(err, decoded) { + const result = decoded as ITestObject + + console.log(result.foo) // bar +}); + // invalid token jwt.verify(token, 'wrong-secret', function(err, decoded) { // err diff --git a/types/jss/index.d.ts b/types/jss/index.d.ts index 18278d80d1..d0136216ed 100644 --- a/types/jss/index.d.ts +++ b/types/jss/index.d.ts @@ -1,50 +1,127 @@ -// Type definitions for jss v0.6 -// Project: https://github.com/Box9/jss -// Definitions by: Valentin Robert +// Type definitions for jss 9.3 +// Project: https://github.com/cssinjs/jss#readme +// Definitions by: Brenton Simpson +// Oleg Slobodskoi // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.2 -interface Properties { - [name: string]: string; +export interface Rule { + className: string; + selector: string; + applyTo(element: HTMLElement): void; + prop(key: string): string; + prop(key: string, value: any): this; + toJSON(): string; } - -interface Selectors { - [selector: string]: Properties; +export interface StyleSheet { + // Gives auto-completion on the rules declared in `createStyleSheet` without + // causing errors for rules added dynamically after creation. + classes: { + [K in keyof T]: string; + } & { [key: string]: string }; + options: any; + linked: boolean; + attached: boolean; + /** + * Attach renderable to the render tree. + */ + attach(): this; + /** + * Remove renderable from render tree. + */ + detach(): this; + /** + * Add a rule to the current stylesheet. + * Will insert a rule also after the stylesheet has been rendered first time. + */ + addRule(style: Style, options?: Partial): Rule; + addRule(name: string, style: Style, options?: Partial): Rule; + /** + * Create and add rules. + * Will render also after Style Sheet was rendered the first time. + */ + addRules(styles: { [key: string]: Style }, options?: Partial): Rule[]; + /** + * Get a rule by name. + */ + getRule(name: string): Rule; + /** + * Delete a rule by name. + * Returns `true`: if rule has been deleted from the DOM. + */ + deleteRule(name: string): boolean; + /** + * Get index of a rule. + */ + indexOf(rule: Rule): number; + /** + * Update the function values with a new data. + */ + update(data?: {}): this; + update(name: string, data: {}): this; + /** + * Convert rules to a CSS string. + */ + toString(options?: { indent?: number }): string; } - -interface JSS { - /** - * Retrieve all rules added via JSS, organized by selectors - */ - get(): Selectors; - - /** - * Retrieve rules added via JSS for a given selector - * @param s CSS selector - */ - get(s: string): Properties; - - /** - * Retrieve all rules specified for a given selector (not necessarily added via JSS) - * @param s CSS selector - */ - getAll(s: string): Properties; - - /** - * Remove all rules added via JSS - */ - remove(): void; - - /** - * Remove all rules added via JSS for the given selector - */ - remove(s: string): void; - - /** - * Add or extend an existing rule - * @param s CSS selector - * @param p CSS properties - */ - set(s: string, p: Properties): void; +export type GenerateClassName = (rule: Rule, sheet?: StyleSheet) => string; +export interface Style { + [key: string]: any; } - -declare var jss: JSS; +export interface JSSPlugin { + [key: string]: () => Partial<{ + onCreateRule(name: string, style: Style, options: RuleOptions): Rule, + onProcessRule(rule: Rule, sheet: StyleSheet): void, + onProcessStyle(style: Style, rule: Rule, sheet: StyleSheet): Style, + onProcessSheet(sheet: StyleSheet): void, + onChangeValue(value: any, prop: string, rule: Rule): any, + onUpdate(data: {}, rule: Rule, sheet: StyleSheet): void, + }>; +} +export interface JSSOptions { + createGenerateClassName(): GenerateClassName; + plugins: ReadonlyArray; + virtual: boolean; + insertionPoint: string | HTMLElement; +} +export interface RuleFactoryOptions { + selector: string; + classes: { [key: string]: string }; + sheet: StyleSheet; + index: number; + jss: JSS; + generateClassName: GenerateClassName; +} +export interface RuleOptions { + index: number; + className: string; +} +declare class JSS { + constructor(options?: Partial); + createStyleSheet( + styles: T, + options?: Partial<{ + media: string, + meta: string, + link: boolean, + element: HTMLStyleElement, + index: number, + generateClassName: GenerateClassName, + classNamePrefix: string, + }>, + ): StyleSheet; + removeStyleSheet(sheet: StyleSheet): this; + setup(options?: Partial): this; + use(plugin: JSSPlugin): this; + createRule(style: Style, options?: Partial): Rule; + createRule(name: string, style: Style, options?: Partial): Rule; +} +/** + * Creates a new instance of JSS. + */ +export function create(options?: Partial): JSS; +declare const sharedInstance: JSS; +/** + * A global JSS instance. + */ +export default sharedInstance; diff --git a/types/jss/jss-tests.ts b/types/jss/jss-tests.ts index 2863bbfb66..0cf3f51350 100644 --- a/types/jss/jss-tests.ts +++ b/types/jss/jss-tests.ts @@ -1,16 +1,62 @@ +// API docs at http://cssinjs.org/js-api +import { + create as createJSS, + default as sharedInstance +} from 'jss'; -jss.set('.demo', { - 'font-size': '15px', - 'color': 'red' +const jss = createJSS().setup({}); + +const styleSheet = jss.createStyleSheet( + { + ruleWithMockObservable: { + subscribe() {} + }, + container: { + display: 'flex', + width: 100, + opacity: .5, + }, + }, + { + link: true, + } +).attach(); + +styleSheet.classes.container; // $ExpectType string +styleSheet.classes.ruleWithMockObservable; // $ExpectType string + +const rule = styleSheet.addRule('dynamicRule', { color: 'indigo' }); +rule.prop('border-radius', 5).prop('color'); // $ExpectType string +styleSheet.classes.dynamicRule; // $ExpectType string + +styleSheet.deleteRule('dynamicRule'); + +// test that `addRule` supports the shorthand signature +const dynamicRule = styleSheet.addRule({ color: 'red' }); + +const div = document.createElement('div'); +dynamicRule.applyTo(div); + +const containerRule = styleSheet.getRule('container'); +const containerJSON = containerRule.toJSON(); +const css = styleSheet.toString(); + +styleSheet.addRules({ + rule1: { + fontFamily: 'Roboto', + color: '#FFFFFF', + }, + rule2: { + fontFamily: 'Inconsolata', + fontSize: 17, + }, }); -jss.get('.demo'); +styleSheet.detach(); -jss.get(); - -jss.getAll('.demo'); - -jss.remove('.demo'); - -jss.remove(); +sharedInstance.createStyleSheet({ + container: { + background: '#000099', + } +}); diff --git a/types/jss/tsconfig.json b/types/jss/tsconfig.json index d22eb9d75e..f34791192c 100644 --- a/types/jss/tsconfig.json +++ b/types/jss/tsconfig.json @@ -2,11 +2,12 @@ "compilerOptions": { "module": "commonjs", "lib": [ - "es6" + "es6", + "dom" ], "noImplicitAny": true, "noImplicitThis": true, - "strictNullChecks": false, + "strictNullChecks": true, "strictFunctionTypes": true, "baseUrl": "../", "typeRoots": [ @@ -20,4 +21,4 @@ "index.d.ts", "jss-tests.ts" ] -} \ No newline at end of file +} diff --git a/types/jss/tslint.json b/types/jss/tslint.json index a41bf5d19a..3db14f85ea 100644 --- a/types/jss/tslint.json +++ b/types/jss/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/klaw/index.d.ts b/types/klaw/index.d.ts index 8134b728c0..7b4e586842 100644 --- a/types/klaw/index.d.ts +++ b/types/klaw/index.d.ts @@ -1,4 +1,4 @@ -// Type definitions for klaw v2.1.0 +// Type definitions for klaw v2.1.1 // Project: https://github.com/jprichardson/node-klaw // Definitions by: Matthew McEachen // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped @@ -30,7 +30,7 @@ declare module "klaw" { type Event = "close" | "data" | "end" | "readable" | "error" - interface Walker { + interface Walker extends Readable { on(event: Event, listener: Function): this on(event: "close", listener: () => void): this on(event: "data", listener: (item: Item) => void): this diff --git a/types/klaw/v1/index.d.ts b/types/klaw/v1/index.d.ts index cbe78af067..74939f30c2 100644 --- a/types/klaw/v1/index.d.ts +++ b/types/klaw/v1/index.d.ts @@ -1,44 +1,39 @@ -// Type definitions for klaw v1.3.0 +// Type definitions for klaw 1.3 // Project: https://github.com/jprichardson/node-klaw // Definitions by: Matthew McEachen // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped /// -declare module "klaw" { +import * as fs from "fs"; +import { Readable, ReadableOptions } from 'stream'; - import * as fs from "fs" - import { Readable, ReadableOptions } from 'stream' +declare function K(root: string, options?: K.Options): K.Walker; - function K(root: string, options?: K.Options): K.Walker - - namespace K { - interface Item { - path: string - stats: fs.Stats - } - - type QueueMethod = "shift" | "pop" - - interface Options extends ReadableOptions { - queueMethod?: QueueMethod - pathSorter?: (pathA: string, pathB: string) => number - fs?: any // fs or mock-fs - filter?: (path: string) => boolean - } - - type Event = "close" | "data" | "end" | "readable" | "error" - - interface Walker { - on(event: Event, listener: Function): this - on(event: "close", listener: () => void): this - on(event: "data", listener: (item: Item) => void): this - on(event: "end", listener: () => void): this - on(event: "readable", listener: () => void): this - on(event: "error", listener: (err: Error) => void): this - read(): Item - } +declare namespace K { + interface Item { + path: string; + stats: fs.Stats; } - export = K + type QueueMethod = "shift" | "pop"; + + interface Options extends ReadableOptions { + queueMethod?: QueueMethod; + pathSorter?: (pathA: string, pathB: string) => number; + fs?: any; // fs or mock-fs + filter?: (path: string) => boolean; + } + + type Event = "close" | "data" | "end" | "readable" | "error"; + + interface Walker { + on(event: Event, listener: Function): this; + on(event: "close" | "end" | "readable", listener: () => void): this; + on(event: "data", listener: (item: Item) => void): this; + on(event: "error", listener: (err: Error) => void): this; + read(): Item; + } } + +export = K; diff --git a/types/klaw/v1/klaw-tests.ts b/types/klaw/v1/klaw-tests.ts index 2487aafd85..5e425a714a 100644 --- a/types/klaw/v1/klaw-tests.ts +++ b/types/klaw/v1/klaw-tests.ts @@ -1,43 +1,44 @@ import * as klaw from "klaw"; -const path = require('path'); +import * as path from "path"; // README.md: Streams 1 (push) example: -let items: klaw.Item[] = [] // files, directories, symlinks, etc +const items: klaw.Item[] = []; // files, directories, symlinks, etc klaw('/some/dir') - .on('data', function(item: klaw.Item) { - items.push(item) - }) - .on('end', function() { - console.dir(items) // => [ ... array of files] + .on('data', (item: klaw.Item) => { + items.push(item); }) + .on('end', () => { + console.dir(items); // => [ ... array of files] + }); // README.md: Streams 2 & 3 (pull) with error handling klaw('/some/dir') - .on('readable', function() { - let item: klaw.Item; - while (item = this.read()) { - items.push(item) + .on('readable', () => { + while (true) { + const item = this.read(); + if (!item) break; + items.push(item); } }) - .on('error', function(err: Error, item: klaw.Item) { - console.log(err.message) - console.log(item.path) // the file the error occurred on - }) - .on('end', function() { - console.log(items) // => [ ... array of files] + .on('error', (err: Error, item: klaw.Item) => { + console.log(err.message); + console.log(item.path); // the file the error occurred on }) + .on('end', () => { + console.log(items); // => [ ... array of files] + }); // README.md: Example (ignore hidden directories): -var filterFunc = function(item: string): boolean { - var basename = path.basename(item); - return basename === '.' || basename[0] !== '.' +function filterFunc(item: string): boolean { + const basename = path.basename(item); + return basename === '.' || basename[0] !== '.'; } klaw('/some/dir', { filter: filterFunc }) - .on('data', function(item: klaw.Item) { + .on('data', (item: klaw.Item) => { // only items of none hidden folders will reach here - }) + }); diff --git a/types/klaw/v1/tslint.json b/types/klaw/v1/tslint.json new file mode 100644 index 0000000000..d4a3f680ce --- /dev/null +++ b/types/klaw/v1/tslint.json @@ -0,0 +1,7 @@ +{ + "extends": "dtslint/dt.json", + "rules": { + // TODOs + "ban-types": false + } +} diff --git a/types/knex/index.d.ts b/types/knex/index.d.ts index aaee0b27f7..479e38c286 100644 --- a/types/knex/index.d.ts +++ b/types/knex/index.d.ts @@ -1,6 +1,9 @@ // Type definitions for Knex.js // Project: https://github.com/tgriesser/knex -// Definitions by: Qubo , Baronfel , Pablo Rodríguez +// Definitions by: Qubo +// Baronfel +// Pablo Rodríguez +// Matt R. Wilson // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped // TypeScript Version: 2.3 @@ -156,7 +159,7 @@ declare namespace Knex { delete(returning?: string | string[]): QueryBuilder; truncate(): QueryBuilder; - transacting(trx: Transaction): QueryBuilder; + transacting(trx?: Transaction): QueryBuilder; connection(connection: any): QueryBuilder; clone(): QueryBuilder; @@ -510,7 +513,7 @@ declare namespace Knex { interface Config { debug?: boolean; - client?: string; + client?: string | typeof Client; dialect?: string; version?: string; connection?: string | ConnectionConfig | MariaSqlConnectionConfig | @@ -676,6 +679,22 @@ declare namespace Knex { interface FunctionHelper { now(): Raw; } + + // + // Clients + // + + class Client extends events.EventEmitter { + constructor(config: Config); + config: Config; + dialect: string; + driverName: string; + connectionSettings: object; + + acquireRawConnection(): Promise; + destroyRawConnection(connection: any): Promise; + validateConnection(connection: any): Promise; + } } export = Knex; diff --git a/types/knex/knex-tests.ts b/types/knex/knex-tests.ts index dec1bf055f..910f0ee427 100644 --- a/types/knex/knex-tests.ts +++ b/types/knex/knex-tests.ts @@ -128,6 +128,13 @@ var knex = Knex({ useNullAsDefault: true, }); +// Using custom client +class TestClient extends Knex.Client {} + +var knex = Knex({ + client: TestClient, +}); + knex('books').insert({title: 'Test'}).returning('*').toString(); // Migrations @@ -672,6 +679,9 @@ knex.transaction<{ length: number }>(function(trx) { console.error(error); }); +// transacting handles undefined +knex.insert({ name: 'Old Books'}).transacting(undefined); + knex.schema.withSchema("public").hasTable("table") as Promise; knex.schema.createTable('users', function (table) { diff --git a/types/koa-conditional-get/index.d.ts b/types/koa-conditional-get/index.d.ts new file mode 100644 index 0000000000..3e4839fc88 --- /dev/null +++ b/types/koa-conditional-get/index.d.ts @@ -0,0 +1,11 @@ +// Type definitions for koa-conditional-get 2.0 +// Project: https://github.com/koajs/conditional-get#readme +// Definitions by: Matthew Bull +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.3 + +import * as koa from 'koa'; + +declare function koaConditionalGet(): koa.Middleware; + +export = koaConditionalGet; diff --git a/types/koa-conditional-get/koa-conditional-get-tests.ts b/types/koa-conditional-get/koa-conditional-get-tests.ts new file mode 100644 index 0000000000..a197ba7398 --- /dev/null +++ b/types/koa-conditional-get/koa-conditional-get-tests.ts @@ -0,0 +1,4 @@ +import Koa = require('koa'); +import conditional = require('koa-conditional-get'); + +new Koa().use(conditional()); diff --git a/types/koa-conditional-get/tsconfig.json b/types/koa-conditional-get/tsconfig.json new file mode 100644 index 0000000000..111408f39b --- /dev/null +++ b/types/koa-conditional-get/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", + "koa-conditional-get-tests.ts" + ] +} diff --git a/types/koa-conditional-get/tslint.json b/types/koa-conditional-get/tslint.json new file mode 100644 index 0000000000..3db14f85ea --- /dev/null +++ b/types/koa-conditional-get/tslint.json @@ -0,0 +1 @@ +{ "extends": "dtslint/dt.json" } diff --git a/types/koa-etag/index.d.ts b/types/koa-etag/index.d.ts new file mode 100644 index 0000000000..807fd7803b --- /dev/null +++ b/types/koa-etag/index.d.ts @@ -0,0 +1,12 @@ +// Type definitions for koa-etag 3.0 +// Project: https://github.com/koajs/etag#readme +// Definitions by: Matthew Bull +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.3 + +import * as koa from 'koa'; +import * as etag from 'etag'; + +declare function koaEtag(options?: etag.Options): koa.Middleware; + +export = koaEtag; diff --git a/types/koa-etag/koa-etag-tests.ts b/types/koa-etag/koa-etag-tests.ts new file mode 100644 index 0000000000..fa2d5515d6 --- /dev/null +++ b/types/koa-etag/koa-etag-tests.ts @@ -0,0 +1,8 @@ +import koaEtag = require('koa-etag'); +import * as Koa from 'koa'; + +new Koa().use(koaEtag()); + +new Koa().use(koaEtag({})); + +new Koa().use(koaEtag({ weak: true })); diff --git a/types/koa-etag/tsconfig.json b/types/koa-etag/tsconfig.json new file mode 100644 index 0000000000..d6b1feb52c --- /dev/null +++ b/types/koa-etag/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", + "koa-etag-tests.ts" + ] +} diff --git a/types/koa-etag/tslint.json b/types/koa-etag/tslint.json new file mode 100644 index 0000000000..3db14f85ea --- /dev/null +++ b/types/koa-etag/tslint.json @@ -0,0 +1 @@ +{ "extends": "dtslint/dt.json" } diff --git a/types/koa-joi-router/index.d.ts b/types/koa-joi-router/index.d.ts index fb7164d47d..bf3f387d31 100644 --- a/types/koa-joi-router/index.d.ts +++ b/types/koa-joi-router/index.d.ts @@ -15,17 +15,12 @@ interface Spec { type: string; body?: Joi.AnySchema; params?: Joi.AnySchema; - [status: number]: Joi.AnySchema; + output?: {[status: number]: Joi.AnySchema}; }; } -interface Router { - route(spec: Spec): Router; - middleware(): Koa.Middleware; -} - interface createRouter { - (): Router; + (): createRouter.Router; Joi: typeof Joi; } @@ -38,6 +33,12 @@ declare namespace createRouter { interface Context extends Koa.Context { request: Request; } + + interface Router { + routes: Spec[]; + route(spec: Spec|Spec[]): Router; + middleware(): Koa.Middleware; + } } declare var createRouter: createRouter; diff --git a/types/koa-joi-router/koa-joi-router-tests.ts b/types/koa-joi-router/koa-joi-router-tests.ts index e36ce95746..76a392bdec 100644 --- a/types/koa-joi-router/koa-joi-router-tests.ts +++ b/types/koa-joi-router/koa-joi-router-tests.ts @@ -38,7 +38,9 @@ const spec4 = { path: '/user', validate: { type: 'json', - 201: Joi.object(), + output: { + 201: Joi.object(), + } }, handler: (ctx: router.Context) => { ctx.status = 201; @@ -69,3 +71,7 @@ const spec6 = { }; router().route(spec6); + +router().route([spec1, spec2, spec3]); + +router().routes.map(({ path }) => path); diff --git a/types/koa-logger/index.d.ts b/types/koa-logger/index.d.ts index 460d70f3fb..4d593786c6 100644 --- a/types/koa-logger/index.d.ts +++ b/types/koa-logger/index.d.ts @@ -1,13 +1,14 @@ -// Type definitions for koa-logger v2.0 +// Type definitions for koa-logger 3.1 // Project: https://github.com/koajs/logger // Definitions by: Joshua DeVinney +// Tomek Łaziuk // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped // TypeScript Version: 2.3 -/// +import { + Middleware, +} from 'koa'; -import * as Koa from 'koa'; - -declare function KoaLogger(): Koa.Middleware; -declare namespace KoaLogger {} +declare function KoaLogger(): Middleware; +declare namespace KoaLogger { } export = KoaLogger; diff --git a/types/koa-logger/tslint.json b/types/koa-logger/tslint.json index a41bf5d19a..f93cf8562a 100644 --- a/types/koa-logger/tslint.json +++ b/types/koa-logger/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/koa-router/index.d.ts b/types/koa-router/index.d.ts index 4ad96140eb..ab61772835 100644 --- a/types/koa-router/index.d.ts +++ b/types/koa-router/index.d.ts @@ -219,7 +219,7 @@ declare class Router { /** * Returns router middleware which dispatches a route matching the request. */ - middlewares(): Router.IMiddleware; + middleware(): Router.IMiddleware; /** * Returns separate middleware for responding to `OPTIONS` requests with diff --git a/types/koa-send/index.d.ts b/types/koa-send/index.d.ts index a15f5b688d..65228c9981 100644 --- a/types/koa-send/index.d.ts +++ b/types/koa-send/index.d.ts @@ -1,24 +1,46 @@ -// Type definitions for koa-send v3.3 +// Type definitions for koa-send 4.1 // Project: https://github.com/koajs/send // Definitions by: Peter Safranek +// Tomek Łaziuk // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped // TypeScript Version: 2.3 -import * as Koa from 'koa'; +import { + Context, +} from "koa"; -interface ISendOptions { - root?: string; - index?: string; - maxAge?: number; - hidden?: boolean; - format?: boolean; - gzip?: boolean; - setHeaders?: Function; - extensions?: string[]; +import { + Stats, +} from "fs"; + +declare function send(ctx: Context, path: string, opts?: send.SendOptions): Promise; + +declare namespace send { + type SetHeaders = (res: Context["res"], path: string, stats: Stats) => any; + + interface SendOptions { + /** Browser cache max-age in milliseconds. (defaults to 0) */ + maxage?: number; + maxAge?: SendOptions["maxage"]; + /** Tell the browser the resource is immutable and can be cached indefinitely. (defaults to false) */ + immutable?: boolean; + /** Allow transfer of hidden files. (defaults to false) */ + hidden?: boolean; + /** Root directory to restrict file access. (defaults to '') */ + root?: string; + /** Name of the index file to serve automatically when visiting the root location. (defaults to none) */ + index?: string; + /** Try to serve the gzipped version of a file automatically when gzip is supported by a client and if the requested file with .gz extension exists. (defaults to true). */ + gzip?: boolean; + /** Try to serve the brotli version of a file automatically when brotli is supported by a client and if the requested file with .br extension exists. (defaults to true). */ + brotli?: boolean; + /** If not false (defaults to true), format the path to serve static file servers and not require a trailing slash for directories, so that you can do both /directory and /directory/. */ + format?: boolean; + /** Function to set custom headers on response. */ + setHeaders?: SetHeaders; + /** Try to match extensions from passed array to search for file when no extension is sufficed in URL. First found is served. (defaults to false) */ + extensions?: string[] | false; + } } -declare function send(ctx: Koa.Context, path: string, opts?: ISendOptions): Promise; - -declare namespace send {} - export = send; diff --git a/types/koa-send/koa-send-tests.ts b/types/koa-send/koa-send-tests.ts index 88a6f16abb..a3b136ea9a 100644 --- a/types/koa-send/koa-send-tests.ts +++ b/types/koa-send/koa-send-tests.ts @@ -1,4 +1,3 @@ - import * as Koa from 'koa'; import * as send from 'koa-send'; @@ -16,7 +15,7 @@ app.use(async (ctx: Koa.Context) => { hidden: true, format: true, gzip: true, - setHeaders: () => {}, + setHeaders: () => { }, extensions: ['shemp'], }); }); diff --git a/types/koa-send/tslint.json b/types/koa-send/tslint.json index a41bf5d19a..f93cf8562a 100644 --- a/types/koa-send/tslint.json +++ b/types/koa-send/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/koa-sslify/index.d.ts b/types/koa-sslify/index.d.ts new file mode 100644 index 0000000000..0bf6c0a1ff --- /dev/null +++ b/types/koa-sslify/index.d.ts @@ -0,0 +1,25 @@ +// Type definitions for koa-sslify 2.1 +// Project: https://github.com/turboMaCk/koa-sslify#readme +// Definitions by: Matthew Bull +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.3 + +import * as koa from 'koa'; + +declare namespace sslify { + interface Options { + trustProtoHeader?: boolean; + trustAzureHeader?: boolean; + port?: number; + hostname?: string; + ignoreUrl?: boolean; + temporary?: boolean; + redirectMethods?: string[]; + internalRedirectMethods?: string[]; + specCompliantDisallow?: boolean; + } +} + +declare function sslify(options: sslify.Options): koa.Middleware; + +export = sslify; diff --git a/types/koa-sslify/koa-sslify-tests.ts b/types/koa-sslify/koa-sslify-tests.ts new file mode 100644 index 0000000000..c8dae23bb4 --- /dev/null +++ b/types/koa-sslify/koa-sslify-tests.ts @@ -0,0 +1,40 @@ +import Koa = require('koa'); +import sslify = require('koa-sslify'); + +new Koa().use(sslify({})); + +new Koa().use(sslify({ + trustAzureHeader: true, +})); + +new Koa().use(sslify({ + trustProtoHeader: true, +})); + +new Koa().use(sslify({ + specCompliantDisallow: true, +})); + +new Koa().use(sslify({ + port: 1234, +})); + +new Koa().use(sslify({ + hostname: 'my-host', +})); + +new Koa().use(sslify({ + temporary: false, +})); + +new Koa().use(sslify({ + internalRedirectMethods: ['GET'], +})); + +new Koa().use(sslify({ + redirectMethods: ['GET'], +})); + +new Koa().use(sslify({ + ignoreUrl: true, +})); diff --git a/types/koa-sslify/tsconfig.json b/types/koa-sslify/tsconfig.json new file mode 100644 index 0000000000..64615e2ab9 --- /dev/null +++ b/types/koa-sslify/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", + "koa-sslify-tests.ts" + ] +} diff --git a/types/koa-sslify/tslint.json b/types/koa-sslify/tslint.json new file mode 100644 index 0000000000..3db14f85ea --- /dev/null +++ b/types/koa-sslify/tslint.json @@ -0,0 +1 @@ +{ "extends": "dtslint/dt.json" } diff --git a/types/koa-webpack/index.d.ts b/types/koa-webpack/index.d.ts new file mode 100644 index 0000000000..b425956f03 --- /dev/null +++ b/types/koa-webpack/index.d.ts @@ -0,0 +1,31 @@ +// Type definitions for koa-webpack 1.0 +// Project: https://github.com/shellscape/koa-webpack#readme +// Definitions by: Luka Maljic +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.3 + +import Koa = require('koa'); +import webpack = require('webpack'); +import webpackDevMiddleware = require('webpack-dev-middleware'); +import webpackHotMiddleware = require('webpack-hot-middleware'); +import connect = require('connect'); + +declare function koaWebpack( + options?: koaWebpack.Options +): Koa.Middleware & koaWebpack.CombinedWebpackMiddleware; + +declare namespace koaWebpack { + interface Options { + compiler?: webpack.Compiler; + config?: webpack.Configuration; + dev?: webpackDevMiddleware.Options; + hot?: webpackHotMiddleware.Options; + } + + interface CombinedWebpackMiddleware { + dev: connect.NextHandleFunction & webpackDevMiddleware.WebpackDevMiddleware; + hot: connect.NextHandleFunction & webpackHotMiddleware.EventStream; + } +} + +export = koaWebpack; diff --git a/types/koa-webpack/koa-webpack-tests.ts b/types/koa-webpack/koa-webpack-tests.ts new file mode 100644 index 0000000000..c153a874d5 --- /dev/null +++ b/types/koa-webpack/koa-webpack-tests.ts @@ -0,0 +1,47 @@ +import Koa = require('koa'); +import webpack = require('webpack'); +import koaWebpack = require('koa-webpack'); + +const app = new Koa(); +const config: webpack.Configuration = {}; +const compiler = webpack(config); + +// Using the middleware + +const middleware = koaWebpack({ + compiler, + config, + dev: { + noInfo: false, + quiet: false, + lazy: true, + watchOptions: { + aggregateTimeout: 300, + poll: true, + }, + publicPath: '/assets/', + index: 'index.html', + headers: { + 'X-Custom-Header': 'yes' + }, + stats: { + colors: true, + }, + reporter: null, + serverSideRender: false + }, + hot: { + log: console.log.bind(console), + path: '/__what', + heartbeat: 2000 + } +}); + +app.use(middleware); + +// Accessing the underlying middleware + +middleware.dev.close(); +middleware.dev.invalidate(); +middleware.dev.waitUntilValid(); +middleware.hot.publish(null); diff --git a/types/koa-webpack/tsconfig.json b/types/koa-webpack/tsconfig.json new file mode 100644 index 0000000000..d3cef374db --- /dev/null +++ b/types/koa-webpack/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", + "koa-webpack-tests.ts" + ] +} diff --git a/types/koa-webpack/tslint.json b/types/koa-webpack/tslint.json new file mode 100644 index 0000000000..3db14f85ea --- /dev/null +++ b/types/koa-webpack/tslint.json @@ -0,0 +1 @@ +{ "extends": "dtslint/dt.json" } diff --git a/types/koa/index.d.ts b/types/koa/index.d.ts index d4f339aa32..64bd8ed41a 100644 --- a/types/koa/index.d.ts +++ b/types/koa/index.d.ts @@ -1,6 +1,8 @@ // Type definitions for Koa 2.x // Project: http://koajs.com -// Definitions by: DavidCai1993 , jKey Lu +// Definitions by: DavidCai1993 +// jKey Lu +// Brice Bernard // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped // TypeScript Version: 2.3 @@ -15,20 +17,22 @@ =============================================== */ /// -import { EventEmitter } from 'events'; -import { IncomingMessage, ServerResponse, Server } from 'http'; -import { Socket, ListenOptions } from 'net'; -import * as compose from 'koa-compose'; -import * as Keygrip from 'keygrip'; -import * as httpAssert from 'http-assert'; -import * as Cookies from 'cookies'; -import * as accepts from 'accepts'; +import * as accepts from "accepts"; +import * as Cookies from "cookies"; +import { EventEmitter } from "events"; +import { IncomingMessage, ServerResponse, Server } from "http"; +import * as httpAssert from "http-assert"; +import * as Keygrip from "keygrip"; +import * as compose from "koa-compose"; +import { Socket, ListenOptions } from "net"; +import * as url from "url"; declare interface ContextDelegatedRequest { /** * Return request header. */ header: any; + /** * Return request header, alias as request.header */ @@ -80,7 +84,6 @@ declare interface ContextDelegatedRequest { */ search: string; - /** * Parse the "Host" header field host * and support X-Forwarded-Host when a @@ -95,6 +98,11 @@ declare interface ContextDelegatedRequest { */ hostname: string; + /** + * Get WHATWG parsed URL object. + */ + URL: url.URL; + /** * Check if the request is fresh, aka * Last-Modified and/or the ETag @@ -388,7 +396,7 @@ declare interface ContextDelegatedResponse { * this.set('Accept', 'application/json'); * this.set({ Accept: 'text/plain', 'X-API-Key': 'tobi' }); */ - set(field: { [key: string]: string; }): void; + set(field: { [key: string]: string }): void; set(field: string, val: string | string[]): void; /** @@ -440,15 +448,36 @@ declare class Application extends EventEmitter { * * http.createServer(app.callback()).listen(...) */ - listen(port?: number, hostname?: string, backlog?: number, listeningListener?: () => void): Server; - listen(port: number, hostname?: string, listeningListener?: () => void): Server; + listen( + port?: number, + hostname?: string, + backlog?: number, + listeningListener?: () => void, + ): Server; + listen( + port: number, + hostname?: string, + listeningListener?: () => void, + ): Server; /* tslint:disable:unified-signatures */ - listen(port: number, backlog?: number, listeningListener?: () => void): Server; + listen( + port: number, + backlog?: number, + listeningListener?: () => void, + ): Server; listen(port: number, listeningListener?: () => void): Server; - listen(path: string, backlog?: number, listeningListener?: () => void): Server; + listen( + path: string, + backlog?: number, + listeningListener?: () => void, + ): Server; listen(path: string, listeningListener?: () => void): Server; listen(options: ListenOptions, listeningListener?: () => void): Server; - listen(handle: any, backlog?: number, listeningListener?: () => void): Server; + listen( + handle: any, + backlog?: number, + listeningListener?: () => void, + ): Server; listen(handle: any, listeningListener?: () => void): Server; /* tslint:enable:unified-signatures*/ @@ -482,7 +511,10 @@ declare class Application extends EventEmitter { * * @api private */ - createContext(req: IncomingMessage, res: ServerResponse): Application.Context; + createContext( + req: IncomingMessage, + res: ServerResponse, + ): Application.Context; /** * Default error handler. @@ -578,7 +610,9 @@ declare namespace Application { toJSON(): any; } - interface BaseContext extends ContextDelegatedRequest, ContextDelegatedResponse { + interface BaseContext + extends ContextDelegatedRequest, + ContextDelegatedResponse { /** * util.inspect() implementation, which * just returns the JSON output. @@ -626,6 +660,8 @@ declare namespace Application { * Default error handling. */ onerror(err: Error): void; + + [key: string]: any; } interface Request extends BaseRequest { diff --git a/types/koa/koa-tests.ts b/types/koa/koa-tests.ts index 1b261fdf44..6dbc073bea 100644 --- a/types/koa/koa-tests.ts +++ b/types/koa/koa-tests.ts @@ -1,21 +1,27 @@ - import * as Koa from "koa"; const app = new Koa(); +app.context.db = () => {}; + +app.use(async ctx => { + console.log(ctx.db); +}); + app.use((ctx, next) => { - const start: any = new Date(); - return next().then(() => { - const end: any = new Date(); - const ms = end - start; - console.log(`${ctx.method} ${ctx.url} - ${ms}ms`); - ctx.assert(true, 404, 'Yep!'); - }); + const start: any = new Date(); + return next().then(() => { + const end: any = new Date(); + const ms = end - start; + console.log(`${ctx.method} ${ctx.url} - ${ms}ms`); + ctx.assert(true, 404, "Yep!"); + }); }); // response app.use(ctx => { - ctx.body = "Hello World"; + ctx.body = "Hello World"; + ctx.body = ctx.URL.toString(); }); app.listen(3000); diff --git a/types/kolite/knockout.dirtyFlag.d.ts b/types/kolite/knockout.dirtyFlag.d.ts index 2f63a110e0..3999f833ae 100644 --- a/types/kolite/knockout.dirtyFlag.d.ts +++ b/types/kolite/knockout.dirtyFlag.d.ts @@ -10,9 +10,14 @@ // DirtyFlag ///////////////////////////////////////////// interface DirtyFlag { - isDirty: KnockoutComputed; new (objectToTrack: any, isInitiallyDirty?: boolean, hashFunction?: () => any): any; + (): DirtyFlagResult; +} + +interface DirtyFlagResult { + isDirty: KnockoutComputed; reset(): void; + forceDirty(): void; } interface KnockoutStatic { diff --git a/types/leaflet.heat/index.d.ts b/types/leaflet.heat/index.d.ts new file mode 100644 index 0000000000..224b6f7c35 --- /dev/null +++ b/types/leaflet.heat/index.d.ts @@ -0,0 +1,32 @@ +// Type definitions for Leaflet.heat 0.2 +// Project: https://github.com/Leaflet/Leaflet.heat +// Definitions by: Önder Ceylan +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.3 + +import * as L from 'leaflet'; + +declare module 'leaflet' { + type HeatLatLngTuple = [number, number, number]; + + interface ColorGradientConfig { + [key: number]: string; + } + + interface HeatMapOptions { + minOpacity?: number; + maxZoom?: number; + max?: number; + radius?: number; + blur?: number; + gradient?: ColorGradientConfig; + } + + interface HeatLayer extends TileLayer { + setOptions(options: HeatMapOptions): HeatLayer; + addLatLng(latlng: LatLng | HeatLatLngTuple): HeatLayer; + setLatLngs(latlngs: Array): HeatLayer; + } + + function heatLayer(latlngs: Array, options: HeatMapOptions): HeatLayer; +} diff --git a/types/leaflet.heat/leaflet.heat-tests.ts b/types/leaflet.heat/leaflet.heat-tests.ts new file mode 100644 index 0000000000..b715255e78 --- /dev/null +++ b/types/leaflet.heat/leaflet.heat-tests.ts @@ -0,0 +1,43 @@ +import * as L from 'leaflet'; +import 'leaflet.heat'; + +const osmUrl = 'http://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png'; +const osmAttrib = '© OpenStreetMap contributors'; +const osm = L.tileLayer(osmUrl, {maxZoom: 18, attribution: osmAttrib}); +const map = new L.Map('map', { + layers: [osm], + center: new L.LatLng(50.5, 30.5), + zoom: 15, +}); + +// Each point in the input array can be either an array like [50.5, 30.5, 0.5], or a Leaflet LatLng object. +const heat: L.HeatLayer = L.heatLayer([ + [50.5, 30.5, 0.2], // lat, lng, intensity + [50.6, 30.4, 0.5], + new L.LatLng(50.7, 30.3), +], {radius: 25}).addTo(map); + +// Set options on the heat layer +heat.setOptions({ + minOpacity: 0.05, + maxZoom: 18, + max: 1.0, + radius: 25, + blur: 15, + gradient: {0.4: 'blue', 0.65: 'lime', 1: 'red'}, +}); + +// Add new point to heat layer +const newLatLng = new L.LatLng(50.8, 30.2); +heat.addLatLng(newLatLng); + +// Set new latLng list to the heat layer +heat.setLatLngs([ + newLatLng, + newLatLng, + newLatLng, + [50.6, 30.4, 0.5], +]); + +// Redraw the heat layer +heat.redraw(); diff --git a/types/leaflet.heat/tsconfig.json b/types/leaflet.heat/tsconfig.json new file mode 100644 index 0000000000..482c984b8c --- /dev/null +++ b/types/leaflet.heat/tsconfig.json @@ -0,0 +1,24 @@ +{ + "compilerOptions": { + "module": "commonjs", + "lib": [ + "es6", + "dom" + ], + "noImplicitAny": true, + "noImplicitThis": true, + "strictNullChecks": true, + "strictFunctionTypes": true, + "baseUrl": "../", + "typeRoots": [ + "../" + ], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true + }, + "files": [ + "index.d.ts", + "leaflet.heat-tests.ts" + ] +} diff --git a/types/leaflet.heat/tslint.json b/types/leaflet.heat/tslint.json new file mode 100644 index 0000000000..f93cf8562a --- /dev/null +++ b/types/leaflet.heat/tslint.json @@ -0,0 +1,3 @@ +{ + "extends": "dtslint/dt.json" +} diff --git a/types/leaflet.markercluster/index.d.ts b/types/leaflet.markercluster/index.d.ts index f60a7a2891..e2f317dd46 100644 --- a/types/leaflet.markercluster/index.d.ts +++ b/types/leaflet.markercluster/index.d.ts @@ -29,7 +29,7 @@ declare module 'leaflet' { getBounds(): LatLngBounds; } - interface MarkerClusterGroupOptions { + interface MarkerClusterGroupOptions extends LayerOptions { /* * When you mouse over a cluster it shows the bounds of its markers. */ diff --git a/types/leaflet/index.d.ts b/types/leaflet/index.d.ts index b1e7ead796..71c6ea4adf 100644 --- a/types/leaflet/index.d.ts +++ b/types/leaflet/index.d.ts @@ -241,20 +241,22 @@ export abstract class Evented extends Class { */ on(eventMap: LeafletEventHandlerFnMap): this; - /* tslint:disable:unified-signatures */ // With an eventMap there are no additional arguments allowed /** * Removes a previously added listener function. If no function is specified, * it will remove all the listeners of that particular event from the object. * Note that if you passed a custom context to on, you must pass the same context * to off in order to remove the listener. */ + // With an eventMap there are no additional arguments allowed + // tslint:disable-next-line:unified-signatures off(type: string, fn?: LeafletEventHandlerFn, context?: any): this; /** * Removes a set of type/listener pairs. */ + // With an eventMap there are no additional arguments allowed + // tslint:disable-next-line:unified-signatures off(eventMap: LeafletEventHandlerFnMap): this; - /* tslint:enable */ /** * Removes all listeners to all events on the object. */ @@ -667,7 +669,8 @@ export function canvas(options?: RendererOptions): Canvas; * added/removed on the map as well. Extends Layer. */ export class LayerGroup

extends Layer { - constructor(layers?: Layer[]); + constructor(layers?: Layer[], options?: LayerOptions); + /** * Returns a GeoJSON representation of the layer group (as a GeoJSON GeometryCollection, GeoJSONFeatureCollection or Multipoint). */ @@ -729,9 +732,9 @@ export class LayerGroup

extends Layer { } /** - * Create a layer group, optionally given an initial set of layers. + * Create a layer group, optionally given an initial set of layers and an `options` object. */ -export function layerGroup(layers: Layer[]): LayerGroup; +export function layerGroup(layers?: Layer[], options?: LayerOptions): LayerGroup; /** * Extended LayerGroup that also has mouse events (propagated from @@ -1128,9 +1131,8 @@ export interface PanOptions { noMoveStart?: boolean; } -/* tslint:disable:no-empty-interface */ // This is not empty, it extends two interfaces into one... +// This is not empty, it extends two interfaces into one... export interface ZoomPanOptions extends ZoomOptions, PanOptions {} -/* tslint:enable */ export interface FitBoundsOptions extends ZoomOptions, PanOptions { paddingTopLeft?: PointExpression; diff --git a/types/leaflet/leaflet-tests.ts b/types/leaflet/leaflet-tests.ts index fc84a78267..a39ea761b1 100644 --- a/types/leaflet/leaflet-tests.ts +++ b/types/leaflet/leaflet-tests.ts @@ -496,3 +496,17 @@ interface MyProperties { iconUrl: 'my-icon.png' }) }) as L.Marker).feature.properties.testProperty = "test"; + +let lg = L.layerGroup(); +lg = L.layerGroup([new L.Layer(), new L.Layer()]); +lg = L.layerGroup([new L.Layer(), new L.Layer()], { + pane: 'overlayPane', + attribution: 'test' +}); + +lg = new L.LayerGroup(); +lg = new L.LayerGroup([new L.Layer(), new L.Layer()]); +lg = new L.LayerGroup([new L.Layer(), new L.Layer()], { + pane: 'overlayPane', + attribution: 'test' +}); diff --git a/types/left-pad/index.d.ts b/types/left-pad/index.d.ts deleted file mode 100644 index 1296c4fe02..0000000000 --- a/types/left-pad/index.d.ts +++ /dev/null @@ -1,8 +0,0 @@ -// Type definitions for left-pad 1.1 -// Project: https://github.com/stevemao/left-pad -// Definitions by: Zlatko Andonovski -// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped - -declare function leftPad(str: string|number, len: number, ch?: string|number): string; - -export = leftPad; diff --git a/types/left-pad/left-pad-tests.ts b/types/left-pad/left-pad-tests.ts deleted file mode 100644 index a3749feb16..0000000000 --- a/types/left-pad/left-pad-tests.ts +++ /dev/null @@ -1,15 +0,0 @@ -import leftPad = require("left-pad"); - -// Tests based on examples in https://github.com/stevemao/left-pad#usage - -leftPad("foo", 5); -// => " foo" - -leftPad("foobar", 6); -// => "foobar"' - -leftPad(1, 2, "0"); -// => "01" - -leftPad(17, 5, 0); -// => "00017" diff --git a/types/less2sass/index.d.ts b/types/less2sass/index.d.ts new file mode 100644 index 0000000000..25848117f2 --- /dev/null +++ b/types/less2sass/index.d.ts @@ -0,0 +1,11 @@ +// Type definitions for less2sass 1.0 +// Project: https://github.com/ekryski/less2sass +// Definitions by: William Lohan +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +declare class Less2Sass { + convert(file: string): string; +} + +declare const less2sass: Less2Sass; +export = less2sass; diff --git a/types/less2sass/less2sass-tests.ts b/types/less2sass/less2sass-tests.ts new file mode 100644 index 0000000000..578b731887 --- /dev/null +++ b/types/less2sass/less2sass-tests.ts @@ -0,0 +1,4 @@ +import * as less2sass from 'less2sass'; + +let scss: string; +scss = less2sass.convert('@myColor: #f938ab; .myClass { color: @myColor; }'); diff --git a/types/less2sass/tsconfig.json b/types/less2sass/tsconfig.json new file mode 100644 index 0000000000..e70848dca8 --- /dev/null +++ b/types/less2sass/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", + "less2sass-tests.ts" + ] +} diff --git a/types/less2sass/tslint.json b/types/less2sass/tslint.json new file mode 100644 index 0000000000..3db14f85ea --- /dev/null +++ b/types/less2sass/tslint.json @@ -0,0 +1 @@ +{ "extends": "dtslint/dt.json" } diff --git a/types/loadware/index.d.ts b/types/loadware/index.d.ts new file mode 100644 index 0000000000..7c45225d44 --- /dev/null +++ b/types/loadware/index.d.ts @@ -0,0 +1,16 @@ +// Type definitions for loadware 2.0 +// Project: https://github.com/franciscop/loadware +// Definitions by: A.J.J. Lyman +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +// tslint:disable-next-line:ban-types +type AnyFunction = Function; + +declare function loadware(...loadable: Array>): ReadonlyArray; + +declare namespace loadware { + type Loadable = string | F | RecursiveLoadable; + interface RecursiveLoadable extends Array> { } +} + +export = loadware; diff --git a/types/loadware/loadware-tests.ts b/types/loadware/loadware-tests.ts new file mode 100644 index 0000000000..630d3fd351 --- /dev/null +++ b/types/loadware/loadware-tests.ts @@ -0,0 +1,20 @@ +import loadware = require("loadware"); + +interface Context { __ContextMarker: never; } +interface Response { __ResponseMarker: never; } +type Middleware = (ctx: Context) => void; + +loadware( + (_: Context) => {}, + [ + (_: Context) => {}, + 'loadware/requires-strings' + ], + [ + [ + [ + (_: Context) => {} + ] + ] + ] +); diff --git a/types/left-pad/tsconfig.json b/types/loadware/tsconfig.json similarity index 94% rename from types/left-pad/tsconfig.json rename to types/loadware/tsconfig.json index 383ebedf76..5921615bf8 100644 --- a/types/left-pad/tsconfig.json +++ b/types/loadware/tsconfig.json @@ -18,6 +18,6 @@ }, "files": [ "index.d.ts", - "left-pad-tests.ts" + "loadware-tests.ts" ] } \ No newline at end of file diff --git a/types/loadware/tslint.json b/types/loadware/tslint.json new file mode 100644 index 0000000000..6746359dda --- /dev/null +++ b/types/loadware/tslint.json @@ -0,0 +1,3 @@ +{ + "extends": "dtslint/dt.json" +} diff --git a/types/lodash/conformsTo.d.ts b/types/lodash/conformsTo.d.ts new file mode 100644 index 0000000000..320b1806e0 --- /dev/null +++ b/types/lodash/conformsTo.d.ts @@ -0,0 +1,2 @@ +import { conformsTo } from "./index"; +export = conformsTo; diff --git a/types/lodash/defaultTo.d.ts b/types/lodash/defaultTo.d.ts new file mode 100644 index 0000000000..89fb56505f --- /dev/null +++ b/types/lodash/defaultTo.d.ts @@ -0,0 +1,2 @@ +import { defaultTo } from "./index"; +export = defaultTo; diff --git a/types/lodash/index.d.ts b/types/lodash/index.d.ts index a0eaef941c..76b0bcd47b 100644 --- a/types/lodash/index.d.ts +++ b/types/lodash/index.d.ts @@ -11585,6 +11585,10 @@ declare namespace _ { lower: number, upper: number ): number; + clamp( + number: number, + upper: number + ): number; } interface LoDashImplicitWrapper { @@ -11595,6 +11599,9 @@ declare namespace _ { lower: number, upper: number ): number; + clamp( + upper: number + ): number; } interface LoDashExplicitWrapper { @@ -11605,6 +11612,9 @@ declare namespace _ { lower: number, upper: number ): LoDashExplicitWrapper; + clamp( + upper: number + ): LoDashExplicitWrapper; } //_.inRange @@ -16635,21 +16645,21 @@ declare namespace _ { * @param predicates The predicates to check. * @return Returns the new function. */ - overEvery(...predicates: Array any>>): (...args: any[]) => boolean; + overEvery(...predicates: Array boolean>>): (...args: T[]) => boolean; } interface LoDashImplicitWrapper { /** * @see _.overEvery */ - overEvery(...predicates: Array any>>): LoDashImplicitWrapper<(...args: any[]) => boolean>; + overEvery(...predicates: Array boolean>>): LoDashImplicitWrapper<(...args: T[]) => boolean>; } interface LoDashExplicitWrapper { /** * @see _.overEvery */ - overEvery(...predicates: Array any>>): LoDashExplicitWrapper<(...args: any[]) => boolean>; + overEvery(...predicates: Array boolean>>): LoDashExplicitWrapper<(...args: T[]) => boolean>; } //_.overSome @@ -16661,21 +16671,21 @@ declare namespace _ { * @param predicates The predicates to check. * @return Returns the new function. */ - overSome(...predicates: Array any>>): (...args: any[]) => boolean; + overSome(...predicates: Array boolean>>): (...args: T[]) => boolean; } interface LoDashImplicitWrapper { /** * @see _.overSome */ - overSome(...predicates: Array any>>): LoDashImplicitWrapper<(...args: any[]) => boolean>; + overSome(...predicates: Array boolean>>): LoDashImplicitWrapper<(...args: T[]) => boolean>; } interface LoDashExplicitWrapper { /** * @see _.overSome */ - overSome(...predicates: Array any>>): LoDashExplicitWrapper<(...args: any[]) => boolean>; + overSome(...predicates: Array boolean>>): LoDashExplicitWrapper<(...args: T[]) => boolean>; } //_.property @@ -17084,13 +17094,13 @@ declare namespace _ { type ArrayIterator = (value: T, index: number, collection: T[]) => TResult; type ListIterator = (value: T, index: number, collection: List) => TResult; type ListIteratee = ListIterator | string | [string, any] | PartialDeep; - type ListIterateeCustom = ListIterator | string | [string, any] | PartialDeep; + type ListIterateeCustom = ListIterator | string | object | [string, any] | PartialDeep; type ListIteratorTypeGuard = (value: T, index: number, collection: List) => value is S; // Note: key should be string, not keyof T, because the actual object may contain extra properties that were not specified in the type. type ObjectIterator = (value: TObject[keyof TObject], key: string, collection: TObject) => TResult; type ObjectIteratee = ObjectIterator | string | [string, any] | PartialDeep; - type ObjectIterateeCustom = ObjectIterator | string | [string, any] | PartialDeep; + type ObjectIterateeCustom = ObjectIterator | string | object | [string, any] | PartialDeep; type ObjectIteratorTypeGuard = (value: TObject[keyof TObject], key: string, collection: TObject) => value is S; type DictionaryIterator = ObjectIterator, TResult>; diff --git a/types/lodash/lodash-tests.ts b/types/lodash/lodash-tests.ts index dbefb1abaa..49c705827f 100644 --- a/types/lodash/lodash-tests.ts +++ b/types/lodash/lodash-tests.ts @@ -9802,8 +9802,10 @@ namespace TestInClamp { let result: number; result = _.clamp(3, 2, 4); + result = _.clamp(3, 4); result = _(3).clamp(2, 4); + result = _(3).clamp(4); } { @@ -13689,60 +13691,60 @@ namespace TestOver { // _.overEvery namespace TestOverEvery { { - let result: (...args: any[]) => boolean; + let result: (...args: number[]) => boolean; - result = _.overEvery(() => true); - result = _.overEvery(() => true, () => true); - result = _.overEvery([() => true]); - result = _.overEvery([() => true], [() => true]); + result = _.overEvery((number) => true); + result = _.overEvery((number) => true, (number) => true); + result = _.overEvery([(number) => true]); + result = _.overEvery([(number) => true], [(number) => true]); } { - let result: _.LoDashImplicitObjectWrapper<(...args: any[]) => boolean>; + let result: _.LoDashImplicitObjectWrapper<(...args: number[]) => boolean>; result = _(Math.max).overEvery(); - result = _(Math.max).overEvery(() => true); + result = _(Math.max).overEvery((number) => true); result = _([Math.max]).overEvery(); - result = _([Math.max]).overEvery([() => true]); + result = _([Math.max]).overEvery([(number) => true]); } { - let result: _.LoDashExplicitObjectWrapper<(...args: any[]) => boolean>; + let result: _.LoDashExplicitObjectWrapper<(...args: number[]) => boolean>; result = _(Math.max).chain().overEvery(); - result = _(Math.max).chain().overEvery(() => true); + result = _(Math.max).chain().overEvery((number) => true); result = _([Math.max]).chain().overEvery(); - result = _([Math.max]).chain().overEvery([() => true]); + result = _([Math.max]).chain().overEvery([(number) => true]); } } // _.overSome namespace TestOverSome { { - let result: (...args: any[]) => boolean; + let result: (...args: number[]) => boolean; - result = _.overSome(() => true); - result = _.overSome(() => true, () => true); - result = _.overSome([() => true]); - result = _.overSome([() => true], [() => true]); + result = _.overSome((n: number) => true); + result = _.overSome((n: number) => true, (n: number) => true); + result = _.overSome([(n: number) => true]); + result = _.overSome([(n: number) => true], [(n: number) => true]); } { - let result: _.LoDashImplicitObjectWrapper<(...args: any[]) => boolean>; + let result: _.LoDashImplicitObjectWrapper<(...args: number[]) => boolean>; result = _(Math.max).overSome(); - result = _(Math.max).overSome(() => true); + result = _(Math.max).overSome((n: number) => true); result = _([Math.max]).overSome(); - result = _([Math.max]).overSome([() => true]); + result = _([Math.max]).overSome([(n: number) => true]); } { - let result: _.LoDashExplicitObjectWrapper<(...args: any[]) => boolean>; + let result: _.LoDashExplicitObjectWrapper<(...args: number[]) => boolean>; result = _(Math.max).chain().overSome(); - result = _(Math.max).chain().overSome(() => true); + result = _(Math.max).chain().overSome((n: number) => true); result = _([Math.max]).chain().overSome(); - result = _([Math.max]).chain().overSome([() => true]); + result = _([Math.max]).chain().overSome([(n: number) => true]); } } diff --git a/types/lodash/tsconfig.json b/types/lodash/tsconfig.json index 8bd56c0b87..af6ba5e2e9 100644 --- a/types/lodash/tsconfig.json +++ b/types/lodash/tsconfig.json @@ -6,8 +6,8 @@ ], "noImplicitAny": true, "noImplicitThis": true, - "strictNullChecks": true, "strictFunctionTypes": true, + "strictNullChecks": true, "baseUrl": "../", "typeRoots": [ "../" @@ -46,6 +46,7 @@ "compact.d.ts", "concat.d.ts", "cond.d.ts", + "conformsTo.d.ts", "constant.d.ts", "countBy.d.ts", "create.d.ts", @@ -55,6 +56,7 @@ "deburr.d.ts", "defaults.d.ts", "defaultsDeep.d.ts", + "defaultTo.d.ts", "defer.d.ts", "delay.d.ts", "difference.d.ts", @@ -316,4 +318,4 @@ "zipObjectDeep.d.ts", "zipWith.d.ts" ] -} \ No newline at end of file +} diff --git a/types/lokijs/index.d.ts b/types/lokijs/index.d.ts index f250786778..74f1b6f09e 100644 --- a/types/lokijs/index.d.ts +++ b/types/lokijs/index.d.ts @@ -1,854 +1,1431 @@ -// Type definitions for lokijs v1.2.5 +// Type definitions for lokijs v1.5.1 // Project: https://github.com/techfort/LokiJS // Definitions by: TeamworkGuy2 // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.3 -// NOTE: definition last updated (2016-3-13) based on latest code as of https://github.com/techfort/LokiJS/commit/3d2cf9546cd22556444deeabc4df314f227ecf5c +// NOTE: definition last updated (2017-11-25) based on latest code as of https://github.com/techfort/LokiJS/commit/f6c8f1c362cfc9ed63d93cd165ef0ac3bad131bf -/** LokiJS +/** + * LokiJS * A lightweight document oriented javascript database * @author Joe Minichino */ - -/** Loki: The main database class - * @constructor - * @param {string} filename - name of the file to be saved to - * @param {object} options - config object +/** comparison operators + * a is the value in the collection + * b is the query value */ -interface Loki extends LokiEventEmitter { - // autosave support (disabled by default) - autosave: boolean; - autosaveInterval: number; // milliseconds between auto-saves - autosaveHandle: number; // ID from setInterval(...) - collections: LokiCollection[]; - databaseVersion: number; - engineVersion: number; - ENV: string;/*NODEJS, CORDOVA, BROWSER*/ - events: { [id: string]: ((...args: any[]) => void)[] }; /*{ - 'init': ((...args) => void)[]; - 'loaded': ((...args) => void)[]; - 'flushChanges': ((...args) => void)[]; - 'close': ((...args) => void)[]; - 'changes': ((...args) => void)[]; - 'warning': ((...args) => void)[]; - };*/ - filename: string; - options: LokiConfigureOptions; - persistenceAdapter: LokiPersistenceInterface; - // persistenceMethod could be 'fs', 'localStorage', or 'adapter' - // this is optional option param, otherwise environment detection will be used - // if user passes their own adapter we will force this method to 'adapter' later, so no need to pass method option. - persistenceMethod: string; /*'fs', 'localStorage', 'adapter'*/ - verbose: boolean; +declare var LokiOps: { + $eq(a: any, b: any): boolean; + // abstract/loose equality + $aeq(a: any, b: any): boolean; + $ne(a: any, b: any): boolean; + // date equality / loki abstract equality test + $dteq(a: any, b: any): boolean; + $gt(a: any, b: any): boolean; + $gte(a: any, b: any): boolean; + $lt(a: any, b: any): boolean; + $lte(a: any, b: any): boolean; + /** ex : coll.find({'orderCount': {$between: [10, 50]}}); */ + $between(a: any, vals: any/*[any, any]*/): boolean; + $in(a: any, b: any): boolean; + $nin(a: any, b: any): boolean; + $keyin(a: any, b: any): boolean; + $nkeyin(a: any, b: any): boolean; + $definedin(a: any, b: any): boolean; + $undefinedin(a: any, b: any): boolean; + $regex(a: any, b: any): boolean; + $containsString(a: any, b: any): boolean; + $containsNone(a: any, b: any): boolean; + $containsAny(a: any, b: any): boolean; + $contains(a: any, b: any): boolean; + $type(a: any, b: any): boolean; + $finite(a: any, b: any): boolean; + $size(a: any, b: any): boolean; + $len(a: any, b: any): boolean; + $where(a: any, b: any): boolean; + // field-level logical operators + // a is the value in the collection + // b is the nested query operation (for '$not') + // or an array of nested query operations (for '$and' and '$or') + $not(a: any, b: any): boolean; + $and(a: any, b: any): boolean; + $or(a: any, b: any): boolean; +}; +declare type LokiOps = typeof LokiOps; - new (filename: string, options: LokiConfigureOptions): Loki; - - // experimental support for browserify's abstract syntax scan to pick up dependency of indexed adapter. - // Hopefully, once this hits npm a browserify require of lokijs should scan the main file and detect this indexed adapter reference. - getIndexedAdapter(): LokiPersistenceInterface; // require("./loki-indexed-adapter.js") +/** if an op is registered in this object, our 'calculateRange' can use it with our binary indices. + * if the op is registered to a function, we will run that function/op as a 2nd pass filter on results. + * those 2nd pass filter functions should be similar to LokiOps functions, accepting 2 vals to compare. + */ +declare var indexedOps: { + $eq: LokiOps["$eq"], + $aeq: true, + $dteq: true, + $gt: true, + $gte: true, + $lt: true, + $lte: true, + $in: true, + $between: true +}; - /** configureOptions - allows reconfiguring database options - * - * @param {object} options - configuration options to apply to loki db object - * @param {boolean} initialConfig - (optional) if this is a reconfig, don't pass this - */ - configureOptions(options: LokiConfigureOptions, initialConfig?: boolean): void; +type PartialModel = { [P in keyof E]?: T | E[P] }; - /** anonym() - shorthand method for quickly creating and populating an anonymous collection. - * This collection is not referenced internally so upon losing scope it will be garbage collected. - * - * Example : var results = new loki().anonym(myDocArray).find({'age': {'$gt': 30} }); - * - * @param {Array} docs - document array to initialize the anonymous collection with - * @param {Array} indexesArray - (Optional) array of property names to index - * @returns {Collection} New collection which you can query or chain - */ - anonym(docs: T | T[], indexesArray?: LokiCollectionOptions): LokiCollection; +type LokiQuery = PartialModel; - addCollection(name: string, options?: LokiCollectionOptions): LokiCollection; - - loadCollection(collection: LokiCollection): void; - - getCollection(collectionName: string): LokiCollection; - - listCollections(): { name: string; type: string; count: number }[]; - - removeCollection(collectionName: string): void; - - getName(): string; - - /** serializeReplacer - used to prevent certain properties from being serialized - */ - serializeReplacer(key: "autosaveHandle", value: T): T; - serializeReplacer(key: "persistenceAdapter", value: T): T; - serializeReplacer(key: "constraints", value: T): T; - serializeReplacer(key: string, value: T): T; - - // toJson - serialize(): string; - - // alias of serialize - toJson(): string; - - /** loadJSON - inflates a loki database from a serialized JSON string - * - * @param {string} serializedDb - a serialized loki database string - * @param {object} options - apply or override collection level settings - */ - loadJSON(serializedDb: string, options?: { [collectionName: string]: { inflate?: (src: any, dst: any) => void; proto: any; } }): void; - - /** loadJSONObject - inflates a loki database from a JS object - * - * @param {object} dbObject - a serialized loki database string - * @param {object} options - apply or override collection level settings - */ - loadJSONObject(dbObject: Loki, options?: { [collectionName: string]: { inflate?: (src: any, dst: any) => void; proto: any; } }): void; - - /** close(callback) - emits the close event with an optional callback. Does not actually destroy the db - * but useful from an API perspective - */ - close(callback?: (...args: any[]) => void): void; - - /**-------------------------+ - | Changes API | - +--------------------------*/ - - /** The Changes API enables the tracking the changes occurred in the collections since the beginning of the session, - * so it's possible to create a differential dataset for synchronization purposes (possibly to a remote db) - */ - - /** generateChangesNotification() - takes all the changes stored in each - * collection and creates a single array for the entire database. If an array of names - * of collections is passed then only the included collections will be tracked. - * - * @param {array} optional array of collection names. No arg means all collections are processed. - * @returns {array} array of changes - * @see private method createChange() in Collection - */ - generateChangesNotification(arrayOfCollectionNames?: string[]): LokiCollectionChange[]; - - /** serializeChanges() - stringify changes for network transmission - * @returns {string} string representation of the changes - */ - serializeChanges(collectionNamesArray?: string[]): string; - - /** clearChanges() - clears all the changes in all collections. - */ - clearChanges(): void; - - /** loadDatabase - Handles loading from file system, local storage, or adapter (indexeddb) - * This method utilizes loki configuration options (if provided) to determine which - * persistence method to use, or environment detection (if configuration was not provided). - * - * @param {object} options - not currently used (remove or allow overrides?) - * @param {function} callback - (Optional) user supplied async callback / error handler - */ - loadDatabase(options: { [collectionName: string]: { inflate?: (src: any, dst: any) => void; proto: any; } }, callback?: (err: any, data: any) => void): void; - - /** saveDatabase - Handles saving to file system, local storage, or adapter (indexeddb) - * This method utilizes loki configuration options (if provided) to determine which - * persistence method to use, or environment detection (if configuration was not provided). - * - * @param {object} options - not currently used (remove or allow overrides?) - * @param {function} callback - (Optional) user supplied async callback / error handler - */ - saveDatabase(callback?: (err: any) => void): void; - - // alias for saveDatabase - save(callback ?: (err: any) => void): void; - - /** deleteDatabase - Handles deleting a database from file system, local - * storage, or adapter (indexeddb) - * This method utilizes loki configuration options (if provided) to determine which - * persistence method to use, or environment detection (if configuration was not provided). - * - * @param {object} options - not currently used (remove or allow overrides?) - * @param {function} callback - user supplied async callback / error handler - */ - deleteDatabase(options: any, callback: (err: any, data: any) => void): void; - - /** autosaveDirty - check whether any collections are 'dirty' meaning we need to save (entire) database - * @returns {boolean} - true if database has changed since last autosave, false if not. - */ - autosaveDirty(): boolean; - - /** autosaveClearFlags - resets dirty flags on all collections. - * Called from saveDatabase() after db is saved. - */ - autosaveClearFlags(): void; - - /** autosaveEnable - begin a javascript interval to periodically save the database. - * - * @param {object} options - not currently used (remove or allow overrides?) - * @param {function} callback - (Optional) user supplied async callback - */ - autosaveEnable(options?: LokiConfigureOptions, callback?: (err: any) => void): void; - - /** autosaveDisable - stop the autosave interval timer. - */ - autosaveDisable(): void; +interface LokiObj { + $loki: number; + meta: { + created: number; // Date().getTime() + revision: number; + updated: number; // Date().getTime() + version: number; + }; } - /** * LokiEventEmitter is a minimalist version of EventEmitter. It enables any * constructor that inherits EventEmitter to emit events and trigger * listeners that have been added to the event through the on(event, callback) method + * + * @constructor LokiEventEmitter */ -interface LokiEventEmitter { - /** - * @prop Events property is a hashmap, with each property being an array of callbacks - */ - events: { [eventName: string]: ((...args: any[]) => void)[] }; +declare class LokiEventEmitter { - new (): LokiEventEmitter; + /** + * @prop events - a hashmap, with each property being an array of callbacks + */ + public events: { [eventName: string]: ((...args: any[]) => any)[] }; /** * @prop asyncListeners - boolean determines whether or not the callbacks associated with each event * should happen in an async fashion or not * Default is false, which means events are synchronous */ - asyncListeners: boolean; + public asyncListeners: boolean; /** - * @prop on(eventName, listener) - adds a listener to the queue of callbacks associated to an event - * @returns {int} the index of the callback in the array of listeners for a particular event + * on(eventName, listener) - adds a listener to the queue of callbacks associated to an event + * @param eventName - the name(s) of the event(s) to listen to + * @param listener - callback function of listener to attach + * @returns the index of the callback in the array of listeners for a particular event */ - on void>(eventName: string, listener: U): U; + on any>(eventName: string | string[], listener: F): F; /** - * @propt emit(eventName, data) - emits a particular event + * emit(eventName, data) - emits a particular event * with the option of passing optional parameters which are going to be processed by the callback * provided signatures match (i.e. if passing emit(event, arg0, arg1) the listener should take two parameters) - * @param {string} eventName - the name of the event - * @param {object} data - optional object passed with the event + * @param eventName - the name of the event + * @param data - optional object passed with the event */ - emit(eventName: string, data?: any): void; + emit(eventName: string, data?: any, arg?: any): void; /** - * @prop remove() - removes the listener at position 'index' from the event 'eventName' + * Alias of LokiEventEmitter.prototype.on + * addListener(eventName, listener) - adds a listener to the queue of callbacks associated to an event + * @param eventName - the name(s) of the event(s) to listen to + * @param listener - callback function of listener to attach + * @returns the event listener added */ - removeListener(eventName: string, listener: (...args: any[]) => void): void; + public addListener: LokiEventEmitter["on"]; + + /** + * removeListener() - removes the listener at position 'index' from the event 'eventName' + * @param eventName - the name(s) of the event(s) which the listener is attached to + * @param listener - the listener callback function to remove from emitter + */ + public removeListener(eventName: string | string[], listener: (...args: any[]) => any): void; } +interface LokiConstructorOptions { + verbose: boolean; + env: "NATIVESCRIPT" | "NODEJS" | "CORDOVA" | "BROWSER" | "NA"; +} + + +interface LokiConfigOptions { + adapter: LokiPersistenceAdapter | null; + autoload: boolean; + autoloadCallback: (err: any) => void; + autosave: boolean; + autosaveCallback: (err?: any) => void; + autosaveInterval: string | number; + persistenceMethod: "fs" | "localStorage" | "memory" | null; + destructureDelimiter: string; + serializationMethod: "normal" | "pretty" | "destructured" | null; + throttledSaves: boolean; +} + + +type DeserializeOptions = { partitioned?: boolean; delimited: false; delimiter?: string; partition?: number } | { partitioned?: boolean; delimited?: true; delimiter: string; partition?: number }; + + +interface ThrottledSaveDrainOptions { + recursiveWait: boolean; + recursiveWaitLimit: boolean; + recursiveWaitLimitDuration: number; + started: number; +} + + +interface Transform { + type: "find" | "where" | "simplesort" | "compoundsort" | "sort" | "limit" | "offset" | "map" | "eqJoin" | "mapReduce" | "update" | "remove"; + value?: any; + property?: string; + desc?: boolean; + dataOptions?: any; + joinData?: any; + leftJoinKey?: any; + rightJoinKey?: any; + mapFun?: any; + mapFunction?: any; + reduceFunction?: any; +} + + +/** + * Loki: The main database class + * @implements LokiEventEmitter + */ +declare class Loki extends LokiEventEmitter { + collections: Collection[]; + options: Partial & LokiConfigOptions & Partial; + filename: string; + name?: string; + databaseVersion: number; + engineVersion: number; + autosave: boolean; + autosaveInterval: number; + autosaveHandle: number | null; + persistenceAdapter: LokiPersistenceAdapter | null | undefined; + persistenceMethod: "fs" | "localStorage" | "memory" | "adapter" | null | undefined; + throttledCallbacks: ((err?: any) => void)[]; + throttledSavePending: boolean; + throttledSaves: boolean; + verbose: boolean; + ENV: "NATIVESCRIPT" | "NODEJS" | "CORDOVA" | "BROWSER" | "NA"; + + /** + * @param filename - name of the file to be saved to + * @param options - (Optional) config options object + * @param options.env - override environment detection as 'NODEJS', 'BROWSER', 'CORDOVA' + * @param [options.verbose=false] - enable console output + * @param [options.autosave=false] - enables autosave + * @param [options.autosaveInterval=5000] - time interval (in milliseconds) between saves (if dirty) + * @param [options.autoload=false] - enables autoload on loki instantiation + * @param options.autoloadCallback - user callback called after database load + * @param options.adapter - an instance of a loki persistence adapter + * @param [options.serializationMethod='normal'] - ['normal', 'pretty', 'destructured'] + * @param options.destructureDelimiter - string delimiter used for destructured serialization + * @param [options.throttledSaves=true] - debounces multiple calls to to saveDatabase reducing number of disk I/O operations + and guaranteeing proper serialization of the calls. + */ + constructor(filename: string, options?: Partial & Partial & Partial); + + // experimental support for browserify's abstract syntax scan to pick up dependency of indexed adapter. + // Hopefully, once this hits npm a browserify require of lokijs should scan the main file and detect this indexed adapter reference. + public getIndexedAdapter(): any; + + /** + * Allows reconfiguring database options + * + * @param options - configuration options to apply to loki db object + * @param options.env - override environment detection as 'NODEJS', 'BROWSER', 'CORDOVA' + * @param options.verbose - enable console output (default is 'false') + * @param options.autosave - enables autosave + * @param options.autosaveInterval - time interval (in milliseconds) between saves (if dirty) + * @param options.autoload - enables autoload on loki instantiation + * @param options.autoloadCallback - user callback called after database load + * @param options.adapter - an instance of a loki persistence adapter + * @param options.serializationMethod - ['normal', 'pretty', 'destructured'] + * @param options.destructureDelimiter - string delimiter used for destructured serialization + * @param initialConfig - (internal) true is passed when loki ctor is invoking + */ + public configureOptions(options?: Partial & Partial, initialConfig?: boolean): void; + + /** + * Copies 'this' database into a new Loki instance. Object references are shared to make lightweight. + * + * @param options - apply or override collection level settings + * @param options.removeNonSerializable - nulls properties not safe for serialization. + */ + public copy(options?: { removeNonSerializable?: boolean }): Loki; + + /** + * Adds a collection to the database. + * @param name - name of collection to add + * @param options - (optional) options to configure collection with. + * @param [options.unique=[]] - array of property names to define unique constraints for + * @param [options.exact=[]] - array of property names to define exact constraints for + * @param [options.indices=[]] - array property names to define binary indexes for + * @param [options.asyncListeners=false] - whether listeners are called asynchronously + * @param [options.disableChangesApi=true] - set to false to enable Changes Api + * @param [options.autoupdate=false] - use Object.observe to update objects automatically + * @param [options.clone=false] - specify whether inserts and queries clone to/from user + * @param [options.cloneMethod='parse-stringify'] - 'parse-stringify', 'jquery-extend-deep', 'shallow, 'shallow-assign' + * @param options.ttlInterval - time interval for clearing out 'aged' documents; not set by default. + * @returns a reference to the collection which was just added + */ + public addCollection(name: string, options?: Partial>): Collection; + + public loadCollection(collection: Collection): void; + + /** + * Retrieves reference to a collection by name. + * @param collectionName - name of collection to look up + * @returns Reference to collection in database by that name, or null if not found + */ + public getCollection(collectionName: string): Collection; + + /** + * Renames an existing loki collection + * @param oldName - name of collection to rename + * @param newName - new name of collection + * @returns reference to the newly renamed collection + */ + public renameCollection(oldName: string, newName: string): Collection; + + public listCollections(): Collection[]; + + /** + * Removes a collection from the database. + * @param collectionName - name of collection to remove + */ + public removeCollection(collectionName: string): void; + + public getName(): string; + + /** + * serializeReplacer - used to prevent certain properties from being serialized + */ + public serializeReplacer(key: "autosaveHandle" | "persistenceAdapter" | "constraints" | "ttl" | "throttledSavePending" | "throttledCallbacks" | string, value: any): any; + + /** + * Serialize database to a string which can be loaded via {@link Loki#loadJSON} + * + * @returns Stringified representation of the loki database. + */ + public serialize(): string; + public serialize(options: { serializationMethod?: "normal" | "pretty" }): string; + public serialize(options: { serializationMethod: "destructured" }): string[]; + public serialize(options?: { serializationMethod?: string | null }): string | string[]; + public serialize(options?: { serializationMethod?: string | null }): string | string[]; + + // alias of serialize + public toJson: Loki["serialize"]; + + /** + * Database level destructured JSON serialization routine to allow alternate serialization methods. + * Internally, Loki supports destructuring via loki "serializationMethod' option and + * the optional LokiPartitioningAdapter class. It is also available if you wish to do + * your own structured persistence or data exchange. + * + * @param options - output format options for use externally to loki + * @param options.partitioned - (default: false) whether db and each collection are separate + * @param options.partition - can be used to only output an individual collection or db (-1) + * @param options.delimited - (default: true) whether subitems are delimited or subarrays + * @param options.delimiter - override default delimiter + * + * @returns A custom, restructured aggregation of independent serializations. + */ + public serializeDestructured(options?: { delimited?: boolean; delimiter?: string; partitioned?: boolean; partition?: number; }): string | string[]; + + /** + * Collection level utility method to serialize a collection in a 'destructured' format + * + * @param [options] - used to determine output of method + * @param [options.delimited] - whether to return single delimited string or an array + * @param [options.delimiter] - (optional) if delimited, this is delimiter to use + * @param [options.collectionIndex] - specify which collection to serialize data for + * + * @returns A custom, restructured aggregation of independent serializations for a single collection. + */ + public serializeCollection(options?: { delimited?: boolean; collectionIndex?: number; delimiter?: string }): string | string[]; + + /** + * Database level destructured JSON deserialization routine to minimize memory overhead. + * Internally, Loki supports destructuring via loki "serializationMethod' option and + * the optional LokiPartitioningAdapter class. It is also available if you wish to do + * your own structured persistence or data exchange. + * + * @param destructuredSource - destructured json or array to deserialize from + * @param [options] - source format options + * @param [options.partitioned=false] - whether db and each collection are separate + * @param [options.partition] - can be used to deserialize only a single partition + * @param [options.delimited=true] - whether subitems are delimited or subarrays + * @param [options.delimiter] - override default delimiter + * + * @returns An object representation of the deserialized database, not yet applied to 'this' db or document array + */ + public deserializeDestructured(destructuredSource: string | string[] | null, options?: DeserializeOptions): any; + + /** + * Collection level utility function to deserializes a destructured collection. + * + * @param destructuredSource - destructured representation of collection to inflate + * @param [options] - used to describe format of destructuredSource input + * @param [options.delimited=false] - whether source is delimited string or an array + * @param [options.delimiter] - if delimited, this is delimiter to use (if other than default) + * + * @returns an array of documents to attach to collection.data. + */ + public deserializeCollection(destructuredSource: string | string[], options?: { partitioned?: boolean; delimited?: boolean; delimiter?: string; }): any[]; + + /** + * Inflates a loki database from a serialized JSON string + * + * @param serializedDb - a serialized loki database string + * @param [options] - apply or override collection level settings + * @param [options.serializationMethod] - the serialization format to deserialize + */ + public loadJSON(serializedDb: string, options?: { serializationMethod?: "normal" | "pretty" | "destructured" | null } & { retainDirtyFlags?: boolean; throttledSaves?: boolean;[collName: string]: any | { proto?: any; inflate?: (src: object, dest?: object) => void } }): void; + + /** + * Inflates a loki database from a JS object + * + * @param dbObject - a serialized loki database string + * @param options - apply or override collection level settings + * @param options.retainDirtyFlags - whether collection dirty flags will be preserved + */ + public loadJSONObject(dbObject: { name?: string; throttledSaves: boolean; collections: Collection[]; databaseVersion: number }, + options?: { retainDirtyFlags?: boolean; throttledSaves?: boolean;[collName: string]: any | { proto?: any; inflate?: (src: object, dest?: object) => void } }): void; + + /** + * Emits the close event. In autosave scenarios, if the database is dirty, this will save and disable timer. + * Does not actually destroy the db. + * + * @param callback - (Optional) if supplied will be registered with close event before emitting. + */ + public close(callback?: (err?: any) => void): void; + + /**-------------------------+ + | Changes API | + +--------------------------*/ + + /** + * The Changes API enables the tracking the changes occurred in the collections since the beginning of the session, + * so it's possible to create a differential dataset for synchronization purposes (possibly to a remote db) + */ + + /** + * (Changes API) : takes all the changes stored in each + * collection and creates a single array for the entire database. If an array of names + * of collections is passed then only the included collections will be tracked. + * + * @param optional array of collection names. No arg means all collections are processed. + * @returns array of changes + * @see private method createChange() in Collection + */ + public generateChangesNotification(arrayOfCollectionNames?: string[] | null): CollectionChange[]; + + /** + * (Changes API) - stringify changes for network transmission + * @returns string representation of the changes + */ + public serializeChanges(collectionNamesArray?: string[]): string; + + /** + * (Changes API) : clears all the changes in all collections. + */ + public clearChanges(): void; + + /** + * Wait for throttledSaves to complete and invoke your callback when drained or duration is met. + * + * @param callback - callback to fire when save queue is drained, it is passed a sucess parameter value + * @param [options] - configuration options + * @param [options.recursiveWait] - (default: true) if after queue is drained, another save was kicked off, wait for it + * @param [options.recursiveWaitLimit] - (default: false) limit our recursive waiting to a duration + * @param [options.recursiveWaitLimitDelay] - (default: 2000) cutoff in ms to stop recursively re-draining + */ + public throttledSaveDrain(callback: (result?: boolean) => void, options?: Partial): void; + + /** + * Internal load logic, decoupled from throttling/contention logic + * + * @param [options] - not currently used (remove or allow overrides?) + * @param [callback] - (Optional) user supplied async callback / error handler + */ + public loadDatabaseInternal(options?: any, callback?: (err?: any, data?: any) => void): void; + + /** + * Handles manually loading from file system, local storage, or adapter (such as indexeddb) + * This method utilizes loki configuration options (if provided) to determine which + * persistence method to use, or environment detection (if configuration was not provided). + * To avoid contention with any throttledSaves, we will drain the save queue first. + * + * If you are configured with autosave, you do not need to call this method yourself. + * + * @param [options] - if throttling saves and loads, this controls how we drain save queue before loading + * @param [options.recursiveWait] - (default: true) wait recursively until no saves are queued + * @param [options.recursiveWaitLimit] - (default: false) limit our recursive waiting to a duration + * @param [options.recursiveWaitLimitDelay] - (default: 2000) cutoff in ms to stop recursively re-draining + * @param [callback] - (Optional) user supplied async callback / error handler + * @example + * db.loadDatabase({}, function(err) { + * if (err) { + * console.log("error : " + err); + * } + * else { + * console.log("database loaded."); + * } + * }); + */ + public loadDatabase(options?: Partial, callback?: (err: any) => void): void; + + /** + * Internal save logic, decoupled from save throttling logic + */ + public saveDatabaseInternal(callback?: (err: any) => void): void; + + /** + * Handles manually saving to file system, local storage, or adapter (such as indexeddb) + * This method utilizes loki configuration options (if provided) to determine which + * persistence method to use, or environment detection (if configuration was not provided). + * + * If you are configured with autosave, you do not need to call this method yourself. + * + * @param [callback] - (Optional) user supplied async callback / error handler + * @example + * db.saveDatabase(function(err) { + * if (err) { + * console.log("error : " + err); + * } + * else { + * console.log("database saved."); + * } + * }); + */ + public saveDatabase(callback?: (err?: any) => void): void; + + // alias + public save: Loki["saveDatabase"]; + + /** + * Handles deleting a database from file system, local + * storage, or adapter (indexeddb) + * This method utilizes loki configuration options (if provided) to determine which + * persistence method to use, or environment detection (if configuration was not provided). + * + * @param callback - (Optional) user supplied async callback / error handler + */ + public deleteDatabase(callback: (err?: any, data?: any) => void): void; + public deleteDatabase(options?: null, callback?: (err?: any, data?: any) => void): void; + public deleteDatabase(options?: ((err?: any, data?: any) => void) | null, callback?: (err?: any, data?: any) => void): void; + + /** + * autosaveDirty - check whether any collections are 'dirty' meaning we need to save (entire) database + * + * @returns true if database has changed since last autosave, false if not. + */ + public autosaveDirty(): boolean; + + /** + * autosaveClearFlags - resets dirty flags on all collections. + * Called from saveDatabase() after db is saved. + * + */ + public autosaveClearFlags(): void; + + /** + * autosaveEnable - begin a javascript interval to periodically save the database. + * + * @param [options] - not currently used (remove or allow overrides?) + * @param [callback] - (Optional) user supplied async callback + */ + public autosaveEnable(options?: any, callback?: (err?: any) => void): void; + + /** + * autosaveDisable - stop the autosave interval timer. + */ + public autosaveDisable(): void; +} + + /*------------------+ | PERSISTENCE | -------------------*/ /** there are two build in persistence adapters for internal use - * fs for use in Nodejs type environments - * localStorage for use in browser environment - * defined as helper classes here so its easy and clean to use - */ + * fs for use in Nodejs type environments + * localStorage for use in browser environment + * defined as helper classes here so its easy and clean to use + */ -interface LokiPersistenceInterface { - loadDatabase(dbname: string, callback: (dataOrErr: string | Error) => void): void; - saveDatabase(dbname: string, dbstring: string, callback: (resOrErr: void | Error) => void): void; - deleteDatabase(dbname: string, callback?: (resOrErr: void | Error) => void): void; - // optional - mode?: string; // 'reference' - // filename may seem redundant but loadDatabase will need to expect this same filename - exportDatabase?(filename: string, param: any, callback?: (err: any) => void): void; +interface LokiPersistenceAdapter { + mode?: string; + loadDatabase(dbname: string, callback: (value: any) => void): void; + deleteDatabase?(dbnameOrOptions: any, callback: (err?: Error | null, data?: any) => void): void; + exportDatabase?(dbname: string, dbref: Loki, callback: (err: Error | null) => void): void; + saveDatabase?(dbname: string, dbstring: any, callback: (err?: Error | null) => void): void; } -/** constructor for fs +/** + * In in-memory persistence adapter for an in-memory database. + * This simple 'key/value' adapter is intended for unit testing and diagnostics. + * + * @param [options] - memory adapter options + * @param [options.asyncResponses=false] - whether callbacks are invoked asynchronously + * @param [options.asyncTimeout=50] - timeout in ms to queue callbacks + * @constructor LokiMemoryAdapter */ -interface LokiFsAdapter extends LokiPersistenceInterface { - fs: any; //require('fs'); +declare class LokiMemoryAdapter implements LokiPersistenceAdapter { + hashStore: { [name: string]: { savecount: number; lastsave: Date; value: string } }; + options: { asyncResponses?: boolean; asyncTimeout?: number }; - /** loadDatabase() - Load data from file, will throw an error if the file does not exist - * @param {string} dbname - the filename of the database to load - * @param {function} callback - the callback to handle the result + constructor(options?: { asyncResponses?: boolean; asyncTimeout?: number }); + + /** + * Loads a serialized database from its in-memory store. + * (Loki persistence adapter interface function) + * + * @param dbname - name of the database (filename/keyname) + * @param callback - adapter callback to return load result to caller */ - loadDatabase(dbname: string, callback: (err: Error, data: string) => void): void; + public loadDatabase(dbname: string, callback: (value: any) => void): void; - /** saveDatabase() - save data to file, will throw an error if the file can't be saved + /** + * Saves a serialized database to its in-memory store. + * (Loki persistence adapter interface function) + * + * @param dbname - name of the database (filename/keyname) + * @param callback - adapter callback to return load result to caller + */ + public saveDatabase(dbname: string, dbstring: any, callback: (err?: Error | null) => void): void; + + /** + * Deletes a database from its in-memory store. + * + * @param dbname - name of the database (filename/keyname) + * @param callback - function to call when done + */ + public deleteDatabase(dbname: string, callback: (err?: Error | null) => void): void; +} + + + +interface PageIterator { + collection: number; + pageIndex: number; + docIndex: number; +} + + +/** + * An adapter for adapters. Converts a non reference mode adapter into a reference mode adapter + * which can perform destructuring and partioning. Each collection will be stored in its own key/save and + * only dirty collections will be saved. If you turn on paging with default page size of 25megs and save + * a 75 meg collection it should use up roughly 3 save slots (key/value pairs sent to inner adapter). + * A dirty collection that spans three pages will save all three pages again + * Paging mode was added mainly because Chrome has issues saving 'too large' of a string within a + * single indexeddb row. If a single document update causes the collection to be flagged as dirty, all + * of that collection's pages will be written on next save. + * + * @param adapter - reference to a 'non-reference' mode loki adapter instance. + * @param options - configuration options for partitioning and paging + * @param [options.paging] - (default: false) set to true to enable paging collection data. + * @param [options.pageSize] - (default : 25MB) you can use this to limit size of strings passed to inner adapter. + * @param [options.delimiter] - allows you to override the default delimeter + * @constructor LokiPartitioningAdapter + */ +declare class LokiPartitioningAdapter implements LokiPersistenceAdapter { + mode: string; + dbref: Loki | null; + dbname: string + adapter: LokiPersistenceAdapter | null; + options: { paging?: boolean; pageSize?: number; delimiter?: string }; + pageIterator: PageIterator | {}; + dirtyPartitions: number[] | undefined; + + constructor(adapter: LokiPersistenceAdapter, options?: { paging?: boolean; pageSize?: number; delimiter?: string }); + + /** + * Loads a database which was partitioned into several key/value saves. + * (Loki persistence adapter interface function) + * + * @param dbname - name of the database (filename/keyname) + * @param callback - adapter callback to return load result to caller + */ + public loadDatabase(dbname: string, callback: (dbOrErr: Loki | null | Error) => void): void; + + /** + * Used to sequentially load each collection partition, one at a time. + * + * @param partition - ordinal collection position to load next + * @param callback - adapter callback to return load result to caller + */ + public loadNextPartition(partition: number, callback: () => void): void; + + /** + * Used to sequentially load the next page of collection partition, one at a time. + * + * @param callback - adapter callback to return load result to caller + */ + public loadNextPage(callback: () => void): void; + + /** + * Saves a database by partioning into separate key/value saves. + * (Loki 'reference mode' persistence adapter interface function) + * + * @param dbname - name of the database (filename/keyname) + * @param dbref - reference to database which we will partition and save. + * @param callback - adapter callback to return load result to caller + */ + public exportDatabase(dbname: string, dbref: Loki, callback: (err: Error | null) => void): void; + + /** + * Helper method used internally to save each dirty collection, one at a time. + * + * @param callback - adapter callback to return load result to caller + */ + public saveNextPartition(callback: (err: Error | null) => void): void; + + /** + * Helper method used internally to generate and save the next page of the current (dirty) partition. + * + * @param callback - adapter callback to return load result to caller + */ + public saveNextPage(callback: (err: Error | null) => void): void; +} + + + +/** + * A loki persistence adapter which persists using node fs module + * @constructor LokiFsAdapter + */ +declare class LokiFsAdapter implements LokiPersistenceAdapter { + + constructor(); + + /** + * loadDatabase() - Load data from file, will throw an error if the file does not exist + * @param dbname - the filename of the database to load + * @param callback - the callback to handle the result + */ + public loadDatabase(dbname: string, callback: (data: any | Error) => void): void; + + /** + * saveDatabase() - save data to file, will throw an error if the file can't be saved * might want to expand this to avoid dataloss on partial save - * @param {string} dbname - the filename of the database to load - * @param {function} callback - the callback to handle the result + * @param dbname - the filename of the database to load + * @param callback - the callback to handle the result */ - saveDatabase(dbname: string, dbstring: string, callback: (err: any) => void): void; + public saveDatabase(dbname: string, dbstring: string | Uint8Array, callback: (err?: Error | null) => void): void; - /** deleteDatabase() - delete the database file, will throw an error if the + /** + * deleteDatabase() - delete the database file, will throw an error if the * file can't be deleted - * @param {string} dbname - the filename of the database to delete - * @param {function} callback - the callback to handle the result + * @param dbname - the filename of the database to delete + * @param callback - the callback to handle the result */ - deleteDatabase(dbname: string, callback: (resOrErr: void | Error) => void): void; + public deleteDatabase(dbname: string, callback: (err?: Error | null) => void): void; } -/** constructor for local storage + +/** + * A loki persistence adapter which persists to web browser's local storage object + * @constructor LokiLocalStorageAdapter */ -interface LokiLocalStorageAdapter extends LokiPersistenceInterface { +declare class LokiLocalStorageAdapter { - /** loadDatabase() - Load data from localstorage - * @param {string} dbname - the name of the database to load - * @param {function} callback - the callback to handle the result + /** + * loadDatabase() - Load data from localstorage + * @param dbname - the name of the database to load + * @param callback - the callback to handle the result */ - loadDatabase(dbname: string, callback: (dataOrErr: string | Error) => void): void; + public loadDatabase(dbname: string, callback: (dataOrError: any | Error) => void): void; - /** saveDatabase() - save data to localstorage, will throw an error if the file can't be saved + /** + * saveDatabase() - save data to localstorage, will throw an error if the file can't be saved * might want to expand this to avoid dataloss on partial save - * @param {string} dbname - the filename of the database to load - * @param {function} callback - the callback to handle the result + * @param dbname - the filename of the database to load + * @param callback - the callback to handle the result */ - saveDatabase(dbname: string, dbstring: string, callback: (resOrErr: void | Error) => void): void; + public saveDatabase(dbname: string, dbstring: string, callback: (err?: Error | null) => void): void; - /** deleteDatabase() - delete the database from localstorage, will throw an error if it + /** + * deleteDatabase() - delete the database from localstorage, will throw an error if it * can't be deleted - * @param {string} dbname - the filename of the database to delete - * @param {function} callback - the callback to handle the result + * @param dbname - the filename of the database to delete + * @param callback - the callback to handle the result */ - deleteDatabase(dbname: string, callback: (resOrErr: void | Error) => void): void; + public deleteDatabase(dbname: string, callback: (err?: Error | null) => void): void; } +interface GetDataOptions { + forceClones: boolean; + forceCloneMethod: ("parse-stringify" | "jquery-extend-deep" | "shallow" | "shallow-assign" | "shallow-recurse-objects") | null; + removeMeta: boolean; +} -/** Resultset class allowing chainable queries. Intended to be instanced internally. + +/** + * Resultset class allowing chainable queries. Intended to be instanced internally. * Collection.find(), Collection.where(), and Collection.chain() instantiate this. * - * Example: + * @example * mycollection.chain() * .find({ 'doors' : 4 }) * .where(function(obj) { return obj.name === 'Toyota' }) * .data(); */ -interface LokiResultset { - // retain reference to collection we are querying against - collection: LokiCollection; +declare class Resultset { + collection: Collection; + filteredrows: number[]; filterInitialized: boolean; - filteredrows: string[]; // technically number[] (e.g. = Object.keys(this.collection.data)) - options: LokiResultsetOptions; - searchIsChained: boolean; - /** - * @constructor - * @param {Collection} collection - The collection which this Resultset will query against. - * @param {Object} options - Object containing one or more options. - * @param {string} options.queryObj - Optional mongo-style query object to initialize resultset with. - * @param {function} options.queryFunc - Optional javascript filter function to initialize resultset with. - * @param {bool} options.firstOnly - Optional boolean used by collection.findOne(). + * @param collection - The collection which this Resultset will query against. + * @param options */ - new (collection: LokiCollection, options: LokiResultsetOptions): LokiResultset | E[]; + constructor(collection: Collection, options?: any); - /** reset() - Reset the resultset to its initial state. + /** + * reset() - Reset the resultset to its initial state. * - * @returns {Resultset} Reference to this resultset, for future chain operations. + * @returns Reference to this resultset, for future chain operations. */ - reset(): LokiResultset; + public reset(): this; - /** toJSON() - Override of toJSON to avoid circular references + /** + * toJSON() - Override of toJSON to avoid circular references */ - toJSON(): LokiResultset; + public toJSON(): Resultset; - /** limit() - Allows you to limit the number of documents passed to next chain operation. + /** + * Allows you to limit the number of documents passed to next chain operation. * A resultset copy() is made to avoid altering original resultset. * - * @param {int} qty - The number of documents to return. - * @returns {Resultset} Returns a copy of the resultset, limited by qty, for subsequent chain ops. + * @param qty - The number of documents to return. + * @returns Returns a copy of the resultset, limited by qty, for subsequent chain ops. */ - limit(qty: number): LokiResultset; + public limit(qty: number): Resultset; - /** offset() - Used for skipping 'pos' number of documents in the resultset. + /** + * Used for skipping 'pos' number of documents in the resultset. * - * @param {int} pos - Number of documents to skip; all preceding documents are filtered out. - * @returns {Resultset} Returns a copy of the resultset, containing docs starting at 'pos' for subsequent chain ops. + * @param pos - Number of documents to skip; all preceding documents are filtered out. + * @returns Returns a copy of the resultset, containing docs starting at 'pos' for subsequent chain ops. */ - offset(pos: number): LokiResultset; + public offset(pos: number): Resultset; - /** copy() - To support reuse of resultset in branched query situations. + /** + * copy() - To support reuse of resultset in branched query situations. * - * @returns {Resultset} Returns a copy of the resultset (set) but the underlying document references will be the same. + * @returns Returns a copy of the resultset (set) but the underlying document references will be the same. */ - copy(): LokiResultset; - // alias of copy() - branch(): LokiResultset; + public copy(): Resultset; + + /** + * Alias of copy() + */ + public branch: Resultset["copy"]; /** * transform() - executes a named collection transform or raw array of transform steps against the resultset. * - * @param transform {string|array} : (Optional) name of collection transform or raw transform array - * @param parameters {object} : (Optional) object property hash of parameters, if the transform requires them. - * @returns {Resultset} : either (this) resultset or a clone of of this resultset (depending on steps) + * @param transform - name of collection transform or raw transform array + * @param parameters - (Optional) object property hash of parameters, if the transform requires them. + * @returns either (this) resultset or a clone of of this resultset (depending on steps) */ - transform(transform?: string | any[], parameters?: any): LokiResultset; + public transform(transform: string | string[] | Transform[], parameters?: object): Resultset; - /** sort() - User supplied compare function is provided two documents to compare. (chainable) - * Example: + /** + * User supplied compare function is provided two documents to compare. (chainable) + * @example * rslt.sort(function(obj1, obj2) { * if (obj1.name === obj2.name) return 0; * if (obj1.name > obj2.name) return 1; * if (obj1.name < obj2.name) return -1; * }); * - * @param {function} comparefun - A javascript compare function used for sorting. - * @returns {Resultset} Reference to this resultset, sorted, for future chain operations. + * @param comparefun - A javascript compare function used for sorting. + * @returns Reference to this resultset, sorted, for future chain operations. */ - sort(comparefun: (a: E, b: E) => number): LokiResultset; + public sort(comparefun: (a: E & LokiObj, b: E & LokiObj) => number): this; - /** simplesort() - Simpler, loose evaluation for user to sort based on a property name. (chainable) + /** + * Simpler, loose evaluation for user to sort based on a property name. (chainable). + * Sorting based on the same lt/gt helper functions used for binary indices. * - * @param {string} propname - name of property to sort by. - * @param {bool} isdesc - (Optional) If true, the property will be sorted in descending order - * @returns {Resultset} Reference to this resultset, sorted, for future chain operations. + * @param propname - name of property to sort by. + * @param isdesc - (Optional) If true, the property will be sorted in descending order + * @returns Reference to this resultset, sorted, for future chain operations. */ - simplesort(propname: string, isdesc?: boolean): LokiResultset; + public simplesort(propname: keyof E, isdesc?: boolean): this; - /** compoundsort() - Allows sorting a resultset based on multiple columns. - * Example : rs.compoundsort(['age', 'name']); to sort by age and then name (both ascending) - * Example : rs.compoundsort(['age', ['name', true]); to sort by age (ascending) and then by name (descending) + /** + * Allows sorting a resultset based on multiple columns. + * @example + * // to sort by age and then name (both ascending) + * rs.compoundsort(['age', 'name']); + * // to sort by age (ascending) and then by name (descending) + * rs.compoundsort(['age', ['name', true]); * - * @param {array} properties - array of property names or subarray of [propertyname, isdesc] used evaluate sort order - * @returns {Resultset} Reference to this resultset, sorted, for future chain operations. + * @param properties - array of property names or subarray of [propertyname, isdesc] used evaluate sort order + * @returns Reference to this resultset, sorted, for future chain operations. */ - compoundsort(properties: ([string, boolean] | [string])[]): LokiResultset; + public compoundsort(properties: [keyof E, boolean][]): this; - /** calculateRange() - Binary Search utility method to find range/segment of values matching criteria. - * this is used for collection.find() and first find filter of resultset/dynview - * slightly different than get() binary search in that get() hones in on 1 value, - * but we have to hone in on many (range) - * @param {string} op - operation, such as $eq - * @param {string} prop - name of property to calculate range for - * @param {object} val - value to use for range calculation. - * @returns {array} [start, end] index array positions - */ - calculateRange(op: "$eq", prop: string, val: any): [number/*start*/, number/*end*/]; - calculateRange(op: "$dteq", prop: string, val: any): [number/*start*/, number/*end*/]; - calculateRange(op: "$gt", prop: string, val: any): [number/*start*/, number/*end*/]; - calculateRange(op: "$gte", prop: string, val: any): [number/*start*/, number/*end*/]; - calculateRange(op: "$lt", prop: string, val: any): [number/*start*/, number/*end*/]; - calculateRange(op: "$lte", prop: string, val: any): [number/*start*/, number/*end*/]; - calculateRange(op: string, prop: string, val: any): [number/*start*/, number/*end*/]; - - /** findOr() - oversee the operation of OR'ed query expressions. + /** + * findOr() - oversee the operation of OR'ed query expressions. * OR'ed expression evaluation runs each expression individually against the full collection, * and finally does a set OR on each expression's results. * Each evaluation can utilize a binary index to prevent multiple linear array scans. * - * @param {array} expressionArray - array of expressions - * @returns {Resultset} this resultset for further chain ops. + * @param expressionArray - array of expressions + * @returns this resultset for further chain ops. */ - findOr(expressionArray: LokiQuery[]): LokiResultset; - $or(expressionArray: LokiQuery[]): LokiResultset; + public findOr(expressionArray: LokiQuery[]): this; - /** findAnd() - oversee the operation of AND'ed query expressions. + public $or: Resultset["findOr"]; + + /** + * findAnd() - oversee the operation of AND'ed query expressions. * AND'ed expression evaluation runs each expression progressively against the full collection, * internally utilizing existing chained resultset functionality. * Only the first filter can utilize a binary index. * - * @param {array} expressionArray - array of expressions - * @returns {Resultset} this resultset for further chain ops. + * @param expressionArray - array of expressions + * @returns this resultset for further chain ops. */ - findAnd(expressionArray: LokiQuery[]): LokiResultset; - $and(expressionArray: LokiQuery[]): LokiResultset; + public findAnd(expressionArray: LokiQuery[]): this; - /** find() - Used for querying via a mongo-style query object. + public $and: Resultset["findAnd"]; + + /** + * Used for querying via a mongo-style query object. * - * @param {object} query - A mongo-style query object used for filtering current results. - * @param {boolean} firstOnly - (Optional) Used by collection.findOne() - * @returns {Resultset} this resultset for further chain ops. + * @param query - A mongo-style query object used for filtering current results. + * @param firstOnly - (Optional) Used by collection.findOne() + * @returns this resultset for further chain ops. */ - //find(query: LokiQuery, firstOnly: boolean): E; - //find(query?: any, firstOnly?: boolean): E[]; - find(query: LokiQuery, firstOnly?: boolean): LokiResultset; + public find(query?: LokiQuery, firstOnly?: boolean): this; - /** where() - Used for filtering via a javascript filter function. + /** + * where() - Used for filtering via a javascript filter function. * - * @param {function} fun - A javascript function used for filtering current results by. - * @returns {Resultset} this resultset for further chain ops. + * @param fun - A javascript function used for filtering current results by. + * @returns this resultset for further chain ops. */ - where(fun: (obj: E) => boolean): LokiResultset; + public where(fun: (data: E & LokiObj) => boolean): this; - /** count() - returns the number of documents in the resultset. + /** + * count() - returns the number of documents in the resultset. * - * @returns {number} The number of documents in the resultset. + * @returns The number of documents in the resultset. */ - count(): number; + public count(): number; - /** data() - Terminates the chain and returns array of filtered documents + /** + * Terminates the chain and returns array of filtered documents * - * @param options {object} : allows specifying 'forceClones' and 'forceCloneMethod' options. - * options : - * forceClones {boolean} : Allows forcing the return of cloned objects even when + * @param [options] - allows specifying 'forceClones' and 'forceCloneMethod' options. + * @param [options.forceClones] - Allows forcing the return of cloned objects even when * the collection is not configured for clone object. - * forceCloneMethod {string} : Allows overriding the default or collection specified cloning method. - * Possible values include 'parse-stringify', 'jquery-extend-deep', and 'shallow' + * @param [options.forceCloneMethod] - Allows overriding the default or collection specified cloning method. + * Possible values include 'parse-stringify', 'jquery-extend-deep', 'shallow', 'shallow-assign' + * @param [options.removeMeta] - Will force clones and strip $loki and meta properties from documents * - * @returns {array} Array of documents in the resultset + * @returns Array of documents in the resultset */ - data(options?: { forceClones?: string; forceCloneMethod?: string; }): E[]; + public data(options?: Partial): (E & LokiObj)[]; - /** update() - used to run an update operation on all documents currently in the resultset. + /** + * Used to run an update operation on all documents currently in the resultset. * - * @param {function} updateFunction - User supplied updateFunction(obj) will be executed for each document object. - * @returns {Resultset} this resultset for further chain ops. + * @param updateFunction - User supplied updateFunction(obj) will be executed for each document object. + * @returns this resultset for further chain ops. */ - update(updateFunction: (obj: E) => void): LokiResultset; + public update(updateFunction: (obj: E) => void): this; - /** remove() - removes all document objects which are currently in resultset from collection (as well as resultset) + /** + * Removes all document objects which are currently in resultset from collection (as well as resultset) * - * @returns {Resultset} this (empty) resultset for further chain ops. + * @returns this (empty) resultset for further chain ops. */ - remove(): LokiResultset; + public remove(): this; - /** mapReduce() - data transformation via user supplied functions + /** + * data transformation via user supplied functions * - * @param {function} mapFunction - this function accepts a single document for you to transform and return - * @param {function} reduceFunction - this function accepts many (array of map outputs) and returns single value + * @param mapFunction - this function accepts a single document for you to transform and return + * @param reduceFunction - this function accepts many (array of map outputs) and returns single value * @returns The output of your reduceFunction */ - mapReduce(mapFunction: (value: E, index: number, array: E[]) => T, reduceFunction: (array: T[]) => U): U; + public mapReduce(mapFunction: (value: E, index: number, array: E[]) => U, reduceFunction: (ary: U[]) => R): R; - /** eqJoin() - Left joining two sets of data. Join keys can be defined or calculated properties + /** + * eqJoin() - Left joining two sets of data. Join keys can be defined or calculated properties * eqJoin expects the right join key values to be unique. Otherwise left data will be joined on the last joinData object with that key - * @param {Array} joinData - Data array to join to. - * @param {String,function} leftJoinKey - Property name in this result set to join on or a function to produce a value to join on - * @param {String,function} rightJoinKey - Property name in the joinData to join on or a function to produce a value to join on - * @param {function} (optional) mapFun - A function that receives each matching pair and maps them into output objects - function(left,right){return joinedObject} - * @returns {Resultset} A resultset with data in the format [{left: leftObj, right: rightObj}] + * @param joinData - Data array to join to. + * @param leftJoinKey - Property name in this result set to join on or a function to produce a value to join on + * @param rightJoinKey - Property name in the joinData to join on or a function to produce a value to join on + * @param [mapFun] - (Optional) A function that receives each matching pair and maps them into output objects - function(left,right){return joinedObject} + * @param [dataOptions] - options to data() before input to your map function + * @param [dataOptions.removeMeta] - allows removing meta before calling mapFun + * @param [dataOptions.forceClones] - forcing the return of cloned objects to your map object + * @param [dataOptions.forceCloneMethod] - Allows overriding the default or collection specified cloning method. + * @returns A resultset with data in the format [{left: leftObj, right: rightObj}] */ - eqJoin(joinData: T[] | LokiResultset, leftJoinKey: string | ((obj: E) => string), rightJoinKey: string | ((obj: T) => string)): LokiResultset<{ left: E; right: T; }>; - eqJoin(joinData: T[] | LokiResultset, leftJoinKey: string | ((obj: E) => string), rightJoinKey: string | ((obj: T) => string), mapFun?: (a: E, b: T) => U): LokiResultset; + public eqJoin( + joinData: Collection | Resultset | any[], + leftJoinKey: string | ((obj: any) => string), + rightJoinKey: string | ((obj: any) => string), + mapFun?: (left: any, right: any) => any, + dataOptions?: Partial + ): Resultset; - map(mapFun: (currentValue: E, index: number, array: E[]) => T): LokiResultset; + /** + * Applies a map function into a new collection for further chaining. + * @param mapFun - javascript map function + * @param [dataOptions] - options to data() before input to your map function + * @param [dataOptions.removeMeta] - allows removing meta before calling mapFun + * @param [dataOptions.forceClones] - forcing the return of cloned objects to your map object + * @param [dataOptions.forceCloneMethod] - Allows overriding the default or collection specified cloning method. + */ + public map(mapFun: (value: E, index: number, array: E[]) => U, dataOptions?: Partial): Resultset; } +interface DynamicViewOptions { + persistent: boolean; + sortPriority: "active" | "passive"; + minRebuildInterval: number; +} -/** DynamicView class is a versatile 'live' view class which can have filters and sorts applied. + +/** + * DynamicView class is a versatile 'live' view class which can have filters and sorts applied. * Collection.addDynamicView(name) instantiates this DynamicView object and notifies it * whenever documents are add/updated/removed so it can remain up-to-date. (chainable) * - * Examples: - * var mydv = mycollection.addDynamicView('test'); // default is non-persistent - * mydv.applyWhere(function(obj) { return obj.name === 'Toyota'; }); - * mydv.applyFind({ 'doors' : 4 }); - * var results = mydv.data(); + * @example + * var mydv = mycollection.addDynamicView('test'); // default is non-persistent + * mydv.applyFind({ 'doors' : 4 }); + * mydv.applyWhere(function(obj) { return obj.name === 'Toyota'; }); + * var results = mydv.data(); * + * @implements LokiEventEmitter */ -interface LokiDynamicView extends LokiEventEmitter { - cachedresultset: LokiResultset; - collection: LokiCollection; - events: { [id: string]: ((...args: any[]) => void)[] }; /*{ - 'rebuild': ((...args) => void)[]; - };*/ - // keep ordered filter pipeline - filterPipeline: LokiFilter[]; - minRebuildInterval: number; +declare class DynamicView extends LokiEventEmitter { name: string; - options: LokiDynamicViewOptions; - persistent: boolean; + collection: Collection; rebuildPending: boolean; - resultset: LokiResultset; - resultdata: E[]; + resultset: Resultset; + resultdata: (E & LokiObj)[]; resultsdirty: boolean; - // sorting member variables, we only support one active search, applied using applySort() or applySimpleSort() - sortFunction: (a: E, b: E) => number; - sortCriteria: ([string, boolean] | [string])[]; + cachedresultset: Resultset | null; + filterPipeline: { type: "find" | "where", val: any; uid?: string | number }[]; + sortFunction: ((a: E & LokiObj, b: E & LokiObj) => number) | null; + sortCriteria: [keyof E, boolean][] | null; sortDirty: boolean; - sortPriority: string; // 'persistentSortPriority', 'passive' (will defer the sort phase until they call data(). most efficient overall), 'active' (will sort async whenever next idle. prioritizes read speeds) + options: Partial; /** - * @constructor - * @param {Collection} collection - A reference to the collection to work against - * @param {string} name - The name of this dynamic view - * @param {object} options - (Optional) Pass in object with 'persistent' and/or 'sortPriority' options. + * @param collection - A reference to the collection to work against + * @param name - The name of this dynamic view + * @param [options] - (Optional) Pass in object with 'persistent' and/or 'sortPriority' options. + * @param [options.persistent=false] - indicates if view is to main internal results array in 'resultdata' + * @param [options.sortPriority='passive'] - 'passive' (sorts performed on call to data) or 'active' (after updates) + * @param [options.minRebuildInterval] - minimum rebuild interval (need clarification to docs here) + * @see {@link Collection#addDynamicView} to construct instances of DynamicView */ - new (collection: LokiCollection, name: string, options?: LokiDynamicViewOptions): LokiDynamicView; + constructor(collection: Collection, name: string, options?: Partial); - /** rematerialize() - intended for use immediately after deserialization (loading) + /** + * rematerialize() - internally used immediately after deserialization (loading) * This will clear out and reapply filterPipeline ops, recreating the view. * Since where filters do not persist correctly, this method allows * restoring the view to state where user can re-apply those where filters. * - * @param {Object} options - (Optional) allows specification of 'removeWhereFilters' option - * @returns {DynamicView} This dynamic view for further chained ops. + * @param [options] - (Optional) allows specification of 'removeWhereFilters' option + * @returns This dynamic view for further chained ops. + * @fires DynamicView.rebuild */ - rematerialize(options?: { removeWhereFilters?: boolean; }): LokiDynamicView; + public rematerialize(options?: { removeWhereFilters?: boolean }): this; - /** branchResultset() - Makes a copy of the internal resultset for branched queries. + /** + * branchResultset() - Makes a copy of the internal resultset for branched queries. * Unlike this dynamic view, the branched resultset will not be 'live' updated, * so your branched query should be immediately resolved and not held for future evaluation. * - * @param {string|array} transform: Optional name of collection transform, or an array of transform steps - * @param {object} parameters: optional parameters (if optional transform requires them) - * @returns {Resultset} A copy of the internal resultset for branched queries. + * @param transform - Optional name of collection transform, or an array of transform steps + * @param [parameters] - optional parameters (if optional transform requires them) + * @returns A copy of the internal resultset for branched queries. */ - branchResultset(transform?: string | any[], parameters?: any): LokiResultset; + public branchResultset(transform: string | string[] | Transform[], parameters?: object): Resultset; - /** toJSON() - Override of toJSON to avoid circular references + /** + * toJSON() - Override of toJSON to avoid circular references */ - toJSON(): LokiDynamicView; + public toJSON(): DynamicView; - /** removeFilters() - Used to clear pipeline and reset dynamic view to initial state. + /** + * removeFilters() - Used to clear pipeline and reset dynamic view to initial state. * Existing options should be retained. + * @param [options] - configure removeFilter behavior + * @param [options.queueSortPhase] - (default: false) if true we will async rebuild view (maybe set default to true in future?) */ - removeFilters(): void; + public removeFilters(options?: { queueSortPhase?: boolean }): void; - /** applySort() - Used to apply a sort to the dynamic view + /** + * applySort() - Used to apply a sort to the dynamic view + * @example + * dv.applySort(function(obj1, obj2) { + * if (obj1.name === obj2.name) return 0; + * if (obj1.name > obj2.name) return 1; + * if (obj1.name < obj2.name) return -1; + * }); * - * @param {function} comparefun - a javascript compare function used for sorting - * @returns {DynamicView} this DynamicView object, for further chain ops. + * @param comparefun - a javascript compare function used for sorting + * @returns this DynamicView object, for further chain ops. */ - applySort(comparefun: (a: E, b: E) => number): LokiDynamicView; + public applySort(comparefun: (a: E & LokiObj, b: E & LokiObj) => number): this; - /** applySimpleSort() - Used to specify a property used for view translation. + /** + * applySimpleSort() - Used to specify a property used for view translation. + * @example + * dv.applySimpleSort("name"); * - * @param {string} propname - Name of property by which to sort. - * @param {boolean} isdesc - (Optional) If true, the sort will be in descending order. - * @returns {DynamicView} this DynamicView object, for further chain ops. + * @param propname - Name of property by which to sort. + * @param [isdesc] - (Optional) If true, the sort will be in descending order. + * @returns this DynamicView object, for further chain ops. */ - applySimpleSort(propname: string, isdesc?: boolean): LokiDynamicView; + public applySimpleSort(propname: keyof E, isdesc?: boolean): this; - /** applySortCriteria() - Allows sorting a resultset based on multiple columns. - * Example : dv.applySortCriteria(['age', 'name']); to sort by age and then name (both ascending) - * Example : dv.applySortCriteria(['age', ['name', true]); to sort by age (ascending) and then by name (descending) - * Example : dv.applySortCriteria(['age', true], ['name', true]); to sort by age (descending) and then by name (descending) + /** + * applySortCriteria() - Allows sorting a resultset based on multiple columns. + * @example + * // to sort by age and then name (both ascending) + * dv.applySortCriteria(['age', 'name']); + * // to sort by age (ascending) and then by name (descending) + * dv.applySortCriteria(['age', ['name', true]); + * // to sort by age (descending) and then by name (descending) + * dv.applySortCriteria(['age', true], ['name', true]); * - * @param {array} properties - array of property names or subarray of [propertyname, isdesc] used evaluate sort order - * @returns {DynamicView} Reference to this DynamicView, sorted, for future chain operations. + * @param criteria - array of property names or subarray of [propertyname, isdesc] used evaluate sort order + * @returns Reference to this DynamicView, sorted, for future chain operations. */ - applySortCriteria(criteria: ([string, boolean] | [string])[]): LokiDynamicView; + public applySortCriteria(criteria: [keyof E, boolean][]): this; - /** startTransaction() - marks the beginning of a transaction. + /** + * startTransaction() - marks the beginning of a transaction. * - * @returns {DynamicView} this DynamicView object, for further chain ops. + * @returns this DynamicView object, for further chain ops. */ - startTransaction(): LokiDynamicView; + public startTransaction(): this; - /** commit() - commits a transaction. + /** + * commit() - commits a transaction. * - * @returns {DynamicView} this DynamicView object, for further chain ops. + * @returns this DynamicView object, for further chain ops. */ - commit(): LokiDynamicView; + public commit(): this; - /** rollback() - rolls back a transaction. + /** + * rollback() - rolls back a transaction. * - * @returns {DynamicView} this DynamicView object, for further chain ops. + * @returns this DynamicView object, for further chain ops. */ - rollback(): LokiDynamicView; + public rollback(): this; - /** Implementation detail. + /** + * Implementation detail. * _indexOfFilterWithId() - Find the index of a filter in the pipeline, by that filter's ID. * - * @param {string|number} uid - The unique ID of the filter. - * @returns {number}: index of the referenced filter in the pipeline; -1 if not found. + * @param [uid] - The unique ID of the filter. + * @returns index of the referenced filter in the pipeline; -1 if not found. */ - _indexOfFilterWithId(uid: string | number): number; + public _indexOfFilterWithId(uid?: string | number): number; - /** Implementation detail. + /** + * Implementation detail. * _addFilter() - Add the filter object to the end of view's filter pipeline and apply the filter to the resultset. * - * @param {object} filter - The filter object. Refer to applyFilter() for extra details. + * @param filter - The filter object. Refer to applyFilter() for extra details. */ - _addFilter(filter: LokiFilter): void; + public _addFilter(filter: { type: "find" | "where", val: any; uid?: string | number }): void; - /** reapplyFilters() - Reapply all the filters in the current pipeline. + /** + * reapplyFilters() - Reapply all the filters in the current pipeline. * - * @returns {DynamicView} this DynamicView object, for further chain ops. + * @returns this DynamicView object, for further chain ops. */ - reapplyFilters(): LokiDynamicView; + public reapplyFilters(): this; - /** applyFilter() - Adds or updates a filter in the DynamicView filter pipeline + /** + * applyFilter() - Adds or updates a filter in the DynamicView filter pipeline * - * @param {object} filter - A filter object to add to the pipeline. + * @param filter - A filter object to add to the pipeline. * The object is in the format { 'type': filter_type, 'val', filter_param, 'uid', optional_filter_id } - * @returns {DynamicView} this DynamicView object, for further chain ops. + * @returns this DynamicView object, for further chain ops. */ - applyFilter(filter: LokiFilter): LokiDynamicView; + public applyFilter(filter: { type: "find" | "where", val: any; uid?: string | number }): this; - /** applyFind() - Adds or updates a mongo-style query option in the DynamicView filter pipeline + /** + * applyFind() - Adds or updates a mongo-style query option in the DynamicView filter pipeline * - * @param {object} query - A mongo-style query object to apply to pipeline - * @param {string|number} uid - Optional: The unique ID of this filter, to reference it in the future. - * @returns {DynamicView} this DynamicView object, for further chain ops. + * @param query - A mongo-style query object to apply to pipeline + * @param [uid] - Optional: The unique ID of this filter, to reference it in the future. + * @returns this DynamicView object, for further chain ops. */ - applyFind(query: LokiQuery, uid?: string | number): LokiDynamicView; + public applyFind(query: any, uid?: string | number): this; - /** applyWhere() - Adds or updates a javascript filter function in the DynamicView filter pipeline + /** + * applyWhere() - Adds or updates a javascript filter function in the DynamicView filter pipeline * - * @param {function} fun - A javascript filter function to apply to pipeline - * @param {string|number} uid - Optional: The unique ID of this filter, to reference it in the future. - * @returns {DynamicView} this DynamicView object, for further chain ops. + * @param fun - A javascript filter function to apply to pipeline + * @param [uid] - Optional: The unique ID of this filter, to reference it in the future. + * @returns this DynamicView object, for further chain ops. */ - applyWhere(fun: (obj: E) => boolean, uid?: string | number): LokiDynamicView; + public applyWhere(fun: (obj: any) => boolean, uid?: string | number): this; - /** removeFilter() - Remove the specified filter from the DynamicView filter pipeline + /** + * removeFilter() - Remove the specified filter from the DynamicView filter pipeline * - * @param {string|number} uid - The unique ID of the filter to be removed. - * @returns {DynamicView} this DynamicView object, for further chain ops. + * @param uid - The unique ID of the filter to be removed. + * @returns this DynamicView object, for further chain ops. */ - removeFilter(uid: string | number): LokiDynamicView; + public removeFilter(uid: string | number): this; - /** count() - returns the number of documents representing the current DynamicView contents. + /** + * count() - returns the number of documents representing the current DynamicView contents. * - * @returns {number} The number of documents representing the current DynamicView contents. + * @returns The number of documents representing the current DynamicView contents. */ - count(): number; + public count(): number; - /** data() - resolves and pending filtering and sorting, then returns document array as result. + /** + * data() - resolves and pending filtering and sorting, then returns document array as result. * - * @returns {array} An array of documents representing the current DynamicView contents. + * @param [options] - optional parameters to pass to resultset.data() if non-persistent + * @param [options.forceClones] - Allows forcing the return of cloned objects even when + * the collection is not configured for clone object. + * @param [options.forceCloneMethod] - Allows overriding the default or collection specified cloning method. + * Possible values include 'parse-stringify', 'jquery-extend-deep', 'shallow', 'shallow-assign' + * @param [options.removeMeta] - Will force clones and strip $loki and meta properties from documents + * @returns An array of documents representing the current DynamicView contents. */ - data(): E[]; + public data(options?: Partial): (E & LokiObj)[]; - /** queueRebuildEvent() - When the view is not sorted we may still wish to be notified of rebuild events. + /** + * queueRebuildEvent() - When the view is not sorted we may still wish to be notified of rebuild events. * This event will throttle and queue a single rebuild event when batches of updates affect the view. */ - queueRebuildEvent(): void; + public queueRebuildEvent(): void; - /** queueSortPhase : If the view is sorted we will throttle sorting to either : + /** + * queueSortPhase : If the view is sorted we will throttle sorting to either : * (1) passive - when the user calls data(), or * (2) active - once they stop updating and yield js thread control */ - queueSortPhase(): void; + public queueSortPhase(): void; - /** performSortPhase() - invoked synchronously or asynchronously to perform final sort phase (if needed) + /** + * performSortPhase() - invoked synchronously or asynchronously to perform final sort phase (if needed) */ - performSortPhase(options?: { suppressRebuildEvent?: boolean; }): void; + public performSortPhase(options?: { persistent?: boolean; suppressRebuildEvent?: boolean }): void; - /** evaluateDocument() - internal method for (re)evaluating document inclusion. + /** + * evaluateDocument() - internal method for (re)evaluating document inclusion. * Called by : collection.insert() and collection.update(). * - * @param {int} objIndex - index of document to (re)run through filter pipeline. - * @param {bool} isNew - true if the document was just added to the collection. + * @param objIndex - index of document to (re)run through filter pipeline. + * @param [isNew] - true if the document was just added to the collection. */ - evaluateDocument(objIndex: number, isNew?: boolean): void; + public evaluateDocument(objIndex: number | string, isNew?: boolean): void; - /** removeDocument() - internal function called on collection.delete() + + /** + * removeDocument() - internal function called on collection.delete() */ - removeDocument(objIndex: number): void; + public removeDocument(objIndex: number | string): void; - /** mapReduce() - data transformation via user supplied functions + /** + * mapReduce() - data transformation via user supplied functions * - * @param {function} mapFunction - this function accepts a single document for you to transform and return - * @param {function} reduceFunction - this function accepts many (array of map outputs) and returns single value + * @param mapFunction - this function accepts a single document for you to transform and return + * @param reduceFunction - this function accepts many (array of map outputs) and returns single value * @returns The output of your reduceFunction */ - mapReduce(mapFunction: (item: E, index: number, array: E[]) => T, reduceFunction: (array: T[]) => U): U; + public mapReduce(mapFunction: (value: E, index: number, array: E[]) => U, reduceFunction: (ary: U[]) => R): R; } - -/** Collection class that handles documents of same type - */ -interface LokiCollection extends LokiEventEmitter { - // option to observe objects and update them automatically, ignored if Object.observe is not supported - autoupdate: boolean; - // option to make event listeners async, default is sync - asyncListeners: boolean; - binaryIndices: { [id: string]: { name: string; dirty: boolean; values: number[] } }; - - cachedIndex: number[]; - cachedBinaryIndex: { [id: string]: { name: string; dirty: boolean; values: number[] } }; - cachedData: E[]; - // changes are tracked by collection and aggregated by the db - changes: LokiCollectionChange[]; - // default clone method (if enabled) is parse-stringify - cloneMethod: string; // 'parse-stringify' - // options to clone objects when inserting them - cloneObjects: boolean; - console: { - log: () => void; - warn: () => void; - error: () => void; - }; - constraints: { - unique: { [id: string]: LokiUniqueIndex }; - exact: { [id: string]: LokiExactIndex }; - }; - data: E[]; - // in autosave scenarios we will use collection level dirty flags to determine whether save is needed. - // currently, if any collection is dirty we will autosave the whole database if autosave is configured. - // defaulting to true since this is called from addCollection and adding a collection should trigger save - dirty: boolean; - // disable track changes - disableChangesApi: boolean; - DynamicViews: LokiDynamicView[]; - events: { [id: string]: ((...args: any[]) => void)[] }; /*{ - 'insert': ((...args) => void)[]; - 'update': ((...args) => void)[]; - 'pre-insert': ((...args) => void)[]; - 'pre-update': ((...args) => void)[]; - 'close': ((...args) => void)[]; - 'flushbuffer': ((...args) => void)[]; - 'error': ((...args) => void)[]; - 'delete': ((...args) => void)[]; - 'warning': ((...args) => void)[]; - };*/ - idIndex: number[]; - maxId: number; // currentMaxId - change manually at your own peril! +interface BinaryIndex { name: string; - // is collection transactional + dirty: boolean; + values: number[]; +} + + +interface CollectionOptions { + disableChangesApi: boolean; + disableDeltaChangesApi: boolean; + adaptiveBinaryIndices: boolean; + asyncListeners: boolean; + autoupdate: boolean; + clone: boolean; + cloneMethod: ("parse-stringify" | "jquery-extend-deep" | "shallow" | "shallow-assign" | "shallow-recurse-objects"); + serializableIndices: boolean; transactional: boolean; + ttl: number; + ttlInterval: number; + exact: (keyof E)[]; + unique: (keyof E)[]; + indices: (keyof E) | (keyof E)[]; +} + + +interface CollectionChange { + name: string; + operation: string; + obj: any; +} + + +/** + * Collection class that handles documents of same type + * @implements LokiEventEmitter + * @see {@link Loki#addCollection} for normal creation of collections + */ +declare class Collection extends LokiEventEmitter { + name: string; objType: string; - // transforms will be used to store frequently used query chains as a series of steps - // which itself can be stored along with the database. - transforms: { [id: string]: any }; - // unique contraints contain duplicate object references, so they are not persisted. - // we will keep track of properties which have unique contraint applied here, and regenerate on load - uniqueNames: string[]; + data: E[]; + adaptiveBinaryIndices: boolean; + asyncListeners: boolean; + autoupdate: boolean; + dirty: boolean; + binaryIndices: { [P in keyof E]: BinaryIndex }; + cachedIndex: number[] | null; + cachedBinaryIndex: { [P in keyof E]: BinaryIndex } | null; + cachedData: E[] | null; + changes: CollectionChange[]; + cloneMethod: ("parse-stringify" | "jquery-extend-deep" | "shallow" | "shallow-assign" | "shallow-recurse-objects") | null; + cloneObjects: boolean; + constraints: { + unique: { [P in keyof E]: UniqueIndex }; + exact: { [P in keyof E]: ExactIndex } + }; + disableChangesApi: boolean; + disableDeltaChangesApi: boolean; + DynamicViews: DynamicView[]; + idIndex: number[]; + ttl: { age: any; ttlInterval: any; daemon: any; }; + maxId: number; + uniqueNames: (keyof E)[]; + transforms: { [name: string]: Transform[] }; + serializableIndices: boolean; + transactional: boolean; + observerCallback: (changes: { object: any }[]) => void; + getChanges: () => CollectionChange[]; + flushChanges: () => void; + getChangeDelta: (obj: any, old?: any) => any; + getObjectDelta: (oldObject: any, newObject?: any) => any; + setChangesApi: (enabled?: boolean) => void; - options: LokiCollectionOptions; - // option to activate a cleaner daemon - clears "aged" documents at set intervals. - ttl: { - age: number; - ttlInterval: number; - daemon: number; + /** + * @param name - collection name + * @param [options] - (optional) configuration object + * @param [options.unique=[]] - array of property names to define unique constraints for + * @param [options.exact=[]] - array of property names to define exact constraints for + * @param [options.indices=[]] - array property names to define binary indexes for + * @param [options.adaptiveBinaryIndices=true] - collection indices will be actively rebuilt rather than lazily + * @param [options.asyncListeners=false] - whether listeners are invoked asynchronously + * @param [options.disableChangesApi=true] - set to false to enable Changes API + * @param [options.disableDeltaChangesApi=true] - set to false to enable Delta Changes API (requires Changes API, forces cloning) + * @param [options.autoupdate=false] - use Object.observe to update objects automatically + * @param [options.clone=false] - specify whether inserts and queries clone to/from user + * @param [options.serializableIndices=true[]] - converts date values on binary indexed properties to epoch time + * @param [options.cloneMethod='parse-stringify'] - 'parse-stringify', 'jquery-extend-deep', 'shallow', 'shallow-assign' + * @param options.ttlInterval - time interval for clearing out 'aged' documents; not set by default. + * @see {@link Loki#addCollection} for normal creation of collections + */ + constructor(name: string, options?: Partial>); + + public console: { + log(...args: any[]): void; + warn(...args: any[]): void; + error(...args: any[]): void; }; - /** Collection class that handles documents of same type - * @constructor - * @param {string} collection name - * @param {array} array of property names to be indicized - * @param {object} configuration object + public addAutoUpdateObserver(obj: any): void; + + public removeAutoUpdateObserver(obj: any): void; + + /** + * Adds a named collection transform to the collection + * @param name - name to associate with transform + * @param transform - an array of transformation 'step' objects to save into the collection + * @example + * users.addTransform('progeny', [ + * { + * type: 'find', + * value: { + * 'age': {'$lte': 40} + * } + * } + * ]); + * + * var results = users.chain('progeny').data(); */ - new (name: string, options?: LokiCollectionOptions): LokiCollection; + public addTransform(name: string, transform: Transform[]): void; - getChanges(): LokiCollectionChange[]; + /** + * Retrieves a named transform from the collection. + * @param name - name of the transform to lookup. + */ + public getTransform(name: string): Transform[]; - setChangesApi(enabled: boolean): void; + /** + * Updates a named collection transform to the collection + * @param name - name to associate with transform + * @param transform - a transformation object to save into collection + */ + public setTransform(name: string, transform: Transform[]): void; - flushChanges(): void; + /** + * Removes a named collection transform from the collection + * @param name - name of collection transform to remove + */ + public removeTransform(name: string): void; - observerCallback: (changes: { object: any }[]) => void; + public byExample(template: object): { $and: any[] }; - addAutoUpdateObserver(object: any): void; + public findObject(template: object): E | null; - removeAutoUpdateObserver(object: any): void; - - addTransform(name: string, transform: any): void; - - setTransform(name: string, transform: any): void; - - removeTransform(name: string): void; - - byExample(template: any): { '$and': any[] }; - - findObject(template: any): E; - - findObjects(template: any): E[]; + public findObjects(template: object): E[]; /*----------------------------+ | TTL daemon | +----------------------------*/ - ttlDaemonFuncGen(): () => void; + public ttlDaemonFuncGen(): () => void; - setTTL(age: number, interval: number): void; + /** + * Updates or applies collection TTL settings. + * @param age - age (in ms) to expire document from collection + * @param interval - time (in ms) to clear collection of aged documents. + */ + public setTTL(age: number, interval: number): void; /*----------------------------+ | INDEXING | @@ -857,711 +1434,575 @@ interface LokiCollection extends LokiEventEmitter { /** * create a row filter that covers all documents in the collection */ - prepareFullDocIndex(): number[]; + public prepareFullDocIndex(): number[]; - /** Ensure binary index on a certain field + /** + * Will allow reconfiguring certain collection options. + * @param [options.adaptiveBinaryIndices] - collection indices will be actively rebuilt rather than lazily */ - ensureIndex(property: string, force?: boolean): void; + public configureOptions(options?: { adaptiveBinaryIndices?: boolean }): void; - ensureUniqueIndex(field: string): LokiUniqueIndex; - - /** Ensure all binary indices + /** + * Ensure binary index on a certain field + * @param property - name of property to create binary index on + * @param [force] - (Optional) flag indicating whether to construct index immediately */ - ensureAllIndexes(force?: boolean): void; + public ensureIndex(property: keyof E, force?: boolean): void; - flagBinaryIndexesDirty(): void; + public getSequencedIndexValues(property: string): string; - flagBinaryIndexDirty(index: string): void; + public ensureUniqueIndex(field: keyof E): UniqueIndex; - count(query?: LokiQuery): number; - - /** Rebuild idIndex + /** + * Ensure all binary indices */ - ensureId(): void; + public ensureAllIndexes(force?: boolean): void; - /** Rebuild idIndex async with callback - useful for background syncing with a remote server + public flagBinaryIndexesDirty(): void; + + public flagBinaryIndexDirty(index: string): void; + + /** + * Quickly determine number of documents in collection (or query) + * @param [query] - (optional) query object to count results of + * @returns number of documents in the collection */ - ensureIdAsync(callback: () => void): void; + public count(query?: LokiQuery): number; - /** Each collection maintains a list of DynamicViews associated with it + /** + * Rebuild idIndex + */ + public ensureId(): void; + + /** + * Rebuild idIndex async with callback - useful for background syncing with a remote server + */ + public ensureIdAsync(callback: () => void): void; + + /** + * Add a dynamic view to the collection + * @param name - name of dynamic view to add + * @param [options] - options to configure dynamic view with + * @param [options.persistent=false] - indicates if view is to main internal results array in 'resultdata' + * @param [options.sortPriority='passive'] - 'passive' (sorts performed on call to data) or 'active' (after updates) + * @param options.minRebuildInterval - minimum rebuild interval (need clarification to docs here) + * @returns reference to the dynamic view added + * @example + * var pview = users.addDynamicView('progeny'); + * pview.applyFind({'age': {'$lte': 40}}); + * pview.applySimpleSort('name'); + * + * var results = pview.data(); + */ + public addDynamicView(name: string, options?: Partial): DynamicView; + + /** + * Remove a dynamic view from the collection + * @param name - name of dynamic view to remove **/ - addDynamicView(name: string, options?: LokiDynamicViewOptions): LokiDynamicView; + public removeDynamicView(name: string): void; - removeDynamicView(name: string): void; + /** + * Look up dynamic view reference from within the collection + * @param name - name of dynamic view to retrieve reference of + * @returns A reference to the dynamic view with that name + **/ + public getDynamicView(name: string): DynamicView | null; - getDynamicView(name: string): LokiDynamicView; - - /** find and update: pass a filtering function to select elements to be updated - * and apply the updatefunctino to those elements iteratively + /** + * Applies a 'mongo-like' find query object and passes all results to an update function. + * For filter function querying you should migrate to [updateWhere()]{@link Collection#updateWhere}. + * + * @param filterObject - 'mongo-like' query object (or deprecated filterFunction mode) + * @param updateFunction - update function to run against filtered documents */ - findAndUpdate(filterFunction: (obj: E) => boolean, updateFunction: (obj: E) => E): void; + public findAndUpdate(filterObject: ((data: E) => boolean) | LokiQuery, updateFunction: (obj: E & LokiObj) => any): void; - /** generate document method - ensure object(s) have meta properties, clone it if necessary, etc. - * @param {object} doc: the document to be inserted (or an array of objects) - * @returns document or documents (if passed an array of objects) + /** + * Applies a 'mongo-like' find query object removes all documents which match that filter. + * + * @param filterObject - 'mongo-like' query object */ - insert(doc: E): E; - insert(doc: E[]): E[]; + public findAndRemove(filterObject?: LokiQuery): void; - /** generate document method - ensure object has meta properties, clone it if necessary, etc. - * @param {object} the document to be inserted + /** + * Adds object(s) to collection, ensure object(s) have meta properties, clone it if necessary, etc. + * @param doc - the document (or array of documents) to be inserted + * @returns document or documents inserted + * @example + * users.insert({ + * name: 'Odin', + * age: 50, + * address: 'Asgard' + * }); + * + * // alternatively, insert array of documents + * users.insert([{ name: 'Thor', age: 35}, { name: 'Loki', age: 30}]); + */ + public insert(doc: E): E | undefined; + public insert(doc: E[]): E[] | undefined; + public insert(doc: E | E[]): E | E[] | undefined; + public insert(doc: E | E[]): E | E[] | undefined; + + /** + * Adds a single object, ensures it has meta properties, clone it if necessary, etc. + * @param doc - the document to be inserted + * @param [bulkInsert] - quiet pre-insert and insert event emits * @returns document or 'undefined' if there was a problem inserting it */ - insertOne(doc: E): E; + public insertOne(doc: E, bulkInsert?: boolean): (E & LokiObj) | undefined; - clear(): void; - - /** Update method + /** + * Empties the collection. + * @param [options] - configure clear behavior + * @param [options.removeIndices] - (default: false) */ - update(doc: E): E; - update(doc: E[]): void; + public clear(options?: { removeIndices?: boolean }): void; - /** Add object to collection + /** + * Updates an object and notifies collection that the document has changed. + * @param doc - document to update within the collection */ - add(obj: E): E; + public update(doc: E): E; + public update(doc: E[]): void; + public update(doc: E | E[]): E | void; + public update(doc: E | E[]): E | void; - removeWhere(query: ((obj: E) => boolean) | LokiQuery): void; - - removeDataOnly(): void; - - /** delete wrapped + /** + * Add object to collection */ - remove(doc: E): E; - remove(doc: number): E; - remove(doc: number[]): void; - remove(doc: E[]): void; + public add(obj: E): E & LokiObj; + public add(obj: E & LokiObj): E & LokiObj; + + /** + * Applies a filter function and passes all results to an update function. + * + * @param filterFunction - filter function whose results will execute update + * @param updateFunction - update function to run against filtered documents + */ + public updateWhere(filterFunction: (data: E) => boolean, updateFunction: (obj: E & LokiObj) => any): void; + + /** + * Remove all documents matching supplied filter function. + * For 'mongo-like' querying you should migrate to [findAndRemove()]{@link Collection#findAndRemove}. + * @param query - query object to filter on + */ + public removeWhere(query: ((value: E, index: number, array: E[]) => boolean) | LokiQuery): void; + + public removeDataOnly(): void; + + /** + * Remove a document from the collection + * @param doc - document to remove from collection + */ + public remove(doc: number | E): E | null; + public remove(doc: number[] | E[]): void; + public remove(doc: number | E | number[] | E[]): E | null | void; + public remove(doc: number | E | number[] | E[]): E | null | void; /*---------------------+ | Finding methods | +----------------------*/ - /** Get by Id - faster than other methods because of the searching algorithm + /** + * Get by Id - faster than other methods because of the searching algorithm + * @param id - $loki id of document you want to retrieve + * @param returnPosition - if 'true' we will return [object, position] + * @returns Object reference if document was found, null if not, + * or an array if 'returnPosition' was passed. */ - get(id: number | string): E; - get(id: number | string, returnPosition?: boolean): E | [E, number]; + public get(id: number): E & LokiObj; + public get(id: number, returnPosition: true): [E & LokiObj, number]; + public get(id: number, returnPosition?: boolean): (E & LokiObj) | [E & LokiObj, number] | null; - by(field: string): (value: any) => E; - by(field: string, value: string): E; - - /** Find one object by index property, by property equal to value + /** + * Perform binary range lookup for the data[dataPosition][binaryIndexName] property value + * Since multiple documents may contain the same value (which the index is sorted on), + * we hone in on range and then linear scan range to find exact index array position. + * @param dataPosition : coll.data array index/position + * @param binaryIndexName : index to search for dataPosition in */ - findOne(query: LokiQuery): E; + public getBinaryIndexPosition(dataPosition: number, binaryIndexName: keyof E): number | null; - /** Chain method, used for beginning a series of chained find() and/or view() operations + /** + * Adaptively insert a selected item to the index. + * @param dataPosition : coll.data array index/position + * @param binaryIndexName : index to search for dataPosition in + */ + public adaptiveBinaryIndexInsert(dataPosition: number, binaryIndexName: keyof E): void; + + /** + * Adaptively update a selected item within an index. + * @param dataPosition : coll.data array index/position + * @param binaryIndexName : index to search for dataPosition in + */ + public adaptiveBinaryIndexUpdate(dataPosition: number, binaryIndexName: keyof E): void; + + /** + * Adaptively remove a selected item from the index. + * @param dataPosition : coll.data array index/position + * @param binaryIndexName : index to search for dataPosition in + */ + public adaptiveBinaryIndexRemove(dataPosition: number, binaryIndexName: keyof E, removedFromIndexOnly?: boolean): void; + + /** + * Internal method used for index maintenance and indexed searching. + * Calculates the beginning of an index range for a given value. + * For index maintainance (adaptive:true), we will return a valid index position to insert to. + * For querying (adaptive:false/undefined), we will : + * return lower bound/index of range of that value (if found) + * return next lower index position if not found (hole) + * If index is empty it is assumed to be handled at higher level, so + * this method assumes there is at least 1 document in index. + * + * @param prop - name of property which has binary index + * @param val - value to find within index + * @param [adaptive] - if true, we will return insert position + */ + public calculateRangeStart(prop: keyof E, val: any, adaptive?: boolean): number; + + /** + * Internal method used for indexed $between. Given a prop (index name), and a value + * (which may or may not yet exist) this will find the final position of that upper range value. + */ + public calculateRangeEnd(prop: keyof E, val: any): number; + + /** + * calculateRange() - Binary Search utility method to find range/segment of values matching criteria. + * this is used for collection.find() and first find filter of resultset/dynview + * slightly different than get() binary search in that get() hones in on 1 value, + * but we have to hone in on many (range) + * @param op - operation, such as $eq + * @param prop - name of property to calculate range for + * @param val - value to use for range calculation. + * @returns [start, end] index array positions + */ + public calculateRange(op: ("$eq" | "$aeq" | "$dteq" | "$gt" | "$gte" | "$lt" | "$lte" | "$between" | "$in"), prop: keyof E, val: any): number[]; + + /** + * Retrieve doc by Unique index + * @param field - name of uniquely indexed property to use when doing lookup + * @param value - unique value to search for + * @returns document matching the value passed + */ + public by(field: keyof E): (value: any) => E | undefined; + public by(field: keyof E, value: any): E | undefined; + public by(field: keyof E, value?: any): E | ((value: any) => E | undefined) | undefined; + public by(field: keyof E, value?: any): E | ((value: any) => E | undefined) | undefined; + + /** + * Find one object by index property, by property equal to value + * @param query - query object used to perform search with + * @returns First matching document, or null if none + */ + public findOne(query?: LokiQuery): (E & LokiObj) | null; + + /** + * Chain method, used for beginning a series of chained find() and/or view() operations * on a collection. * - * @param {array} transform : Ordered array of transform step objects similar to chain - * @param {object} parameters: Object containing properties representing parameters to substitute - * @returns {Resultset} : (or data array if any map or join functions where called) + * @param [transform] - Ordered array of transform step objects similar to chain + * @param [parameters] - Object containing properties representing parameters to substitute + * @returns (this) resultset, or data array if any map or join functions where called */ - chain(transform?: string | any[], parameters?: any): LokiResultset; + public chain(): Resultset; + public chain(transform?: string | string[] | Transform[], parameters?: object): Resultset; /** - * Find method, api is similar to mongodb except for now it only supports one search parameter. - * for more complex queries use view() and storeView() + * Find method, api is similar to mongodb. + * for more complex queries use [chain()]{@link Collection#chain} or [where()]{@link Collection#where}. + * @example {@tutorial Query Examples} + * @param query - 'mongo-like' query object + * @returns Array of matching documents */ - find(): E[]; - find(query: LokiQuery): LokiResultset; + public find(query?: LokiQuery): (E & LokiObj)[]; - /** Find object by unindexed field by property equal to value, + /** + * Find object by unindexed field by property equal to value, * simply iterates and returns the first element matching the query */ - findOneUnindexed(prop: string, value: any): E; - - /** Transaction methods */ - - /** start the transation */ - startTransaction(): void; - - /** commit the transation */ - commit(): void; - - /** roll back the transation */ - rollback(): void; - - // async executor. This is only to enable callbacks at the end of the execution. - async(fun: () => void, callback: () => void): void; - - /** Create view function - filter - */ - where(fun: (obj: E) => boolean): LokiResultset; - - /** Map Reduce - */ - mapReduce(mapFunction: (item: E, index: number, array: E[]) => U, reduceFunction: (array: U[]) => V): V; - - /** eqJoin - Join two collections on specified properties - */ - eqJoin(joinData: T[] | LokiResultset, leftJoinProp: string | ((obj: E) => string), rightJoinProp: string | ((obj: T) => string)): LokiResultset<{ left: E; right: T; }>; - eqJoin(joinData: T[] | LokiResultset, leftJoinProp: string | ((obj: E) => string), rightJoinProp: string | ((obj: T) => string), mapFun?: (a: E, b: T) => U): LokiResultset; - - /* ------ STAGING API -------- */ - /** stages: a map of uniquely identified 'stages', which hold copies of objects to be - * manipulated without affecting the data in the original collection - */ - stages: { [id: string]: any }; - - /** create a stage and/or retrieve it - */ - getStage(name: string): E[]; - - /** a collection of objects recording the changes applied through a commmitStage - */ - commitLog: { - timestamp: number; // timestamp (i.e. new Date().getTime()) - message: any; - data: E; - }[]; - - /** create a copy of an object and insert it into a stage - */ - stage(stageName: string, obj: E): E; - - /** re-attach all objects to the original collection, so indexes and views can be rebuilt - * then create a message to be inserted in the commitlog - */ - commitStage(stageName: string, message: any): void; - - no_op(): void; - - extract(field: string): any[]; - - max(field: string): number; - - min(field: string): number; - - maxRecord(field: string): { index: number; value: any; }; - - minRecord(field: string): { index: number; value: any; }; - - extractNumerical(field: string): number[]; - - avg(field: string): number; - - stdDev(field: string): number; - - mode(field: string): string | number; - - median(field: string): number; -} - - - - -/** comparison operators - * a is the value in the collection - * b is the query value - */ -interface LokiOps { - $eq(a: any, b: any): boolean; - $ne(a: any, b: any): boolean; - $dteq(a: any, b: any): boolean; - $gt(a: any, b: any): boolean; - $gte(a: any, b: any): boolean; - $lt(a: any, b: any): boolean; - $lte(a: any, b: any): boolean; - $in(a: any, b: { indexOf: (value: any) => boolean }): boolean; - $nin(a: any, b: { indexOf: (value: any) => boolean }): boolean; - $keyin(a: string, b: any): boolean; - $nkeyin(a: string, b: any): boolean; - $definedin(a: any, b: any): boolean; - $undefinedin(a: any, b: any): boolean; - $regex(a: any, b: RegExp | { test: (str: string) => boolean }): boolean; - $containsString(a: string | any, b: string): boolean; - $containsNone(a: any, b: any): boolean; - $containsAny(a: any, b: any | any[]): boolean; - $contains(a: any, b: any | any[]): boolean; - $type(a: any, b: any): boolean; - $size(a: any, b: any): boolean; - $len(a: any, b: any): boolean; - // field-level logical operators - // a is the value in the collection - // b is the nested query operation (for '$not') - // or an array of nested query operations (for '$and' and '$or') - $not(a: any, b: any): boolean; - $and(a: any, b: any[]): boolean; - $or(a: any, b: any[]): boolean; -} - - -interface LokiKeyValueStore { - keys: K[]; - values: V[]; - - sort(a: any, b: any): number; - setSort(fun: (a: K, b: K) => number): void; - bs(): LokiBSonSort; - set(key: K, value: V): void; - get(key: K): V; -} - - -interface LokiUniqueIndex { - field: string; - keyMap: { [id: string]: E }; - lokiMap: { [id: number]: any }; - - new (uniqueField: string): LokiUniqueIndex; - - set(obj: E): void; - get(key: string): E; - byId(id: number): E; - update(obj: E): void; - remove(key: string): void; - clear(): void; -} - - -interface LokiExactIndex { - index: { [id: string]: E[] }; - field: string; - - new (exactField: string): LokiExactIndex - - /** add the value you want returned to the key in the index */ - set(key: string, val: E): void; - /** remove the value from the index, if the value was the last one, remove the key */ - remove(key: string, val: E): void; - /** get the values related to the key, could be more than one */ - get(key: string): E[]; - /** clear will zap the index */ - clear(key?: any): void; -} - - -interface LokiSortedIndex { - field: string; - keys: K[]; - values: V[][]; - - new (sortedField: string): LokiSortedIndex; - - // set the default sort - sort(a: any, b: any): number; - bs(): LokiBSonSort; - // and allow override of the default sort - setSort(fun: (a: any, b: any) => number): void; - // add the value you want returned to the key in the index - set(key: K, value: V): void; - // get all values which have a key == the given key - get(key: K): V[]; - // get all values which have a key < the given key - getLt(key: K): V[]; - // get all values which have a key > the given key - getGt(key: K): V[]; - // get all vals from start to end - getAll(key: K, start: number, end: number): V[]; - // just in case someone wants to do something smart with ranges - getPos(key: K): { found: boolean; index: number; }; - // remove the value from the index, if the value was the last one, remove the key - remove(key: K, value: V): void; - // clear will zap the index - clear(): void; -} - - -interface LokiConfigureOptions { - adapter?: LokiPersistenceInterface; - autoload?: boolean; - autoloadCallback?: (dataOrErr: any | Error) => void; - autosave?: boolean; - autosaveCallback?: (err: any) => void; - autosaveInterval?: number; // milliseconds between auto-saves - env?: string; /*'NODEJS', 'BROWSER', 'CORDOVA'*/ - persistenceMethod?: string; /*'fs', 'localStorage', 'adapter'*/ - verbose?: boolean; -} - - -interface LokiCollectionOptions { - asyncListeners?: boolean; - autoupdate?: boolean; - clone?: boolean; - cloneMethod?: string; - disableChangesApi?: boolean; - exact?: string[]; - indices?: string | string[]; - transactional?: boolean; - unique?: string | string[]; -} - - -interface LokiDynamicViewOptions { - minRebuildInterval?: number; - persistent?: boolean; - sortPriority: string; /*'active', 'passive'*/ -} - - -interface LokiResultsetOptions { - firstOnly?: boolean; - queryObj?: LokiQuery; - queryFunc?: (item: E) => boolean; -} - - -interface LokiQuery { -} - - -interface LokiFilter { - type: string; /*'find', 'where'*/ - val: LokiQuery | ((obj: E, index: number, array: E[]) => boolean); - uid: number | string; -} - - -interface LokiElementMetaData { - created: number; // unix style timestamp (i.e. new Date().getTime()) - revision: number; -} - - -interface LokiCollectionChange { - name: string; - operation: string;/*'I', 'R', 'U'*/ - obj: any; -} - - -interface LokiBSonSort { - (fun: (a: T, b: T) => number): (array: T[], item: T) => { found: boolean; index: number; }; -} - - -/* -interface LokiUtils { - copyProperties(src: any, dest: any): void; - - // used to recursively scan hierarchical transform step object for param substitution - resolveTransformObject(subObj: U, params: any, depth?: number): U; - - // top level utility to resolve an entire (single) transform (array of steps) for parameter substitution - resolveTransformParams(transform: U[], params: any): U[]; -} - -// Sort helper that support null and undefined -declare function ltHelper(prop1: any, prop2: any, equal?: boolean): boolean; - -declare function gtHelper(prop1: any, prop2: any, equal?: boolean): boolean; - -declare function sortHelper(prop1: any, prop2: any, desc?: boolean): number; - -declare function doQueryOp(val: any, op: any): boolean; - -declare function containsCheckFn(a: T[], b): (curr: T) => boolean; -declare function containsCheckFn(a: string, b): (curr: string) => boolean; -declare function containsCheckFn(a: T, b): (curr: string) => boolean; -*/ - -/** General utils, including statistical functions - */ -/* -declare function isDeepProperty(field: string): boolean; - -declare function parseBase10(num: string | number): number; - -declare function isNotUndefined(obj: any): boolean; - -declare function add(a: string | number, b: string | number): number; - -declare function sub(a: string | number, b: string | number): number; - -declare function median(values: number[]): number; - -declare function average(array: (string | number)[]); - -declare function standardDeviation(values: (string | number)[]): number; - -declare function deepProperty(obj: any, property: string, isDeep?: boolean): any; - -declare function binarySearch(array: U[], item: U, fun: (a: U, b: U) => number): { found: boolean; index: number; }; - -// compoundeval() - helper function for compoundsort(), performing individual object comparisons -// -// @param {array} properties - array of property names, in order, by which to evaluate sort order -// @param {object} obj1 - first object to compare -// @param {object} obj2 - second object to compare -// @returns {integer} 0, -1, or 1 to designate if identical (sortwise) or which should be first -declare function compoundeval(properties: ([string, boolean] | [string])[], obj1: any, obj2: any): number; - -// dotSubScan - helper function used for dot notation queries. -declare function dotSubScan(root: any | any[], propPath: string[], fun: (root, value: V) => boolean, value: V): boolean; - -// making indexing opt-in... our range function knows how to deal with these ops : -//var indexedOpsList = ['$eq', '$dteq', '$gt', '$gte', '$lt', '$lte']; - -declare function clone(data: U, method?: string): U; // stage: 'parse-stringify', 'jquery-extend-deep', 'shallow' - -declare function cloneObjectArray(objarray: U[], method?: string): U; // stage: 'parse-stringify', 'jquery-extend-deep', 'shallow' - -declare function localStorageAvailable(): boolean; -*/ - - - - -/* ======== loki-indexed-adapter.js ======== */ -interface LokiIndexedAdapter { - app: string; - catalog: LokiCatalog; - - /** IndexedAdapter - Loki persistence adapter class for indexedDb. - * This class fulfills abstract adapter interface which can be applied to other storage methods - * Utilizes the included LokiCatalog app/key/value database for actual database persistence. - * @param {string} appname - Application name context can be used to distinguish subdomains or just 'loki' - */ - new (appname: string): LokiIndexedAdapter; - - /** checkAvailability - used to check if adapter is available - * @returns {boolean} true if indexeddb is available, false if not. - */ - checkAvailability(): boolean; - - /** loadDatabase() - Retrieves a serialized db string from the catalog. - * @param {string} dbname - the name of the database to retrieve. - * @param {function} callback - callback should accept string param containing serialized db string. - */ - loadDatabase(dbname: string, callback?: (data: any) => void): void; - - // alias for loadDatabase - loadKey(dbname: string, callback?: (data: any) => void): void; - - /** saveDatabase() - Saves a serialized db to the catalog. - * @param {string} dbname - the name to give the serialized database within the catalog. - * @param {string} dbstring - the serialized db string to save. - * @param {function} callback - (Optional) callback passed obj.success with true or false - */ - saveDatabase(dbname: string, dbstring: string, callback?: (err: Error | void) => void): void; - - // alias for saveDatabase - saveKey(dbname: string, dbstring: string, callback?: (err: Error | void) => void): void; - - /** deleteDatabase() - Deletes a serialized db from the catalog. - * @param {string} dbname - the name of the database to delete from the catalog. - */ - deleteDatabase(dbname: string): void; - - // alias for deleteDatabase - deleteKey(dbname: string): void; - - /** getDatabaseList() - Retrieves object array of catalog entries for current app. - * @param {function} callback - should accept array of database names in the catalog for current app. - */ - getDatabaseList(callback: (names: string[]) => void): void; - - // alias for getDatabaseList - getKeyList(callback: (names: string[]) => void): void; - - /** getCatalogSummary - allows retrieval of list of all keys in catalog along with size - * @param {function} callback - (Optional) callback to accept result array. - */ - getCatalogSummary(callback: (entries: { app: string; key: string; size: number; }) => void): void; -} - - -/** LokiCatalog - underlying App/Key/Value catalog persistence - * This non-interface class implements the actual persistence. - * Used by the IndexedAdapter class. - */ -interface LokiCatalog { - db: IDBDatabase; - - new (callback: (cat: LokiCatalog) => void): LokiCatalog; - - initializeLokiCatalog(callback: (cat: LokiCatalog) => void): void; - - getAppKey(app: string, key: string, callback: (resObj: any) => void): void; - - getAppKeyById(id: any, callback: (result: any, data: T) => void, data: T): void; - - setAppKey(app: string, key: string, val: any, callback: (res: { success: boolean }) => void): void; - - deleteAppKey(id: any, callback: (res: { success: boolean; }) => void): void; - - getAppKeys(app: string, callback: (data: any[]) => void): void; - - // Hide 'cursoring' and return array of { id: id, key: key } - getAllKeys(callback: (data: any[]) => void): void; -} -/* ======== END loki-indexed-adapter.js ======== */ - - - -/* ======== loki-crypted-file-adapter.js ======== */ -/** - * @file lokiCryptedFileAdapter.js - * @author Hans Klunder - */ - -/** require libs */ -//var fs = require('fs'); -//var cryptoLib = require('crypto'); -//var isError = require('util').isError; - -/* The default Loki File adapter uses plain text JSON files. This adapter crypts the database string and wraps the result -* in a JSON including enough info to be able to decrypt it (except for the 'secret' of course !) -* -* The idea is that the 'secret' does not reside in your source code but is supplied by some other source (e.g. the user in node-webkit) -* -* The idea + encrypt/decrypt routines are borrowed from https://github.com/mmoulton/krypt/blob/develop/lib/krypt.js -* not using the krypt module to avoid third party dependencies -*/ -interface LokiCryptedFileAdapter { - secret: string; - - /** The constructor is automatically called on `require` , see examples below - * @constructor - */ - new (): LokiCryptedFileAdapter; - - /** setSecret() - set the secret to be used during encryption and decryption - * - * @param {string} secret - the secret to be used - */ - setSecret(secret: string): void; - - /** loadDatabase() - Retrieves a serialized db string from the catalog. - * - * @example - // LOAD - var cryptedFileAdapter = require('./lokiCryptedFileAdapter'); - cryptedFileAdapter.setSecret('mySecret'); // you should change 'mySecret' to something supplied by the user - var db = new loki('test.crypted', { adapter: cryptedFileAdapter }); //you can use any name, not just '*.crypted' - db.loadDatabase(function(result) { - console.log('done'); - }); - * - * @param {string} dbname - the name of the database to retrieve. - * @param {function} callback - callback should accept string param containing serialized db string. - */ - loadDatabase(dbname: string, callback: (decryptedDataOrErr: string | any) => void): void; + public findOneUnindexed(prop: keyof E, value: any): (E & LokiObj) | null; /** - * - @example - // SAVE : will save database in 'test.crypted' - var cryptedFileAdapter = require('./lokiCryptedFileAdapter'); - cryptedFileAdapter.setSecret('mySecret'); // you should change 'mySecret' to something supplied by the user - var loki=require('lokijs'); - var db = new loki('test.crypted',{ adapter: cryptedFileAdapter }); //you can use any name, not just '*.crypted' - var coll = db.addCollection('testColl'); - coll.insert({test: 'val'}); - db.saveDatabase(); // could pass callback if needed for async complete - - @example - // if you have the krypt module installed you can use: - krypt --decrypt test.crypted --secret mySecret - to view the contents of the database - - * saveDatabase() - Saves a serialized db to the catalog. - * - * @param {string} dbname - the name to give the serialized database within the catalog. - * @param {string} dbstring - the serialized db string to save. - * @param {function} callback - (Optional) callback passed obj.success with true or false + * Transaction methods */ - saveDatabase(dbname: string, dbstring: string, callback: (err: any) => void): void; + + /** start the transation */ + public startTransaction(): void; + + /** commit the transation */ + public commit(): void; + + /** roll back the transation */ + public rollback(): void; + + // async executor. This is only to enable callbacks at the end of the execution. + public async(fun: () => void, callback: () => void): void; + + /** + * Query the collection by supplying a javascript filter function. + * @example + * var results = coll.where(function(obj) { + * return obj.legs === 8; + * }); + * + * @param fun - filter function to run against all collection docs + * @returns all documents which pass your filter function + */ + public where(fun: (data: E) => boolean): (E & LokiObj)[]; + + /** + * Map Reduce operation + * + * @param mapFunction - function to use as map function + * @param reduceFunction - function to use as reduce function + * @returns The result of your mapReduce operation + */ + public mapReduce(mapFunction: (value: E, index: number, array: E[]) => U, reduceFunction: (ary: U[]) => R): R; + + /** + * Join two collections on specified properties + * + * @param joinData - array of documents to 'join' to this collection + * @param leftJoinProp - property name in collection + * @param rightJoinProp - property name in joinData + * @param mapFun - (Optional) map function to use + * @param dataOptions - options to data() before input to your map function + * @param [dataOptions.removeMeta] - allows removing meta before calling mapFun + * @param [dataOptions.forceClones] - forcing the return of cloned objects to your map object + * @param [dataOptions.forceCloneMethod] - Allows overriding the default or collection specified cloning method. + * @returns Result of the mapping operation + */ + public eqJoin( + joinData: Collection | Resultset | any[], + leftJoinProp: string | ((obj: any) => string), + rightJoinProp: string | ((obj: any) => string), + mapFun?: (left: any, right: any) => any, + dataOptions?: Partial + ): Resultset; + + /* ------ STAGING API -------- */ + /** + * stages: a map of uniquely identified 'stages', which hold copies of objects to be + * manipulated without affecting the data in the original collection + */ + public stages: { [name: string]: any }; + + /** + * (Staging API) create a stage and/or retrieve it + */ + public getStage(name: string): any; + + /** + * a collection of objects recording the changes applied through a commmitStage + */ + public commitLog: { timestamp: number; message: string; data: any }[]; + + + /** + * (Staging API) create a copy of an object and insert it into a stage + */ + public stage(stageName: string, obj: F): F; + + /** + * (Staging API) re-attach all objects to the original collection, so indexes and views can be rebuilt + * then create a message to be inserted in the commitlog + * @param stageName - name of stage + * @param message + */ + public commitStage(stageName: string, message: string): void; + + public no_op: () => void; + + public extract(field: string): any[]; + + public max(field: string): number; + + public min(field: string): number; + + public maxRecord(field: string): { index: number; value: any }; + + public minRecord(field: string): { index: number; value: any }; + + public extractNumerical(field: string): number[]; + + /** + * Calculates the average numerical value of a property + * + * @param field - name of property in docs to average + * @returns average of property in all docs in the collection + */ + public avg(field: string): number; + + /** + * Calculate standard deviation of a field + * @param field + */ + public stdDev(field: string): number; + + /** + * @param field + */ + public mode(field: string): string | undefined; + + /** + * @param field - property name + */ + public median(field: string): number; } -interface LokiCryptedFileAdapterEncryptResult { - cipher: string; - keyDerivation: string; - keyLength: number; - iterations: number; - iv: string; - salt: string; - value: string; + +declare class KeyValueStore { + keys: any[]; + values: any[]; + + constructor(); + + public sort(a: any, b: any): -1 | 0 | 1; + + public setSort(fun: (target: any, test: any) => any): void; + + public bs(): (array: any[], item: any) => { found: boolean; index: number }; + + public set(key: any, value: any): void; + + public get(key: any): any[]; } -/* ======== END loki-crypted-file-adapter.js ======== */ +declare class UniqueIndex { + field: keyof E; + keyMap: { [fieldValue: string]: E/*{ $loki: number }*/ | undefined }; + lokiMap: { [$loki: number]: string | number | undefined }; -/* ======== loki-angular.js ======== */ -/* introduces a angular module named lokijs that returns the 'lokijs' module - var module = angular.module('lokijs', []) - .factory('Loki', function Loki() { - return lokijs; - }); - return module; -*/ -/* ======== END loki-angular.js ======== */ + constructor(uniqueField: keyof E); + + public set(obj: E/*{ $loki: number }*/): void; + + public get(key: string | number): E | undefined; + + public byId(id: number): E | undefined; + + /** + * Updates a document's unique index given an updated object. + * @param {Object} obj Original document object + * @param {Object} doc New document object (likely the same as obj) + */ + public update(obj: E/*{ $loki: number }*/, doc: any): void; + + public remove(key: string): void; + + public clear(): void; +} +declare class ExactIndex { + field: keyof E; + index: { [key: string]: E[] | undefined }; -/* ======== jquery-sync-adapter.js ======== */ + constructor(exactField: keyof E); -/** LokiJS JquerySyncAdapter - * A remote sync adapter example for LokiJS + // add the value you want returned to the key in the index + public set(key: string | number, val: E): void; + + // remove the value from the index, if the value was the last one, remove the key + public remove(key: string | number, val: E): void; + + // get the values related to the key, could be more than one + public get(key: string | number): E[] | undefined; + + // clear will zap the index + public clear(key?: null): void; +} + + + +declare class SortedIndex { + field: string; + keys: any[]; + values: any[]; + + constructor(sortedField: string); + + // set the default sort + public sort(a: any, b: any): -1 | 0 | 1; + + public bs(): (array: any[], item: any) => { found: boolean; index: number }; + + // and allow override of the default sort + public setSort(fun: (target: any, test: any) => number): void; + + // add the value you want returned to the key in the index + public set(key: any, value: any): void; + + // get all values which have a key == the given key + public get(key: any): any[]; + + // get all values which have a key < the given key + public getLt(key: any): any[]; + + // get all values which have a key > the given key + public getGt(key: any): any[]; + + // get all vals from start to end + public getAll(key: any, start: number, end: number): any[]; + + // just in case someone wants to do something smart with ranges + public getPos(key: any): { found: boolean; index: number }; + + // remove the value from the index, if the value was the last one, remove the key + public remove(key: any, value: any): void; + + // clear will zap the index + public clear(): void; +} + + +// type aliases to allow the nested classes inside LokiConstructor to extend classes sharing them same name(s) as themselves +declare class _Collection extends Collection { } +declare class _KeyValueStore extends KeyValueStore { } +declare class _LokiMemoryAdapter extends LokiMemoryAdapter { } +declare class _LokiPartitioningAdapter extends LokiPartitioningAdapter { } +declare class _LokiLocalStorageAdapter extends LokiLocalStorageAdapter { } +declare class _LokiFsAdapter extends LokiFsAdapter { } + + +/** + * LokiJS + * A lightweight document oriented javascript database * @author Joe Minichino */ - -/** this adapter assumes an object options is passed, - * containing the following properties: - * ajaxLib: jquery or compatible ajax library - * save: { url: the url to save to, dataType [optional]: json|xml|etc., type [optional]: POST|GET|PUT} - * load: { url: the url to load from, dataType [optional]: json|xml| etc., type [optional]: POST|GET|PUT } - */ -interface LokiJquerySyncAdapter { - options: LokiJquerySyncAdapterOptions - - new (options: LokiJquerySyncAdapterOptions): LokiJquerySyncAdapter; - - saveDatabase(name: string, data: any, callback?: (data: any, textStatus: string, xhr: XMLHttpRequest) => any): void; - - loadDatabase(name: string, callback?: (data: any, textStatus: string, xhr: XMLHttpRequest) => any): void; +declare class LokiConstructor extends Loki { + constructor(filename: string, options?: Partial & Partial & Partial); } - - -interface LokiJquerySyncAdapterOptions { - ajaxLib: { ajax(options: any): any; }; - save: { - url: any; - type?: string; /*'GET', 'POST, 'DELETE', etc.*/ - dataType?: string; /*'json', 'xml', etc.*/ +declare module LokiConstructor { + export var persistenceAdapters: { + fs: _LokiFsAdapter, + localStorage: _LokiLocalStorageAdapter }; - load: { - url: any; - type?: string; /*'GET', 'POST, 'DELETE', etc.*/ - dataType?: string; /*'json', 'xml', etc.*/ - }; -} + export function aeq(prop1: any, prop2: any): boolean; -interface LokiJquerySyncAdapterError extends Error { - name: string; // "JquerySyncAdapterError" - message: any; + function lt(prop1: any, prop2: any, equal?: boolean): boolean; - new (message: any): LokiJquerySyncAdapterError; -} -/* ======== END jquery-sync-adapter.js ======== */ + function gt(prop1: any, prop2: any, equal?: boolean): boolean; + export var LokiOps: LokiOps; -declare var LokiCryptedFileAdapterConstructor: { - new (): LokiCryptedFileAdapter; -} + export class Collection extends _Collection { } -declare module "lokiCryptedFileAdapter" { - export = LokiCryptedFileAdapterConstructor; -} + export class KeyValueStore extends _KeyValueStore { } + export class LokiMemoryAdapter extends _LokiMemoryAdapter { } -declare var LokiIndexedAdapterConstructor: { - new (filename: string): LokiIndexedAdapter; -} + export class LokiPartitioningAdapter extends _LokiPartitioningAdapter { } -declare module "loki-indexed-adapter" { - export = LokiIndexedAdapterConstructor; -} + export class LokiLocalStorageAdapter extends _LokiLocalStorageAdapter { } - -declare var LokiConstructor: { - new (filename: string, options?: LokiConfigureOptions): Loki; - LokiOps: LokiOps; - Collection: LokiCollection; - KeyValueStore: LokiKeyValueStore; + export class LokiFsAdapter extends _LokiFsAdapter { } } declare module "lokijs" { diff --git a/types/lokijs/lokijs-tests.ts b/types/lokijs/lokijs-tests.ts index 2e08370c02..167adba4ad 100644 --- a/types/lokijs/lokijs-tests.ts +++ b/types/lokijs/lokijs-tests.ts @@ -37,10 +37,10 @@ class QueenAnt extends Ant { class AntColony { - ants: LokiCollection; - queens: LokiCollection; + ants: Loki.Collection; + queens: Loki.Collection; - constructor(ants?: LokiCollection, queens?: LokiCollection) { + constructor(ants: Loki.Collection, queens: Loki.Collection) { this.ants = ants; this.queens = queens; } diff --git a/types/lokijs/tsconfig.json b/types/lokijs/tsconfig.json index bd01821699..96175c28a4 100644 --- a/types/lokijs/tsconfig.json +++ b/types/lokijs/tsconfig.json @@ -7,7 +7,7 @@ ], "noImplicitAny": true, "noImplicitThis": true, - "strictNullChecks": false, + "strictNullChecks": true, "strictFunctionTypes": true, "baseUrl": "../", "typeRoots": [ diff --git a/types/lolex/index.d.ts b/types/lolex/index.d.ts index 510cb911ec..68f87793d9 100644 --- a/types/lolex/index.d.ts +++ b/types/lolex/index.d.ts @@ -217,4 +217,4 @@ export interface LolexInstallOpts { * @param toFake Names of methods that should be faked. * @type TClock Type of clock to create. */ -export declare function install(opts: LolexInstallOpts): TClock; +export declare function install(opts?: LolexInstallOpts): TClock; diff --git a/types/lozad/index.d.ts b/types/lozad/index.d.ts index eb0213f6c3..6257c47043 100644 --- a/types/lozad/index.d.ts +++ b/types/lozad/index.d.ts @@ -1,25 +1,25 @@ -// Type definitions for lozad 1.0 +// Type definitions for lozad 1.1 // Project: https://github.com/ApoorvSaxena/lozad.js // Definitions by: York Yao // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -interface Option { - rootMargin?: string; - threshold?: number; - load?(element: HTMLElement | HTMLCanvasElement): void; -} - -interface Observer { - observe(): void; -} - -declare function lozad(selector?: string, options?: Option): Observer; - declare namespace lozad { + interface Option { + rootMargin?: string; + threshold?: number; + load?(element: HTMLElement | HTMLCanvasElement): void; + } + + interface Observer { + observe(): void; + } + const prototype: { }; } +declare function lozad(selector?: string, options?: lozad.Option): lozad.Observer; + export as namespace lozad; export = lozad; diff --git a/types/lunr/index.d.ts b/types/lunr/index.d.ts index 514a8fa578..e16851b52b 100644 --- a/types/lunr/index.d.ts +++ b/types/lunr/index.d.ts @@ -626,6 +626,19 @@ declare namespace lunr { */ function stemmer(token: Token): Token; + /** + * lunr.generateStopWordFilter builds a stopWordFilter function from the provided + * list of stop words. + * + * The built in lunr.stopWordFilter is built using this generator and can be used + * to generate custom stopWordFilters for applications or non English languages. + * + * @param stopWords - The list of stop words + * @see lunr.Pipeline + * @see lunr.stopWordFilter + */ + function generateStopWordFilter(stopWords: string[]): PipelineFunction; + /** * lunr.stopWordFilter is an English language stop word list filter, any words * contained in the list will not be passed through the filter. @@ -784,7 +797,7 @@ declare namespace lunr { * * @see lunr.tokenizer */ - const separator: RegExp; + let separator: RegExp; } /** diff --git a/types/mapbox-gl/index.d.ts b/types/mapbox-gl/index.d.ts index ddaafced3d..520f267b5f 100644 --- a/types/mapbox-gl/index.d.ts +++ b/types/mapbox-gl/index.d.ts @@ -1,4 +1,4 @@ -// Type definitions for Mapbox GL JS v0.41.0 +// Type definitions for Mapbox GL JS v0.42.2 // Project: https://github.com/mapbox/mapbox-gl-js // Definitions by: Dominik Bruderer , Patrick Reames // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped @@ -7,1080 +7,1110 @@ /// declare namespace mapboxgl { - let accessToken: string; - let version: string; - export function supported(options?: {failIfMajorPerformanceCaveat?: boolean}): boolean; - export function setRTLTextPlugin(pluginURL: string, callback: Function): void; + let accessToken: string; + let version: string; - type LngLatLike = number[] | LngLat; - type LngLatBoundsLike = number[][] | LngLatLike[] | LngLatBounds; - type PointLike = number[] | Point; + export function supported(options?: { failIfMajorPerformanceCaveat?: boolean }): boolean; - /** - * Map - */ - export class Map extends Evented { - constructor(options?: MapboxOptions); + export function setRTLTextPlugin(pluginURL: string, callback: Function): void; - addControl(control: Control, position?: 'top-right' | 'top-left' | 'bottom-right' | 'bottom-left'): this; + type LngLatLike = number[] | LngLat; + type LngLatBoundsLike = number[][] | LngLatLike[] | LngLatBounds; + type PointLike = number[] | Point; + type Expression = any[]; - removeControl(control: Control): this; + /** + * Map + */ + export class Map extends Evented { + constructor(options?: MapboxOptions); - addClass(klass: string, options?: mapboxgl.StyleOptions): this; + addControl(control: Control, position?: 'top-right' | 'top-left' | 'bottom-right' | 'bottom-left'): this; - removeClass(klass: string, options?: mapboxgl.StyleOptions): this; + removeControl(control: Control): this; - setClasses(klasses: string[], options?: mapboxgl.StyleOptions): this; + addClass(klass: string, options?: mapboxgl.StyleOptions): this; - hasClass(klass: string): boolean; + removeClass(klass: string, options?: mapboxgl.StyleOptions): this; - getClasses(): string[]; + setClasses(klasses: string[], options?: mapboxgl.StyleOptions): this; - resize(): this; + hasClass(klass: string): boolean; - getBounds(): mapboxgl.LngLatBounds; + getClasses(): string[]; - setMaxBounds(lnglatbounds?: LngLatBoundsLike): this; + resize(): this; - setMinZoom(minZoom?: number): this; + getBounds(): mapboxgl.LngLatBounds; - getMinZoom(): number; + setMaxBounds(lnglatbounds?: LngLatBoundsLike): this; - setMaxZoom(maxZoom?: number): this; + setMinZoom(minZoom?: number): this; - getMaxZoom(): number; + getMinZoom(): number; - project(lnglat: LngLatLike): mapboxgl.Point; + setMaxZoom(maxZoom?: number): this; - unproject(point: PointLike): mapboxgl.LngLat; + getMaxZoom(): number; - queryRenderedFeatures(pointOrBox?: PointLike | PointLike[], parameters?: {layers?: string[], filter?: any[]}): GeoJSON.Feature[]; + project(lnglat: LngLatLike): mapboxgl.Point; - querySourceFeatures(sourceID: string, parameters?: {sourceLayer?: string, filter?: any[]}): GeoJSON.Feature[]; + unproject(point: PointLike): mapboxgl.LngLat; - setStyle(style: mapboxgl.Style | string): this; + queryRenderedFeatures(pointOrBox?: PointLike | PointLike[], parameters?: { layers?: string[], filter?: any[] }): GeoJSON.Feature[]; - getStyle(): mapboxgl.Style; + querySourceFeatures(sourceID: string, parameters?: { sourceLayer?: string, filter?: any[] }): GeoJSON.Feature[]; - isStyleLoaded(): boolean; + setStyle(style: mapboxgl.Style | string): this; - addSource(id: string, source: VectorSource | RasterSource | GeoJSONSource | ImageSource | VideoSource | GeoJSONSourceRaw): this; + getStyle(): mapboxgl.Style; - isSourceLoaded(id: string): boolean; + isStyleLoaded(): boolean; - areTilesLoaded(): boolean; + addSource(id: string, source: VectorSource | RasterSource | GeoJSONSource | ImageSource | VideoSource | GeoJSONSourceRaw): this; - removeSource(id: string): this; + isSourceLoaded(id: string): boolean; - getSource(id: string): VectorSource | RasterSource | GeoJSONSource | ImageSource | VideoSource; + areTilesLoaded(): boolean; - addImage(name: string, image: HTMLImageElement | ArrayBufferView, options?: {width?: number, height?: number, pixelRatio?: number}): this; + removeSource(id: string): this; - removeImage(name: string): this; + getSource(id: string): VectorSource | RasterSource | GeoJSONSource | ImageSource | VideoSource; - loadImage(url: string, callback: Function): this; + addImage(name: string, image: HTMLImageElement | ArrayBufferView, options?: { width?: number, height?: number, pixelRatio?: number }): this; - addLayer(layer: mapboxgl.Layer, before?: string): this; + removeImage(name: string): this; - moveLayer(id: string, beforeId?: string): this; + loadImage(url: string, callback: Function): this; - removeLayer(id: string): this; + addLayer(layer: mapboxgl.Layer, before?: string): this; - getLayer(id: string): mapboxgl.Layer; + moveLayer(id: string, beforeId?: string): this; - setFilter(layer: string, filter?: any[]): this; + removeLayer(id: string): this; - setLayerZoomRange(layerId: string, minzoom: number, maxzoom: number): this; + getLayer(id: string): mapboxgl.Layer; - getFilter(layer: string): any[]; + setFilter(layer: string, filter?: any[]): this; - setPaintProperty(layer: string, name: string, value: any, klass?: string): this; + setLayerZoomRange(layerId: string, minzoom: number, maxzoom: number): this; - getPaintProperty(layer: string, name: string, klass?: string): any; + getFilter(layer: string): any[]; - setLayoutProperty(layer: string, name: string, value: any): this; + setPaintProperty(layer: string, name: string, value: any, klass?: string): this; - getLayoutProperty(layer: string, name: string, klass?: string): any; + getPaintProperty(layer: string, name: string, klass?: string): any; - setLight(options: mapboxgl.Light, lightOptions: any): this; + setLayoutProperty(layer: string, name: string, value: any): this; - getLight(): mapboxgl.Light; + getLayoutProperty(layer: string, name: string, klass?: string): any; - getContainer(): HTMLElement; + setLight(options: mapboxgl.Light, lightOptions: any): this; - getCanvasContainer(): HTMLElement; + getLight(): mapboxgl.Light; - getCanvas(): HTMLCanvasElement; + getContainer(): HTMLElement; - loaded(): boolean; + getCanvasContainer(): HTMLElement; - remove(): void; + getCanvas(): HTMLCanvasElement; - onError(): void; + loaded(): boolean; - showTileBoundaries: boolean; + remove(): void; - showCollisionBoxes: boolean; + onError(): void; - repaint: boolean; + showTileBoundaries: boolean; - getCenter(): mapboxgl.LngLat; + showCollisionBoxes: boolean; - setCenter(center: LngLatLike, eventData?: mapboxgl.EventData): this; + repaint: boolean; - panBy(offset: number[], options?: mapboxgl.AnimationOptions, eventData?: mapboxgl.EventData): this; + getCenter(): mapboxgl.LngLat; - panTo(lnglat: LngLatLike, options?: mapboxgl.AnimationOptions, eventdata?: mapboxgl.EventData): this; + setCenter(center: LngLatLike, eventData?: mapboxgl.EventData): this; - getZoom(): number; + panBy(offset: number[], options?: mapboxgl.AnimationOptions, eventData?: mapboxgl.EventData): this; - setZoom(zoom: number, eventData?: mapboxgl.EventData): this; + panTo(lnglat: LngLatLike, options?: mapboxgl.AnimationOptions, eventdata?: mapboxgl.EventData): this; - zoomTo(zoom: number, options?: mapboxgl.AnimationOptions, eventData?: mapboxgl.EventData): this; + getZoom(): number; - zoomIn(options?: mapboxgl.AnimationOptions, eventData?: mapboxgl.EventData): this; + setZoom(zoom: number, eventData?: mapboxgl.EventData): this; - zoomOut(options?: mapboxgl.AnimationOptions, eventData?: mapboxgl.EventData): this; + zoomTo(zoom: number, options?: mapboxgl.AnimationOptions, eventData?: mapboxgl.EventData): this; - getBearing(): number; + zoomIn(options?: mapboxgl.AnimationOptions, eventData?: mapboxgl.EventData): this; - setBearing(bearing: number, eventData?: mapboxgl.EventData): this; + zoomOut(options?: mapboxgl.AnimationOptions, eventData?: mapboxgl.EventData): this; - rotateTo(bearing: number, options?: mapboxgl.AnimationOptions, eventData?: EventData): this; + getBearing(): number; - resetNorth(options?: mapboxgl.AnimationOptions, eventData?: mapboxgl.EventData): this; + setBearing(bearing: number, eventData?: mapboxgl.EventData): this; - snapToNorth(options?: mapboxgl.AnimationOptions, eventData?: mapboxgl.EventData): this; + rotateTo(bearing: number, options?: mapboxgl.AnimationOptions, eventData?: EventData): this; - getPitch(): number; + resetNorth(options?: mapboxgl.AnimationOptions, eventData?: mapboxgl.EventData): this; - setPitch(pitch: number, eventData?: EventData): this; + snapToNorth(options?: mapboxgl.AnimationOptions, eventData?: mapboxgl.EventData): this; - fitBounds(bounds: LngLatBoundsLike, options?: { linear?: boolean, easing?: Function, padding?: number | mapboxgl.PaddingOptions, offset?: PointLike, maxZoom?: number }, eventData?: mapboxgl.EventData): this; + getPitch(): number; - jumpTo(options: mapboxgl.CameraOptions, eventData?: mapboxgl.EventData): this; + setPitch(pitch: number, eventData?: EventData): this; - easeTo(options: mapboxgl.CameraOptions | mapboxgl.AnimationOptions, eventData?: mapboxgl.EventData): this; + fitBounds(bounds: LngLatBoundsLike, options?: { linear?: boolean, easing?: Function, padding?: number | mapboxgl.PaddingOptions, offset?: PointLike, maxZoom?: number }, eventData?: mapboxgl.EventData): this; - flyTo(options: mapboxgl.FlyToOptions, eventData?: mapboxgl.EventData): this; + jumpTo(options: mapboxgl.CameraOptions, eventData?: mapboxgl.EventData): this; - isMoving(): boolean; + easeTo(options: mapboxgl.CameraOptions | mapboxgl.AnimationOptions, eventData?: mapboxgl.EventData): this; - stop(): this; + flyTo(options: mapboxgl.FlyToOptions, eventData?: mapboxgl.EventData): this; - scrollZoom: ScrollZoomHandler; + isMoving(): boolean; - boxZoom: BoxZoomHandler; + stop(): this; - dragRotate: DragRotateHandler; + scrollZoom: ScrollZoomHandler; - dragPan: DragPanHandler; + boxZoom: BoxZoomHandler; - keyboard: KeyboardHandler; + dragRotate: DragRotateHandler; - doubleClickZoom: DoubleClickZoomHandler; + dragPan: DragPanHandler; - touchZoomRotate: TouchZoomRotateHandler; - } + keyboard: KeyboardHandler; - export interface MapboxOptions { - /** If true, an attribution control will be added to the map. */ - attributionControl?: boolean; + doubleClickZoom: DoubleClickZoomHandler; - bearing?: number; + touchZoomRotate: TouchZoomRotateHandler; + } - /** Snap to north threshold in degrees. */ - bearingSnap?: number; + export interface MapboxOptions { + /** If true, an attribution control will be added to the map. */ + attributionControl?: boolean; - /** If true, enable the "box zoom" interaction (see BoxZoomHandler) */ - boxZoom?: boolean; + bearing?: number; - /** initial map center */ - center?: LngLatLike; + /** Snap to north threshold in degrees. */ + bearingSnap?: number; - /** Style class names with which to initialize the map */ - classes?: string[]; + /** If true, enable the "box zoom" interaction (see BoxZoomHandler) */ + boxZoom?: boolean; - /** ID of the container element */ - container?: string | Element; + /** initial map center */ + center?: LngLatLike; - /** If true, enable the "drag to pan" interaction (see DragPanHandler). */ - dragPan?: boolean; + /** Style class names with which to initialize the map */ + classes?: string[]; - /** If true, enable the "drag to rotate" interaction (see DragRotateHandler). */ - dragRotate?: boolean; + /** ID of the container element */ + container?: string | Element; - /** If true, enable the "double click to zoom" interaction (see DoubleClickZoomHandler). */ - doubleClickZoom?: boolean; + /** If true, enable the "drag to pan" interaction (see DragPanHandler). */ + dragPan?: boolean; - /** If true, the map will track and update the page URL according to map position */ - hash?: boolean; + /** If true, enable the "drag to rotate" interaction (see DragRotateHandler). */ + dragRotate?: boolean; - /** If true, map creation will fail if the implementation determines that the performance of the created WebGL context would be dramatically lower than expected. */ - failIfMayorPerformanceCaveat?: boolean; + /** If true, enable the "double click to zoom" interaction (see DoubleClickZoomHandler). */ + doubleClickZoom?: boolean; - /** If false, no mouse, touch, or keyboard listeners are attached to the map, so it will not respond to input */ - interactive?: boolean; + /** If true, the map will track and update the page URL according to map position */ + hash?: boolean; - /** If true, enable keyboard shortcuts (see KeyboardHandler). */ - keyboard?: boolean; + /** If true, map creation will fail if the implementation determines that the performance of the created WebGL context would be dramatically lower than expected. */ + failIfMayorPerformanceCaveat?: boolean; - logoPosition?: 'top-left' | 'top-right' | 'bottom-left' | 'bottom-right'; + /** If false, no mouse, touch, or keyboard listeners are attached to the map, so it will not respond to input */ + interactive?: boolean; - /** If set, the map is constrained to the given bounds. */ - maxBounds?: LngLatBoundsLike; + /** If true, enable keyboard shortcuts (see KeyboardHandler). */ + keyboard?: boolean; - /** Maximum zoom of the map */ - maxZoom?: number; + logoPosition?: 'top-left' | 'top-right' | 'bottom-left' | 'bottom-right'; - /** Minimum zoom of the map */ - minZoom?: number; + /** If set, the map is constrained to the given bounds. */ + maxBounds?: LngLatBoundsLike; - /** If true, The maps canvas can be exported to a PNG using map.getCanvas().toDataURL();. This is false by default as a performance optimization. */ - preserveDrawingBuffer?: boolean; + /** Maximum zoom of the map */ + maxZoom?: number; - pitch?: number; + /** Minimum zoom of the map */ + minZoom?: number; - refreshExpiredTiles?: boolean; + /** If true, The maps canvas can be exported to a PNG using map.getCanvas().toDataURL();. This is false by default as a performance optimization. */ + preserveDrawingBuffer?: boolean; - renderWorldCopies?: boolean; + pitch?: number; - /** If true, enable the "scroll to zoom" interaction */ - scrollZoom?: boolean; + refreshExpiredTiles?: boolean; - /** stylesheet location */ - style?: mapboxgl.Style | string; + renderWorldCopies?: boolean; - /** If true, the map will automatically resize when the browser window resizes */ - trackResize?: boolean; + /** If true, enable the "scroll to zoom" interaction */ + scrollZoom?: boolean; - /** If true, enable the "pinch to rotate and zoom" interaction (see TouchZoomRotateHandler). */ - touchZoomRotate?: boolean; + /** stylesheet location */ + style?: mapboxgl.Style | string; - /** Initial zoom level */ - zoom?: number; + /** If true, the map will automatically resize when the browser window resizes */ + trackResize?: boolean; - /** Maximum tile cache size for each layer. */ - maxTileCacheSize?: number; - } + /** If true, enable the "pinch to rotate and zoom" interaction (see TouchZoomRotateHandler). */ + touchZoomRotate?: boolean; - export interface PaddingOptions { - top: number; - bottom: number; - left: number; - right: number; - } + /** Initial zoom level */ + zoom?: number; - /** - * BoxZoomHandler - */ - export class BoxZoomHandler { - constructor(map: mapboxgl.Map); + /** Maximum tile cache size for each layer. */ + maxTileCacheSize?: number; + } - isEnabled(): boolean; + export interface PaddingOptions { + top: number; + bottom: number; + left: number; + right: number; + } - isActive(): boolean; + /** + * BoxZoomHandler + */ + export class BoxZoomHandler { + constructor(map: mapboxgl.Map); - enable(): void; + isEnabled(): boolean; - disable(): void; - } + isActive(): boolean; - /** - * ScrollZoomHandler - */ - export class ScrollZoomHandler { - constructor(map: mapboxgl.Map); + enable(): void; - isEnabled(): boolean; + disable(): void; + } - enable(): void; + /** + * ScrollZoomHandler + */ + export class ScrollZoomHandler { + constructor(map: mapboxgl.Map); - disable(): void; - } + isEnabled(): boolean; - /** - * DragPenHandler - */ - export class DragPanHandler { - constructor(map: mapboxgl.Map); + enable(): void; - isEnabled(): boolean; + disable(): void; + } - isActive(): boolean; + /** + * DragPenHandler + */ + export class DragPanHandler { + constructor(map: mapboxgl.Map); - enable(): void; + isEnabled(): boolean; - disable(): void; - } + isActive(): boolean; - /** - * DragRotateHandler - */ - export class DragRotateHandler { - constructor(map: mapboxgl.Map, options?: {bearingSnap?: number, pitchWithRotate?: boolean}); + enable(): void; - isEnabled(): boolean; + disable(): void; + } - isActive(): boolean; + /** + * DragRotateHandler + */ + export class DragRotateHandler { + constructor(map: mapboxgl.Map, options?: { bearingSnap?: number, pitchWithRotate?: boolean }); - enable(): void; + isEnabled(): boolean; - disable(): void; - } + isActive(): boolean; - /** - * KeyboardHandler - */ - export class KeyboardHandler { - constructor(map: mapboxgl.Map); + enable(): void; - isEnabled(): boolean; + disable(): void; + } - enable(): void; + /** + * KeyboardHandler + */ + export class KeyboardHandler { + constructor(map: mapboxgl.Map); - disable(): void; - } + isEnabled(): boolean; - /** - * DoubleClickZoomHandler - */ - export class DoubleClickZoomHandler { - constructor(map: mapboxgl.Map); + enable(): void; - isEnabled(): boolean; + disable(): void; + } - enable(): void; + /** + * DoubleClickZoomHandler + */ + export class DoubleClickZoomHandler { + constructor(map: mapboxgl.Map); - disable(): void; - } + isEnabled(): boolean; - /** - * TouchZoomRotateHandler - */ - export class TouchZoomRotateHandler { - constructor(map: mapboxgl.Map); + enable(): void; - isEnabled(): boolean; + disable(): void; + } - enable(): void; + /** + * TouchZoomRotateHandler + */ + export class TouchZoomRotateHandler { + constructor(map: mapboxgl.Map); - disable(): void; + isEnabled(): boolean; - disableRotation(): void; + enable(): void; - enableRotation(): void; - } + disable(): void; - export interface IControl { - onAdd(map: Map): HTMLElement; - onRemove(map: Map): any; - getDefaultPosition(): string; - } + disableRotation(): void; - /** - * Control - */ - export class Control extends Evented { - } + enableRotation(): void; + } - /** - * Navigation - */ - export class NavigationControl extends Control { - constructor(); - } + export interface IControl { + onAdd(map: Map): HTMLElement; - export class PositionOptions { - enableHighAccuracy?: boolean; - timeout?: number; - maximumAge?: number; - } + onRemove(map: Map): any; - export class FitBoundsOptions { - maxZoom?: number; - } + getDefaultPosition(): string; + } - /** - * Geolocate - */ - export class GeolocateControl extends Control { - constructor(options?: {positionOptions?: PositionOptions, fitBoundsOptions?: FitBoundsOptions, trackUserLocation?: boolean, showUserLocation?: boolean}); - } + /** + * Control + */ + export class Control extends Evented { + } - /** - * Attribution - */ - export class AttributionControl extends Control { - constructor(options?: {compact?: boolean}); - } + /** + * Navigation + */ + export class NavigationControl extends Control { + constructor(); + } - /** - * Scale - */ - export class ScaleControl extends Control { - constructor(options?: {maxWidth?: number, unit?: string}) - } + export class PositionOptions { + enableHighAccuracy?: boolean; + timeout?: number; + maximumAge?: number; + } - /** - * Fullscreen - */ - export class FullscreenControl extends Control { - constructor(); - } + export class FitBoundsOptions { + maxZoom?: number; + } - /** - * Popup - */ - export class Popup extends Evented { - constructor(options?: mapboxgl.PopupOptions); + /** + * Geolocate + */ + export class GeolocateControl extends Control { + constructor(options?: { positionOptions?: PositionOptions, fitBoundsOptions?: FitBoundsOptions, trackUserLocation?: boolean, showUserLocation?: boolean }); + } - addTo(map: mapboxgl.Map): this; + /** + * Attribution + */ + export class AttributionControl extends Control { + constructor(options?: { compact?: boolean }); + } - isOpen(): boolean; + /** + * Scale + */ + export class ScaleControl extends Control { + constructor(options?: { maxWidth?: number, unit?: string }) + } - remove(): this; + /** + * Fullscreen + */ + export class FullscreenControl extends Control { + constructor(); + } - getLngLat(): mapboxgl.LngLat; + /** + * Popup + */ + export class Popup extends Evented { + constructor(options?: mapboxgl.PopupOptions); - setLngLat(lnglat: LngLatLike): this; + addTo(map: mapboxgl.Map): this; - setText(text: string): this; + isOpen(): boolean; - setHTML(html: string): this; + remove(): this; - setDOMContent(htmlNode: Node): this; - } + getLngLat(): mapboxgl.LngLat; - export interface PopupOptions { - closeButton?: boolean; + setLngLat(lnglat: LngLatLike): this; - closeOnClick?: boolean; + setText(text: string): this; - anchor?: 'top' | 'bottom' | 'left' | 'right' | 'top-left' | 'top-right' | 'bottom-left' | 'bottom-right'; + setHTML(html: string): this; - offset?: number | PointLike | { [key:string]: PointLike;}; - } + setDOMContent(htmlNode: Node): this; + } - export interface Style { - bearing?: number; - center?: number[]; - glyphs?: string; - layers?: Layer[]; - metadata?: any; - name?: string; - pitch?: number; - light?: Light; - sources?: any; - sprite?: string; - transition?: Transition; - version: number; - zoom?: number; - } + export interface PopupOptions { + closeButton?: boolean; - export interface Transition { - delay?: number; - duration?: number; - } + closeOnClick?: boolean; - export interface Light { - "anchor"?: "map" | "viewport"; - "position"?: number[]; - "color"?: string; - "intensity"?: number; - } + anchor?: 'top' | 'bottom' | 'left' | 'right' | 'top-left' | 'top-right' | 'bottom-left' | 'bottom-right'; - export interface Source { - type: "vector" | "raster" | "geojson" | "image" | "video" | "canvas"; - } + offset?: number | PointLike | { [key: string]: PointLike; }; + } - /** - * GeoJSONSource - */ + export interface Style { + bearing?: number; + center?: number[]; + glyphs?: string; + layers?: Layer[]; + metadata?: any; + name?: string; + pitch?: number; + light?: Light; + sources?: any; + sprite?: string; + transition?: Transition; + version: number; + zoom?: number; + } - export interface GeoJSONSourceRaw extends Source, GeoJSONSourceOptions { - type: "geojson"; - } + export interface Transition { + delay?: number; + duration?: number; + } - export class GeoJSONSource implements GeoJSONSourceRaw { - type: "geojson"; + export interface Light { + 'anchor'?: 'map' | 'viewport'; + 'position'?: number[]; + 'color'?: string; + 'intensity'?: number; + } - constructor(options?: mapboxgl.GeoJSONSourceOptions); + export interface Source { + type: 'vector' | 'raster' | 'geojson' | 'image' | 'video' | 'canvas'; + } - setData(data: GeoJSON.Feature | GeoJSON.FeatureCollection | String): this; - } + /** + * GeoJSONSource + */ - export interface GeoJSONSourceOptions { - data?: GeoJSON.Feature | GeoJSON.FeatureCollection | string; + export interface GeoJSONSourceRaw extends Source, GeoJSONSourceOptions { + type: 'geojson'; + } - maxzoom?: number; + export class GeoJSONSource implements GeoJSONSourceRaw { + type: 'geojson'; - buffer?: number; + constructor(options?: mapboxgl.GeoJSONSourceOptions); - tolerance?: number; + setData(data: GeoJSON.Feature | GeoJSON.FeatureCollection | String): this; + } - cluster?: number | boolean; + export interface GeoJSONSourceOptions { + data?: GeoJSON.Feature | GeoJSON.FeatureCollection | string; - clusterRadius?: number; + maxzoom?: number; - clusterMaxZoom?: number; - } + buffer?: number; - /** - * VideoSource - */ - export interface VideoSource extends VideoSourceOptions { } - export class VideoSource implements Source { - type: "video"; + tolerance?: number; - constructor(options?: mapboxgl.VideoSourceOptions); + cluster?: number | boolean; - getVideo(): HTMLVideoElement; + clusterRadius?: number; - setCoordinates(coordinates: number[][]): this; - } + clusterMaxZoom?: number; + } - export interface VideoSourceOptions { - urls?: string[]; + /** + * VideoSource + */ + export interface VideoSource extends VideoSourceOptions { + } - coordinates?: number[][]; - } + export class VideoSource implements Source { + type: 'video'; - /** - * ImageSource - */ - export interface ImageSource extends ImageSourceOptions { } - export class ImageSource implements Source { - type: "image"; + constructor(options?: mapboxgl.VideoSourceOptions); - constructor(options?: mapboxgl.ImageSourceOptions); + getVideo(): HTMLVideoElement; - setCoordinates(coordinates: number[][]): this; - } + setCoordinates(coordinates: number[][]): this; + } - export interface ImageSourceOptions { - url?: string; + export interface VideoSourceOptions { + urls?: string[]; - coordinates?: number[][]; - } + coordinates?: number[][]; + } - /** - * CanvasSource - */ - export class CanvasSource implements Source, CanvasSourceOptions { - type: "canvas"; + /** + * ImageSource + */ + export interface ImageSource extends ImageSourceOptions { + } - coordinates: number[][]; + export class ImageSource implements Source { + type: 'image'; - canvas: string; + constructor(options?: mapboxgl.ImageSourceOptions); - getCanvas(): HTMLCanvasElement; + setCoordinates(coordinates: number[][]): this; + } - setCoordinates(coordinates: number[][]): this; - } + export interface ImageSourceOptions { + url?: string; - export interface CanvasSourceOptions { - coordinates: number[][]; + coordinates?: number[][]; + } - animate?: boolean; + /** + * CanvasSource + */ + export class CanvasSource implements Source, CanvasSourceOptions { + type: 'canvas'; - canvas: string; - } + coordinates: number[][]; - interface VectorSource extends Source { - type: "vector"; - url?: string; - tiles?: string[]; - minzoom?: number; - maxzoom?: number; - } + canvas: string; - interface RasterSource extends Source { - type: "raster"; - url: string; - tiles?: string[]; - minzoom?: number; - maxzoom?: number; - tileSize?: number; - } + getCanvas(): HTMLCanvasElement; - /** - * LngLat - */ - export class LngLat { - lng: number; - lat: number; + setCoordinates(coordinates: number[][]): this; + } - constructor(lng: number, lat: number); + export interface CanvasSourceOptions { + coordinates: number[][]; - /** Return a new LngLat object whose longitude is wrapped to the range (-180, 180). */ - wrap(): mapboxgl.LngLat; + animate?: boolean; - /** Return a LngLat as an array */ - toArray(): number[]; + canvas: string; + } - /** Return a LngLat as a string */ - toString(): string; + interface VectorSource extends Source { + type: 'vector'; + url?: string; + tiles?: string[]; + minzoom?: number; + maxzoom?: number; + } - toBounds(radius: number): LngLatBounds; + interface RasterSource extends Source { + type: 'raster'; + url: string; + tiles?: string[]; + minzoom?: number; + maxzoom?: number; + tileSize?: number; + } - static convert(input: LngLatLike): mapboxgl.LngLat; - } + /** + * LngLat + */ + export class LngLat { + lng: number; + lat: number; - /** - * LngLatBounds - */ - export class LngLatBounds { - sw: LngLatLike; - ne: LngLatLike; - constructor(sw?: LngLatLike, ne?: LngLatLike); + constructor(lng: number, lat: number); - setNorthEast(ne: LngLatLike): this; + /** Return a new LngLat object whose longitude is wrapped to the range (-180, 180). */ + wrap(): mapboxgl.LngLat; - setSouthWest(sw: LngLatLike): this; + /** Return a LngLat as an array */ + toArray(): number[]; - /** Extend the bounds to include a given LngLat or LngLatBounds. */ - extend(obj: mapboxgl.LngLat | mapboxgl.LngLatBounds): this; + /** Return a LngLat as a string */ + toString(): string; - /** Get the point equidistant from this box's corners */ - getCenter(): mapboxgl.LngLat; + toBounds(radius: number): LngLatBounds; - /** Get southwest corner */ - getSouthWest(): mapboxgl.LngLat; + static convert(input: LngLatLike): mapboxgl.LngLat; + } - /** Get northeast corner */ - getNorthEast(): mapboxgl.LngLat; + /** + * LngLatBounds + */ + export class LngLatBounds { + sw: LngLatLike; + ne: LngLatLike; - /** Get northwest corner */ - getNorthWest(): mapboxgl.LngLat; + constructor(sw?: LngLatLike, ne?: LngLatLike); - /** Get southeast corner */ - getSouthEast(): mapboxgl.LngLat; + setNorthEast(ne: LngLatLike): this; - /** Get west edge longitude */ - getWest(): number; + setSouthWest(sw: LngLatLike): this; - /** Get south edge latitude */ - getSouth(): number; + /** Extend the bounds to include a given LngLat or LngLatBounds. */ + extend(obj: mapboxgl.LngLat | mapboxgl.LngLatBounds): this; - /** Get east edge longitude */ - getEast(): number; + /** Get the point equidistant from this box's corners */ + getCenter(): mapboxgl.LngLat; - /** Get north edge latitude */ - getNorth(): number; + /** Get southwest corner */ + getSouthWest(): mapboxgl.LngLat; - /** Returns a LngLatBounds as an array */ - toArray(): number[][]; + /** Get northeast corner */ + getNorthEast(): mapboxgl.LngLat; - /** Return a LngLatBounds as a string */ - toString(): string; + /** Get northwest corner */ + getNorthWest(): mapboxgl.LngLat; - /** Convert an array to a LngLatBounds object, or return an existing LngLatBounds object unchanged. */ - static convert(input: LngLatBoundsLike): mapboxgl.LngLatBounds; - } + /** Get southeast corner */ + getSouthEast(): mapboxgl.LngLat; - /** - * Point - */ - // Todo: Pull out class to seperate definition for Module "point-geometry" - export class Point { - x: number; - y: number; + /** Get west edge longitude */ + getWest(): number; - constructor(x: number, y: number); + /** Get south edge latitude */ + getSouth(): number; - clone(): Point; + /** Get east edge longitude */ + getEast(): number; - add(p: number): Point; + /** Get north edge latitude */ + getNorth(): number; - sub(p: number): Point; + /** Returns a LngLatBounds as an array */ + toArray(): number[][]; - mult(k: number): Point; + /** Return a LngLatBounds as a string */ + toString(): string; - div(k: number): Point; + /** Convert an array to a LngLatBounds object, or return an existing LngLatBounds object unchanged. */ + static convert(input: LngLatBoundsLike): mapboxgl.LngLatBounds; + } - rotate(a: number): Point; + /** + * Point + */ + // Todo: Pull out class to seperate definition for Module "point-geometry" + export class Point { + x: number; + y: number; - matMult(m: number): Point; + constructor(x: number, y: number); - unit(): Point; + clone(): Point; - perp(): Point; + add(p: number): Point; - round(): Point; + sub(p: number): Point; - mag(): number; + mult(k: number): Point; - equals(p: Point): boolean; + div(k: number): Point; - dist(p: Point): number; + rotate(a: number): Point; - distSqr(p: Point): number; + matMult(m: number): Point; - angle(): number; + unit(): Point; - angleTo(p: Point): number; + perp(): Point; - angleWidth(p: Point): number; + round(): Point; - angleWithSep(x: number, y: number): number; + mag(): number; - static convert(a: PointLike): Point; - } + equals(p: Point): boolean; - export class Marker { - constructor(element?: HTMLElement, options?: { offset?: PointLike }); + dist(p: Point): number; - addTo(map: Map): this; + distSqr(p: Point): number; - remove(): this; + angle(): number; - getLngLat(): LngLat; + angleTo(p: Point): number; - setLngLat(lngLat: LngLatLike): this; + angleWidth(p: Point): number; - setPopup(popup?: Popup): this; + angleWithSep(x: number, y: number): number; - getPopup(): Popup; + static convert(a: PointLike): Point; + } - togglePopup(): this; - } + export class Marker { + constructor(element?: HTMLElement, options?: { offset?: PointLike }); - /** - * Evented - */ - export class Evented { - on(type: string, listener: Function): this; + addTo(map: Map): this; - on(type: string, layer: string, listener: Function): this; + remove(): this; - off(type?: string | any, listener?: Function): this; + getLngLat(): LngLat; - off(type?: string | any, layer?: string, listener?: Function): this; + setLngLat(lngLat: LngLatLike): this; - once(type: string, listener: Function): this; + setPopup(popup?: Popup): this; - fire(type: string, data?: mapboxgl.EventData | Object): this; + getPopup(): Popup; - listens(type: string): boolean; - } + togglePopup(): this; + } - /** - * StyleOptions - */ - export interface StyleOptions { - transition?: boolean; - } - - /** - * EventData - */ - export class EventData { - type: string; - target: Map; - originalEvent: Event; - point: mapboxgl.Point; - lngLat: mapboxgl.LngLat; - } - - export class MapMouseEvent { - type: string; - target: Map; - originalEvent: MouseEvent; - point: mapboxgl.Point; - lngLat: mapboxgl.LngLat; - } - - export class MapTouchEvent { - type: string; - target: Map; - originalEvent: TouchEvent; - point: mapboxgl.Point; - lngLat: mapboxgl.LngLat; - points: Point[]; - lngLats: LngLat[]; - } - - export class MapBoxZoomEvent { - originalEvent: MouseEvent; - boxZoomBounds: LngLatBounds; - } - - export class MapDataEvent { - type: string; - dataType: "source" | "style" | "tile"; - isSourceLoaded?: boolean; - source?: mapboxgl.Source; - coord?: any; - } - - /** - * AnimationOptions - */ - export interface AnimationOptions { - /** Number in milliseconds */ - duration?: number; - easing?: Function; - /** point, origin of movement relative to map center */ - offset?: PointLike; - /** When set to false, no animation happens */ - animate?: boolean; - } - - /** - * CameraOptions - */ - export interface CameraOptions { - /** Map center */ - center?: LngLatLike; - /** Map zoom level */ - zoom?: number; - /** Map rotation bearing in degrees counter-clockwise from north */ - bearing?: number; - /** Map angle in degrees at which the camera is looking at the ground */ - pitch?: number; - /** If zooming, the zoom center (defaults to map center) */ - around?: LngLatLike; - } - - /** - * FlyToOptions - */ - export interface FlyToOptions extends AnimationOptions, CameraOptions { - curve?: number; - minZoom?: number; - speed?: number; - screenSpeed?: number; - easing?: Function; - } - - /** - * MapEvent - */ - export interface MapEvent { - resize?: void; - webglcontextlost?: {originalEvent: WebGLContextEvent}; - webglcontextrestored?: {originalEvent: WebGLContextEvent}; - remove?: void; - dataloading?: {data: mapboxgl.MapDataEvent}; - data?: {data: mapboxgl.MapDataEvent}; - render?: void; - contextmenu?: {data: mapboxgl.MapMouseEvent}; - dblclick?: {data: mapboxgl.MapMouseEvent}; - click?: {data: mapboxgl.MapMouseEvent}; - tiledataloading?: {data: mapboxgl.MapDataEvent}; - sourcedataloading?: {data: mapboxgl.MapDataEvent}; - styledataloading?: {data: mapboxgl.MapDataEvent}; - touchcancel?: {data: mapboxgl.MapTouchEvent}; - touchmove?: {data: mapboxgl.MapTouchEvent}; - touchend?: {data: mapboxgl.MapTouchEvent}; - touchstart?: {data: mapboxgl.MapTouchEvent}; - mousemove?: {data: mapboxgl.MapMouseEvent}; - mouseup?: {data: mapboxgl.MapMouseEvent}; - mousedown?: {data: mapboxgl.MapMouseEvent}; - moveend?: {data: mapboxgl.MapMouseEvent | mapboxgl.MapTouchEvent}; - move?: {data: mapboxgl.MapMouseEvent | mapboxgl.MapTouchEvent}; - movestart?: {data: mapboxgl.MapMouseEvent | mapboxgl.MapTouchEvent}; - mouseout?:{data: mapboxgl.MapMouseEvent}; - load?: void; - sourcedata?: {data: mapboxgl.MapDataEvent}; - styledata?: {data: mapboxgl.MapDataEvent}; - zoomend?: {data: mapboxgl.MapMouseEvent | mapboxgl.MapTouchEvent}; - zoom?: {data: mapboxgl.MapMouseEvent | mapboxgl.MapTouchEvent}; - zoomstart?: {data: mapboxgl.MapMouseEvent | mapboxgl.MapTouchEvent}; - boxzoomcancel?: {data: mapboxgl.MapBoxZoomEvent}; - boxzoomstart?: {data: mapboxgl.MapBoxZoomEvent}; - boxzoomend?: {data: mapboxgl.MapBoxZoomEvent}; - rotate?: {data: mapboxgl.MapMouseEvent | mapboxgl.MapTouchEvent}; - rotatestart?: {data: mapboxgl.MapMouseEvent | mapboxgl.MapTouchEvent}; - rotateend?: {data: mapboxgl.MapMouseEvent | mapboxgl.MapTouchEvent}; - drag?: {data: mapboxgl.MapMouseEvent | mapboxgl.MapTouchEvent}; - dragend?: {data: mapboxgl.MapMouseEvent | mapboxgl.MapTouchEvent}; - pitch?: {data: mapboxgl.EventData}; - } - - export interface Layer { - id: string; - type?: "fill" | "line" | "symbol" | "circle" | "fill-extrusion" | "raster" | "background" | "heatmap"; - - metadata?: any; - ref?: string; - - source?: string | VectorSource | RasterSource | GeoJSONSource | ImageSource | VideoSource | GeoJSONSourceRaw; - - "source-layer"?: string; - - minzoom?: number; - maxzoom?: number; - - interactive?: boolean; - - filter?: any[]; - layout?: BackgroundLayout | FillLayout | FillExtrusionLayout | LineLayout | SymbolLayout | RasterLayout | CircleLayout; - paint?: BackgroundPaint | FillPaint | FillExtrusionPaint | LinePaint | SymbolPaint | RasterPaint | CirclePaint; - } - - export interface StyleFunction { - stops?: any[][]; - property?: string; - base?: number; - type?: "identity" | "exponential" | "interval" | "categorical"; - default?: any; - "colorSpace"?: "rgb" | "lab" | "interval"; - } - - export interface BackgroundLayout { - visibility?: "visible" | "none"; - } - export interface BackgroundPaint { - "background-color"?: string; - "background-pattern"?: string; - "background-opacity"?: number; - } - - export interface FillLayout { - visibility?: "visible" | "none"; - } - export interface FillPaint { - "fill-antialias"?: boolean; - "fill-opacity"?: number | StyleFunction; - "fill-color"?: string | StyleFunction; - "fill-outline-color"?: string | StyleFunction; - "fill-translate"?: number[]; - "fill-translate-anchor"?: "map" | "viewport"; - "fill-pattern"?: "string"; - } - - export interface FillExtrusionLayout { - visibility?: "visible" | "none"; - } - export interface FillExtrusionPaint { - "fill-extrusion-opacity"?: number; - "fill-extrusion-color"?: string | StyleFunction; - "fill-extrusion-translate"?: number[]; - "fill-extrusion-translate-anchor"?: "map" | "viewport"; - "fill-extrusion-pattern"?: string; - "fill-extrusion-height"?: number | StyleFunction; - "fill-extrusion-base"?: number | StyleFunction; - } - - export interface LineLayout { - visibility?: "visible" | "none"; - - "line-cap"?: "butt" | "round" | "square"; - "line-join"?: "bevel" | "round" | "miter"; - "line-miter-limit"?: number; - "line-round-limit"?: number; - } - export interface LinePaint { - "line-opacity"?: number | StyleFunction; - "line-color"?: string | StyleFunction; - "line-translate"?: number[]; - "line-translate-anchor"?: "map" | "viewport"; - "line-width"?: number | StyleFunction; - "line-gap-width"?: number | StyleFunction; - "line-offset"?: number | StyleFunction; - "line-blur"?: number | StyleFunction; - "line-dasharray"?: number[]; - "line-dasharray-transition"?: Transition; - "line-pattern"?: string; - } - - export interface SymbolLayout { - visibility?: "visible" | "none"; - - "symbol-placement"?: "point" | "line"; - "symbol-spacing"?: number; - "symbol-avoid-edges"?: boolean; - "icon-allow-overlap"?: boolean; - "icon-ignore-placement"?: boolean; - "icon-optional"?: boolean; - "icon-rotation-alignment"?: "map" | "viewport" | "auto"; - "icon-pitch-alignment"?: "map" | "viewport"| "auto"; - "icon-size"?: number | StyleFunction; - "icon-text-fit"?: "none" | "both" | "width" | "height"; - "icon-text-fit-padding"?: number[]; - "icon-image"?: string | StyleFunction; - "icon-rotate"?: number | StyleFunction; - "icon-padding"?: number; - "icon-keep-upright"?: boolean; - "icon-offset"?: number[] | StyleFunction; - "text-pitch-alignment"?: "map" | "viewport" | "auto"; - "text-rotation-alignment"?: "map" | "viewport" | "auto"; - "text-field"?: string | StyleFunction; - "text-font"?: string | string[]; - "text-size"?: number | StyleFunction; - "text-max-width"?: number; - "text-line-height"?: number; - "text-letter-spacing"?: number; - "text-justify"?: "left" | "center" | "right"; - "text-anchor"?: "center" | "left" | "right" | "top" | "bottom" | "top-left" | "top-right" | "bottom-left" | "bottom-right"; - "text-max-angle"?: number; - "text-rotate"?: number | StyleFunction; - "text-padding"?: number; - "text-keep-upright"?: boolean; - "text-transform"?: "none" | "uppercase" | "lowercase" | StyleFunction; - "text-offset"?: number[]; - "text-allow-overlap"?: boolean; - "text-ignore-placement"?: boolean; - "text-optional"?: boolean; - - } - export interface SymbolPaint { - "icon-opacity"?: number | StyleFunction; - "icon-color"?: string | StyleFunction; - "icon-halo-color"?: string | StyleFunction; - "icon-halo-width"?: number | StyleFunction; - "icon-halo-blur"?: number | StyleFunction; - "icon-translate"?: number[]; - "icon-translate-anchor"?: "map" | "viewport"; - "text-opacity"?: number | StyleFunction; - "text-color"?: string | StyleFunction; - "text-halo-color"?: string | StyleFunction; - "text-halo-width"?: number | StyleFunction; - "text-halo-blur"?: number | StyleFunction; - "text-translate"?: number[]; - "text-translate-anchor"?: "map" | "viewport"; - } - - export interface RasterLayout { - visibility?: "visible" | "none"; - } - - export interface RasterPaint { - "raster-opacity"?: number; - "raster-hue-rotate"?: number; - "raster-brightness-min"?: number; - "raster-brightness-max"?: number; - "raster-saturation"?: number; - "raster-contrast"?: number; - "raster-fade-duration"?: number; - } - - export interface CircleLayout { - visibility?: "visible" | "none"; - } - - export interface CirclePaint { - "circle-radius"?: number | StyleFunction; - "circle-radius-transition"?: Transition; - "circle-color"?: string | StyleFunction; - "circle-blur"?: number | StyleFunction; - "circle-opacity"?: number | StyleFunction; - "circle-translate"?: number[]; - "circle-translate-anchor"?: "map" | "viewport"; - "circle-pitch-scale"?: "map" | "viewport"; - "circle-pitch-alignment"?: "map" | "viewport"; - "circle-stroke-width"?: number | StyleFunction; - "circle-stroke-color"?: string | StyleFunction; - "circle-stroke-opacity"?: number | StyleFunction; - } + /** + * Evented + */ + export class Evented { + on(type: string, listener: Function): this; + + on(type: string, layer: string, listener: Function): this; + + off(type?: string | any, listener?: Function): this; + + off(type?: string | any, layer?: string, listener?: Function): this; + + once(type: string, listener: Function): this; + + fire(type: string, data?: mapboxgl.EventData | Object): this; + + listens(type: string): boolean; + } + + /** + * StyleOptions + */ + export interface StyleOptions { + transition?: boolean; + } + + /** + * EventData + */ + export class EventData { + type: string; + target: Map; + originalEvent: Event; + point: mapboxgl.Point; + lngLat: mapboxgl.LngLat; + } + + export class MapMouseEvent { + type: string; + target: Map; + originalEvent: MouseEvent; + point: mapboxgl.Point; + lngLat: mapboxgl.LngLat; + } + + export class MapTouchEvent { + type: string; + target: Map; + originalEvent: TouchEvent; + point: mapboxgl.Point; + lngLat: mapboxgl.LngLat; + points: Point[]; + lngLats: LngLat[]; + } + + export class MapBoxZoomEvent { + originalEvent: MouseEvent; + boxZoomBounds: LngLatBounds; + } + + export class MapDataEvent { + type: string; + dataType: 'source' | 'style' | 'tile'; + isSourceLoaded?: boolean; + source?: mapboxgl.Source; + coord?: any; + } + + /** + * AnimationOptions + */ + export interface AnimationOptions { + /** Number in milliseconds */ + duration?: number; + easing?: Function; + /** point, origin of movement relative to map center */ + offset?: PointLike; + /** When set to false, no animation happens */ + animate?: boolean; + } + + /** + * CameraOptions + */ + export interface CameraOptions { + /** Map center */ + center?: LngLatLike; + /** Map zoom level */ + zoom?: number; + /** Map rotation bearing in degrees counter-clockwise from north */ + bearing?: number; + /** Map angle in degrees at which the camera is looking at the ground */ + pitch?: number; + /** If zooming, the zoom center (defaults to map center) */ + around?: LngLatLike; + } + + /** + * FlyToOptions + */ + export interface FlyToOptions extends AnimationOptions, CameraOptions { + curve?: number; + minZoom?: number; + speed?: number; + screenSpeed?: number; + easing?: Function; + } + + /** + * MapEvent + */ + export interface MapEvent { + resize?: void; + webglcontextlost?: { originalEvent: WebGLContextEvent }; + webglcontextrestored?: { originalEvent: WebGLContextEvent }; + remove?: void; + dataloading?: { data: mapboxgl.MapDataEvent }; + data?: { data: mapboxgl.MapDataEvent }; + render?: void; + contextmenu?: { data: mapboxgl.MapMouseEvent }; + dblclick?: { data: mapboxgl.MapMouseEvent }; + click?: { data: mapboxgl.MapMouseEvent }; + tiledataloading?: { data: mapboxgl.MapDataEvent }; + sourcedataloading?: { data: mapboxgl.MapDataEvent }; + styledataloading?: { data: mapboxgl.MapDataEvent }; + touchcancel?: { data: mapboxgl.MapTouchEvent }; + touchmove?: { data: mapboxgl.MapTouchEvent }; + touchend?: { data: mapboxgl.MapTouchEvent }; + touchstart?: { data: mapboxgl.MapTouchEvent }; + mousemove?: { data: mapboxgl.MapMouseEvent }; + mouseup?: { data: mapboxgl.MapMouseEvent }; + mousedown?: { data: mapboxgl.MapMouseEvent }; + moveend?: { data: mapboxgl.MapMouseEvent | mapboxgl.MapTouchEvent }; + move?: { data: mapboxgl.MapMouseEvent | mapboxgl.MapTouchEvent }; + movestart?: { data: mapboxgl.MapMouseEvent | mapboxgl.MapTouchEvent }; + mouseout?: { data: mapboxgl.MapMouseEvent }; + load?: void; + sourcedata?: { data: mapboxgl.MapDataEvent }; + styledata?: { data: mapboxgl.MapDataEvent }; + zoomend?: { data: mapboxgl.MapMouseEvent | mapboxgl.MapTouchEvent }; + zoom?: { data: mapboxgl.MapMouseEvent | mapboxgl.MapTouchEvent }; + zoomstart?: { data: mapboxgl.MapMouseEvent | mapboxgl.MapTouchEvent }; + boxzoomcancel?: { data: mapboxgl.MapBoxZoomEvent }; + boxzoomstart?: { data: mapboxgl.MapBoxZoomEvent }; + boxzoomend?: { data: mapboxgl.MapBoxZoomEvent }; + rotate?: { data: mapboxgl.MapMouseEvent | mapboxgl.MapTouchEvent }; + rotatestart?: { data: mapboxgl.MapMouseEvent | mapboxgl.MapTouchEvent }; + rotateend?: { data: mapboxgl.MapMouseEvent | mapboxgl.MapTouchEvent }; + drag?: { data: mapboxgl.MapMouseEvent | mapboxgl.MapTouchEvent }; + dragend?: { data: mapboxgl.MapMouseEvent | mapboxgl.MapTouchEvent }; + pitch?: { data: mapboxgl.EventData }; + } + + export interface Layer { + id: string; + type?: 'fill' | 'line' | 'symbol' | 'circle' | 'fill-extrusion' | 'raster' | 'background' | 'heatmap'; + + metadata?: any; + ref?: string; + + source?: string | VectorSource | RasterSource | GeoJSONSource | ImageSource | VideoSource | GeoJSONSourceRaw; + + 'source-layer'?: string; + + minzoom?: number; + maxzoom?: number; + + interactive?: boolean; + + filter?: any[]; + layout?: BackgroundLayout | FillLayout | FillExtrusionLayout | LineLayout | SymbolLayout | RasterLayout | CircleLayout | HeatmapLayout; + paint?: BackgroundPaint | FillPaint | FillExtrusionPaint | LinePaint | SymbolPaint | RasterPaint | CirclePaint | HeatmapPaint; + } + + export interface StyleFunction { + stops?: any[][]; + property?: string; + base?: number; + type?: 'identity' | 'exponential' | 'interval' | 'categorical'; + default?: any; + 'colorSpace'?: 'rgb' | 'lab' | 'interval'; + } + + export interface BackgroundLayout { + visibility?: 'visible' | 'none'; + } + + export interface BackgroundPaint { + 'background-color'?: string | Expression; + 'background-pattern'?: string; + 'background-opacity'?: number | Expression; + } + + export interface FillLayout { + visibility?: 'visible' | 'none'; + } + + export interface FillPaint { + 'fill-antialias'?: boolean; + 'fill-opacity'?: number | StyleFunction | Expression; + 'fill-color'?: string | StyleFunction | Expression; + 'fill-outline-color'?: string | StyleFunction | Expression; + 'fill-translate'?: number[] | Expression; + 'fill-translate-anchor'?: 'map' | 'viewport'; + 'fill-pattern'?: string; + } + + export interface FillExtrusionLayout { + visibility?: 'visible' | 'none'; + } + + export interface FillExtrusionPaint { + 'fill-extrusion-opacity'?: number | Expression; + 'fill-extrusion-color'?: string | StyleFunction | Expression; + 'fill-extrusion-translate'?: number[] | Expression; + 'fill-extrusion-translate-anchor'?: 'map' | 'viewport'; + 'fill-extrusion-pattern'?: string; + 'fill-extrusion-height'?: number | StyleFunction | Expression; + 'fill-extrusion-base'?: number | StyleFunction | Expression; + } + + export interface LineLayout { + visibility?: 'visible' | 'none'; + + 'line-cap'?: 'butt' | 'round' | 'square'; + 'line-join'?: 'bevel' | 'round' | 'miter'; + 'line-miter-limit'?: number | Expression; + 'line-round-limit'?: number | Expression; + } + + export interface LinePaint { + 'line-opacity'?: number | StyleFunction | Expression; + 'line-color'?: string | StyleFunction | Expression; + 'line-translate'?: number[] | Expression; + 'line-translate-anchor'?: 'map' | 'viewport'; + 'line-width'?: number | StyleFunction | Expression; + 'line-gap-width'?: number | StyleFunction | Expression; + 'line-offset'?: number | StyleFunction | Expression; + 'line-blur'?: number | StyleFunction | Expression; + 'line-dasharray'?: number[]; + 'line-dasharray-transition'?: Transition; + 'line-pattern'?: string; + } + + export interface SymbolLayout { + visibility?: 'visible' | 'none'; + + 'symbol-placement'?: 'point' | 'line'; + 'symbol-spacing'?: number | Expression; + 'symbol-avoid-edges'?: boolean; + 'icon-allow-overlap'?: boolean; + 'icon-ignore-placement'?: boolean; + 'icon-optional'?: boolean; + 'icon-rotation-alignment'?: 'map' | 'viewport' | 'auto'; + 'icon-pitch-alignment'?: 'map' | 'viewport' | 'auto'; + 'icon-size'?: number | StyleFunction | Expression; + 'icon-text-fit'?: 'none' | 'both' | 'width' | 'height'; + 'icon-text-fit-padding'?: number[] | Expression; + 'icon-image'?: string | StyleFunction; + 'icon-rotate'?: number | StyleFunction | Expression; + 'icon-padding'?: number | Expression; + 'icon-keep-upright'?: boolean; + 'icon-offset'?: number[] | StyleFunction | Expression; + 'text-pitch-alignment'?: 'map' | 'viewport' | 'auto'; + 'text-rotation-alignment'?: 'map' | 'viewport' | 'auto'; + 'text-field'?: string | StyleFunction; + 'text-font'?: string | string[]; + 'text-size'?: number | StyleFunction | Expression; + 'text-max-width'?: number | Expression; + 'text-line-height'?: number | Expression; + 'text-letter-spacing'?: number | Expression; + 'text-justify'?: 'left' | 'center' | 'right'; + 'text-anchor'?: 'center' | 'left' | 'right' | 'top' | 'bottom' | 'top-left' | 'top-right' | 'bottom-left' | 'bottom-right'; + 'text-max-angle'?: number | Expression; + 'text-rotate'?: number | StyleFunction | Expression; + 'text-padding'?: number | Expression; + 'text-keep-upright'?: boolean; + 'text-transform'?: 'none' | 'uppercase' | 'lowercase' | StyleFunction | Expression; + 'text-offset'?: number[] | Expression; + 'text-allow-overlap'?: boolean; + 'text-ignore-placement'?: boolean; + 'text-optional'?: boolean; + + } + + export interface SymbolPaint { + 'icon-opacity'?: number | StyleFunction | Expression; + 'icon-color'?: string | StyleFunction | Expression; + 'icon-halo-color'?: string | StyleFunction | Expression; + 'icon-halo-width'?: number | StyleFunction | Expression; + 'icon-halo-blur'?: number | StyleFunction | Expression; + 'icon-translate'?: number[] | Expression; + 'icon-translate-anchor'?: 'map' | 'viewport'; + 'text-opacity'?: number | StyleFunction | Expression; + 'text-color'?: string | StyleFunction | Expression; + 'text-halo-color'?: string | StyleFunction | Expression; + 'text-halo-width'?: number | StyleFunction | Expression; + 'text-halo-blur'?: number | StyleFunction | Expression; + 'text-translate'?: number[] | Expression; + 'text-translate-anchor'?: 'map' | 'viewport'; + } + + export interface RasterLayout { + visibility?: 'visible' | 'none'; + } + + export interface RasterPaint { + 'raster-opacity'?: number | Expression; + 'raster-hue-rotate'?: number | Expression; + 'raster-brightness-min'?: number | Expression; + 'raster-brightness-max'?: number | Expression; + 'raster-saturation'?: number | Expression; + 'raster-contrast'?: number | Expression; + 'raster-fade-duration'?: number | Expression; + } + + export interface CircleLayout { + visibility?: 'visible' | 'none'; + } + + export interface CirclePaint { + 'circle-radius'?: number | StyleFunction | Expression; + 'circle-radius-transition'?: Transition; + 'circle-color'?: string | StyleFunction | Expression; + 'circle-blur'?: number | StyleFunction | Expression; + 'circle-opacity'?: number | StyleFunction | Expression; + 'circle-translate'?: number[] | Expression; + 'circle-translate-anchor'?: 'map' | 'viewport'; + 'circle-pitch-scale'?: 'map' | 'viewport'; + 'circle-pitch-alignment'?: 'map' | 'viewport'; + 'circle-stroke-width'?: number | StyleFunction | Expression; + 'circle-stroke-color'?: string | StyleFunction | Expression; + 'circle-stroke-opacity'?: number | StyleFunction | Expression; + } + + export interface HeatmapLayout { + visibility?: 'visible' | 'none'; + } + + export interface HeatmapPaint { + 'heatmap-radius'?: number | Expression; + 'heatmap-transition'?: Transition; + 'heatmap-weight'?: number | StyleFunction | Expression; + 'heatmap-intensity'?: number | Expression; + 'heatmap-color'?: string | Expression; + 'heatmap-color-transition'?: Transition; + 'heatmap-opacity'?: number | Expression; + 'heatmap-opacity-transition'?: Transition; + } } declare module 'mapbox-gl' { - export = mapboxgl; + export = mapboxgl; } declare module 'mapbox-gl/dist/mapbox-gl' { - export = mapboxgl; + export = mapboxgl; } diff --git a/types/mapnik/index.d.ts b/types/mapnik/index.d.ts new file mode 100644 index 0000000000..33b455f0dd --- /dev/null +++ b/types/mapnik/index.d.ts @@ -0,0 +1,49 @@ +// Type definitions for mapnik 3.x +// Project: http://mapnik.org +// Definitions by: Loli +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +/// +export const settings: any; +export function register_default_fonts(): void; +export function register_default_input_plugins(): void; +export function register_datasource(path: string): void; +export class VectorTile { + constructor(z: number, x: number, y: number) + addDataSync(vectorTile: any): void; +} +export class Datasource { + constructor(datasource: any) + featureset(): Featureset; +} + +export class Featureset { + constructor() + next(): FeaturesetNext; +} +export class FeaturesetNext { + constructor() + toJSON(): string; +} + +export class Image { + constructor(x: number, y: number) + encode(type: string, callback?: (err: Error, buffer: Buffer) => void): void; + getData(): Buffer; +} + +export interface Image { + // constructor(x: number, y: number) + new(x: number, y: number): () => void; + encode(type: string, callback?: (err: Error, buffer: Buffer) => void): void; + getData(): Buffer; + save(fp: string): () => void; + open(fp: string): () => void; +} + +export class Map { + constructor(x: number, y: number) + load(xml: string, callback?: (err: Error, map: Map) => void): void; + zoomAll(): void; + render(images: Image | VectorTile , callback?: (err: Error, map: Image) => void): void; +} diff --git a/types/mapnik/mapnik-tests.ts b/types/mapnik/mapnik-tests.ts new file mode 100644 index 0000000000..23e726f111 --- /dev/null +++ b/types/mapnik/mapnik-tests.ts @@ -0,0 +1,40 @@ +import * as mapnik from "mapnik"; +import * as fs from "fs"; +import * as path from "path"; + +mapnik.register_default_fonts(); +mapnik.register_default_input_plugins(); + +const map: mapnik.Map = new mapnik.Map(256, 256); +map.load('./test/stylesheet.xml', function xx(err: Error, map: mapnik.Map) { + if (err) throw err; + map.zoomAll(); + const im: mapnik.Image = new mapnik.Image(256, 256); + map.render(im, function xxx(err: Error, im: mapnik.Image) { + if (err) throw err; + im.encode('png', function xxxx(err: Error, buffer: Buffer) { + if (err) throw err; + fs.writeFile('map.png', buffer, function xxxxx(err: Error) { + if (err) throw err; + console.log('saved map image to map.png'); + }); + }); + }); +}); + +// new mapnik.Image.open("xxx").save("xx"); + +mapnik.register_datasource(path.join(mapnik.settings.paths.input_plugins, 'shape.input')); +const ds: mapnik.Datasource = new mapnik.Datasource({type: 'shape', file: 'test/data/world_merc.shp'}); +const featureset: mapnik.Featureset = ds.featureset(); +const geojson: any = { + type: "FeatureCollection", + features: [ + ] +}; +let feat: mapnik.FeaturesetNext = featureset.next(); +while (feat) { + geojson.features.push(JSON.parse(feat.toJSON())); + feat = featureset.next(); +} +fs.writeFileSync("output.geojson", JSON.stringify(geojson, null, 2)); diff --git a/types/mapnik/tsconfig.json b/types/mapnik/tsconfig.json new file mode 100644 index 0000000000..81f111a37e --- /dev/null +++ b/types/mapnik/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", + "mapnik-tests.ts" + ] +} \ No newline at end of file diff --git a/types/mapnik/tslint.json b/types/mapnik/tslint.json new file mode 100644 index 0000000000..2750cc0197 --- /dev/null +++ b/types/mapnik/tslint.json @@ -0,0 +1 @@ +{ "extends": "dtslint/dt.json" } \ No newline at end of file diff --git a/types/material-ui/index.d.ts b/types/material-ui/index.d.ts index 22b5d1711f..5ae63560cc 100644 --- a/types/material-ui/index.d.ts +++ b/types/material-ui/index.d.ts @@ -1440,6 +1440,7 @@ declare namespace __MaterialUI { hintText?: React.ReactNode; iconStyle?: React.CSSProperties; id?: string; + name?: string; labelStyle?: React.CSSProperties; multiple?: boolean; onBlur?: React.FocusEventHandler<{}>; diff --git a/types/materialize-css/index.d.ts b/types/materialize-css/index.d.ts index a457c3ad1a..ebc997c51f 100644 --- a/types/materialize-css/index.d.ts +++ b/types/materialize-css/index.d.ts @@ -1,712 +1,418 @@ -// Type definitions for materialize-css 0.100 +// Type definitions for materialize-css 1.0 // Project: http://materializecss.com/ -// Definitions by: Erik Lieben -// Leon Yu -// Sukhdeep Singh -// Jean-Francois Cere -// Sebastien Cote +// Definitions by: 胡玮文 // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -// TypeScript Version: 2.3 +// TypeScript Version: 2.4 /// -/// -declare namespace Materialize { - /** - * The collapsible options - */ - interface CollapsibleOptions { - /** - * A setting that changes the collapsible behavior to expandable instead of the default accordion style - */ - accordion?: boolean; +export = M; - /** - * Callback for Collapsible section close. - * @default `function() { alert('Closed'); }` - */ - onClose?: Function; +declare global { + namespace M { + class Autocomplete extends Component { + /** + * Get Instance + */ + static getInstance(elem: Element): Autocomplete; - /** - * Callback for Collapsible section open. - * @default `function() { alert('Opened'); }` - */ - onOpen?: Function; - } + /** + * Select a specific autocomplete options. + * @param el Element of the autocomplete option. + */ + selectOption(el: Element): void; - interface TooltipOptions { - /** - * The delay before the tooltip shows (in milliseconds) - */ - delay: number; - /** - * Tooltip text. Can use custom HTML if you set the html option - */ - tooltip?: string; - /** - * Set the direction of the tooltip. 'top', 'right', 'bottom', 'left'. - * - * @default `'bottom'` - */ - position?: string; - /** - * Allow custom html inside the tooltip. - * - * @default `false` - */ - html?: boolean; - } + /** + * Update autocomplete options data. + * @param data Autocomplete options data object. + */ + updateData(data: AutocompleteData): void; - /** - * The dropdown options - */ - interface DropDownOptions { - /** - * The duration of the transition enter in milliseconds. - * @default `300` - */ - inDuration?: number; + /** + * If the autocomplete is open. + */ + isOpen: boolean; - /** - * The duration of the transition out in milliseconds. - * @default `225` - */ - outDuration?: number; + /** + * Number of matching autocomplete options. + */ + count: number; - /** - * If true, constrainWidth to the size of the dropdown activator. - * @default `true` - */ - constrainWidth?: boolean; - /** - * If true, the dropdown will open on hover. - * @default `false` - */ - hover?: boolean; + /** + * Index of the current selected option. + */ + activeIndex: number; + } - /** - * This defines the spacing from the aligned edge. - * @default `0` - */ - gutter?: number; + interface AutocompleteData { + [key: string]: string | null; + } - /** - * If true, the dropdown will show below the activator. - * @default `false` - */ - belowOrigin?: boolean; + interface AutocompleteOptions { + /** + * Data object defining autocomplete options with optional icon strings. + */ + data: AutocompleteData; - /** - * Defines the edge the menu is aligned to. - * @default `'left'` - */ - alignment?: string; - /** - * If true, stops the event propagating from the dropdown origin click handler. - * - * @default `false` - */ - stopPropagation?: boolean; - } + /** + * Limit of results the autocomplete shows. + * @default infinity + */ + limit: number; - /** - * The slider options - */ - interface SliderOptions { - /** - * Set to false to hide slide indicators. - * @default `true` - */ - indicators?: boolean; + /** + * Callback for when autocompleted. + */ + onAutocomplete: (this: Autocomplete, text: string) => void; - /** - * Set height of slider. - * @default `400` - */ - height?: number; + /** + * Minimum number of characters before autocomplete starts. + * @default 1 + */ + minLength: number; - /** - * Set the duration of the transition animation in ms. - * @default `500` - */ - transition?: number; + /** + * Sort function that defines the order of the list of autocomplete options. + */ + sortFunction: (a: string, b: string, inputText: string) => number; + } - /** - * Set the duration between transitions in ms. - * @default `6000` - */ - interval?: number; - } + class Sidenav extends Component { + /** + * Get Instance + */ + static getInstance(elem: Element): Sidenav; - /** - * The carousel options - */ - interface CarouselOptions { - /** - * Transition duration in milliseconds - * @default `200` - */ - duration?: number; + /** + * Opens Sidenav + */ + open(): void; - /** - * Perspective zoom. If 0, all items are the same size. - * @default `-100` - */ - dist?: number; + /** + * Closes Sidenav + */ + close(): void; - /** - * Set the duration of the transition animation in ms. - * @default `500` - */ - shift?: number; + /** + * Describes open/close state of Sidenav + */ + isOpen: boolean; - /** - * Set the duration between transitions in ms. - * @default `6000` - */ - padding?: number; + /** + * Describes if sidenav is fixed + */ + isFixed: boolean; - /** - * Set the width of the carousel. - * @default `false` - */ - fullWidth?: boolean; - /** - * Set to true to show indicators. - * - * @default `false` - */ - indicators?: boolean; - /** - * Don't wrap around and cycle through items. - * - * @default `false` - */ - noWrap?: boolean; - } + /** + * Describes if Sidenav is being dragged + */ + isDragged: boolean; + } - /** - * The modal options - */ - interface ModalOptions { - /** - * Modal can be dismissed by clicking outside of the modal. - * @default `true` - */ - dismissible?: boolean; + /** + * Options for the Sidenav + */ + interface SidenavOptions { + /** + * Side of screen on which Sidenav appears + * @default 'left' + */ + edge: 'left' | 'right'; - /** - * Opacity of modal background. - * @default `.5` - */ - opacity?: number; + /** + * Allow swipe gestures to open/close Sidenav + * @default true + */ + draggable: boolean; - /** - * Transition in duration. - * @default `300` - */ - inDuration?: number; + /** + * Length in ms of enter transition + * @default 250 + */ + inDuration: number; - /** - * Transition out duration. - * @default `200` - */ - outDuration?: number; - /** - * Starting top style attribute - * @default `4%` - */ - startingTop?: string; - /** - * Ending top style attribute - * @default `10%` - */ - endingTop?: string; + /** + * Length in ms of exit transition + * @default 200 + */ + outDuration: number; - /** - * Callback for Modal open. - * @default `function() { alert('Ready'); }` - */ - ready?: Function; + /** + * Function called when sidenav starts entering + */ + onOpenStart: (this: Sidenav, elem: Element) => void; - /** - * Callback for Modal close. - * @default `function() { alert('Closed'); }` - */ - complete?: Function; - } + /** + * Function called when sidenav finishes entering + */ + onOpenEnd: (this: Sidenav, elem: Element) => void; - /** - * The push pin options - */ - interface PushpinOptions { - /** - * The distance in pixels from the top of the page where the element becomes fixed. - * @default `0` - */ - top?: number; + /** + * Function called when sidenav starts exiting + */ + onCloseStart: (this: Sidenav, elem: Element) => void; - /** - * The distance in pixels from the top of the page where the elements stops being fixed. - * @default `Infinity` - */ - bottom?: number; + /** + * Function called when sidenav finishes exiting + */ + onCloseEnd: (this: Sidenav, elem: Element) => void; + } - /** - * The offset from the top the element will be fixed at. - * @default `0` - */ - offset?: number; - } + class Tabs extends Component { + /** + * Get Instance + */ + static getInstance(elem: Element): Tabs; - /** - * The scroll spy options - */ - interface ScrollSpyOptions { - /** - * Offset from top. - * @default `200` - */ - scrollOffset?: number; - /** - * Class name to be added to the active link. - * @default `active` - */ - activeClass?: string; - /** - * Function that returns a selector to add activeClass to. The parameter is the section id - */ - getActiveElement?: Function; - } + /** + * Show tab content that corresponds to the tab with the id + * @param tabId The id of the tab that you want to switch to + */ + select(tabId: string): void; - /** - * The slideNav options - */ - interface SideNavOptions { - /** - * The sideNav width. - * @default `240` - */ - menuWidth?: number; + /** + * The index of tab that is currently shown + */ + index: number; + } - /** - * The horizontal origin. - * @default `'left'` - */ - edge?: string; + /** + * Options for the Tabs + */ + interface TabsOptions { + /** + * Transition duration in milliseconds. + * @default 300 + */ + duration: number; - /** - * Closes sideNav on clicks, useful for Angular/Meteor. - * @default `false` - */ - closeOnClick?: boolean; + /** + * Callback for when a new tab content is shown + */ + onShow: (this: Tabs, newContent: Element) => void; - /** - * Choose whether you can drag to open on touch screens. - * @default `true` - */ - draggable?: boolean; + /** + * Set to true to enable swipeable tabs. This also uses the responsiveThreshold option + * @default false + */ + swipeable: boolean; - /** - * Execute a callback function when sideNav is opened. - * - * The callback provides a parameter which refers to the sideNav being opened. - */ - onOpen?: Function; + /** + * The maximum width of the screen, in pixels, where the swipeable functionality initializes. + * @default infinity + */ + responsiveThreshold: number; + } - /** - * Execute a callback function when sideNav is closed. - * - * The callback provides a parameter which refers to the sideNav being closed. - */ - onClose?: Function; - } + class Modal extends Component { + /** + * Get Instance + */ + static getInstance(elem: Element): Modal; - interface ScrollFireOptions { - /** - * The selector for the element that is being tracked. - */ - selector?: string; + /** + * Open modal + */ + open(): void; - /** - * Offset to use when activating the scroll fire event - * If this is 0, the callback will be fired when the selector element is at the very bottom of the user's window. - */ - offset?: number; + /** + * Close modal + */ + close(): void; - /** - * The string function call that you want to make when the user scrolls to the threshold. - * It will only be called once. - * Example: 'console.log("hello, world!")'; - * or callback: () => { console.log('hello world'); } - */ - callback?: string | (() => void); - } + /** + * If the modal is open. + */ + isOpen: boolean; - interface TabOptions { - /** - * Execute a callback function when the tab is changed. - * - * The callback provides a parameter which refers to the current tab being shown. - */ - onShow?: Function; + /** + * ID of the modal element + */ + id: string; + } - /** - * Set to true to enable swipeable tabs. This also uses the responsiveThreshold option. - * - * @default `false` - */ - swipeable?: boolean; + /** + * Options for the Modal + */ + interface ModalOptions { + /** + * Opacity of the modal overlay. + * @default 0.5 + */ + opacity: number; - /** - * The maximum width of the screen, in pixels, where the swipeable functionality initializes. - * - * @default `Infinity` - */ - responsiveThreshold?: number; - } + /** + * Transition in duration in milliseconds. + * @default 250 + */ + inDuration: number; - interface ChipDataObject { - tag: string; - image?: string; - id?: number; - } + /** + * Transition out duration in milliseconds. + * @default 250 + */ + outDuration: number; - interface ChipOptions { - /** - * Set the chip data - */ - data?: ChipDataObject[]; - /** - * Set first placeholder when there are no tags - */ - placeholder?: string; - /** - * Set second placeholder when adding additional tags. - */ - secondaryPlaceholder?: string; - /** - * Set autocomplete data. - */ - autocompleteData?: any; - /** - * Set autocomplete limit. - */ - autocompleteLimit?: number; - /** - * Set autocompleteOptions - */ - autocompleteOptions?: AutoCompleteOptions; - } + /** + * Callback function called when modal is finished entering. + */ + ready: (this: Modal, elem: Element, openingTrigger: Element) => void; - interface AutoCompleteOptions { - /** - * The JSON object data to be used for the autocomplete suggetions list - */ - data: object; - /** - * The max amount of results that can be shown at once. - * @default `Infinity` - */ - limit?: number; - /** - * Callback function when value is autcompleted. - */ - onAutocomplete?: (val: any) => void; - /** - * The minimum length of the input for the autocomplete to start. - * @default `1` - */ - minLength?: number; - } + /** + * Callback function called when modal is finished exiting. + */ + complete: (this: Modal, elem: Element) => void; - interface Toast { - /** - * Dismiss all toasts - */ - removeAll: Function; - } + /** + * Allow modal to be dismissed by keyboard or overlay click. + * @default true + */ + dismissible: boolean; - /** - * The Materialize object - */ - interface Materialize { - /** - * Displays a toast message on screen - * - * @param string | JQuery message The message to display on screen - * @param number displayLength The duration in milliseconds to display the message on screen - * @param string className The className to use to format the message to display - * @param Function completeCallback Callback function to call when the messages completes/hides. - */ - toast(message: string | JQuery, displayLength: number, className?: string, completeCallback?: Function): void; + /** + * Starting top offset + * @default '4%' + */ + startingTop: string; - /** - * Fires an event when the page is scrolled to a certain area - * - * @param ScrollFireOptions options optional parameter with scroll fire options - */ - scrollFire(options?: ScrollFireOptions[]): void; + /** + * Ending top offset + * @default '10%' + */ + endingTop: string; + } - /** - * A staggered reveal effect for any UL Tag with list items - * - * @param string selector the selector for the list to show in staggered fasion - */ - showStaggeredList(selector: string): void; + class Tooltip extends Component { + /** + * Get Instance + */ + static getInstance(elem: Element): Tooltip; - /** - * Fade in images. It also animates grayscale and brightness to give it a unique effect. - * - * @param string selector the selector for the image to fade in - */ - fadeInImage(selector: string): void; + /** + * Show tooltip. + */ + open(): void; - /** - * Update all text field to reinitialize all the Materialize labels on the page if dynamically adding inputs - */ - updateTextFields(): void; + /** + * Hide tooltip. + */ + close(): void; - /** - * Toast functions - */ - Toast: Toast; - } -} - -/** - * Declare Pickadate namespace again in order to add more Materialize specific properties to TimeOptions interface - * - * @see http://www.typescriptlang.org/docs/handbook/declaration-merging.html - */ -declare namespace Pickadate { - interface TimeOptions { - /** - * Set default time such as : 'now', '1:30AM', '16:30'. - * @default `'now'` - */ - default?: string; - /** - * set default time to * milliseconds from now (using with default = 'now') - * @default `0` - */ - fromnow?: number; - /** - * Use AM/PM or 24-hour format - * @default `false` - */ - twelvehour?: boolean; - /** - * text for done-button - * @default `'OK'` - */ - donetext?: string; - /** - * text for clear-button - * @default `'Clear'` - */ - cleartext?: string; - /** - * Text for cancel-button - * @default `'Cancel'` - */ - canceltext?: string; - /** - * automatic close timepicker - * @default `false` - */ - autoclose?: boolean; - /** - * make AM PM clickable - * @default `true` - */ - ampmclickable?: boolean; - /** - * Function for after opening timepicker - */ - aftershow?: Function; - } -} - -declare var Materialize: Materialize.Materialize; - -interface JQuery { - /** - * open Fixed Action Button - */ - openFAB(): void; - /** - * close Fixed Action Button - */ - closeFAB(): void; - - /** - * Select allows user input through specified options. - * - * @param string method "destroy" destroy the material select - */ - material_select(method?: string): void; - - /** - * Use a character counter in fields where a character restriction is in place. - */ - characterCounter(): JQuery; - - /** - * Collapsibles are accordion elements that expand when clicked on. - * They allow you to hide content that is not immediately relevant to the user. - * - * @param CollapsibleOptions | string options the collapsible options or the string "destroy" to destroy the collapsible - */ - collapsible(options?: Materialize.CollapsibleOptions | string): JQuery; - - /** - * Programmatically trigger an event on a selected index - * - * @param string method the string "open" or "close" to open or to close the collapsible element on specified index - * @param number index the element index to trigger "open" or "close" function - */ - collapsible(method: string, index: number): JQuery; - - /** - * Tooltips are small, interactive, textual hints for mainly graphical elements. - * When using icons for actions you can use a tooltip to give people clarification on its function. - * - * @param TooltipOptions | string options the tooltip options or the string "remove" to remove the tooltip function - */ - tooltip(options?: Materialize.TooltipOptions | string): JQuery; - - /** - * Add a dropdown list to any button. - * Make sure that the data-activates attribute matches the id in the
    tag. - * - * @param DropDownOptions options the drop down options - */ - dropdown(options?: Materialize.DropDownOptions): void; - - /** - * Material box is a material design implementation of the Lightbox plugin. - */ - materialbox(): JQuery; - - /** - * slider is a simple and elegant image carousel. - * You can also have captions that will be transitioned on their own depending on their alignment. - * You can also have indicators that show up on the bottom of the slider. - * - * @param SliderOptions options the slider options - */ - slider(options?: Materialize.SliderOptions): JQuery; - - /** - * slider is a simple and elegant image carousel. - * You can also have captions that will be transitioned on their own depending on their alignment. - * You can also have indicators that show up on the bottom of the slider. - * - * @param string method the string "start" to start the animation or "pauze" to pauze the animation - */ - slider(method: string): JQuery; - - /** - * Our slider is a simple and elegant image carousel. - * You can also have captions that will be transitioned on their own depending on their alignment. - * You can also have indicators that show up on the bottom of the slider. - * - * @param CarouselOptions options the slider options or the string "start" to start the animation or "pauze" to pauze the animation - */ - carousel(options?: Materialize.CarouselOptions): JQuery; - - /** - * Our slider is a simple and elegant image carousel. - * You can also have captions that will be transitioned on their own depending on their alignment. - * You can also have indicators that show up on the bottom of the slider. - * - * @param string method the methods to pause, start, move to next and move to previous slide. - */ - carousel(method: string, count?: number): JQuery; - - /** - * Modal for dialog boxes, confirmation messages, or other content that can be called up. - * - * To customize the behaviour of a modal - * - * @param ModalOptions options the lean modal options - */ - modal(options?: Materialize.ModalOptions): void; - - /** - * Modal for dialog boxes, confirmation messages, or other content that can be called up. - * - * For opening and closing modals programatically. - * - * @param string action action to do (`open` or `close) - */ - modal(action: string, options?: Materialize.ModalOptions): void; - - /** - * Parallax is an effect where the background content or image in this case, is moved at a different speed than the foreground content while scrolling. - */ - parallax(): JQuery; - - /** - * Pushpin is a fixed positioning plugin. - * - * @param PushpinOptions options the push pin options - */ - pushpin(options?: Materialize.PushpinOptions): JQuery; - - /** - * Scrollspy is a jQuery plugin that tracks certain elements and which element the user's screen is currently centered on. - * - * @param ScrollSpyOptions options the scroll spy options - */ - scrollSpy(options?: Materialize.ScrollSpyOptions): JQuery; - - /** - * A slide out menu. You can add a dropdown to your sidebar by using our collapsible component. - * - * @param SideNavOptions | string methodOrOptions the slide navigation options or a string with "show" to reveal or "hide" to hide the menu - */ - sideNav(methodOrOptions?: Materialize.SideNavOptions | string): void; - - /** - * Programmatically trigger the tab change event - * - * @param string method : the method to call (always "select_tab") - * @param string tab : id of the tab to open - */ - tabs(method?: string, tab?: string): JQuery; - - /** - * Tab Initialization with options - * - * @param TabOptions options jQuery plugin options - */ - tabs(options?: Materialize.TabOptions): JQuery; - - /** - * Chip Initialization - * - * @param ChipOptions options Material chip options - */ - material_chip(options?: Materialize.ChipOptions): JQuery; - - /** - * To access chip data - * - * @param string method name of the method to invoke - */ - material_chip(method: string): Materialize.ChipDataObject[] | Materialize.ChipDataObject; - - /** - * Add an autocomplete dropdown below your input to suggest possible values. - * @param autocompleteOptions options : @see autocompleteOptions for possible options - */ - autocomplete(options: Materialize.AutoCompleteOptions): JQuery; - - /** - * Feature discovery - open and close a tap target - * @param string action : either `'open'` or `'close'` - */ - tapTarget(action?: string): JQuery; + /** + * If tooltip is open. + */ + isOpen: boolean; + + /** + * If tooltip is hovered. + */ + isHovered: boolean; + } + + interface TooltipOptions { + /** + * Delay time before tooltip disappears. + * @default 0 + */ + exitDelay: number; + + /** + * Delay time before tooltip appears. + * @default 200 + */ + enterDelay: number; + + /** + * Can take regular text or HTML strings. + * @default null + */ + html: string | null; + + /** + * Set distance tooltip appears away from its activator excluding transitionMovement. + * @default 5 + */ + margin: number; + + /** + * Enter transition duration. + * @default 300 + */ + inDuration: number; + + /** + * Exit transition duration. + * @default 250 + */ + outDuration: number; + + /** + * Set the direction of the tooltip. + * @default 'bottom' + */ + position: 'top' | 'right' | 'bottom' | 'left'; + + /** + * Amount in px that the tooltip moves during its transition. + * @default 10 + */ + transitionMovement: number; + } + + function updateTextFields(): void; + + class CharacterCounter extends Component { + /** + * Get Instance + */ + static getInstance(elem: Element): CharacterCounter; + } + + abstract class Component { + /** + * Construct component instance and set everything up + */ + constructor(elem: Element, options?: Partial); + + /** + * Destroy plugin instance and teardown + */ + destroy(): void; + + /** + * The DOM element the plugin was initialized with + */ + el: Element; + + /** + * The options the instance was initialized with + */ + options: TOptions; + } + } + + interface JQuery { + // Pick to check methods exist. + autocomplete(method: keyof Pick): JQuery; + autocomplete(method: keyof Pick, el: Element): JQuery; + autocomplete(method: keyof Pick, data: M.AutocompleteData): JQuery; + autocomplete(options?: Partial): JQuery; + + sidenav(method: keyof Pick): JQuery; + sidenav(options?: Partial): JQuery; + + tabs(method: keyof Pick): JQuery; + tabs(method: keyof Pick, tabId: string): JQuery; + tabs(options?: Partial): JQuery; + + tooltip(method: keyof Pick): JQuery; + tooltip(options?: Partial): JQuery; + + modal(method: keyof Pick): JQuery; + modal(options?: Partial): JQuery; + + // tslint:disable-next-line unified-signatures + characterCounter(method: keyof Pick): JQuery; + characterCounter(): JQuery; + } } diff --git a/types/materialize-css/test/materialize-css-global.test.ts b/types/materialize-css/test/materialize-css-global.test.ts new file mode 100644 index 0000000000..fa228b444f --- /dev/null +++ b/types/materialize-css/test/materialize-css-global.test.ts @@ -0,0 +1,18 @@ +const elem = document.querySelector('.whatever')!; +// $ExpectType Sidenav +const sidenav = new M.Sidenav(elem); + +// $ExpectType Tabs +const tabs = new M.Tabs(elem); + +// $ExpectType Modal +const modal = new M.Modal(elem); + +// $ExpectType Autocomplete +const autocomplete = new M.Autocomplete(elem); + +// $ExpectType CharacterCounter +const characterCounter = new M.CharacterCounter(elem); + +// $ExpectType Tooltip +const tooltips = new M.Tooltip(elem); diff --git a/types/materialize-css/test/materialize-css-jquery.test.ts b/types/materialize-css/test/materialize-css-jquery.test.ts new file mode 100644 index 0000000000..42af7fcefd --- /dev/null +++ b/types/materialize-css/test/materialize-css-jquery.test.ts @@ -0,0 +1,30 @@ +$(".whatever").sidenav(); +$(".whatever").sidenav({ inDuration: 200 }); +$(".whatever").sidenav("open"); +$(".whatever").sidenav("destroy"); + +$(".whatever").tabs(); +$(".whatever").tabs({ duration: 200 }); +$(".whatever").tabs("destroy"); +$(".whatever").tabs("select", "id"); + +$(".whatever").modal(); +$(".whatever").modal({ inDuration: 200 }); +$(".whatever").modal("open"); +$(".whatever").modal("destroy"); + +$(".whatever").characterCounter(); +$(".whatever").characterCounter("destroy"); + +$(".whatever").autocomplete({ + data: { + Apple: null, + Google: "https://placehold.it/250x250" + } +}); +$(".whatever").autocomplete("updateData", { Microsoft: null }); + +$(".whatever").tooltip(); +$(".whatever").tooltip({ html: "" }); +$(".whatever").tooltip("open"); +$(".whatever").tooltip("destroy"); diff --git a/types/materialize-css/test/materialize-css-module.test.ts b/types/materialize-css/test/materialize-css-module.test.ts new file mode 100644 index 0000000000..2665586b5d --- /dev/null +++ b/types/materialize-css/test/materialize-css-module.test.ts @@ -0,0 +1,142 @@ +import * as materialize from "materialize-css"; + +const elem = document.querySelector('.whatever')!; + +// Sidenav +// $ExpectType Sidenav +new materialize.Sidenav(elem); +// $ExpectType Sidenav +const sidenav = new materialize.Sidenav(elem, { + edge: "left", + inDuration: 300, + onCloseStart(el) { + // $ExpectType Sidenav + this; + // $ExpectType Element + el; + } +}); +// $ExpectType void +sidenav.open(); +// $ExpectType void +sidenav.destroy(); +// $ExpectType SidenavOptions +sidenav.options; +// $ExpectType Element +sidenav.el; +// $ExpectType boolean +sidenav.isOpen; + +// Tabs +// $ExpectType Tabs +new materialize.Tabs(elem); +// $ExpectType Tabs +const tabs = new materialize.Tabs(elem, { + duration: 200, + onShow(content) { + // $ExpectType Tabs + this; + // $ExpectType Element + content; + } +}); +// $ExpectType void +tabs.destroy(); +// $ExpectType void +tabs.select("id"); +// $ExpectType TabsOptions +tabs.options; +// $ExpectType Element +tabs.el; +// $ExpectType number +tabs.index; + +// Modal +// $ExpectType Modal +new materialize.Modal(elem); +// $ExpectType Modal +const modal = new materialize.Modal(elem, { + inDuration: 300, + ready(el, trigger) { + // $ExpectType Modal + this; + // $ExpectType Element + el; + // $ExpectType Element + trigger; + } +}); +// $ExpectType void +modal.open(); +// $ExpectType void +modal.destroy(); +// $ExpectType ModalOptions +modal.options; +// $ExpectType Element +modal.el; +// $ExpectType boolean +modal.isOpen; + +// CharacterCounter +// $ExpectType CharacterCounter +const characterCounter = new materialize.CharacterCounter(elem); +// $ExpectType void +characterCounter.destroy(); +// $ExpectType Element +characterCounter.el; + +// Autocomplete +// $ExpectType Autocomplete +new materialize.Autocomplete(elem); +// $ExpectType Autocomplete +const autocomplete = new materialize.Autocomplete(elem, { + data: { + Apple: null, + Google: "https://placehold.it/250x250" + }, + minLength: 3, + onAutocomplete(text) { + // $ExpectType Autocomplete + this; + // $ExpectType string + text; + }, + sortFunction(a, b, input) { + // $ExpectType string + a; + // $ExpectType string + b; + // $ExpectType string + input; + return 0; + } +}); +// $ExpectType void +autocomplete.updateData({ Microsoft: null }); +// $ExpectType void +autocomplete.destroy(); +// $ExpectType AutocompleteOptions +autocomplete.options; +// $ExpectType Element +autocomplete.el; +// $ExpectType boolean +autocomplete.isOpen; + +// Tooltip +// $ExpectType Tooltip +new materialize.Tooltip(elem); +// $ExpectType Tooltip +const tooltip = new materialize.Tooltip(elem, { + inDuration: 300, + position: "right" +}); +// $ExpectType void +tooltip.open(); +// $ExpectType void +tooltip.destroy(); +// $ExpectType TooltipOptions +tooltip.options; +// $ExpectType Element +tooltip.el; +// $ExpectType boolean +tooltip.isOpen; diff --git a/types/materialize-css/tsconfig.json b/types/materialize-css/tsconfig.json index cc986baa67..316e2f8361 100644 --- a/types/materialize-css/tsconfig.json +++ b/types/materialize-css/tsconfig.json @@ -7,7 +7,7 @@ ], "noImplicitAny": true, "noImplicitThis": true, - "strictNullChecks": false, + "strictNullChecks": true, "strictFunctionTypes": true, "baseUrl": "../", "typeRoots": [ @@ -19,6 +19,8 @@ }, "files": [ "index.d.ts", - "materialize-css-tests.ts" + "test/materialize-css-global.test.ts", + "test/materialize-css-module.test.ts", + "test/materialize-css-jquery.test.ts" ] -} \ No newline at end of file +} diff --git a/types/materialize-css/tslint.json b/types/materialize-css/tslint.json index 99070fa5c7..5f6e69415a 100644 --- a/types/materialize-css/tslint.json +++ b/types/materialize-css/tslint.json @@ -1,7 +1,6 @@ { - "extends": "dtslint/dt.json", - "rules": { - "ban-types": false, - "prefer-method-signature": false - } -} + "extends": "dtslint/dt.json", + "rules": { + + } + } diff --git a/types/materialize-css/v0/index.d.ts b/types/materialize-css/v0/index.d.ts new file mode 100644 index 0000000000..a457c3ad1a --- /dev/null +++ b/types/materialize-css/v0/index.d.ts @@ -0,0 +1,712 @@ +// Type definitions for materialize-css 0.100 +// Project: http://materializecss.com/ +// Definitions by: Erik Lieben +// Leon Yu +// Sukhdeep Singh +// Jean-Francois Cere +// Sebastien Cote +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.3 + +/// +/// + +declare namespace Materialize { + /** + * The collapsible options + */ + interface CollapsibleOptions { + /** + * A setting that changes the collapsible behavior to expandable instead of the default accordion style + */ + accordion?: boolean; + + /** + * Callback for Collapsible section close. + * @default `function() { alert('Closed'); }` + */ + onClose?: Function; + + /** + * Callback for Collapsible section open. + * @default `function() { alert('Opened'); }` + */ + onOpen?: Function; + } + + interface TooltipOptions { + /** + * The delay before the tooltip shows (in milliseconds) + */ + delay: number; + /** + * Tooltip text. Can use custom HTML if you set the html option + */ + tooltip?: string; + /** + * Set the direction of the tooltip. 'top', 'right', 'bottom', 'left'. + * + * @default `'bottom'` + */ + position?: string; + /** + * Allow custom html inside the tooltip. + * + * @default `false` + */ + html?: boolean; + } + + /** + * The dropdown options + */ + interface DropDownOptions { + /** + * The duration of the transition enter in milliseconds. + * @default `300` + */ + inDuration?: number; + + /** + * The duration of the transition out in milliseconds. + * @default `225` + */ + outDuration?: number; + + /** + * If true, constrainWidth to the size of the dropdown activator. + * @default `true` + */ + constrainWidth?: boolean; + /** + * If true, the dropdown will open on hover. + * @default `false` + */ + hover?: boolean; + + /** + * This defines the spacing from the aligned edge. + * @default `0` + */ + gutter?: number; + + /** + * If true, the dropdown will show below the activator. + * @default `false` + */ + belowOrigin?: boolean; + + /** + * Defines the edge the menu is aligned to. + * @default `'left'` + */ + alignment?: string; + /** + * If true, stops the event propagating from the dropdown origin click handler. + * + * @default `false` + */ + stopPropagation?: boolean; + } + + /** + * The slider options + */ + interface SliderOptions { + /** + * Set to false to hide slide indicators. + * @default `true` + */ + indicators?: boolean; + + /** + * Set height of slider. + * @default `400` + */ + height?: number; + + /** + * Set the duration of the transition animation in ms. + * @default `500` + */ + transition?: number; + + /** + * Set the duration between transitions in ms. + * @default `6000` + */ + interval?: number; + } + + /** + * The carousel options + */ + interface CarouselOptions { + /** + * Transition duration in milliseconds + * @default `200` + */ + duration?: number; + + /** + * Perspective zoom. If 0, all items are the same size. + * @default `-100` + */ + dist?: number; + + /** + * Set the duration of the transition animation in ms. + * @default `500` + */ + shift?: number; + + /** + * Set the duration between transitions in ms. + * @default `6000` + */ + padding?: number; + + /** + * Set the width of the carousel. + * @default `false` + */ + fullWidth?: boolean; + /** + * Set to true to show indicators. + * + * @default `false` + */ + indicators?: boolean; + /** + * Don't wrap around and cycle through items. + * + * @default `false` + */ + noWrap?: boolean; + } + + /** + * The modal options + */ + interface ModalOptions { + /** + * Modal can be dismissed by clicking outside of the modal. + * @default `true` + */ + dismissible?: boolean; + + /** + * Opacity of modal background. + * @default `.5` + */ + opacity?: number; + + /** + * Transition in duration. + * @default `300` + */ + inDuration?: number; + + /** + * Transition out duration. + * @default `200` + */ + outDuration?: number; + /** + * Starting top style attribute + * @default `4%` + */ + startingTop?: string; + /** + * Ending top style attribute + * @default `10%` + */ + endingTop?: string; + + /** + * Callback for Modal open. + * @default `function() { alert('Ready'); }` + */ + ready?: Function; + + /** + * Callback for Modal close. + * @default `function() { alert('Closed'); }` + */ + complete?: Function; + } + + /** + * The push pin options + */ + interface PushpinOptions { + /** + * The distance in pixels from the top of the page where the element becomes fixed. + * @default `0` + */ + top?: number; + + /** + * The distance in pixels from the top of the page where the elements stops being fixed. + * @default `Infinity` + */ + bottom?: number; + + /** + * The offset from the top the element will be fixed at. + * @default `0` + */ + offset?: number; + } + + /** + * The scroll spy options + */ + interface ScrollSpyOptions { + /** + * Offset from top. + * @default `200` + */ + scrollOffset?: number; + /** + * Class name to be added to the active link. + * @default `active` + */ + activeClass?: string; + /** + * Function that returns a selector to add activeClass to. The parameter is the section id + */ + getActiveElement?: Function; + } + + /** + * The slideNav options + */ + interface SideNavOptions { + /** + * The sideNav width. + * @default `240` + */ + menuWidth?: number; + + /** + * The horizontal origin. + * @default `'left'` + */ + edge?: string; + + /** + * Closes sideNav on clicks, useful for Angular/Meteor. + * @default `false` + */ + closeOnClick?: boolean; + + /** + * Choose whether you can drag to open on touch screens. + * @default `true` + */ + draggable?: boolean; + + /** + * Execute a callback function when sideNav is opened. + * + * The callback provides a parameter which refers to the sideNav being opened. + */ + onOpen?: Function; + + /** + * Execute a callback function when sideNav is closed. + * + * The callback provides a parameter which refers to the sideNav being closed. + */ + onClose?: Function; + } + + interface ScrollFireOptions { + /** + * The selector for the element that is being tracked. + */ + selector?: string; + + /** + * Offset to use when activating the scroll fire event + * If this is 0, the callback will be fired when the selector element is at the very bottom of the user's window. + */ + offset?: number; + + /** + * The string function call that you want to make when the user scrolls to the threshold. + * It will only be called once. + * Example: 'console.log("hello, world!")'; + * or callback: () => { console.log('hello world'); } + */ + callback?: string | (() => void); + } + + interface TabOptions { + /** + * Execute a callback function when the tab is changed. + * + * The callback provides a parameter which refers to the current tab being shown. + */ + onShow?: Function; + + /** + * Set to true to enable swipeable tabs. This also uses the responsiveThreshold option. + * + * @default `false` + */ + swipeable?: boolean; + + /** + * The maximum width of the screen, in pixels, where the swipeable functionality initializes. + * + * @default `Infinity` + */ + responsiveThreshold?: number; + } + + interface ChipDataObject { + tag: string; + image?: string; + id?: number; + } + + interface ChipOptions { + /** + * Set the chip data + */ + data?: ChipDataObject[]; + /** + * Set first placeholder when there are no tags + */ + placeholder?: string; + /** + * Set second placeholder when adding additional tags. + */ + secondaryPlaceholder?: string; + /** + * Set autocomplete data. + */ + autocompleteData?: any; + /** + * Set autocomplete limit. + */ + autocompleteLimit?: number; + /** + * Set autocompleteOptions + */ + autocompleteOptions?: AutoCompleteOptions; + } + + interface AutoCompleteOptions { + /** + * The JSON object data to be used for the autocomplete suggetions list + */ + data: object; + /** + * The max amount of results that can be shown at once. + * @default `Infinity` + */ + limit?: number; + /** + * Callback function when value is autcompleted. + */ + onAutocomplete?: (val: any) => void; + /** + * The minimum length of the input for the autocomplete to start. + * @default `1` + */ + minLength?: number; + } + + interface Toast { + /** + * Dismiss all toasts + */ + removeAll: Function; + } + + /** + * The Materialize object + */ + interface Materialize { + /** + * Displays a toast message on screen + * + * @param string | JQuery message The message to display on screen + * @param number displayLength The duration in milliseconds to display the message on screen + * @param string className The className to use to format the message to display + * @param Function completeCallback Callback function to call when the messages completes/hides. + */ + toast(message: string | JQuery, displayLength: number, className?: string, completeCallback?: Function): void; + + /** + * Fires an event when the page is scrolled to a certain area + * + * @param ScrollFireOptions options optional parameter with scroll fire options + */ + scrollFire(options?: ScrollFireOptions[]): void; + + /** + * A staggered reveal effect for any UL Tag with list items + * + * @param string selector the selector for the list to show in staggered fasion + */ + showStaggeredList(selector: string): void; + + /** + * Fade in images. It also animates grayscale and brightness to give it a unique effect. + * + * @param string selector the selector for the image to fade in + */ + fadeInImage(selector: string): void; + + /** + * Update all text field to reinitialize all the Materialize labels on the page if dynamically adding inputs + */ + updateTextFields(): void; + + /** + * Toast functions + */ + Toast: Toast; + } +} + +/** + * Declare Pickadate namespace again in order to add more Materialize specific properties to TimeOptions interface + * + * @see http://www.typescriptlang.org/docs/handbook/declaration-merging.html + */ +declare namespace Pickadate { + interface TimeOptions { + /** + * Set default time such as : 'now', '1:30AM', '16:30'. + * @default `'now'` + */ + default?: string; + /** + * set default time to * milliseconds from now (using with default = 'now') + * @default `0` + */ + fromnow?: number; + /** + * Use AM/PM or 24-hour format + * @default `false` + */ + twelvehour?: boolean; + /** + * text for done-button + * @default `'OK'` + */ + donetext?: string; + /** + * text for clear-button + * @default `'Clear'` + */ + cleartext?: string; + /** + * Text for cancel-button + * @default `'Cancel'` + */ + canceltext?: string; + /** + * automatic close timepicker + * @default `false` + */ + autoclose?: boolean; + /** + * make AM PM clickable + * @default `true` + */ + ampmclickable?: boolean; + /** + * Function for after opening timepicker + */ + aftershow?: Function; + } +} + +declare var Materialize: Materialize.Materialize; + +interface JQuery { + /** + * open Fixed Action Button + */ + openFAB(): void; + /** + * close Fixed Action Button + */ + closeFAB(): void; + + /** + * Select allows user input through specified options. + * + * @param string method "destroy" destroy the material select + */ + material_select(method?: string): void; + + /** + * Use a character counter in fields where a character restriction is in place. + */ + characterCounter(): JQuery; + + /** + * Collapsibles are accordion elements that expand when clicked on. + * They allow you to hide content that is not immediately relevant to the user. + * + * @param CollapsibleOptions | string options the collapsible options or the string "destroy" to destroy the collapsible + */ + collapsible(options?: Materialize.CollapsibleOptions | string): JQuery; + + /** + * Programmatically trigger an event on a selected index + * + * @param string method the string "open" or "close" to open or to close the collapsible element on specified index + * @param number index the element index to trigger "open" or "close" function + */ + collapsible(method: string, index: number): JQuery; + + /** + * Tooltips are small, interactive, textual hints for mainly graphical elements. + * When using icons for actions you can use a tooltip to give people clarification on its function. + * + * @param TooltipOptions | string options the tooltip options or the string "remove" to remove the tooltip function + */ + tooltip(options?: Materialize.TooltipOptions | string): JQuery; + + /** + * Add a dropdown list to any button. + * Make sure that the data-activates attribute matches the id in the
      tag. + * + * @param DropDownOptions options the drop down options + */ + dropdown(options?: Materialize.DropDownOptions): void; + + /** + * Material box is a material design implementation of the Lightbox plugin. + */ + materialbox(): JQuery; + + /** + * slider is a simple and elegant image carousel. + * You can also have captions that will be transitioned on their own depending on their alignment. + * You can also have indicators that show up on the bottom of the slider. + * + * @param SliderOptions options the slider options + */ + slider(options?: Materialize.SliderOptions): JQuery; + + /** + * slider is a simple and elegant image carousel. + * You can also have captions that will be transitioned on their own depending on their alignment. + * You can also have indicators that show up on the bottom of the slider. + * + * @param string method the string "start" to start the animation or "pauze" to pauze the animation + */ + slider(method: string): JQuery; + + /** + * Our slider is a simple and elegant image carousel. + * You can also have captions that will be transitioned on their own depending on their alignment. + * You can also have indicators that show up on the bottom of the slider. + * + * @param CarouselOptions options the slider options or the string "start" to start the animation or "pauze" to pauze the animation + */ + carousel(options?: Materialize.CarouselOptions): JQuery; + + /** + * Our slider is a simple and elegant image carousel. + * You can also have captions that will be transitioned on their own depending on their alignment. + * You can also have indicators that show up on the bottom of the slider. + * + * @param string method the methods to pause, start, move to next and move to previous slide. + */ + carousel(method: string, count?: number): JQuery; + + /** + * Modal for dialog boxes, confirmation messages, or other content that can be called up. + * + * To customize the behaviour of a modal + * + * @param ModalOptions options the lean modal options + */ + modal(options?: Materialize.ModalOptions): void; + + /** + * Modal for dialog boxes, confirmation messages, or other content that can be called up. + * + * For opening and closing modals programatically. + * + * @param string action action to do (`open` or `close) + */ + modal(action: string, options?: Materialize.ModalOptions): void; + + /** + * Parallax is an effect where the background content or image in this case, is moved at a different speed than the foreground content while scrolling. + */ + parallax(): JQuery; + + /** + * Pushpin is a fixed positioning plugin. + * + * @param PushpinOptions options the push pin options + */ + pushpin(options?: Materialize.PushpinOptions): JQuery; + + /** + * Scrollspy is a jQuery plugin that tracks certain elements and which element the user's screen is currently centered on. + * + * @param ScrollSpyOptions options the scroll spy options + */ + scrollSpy(options?: Materialize.ScrollSpyOptions): JQuery; + + /** + * A slide out menu. You can add a dropdown to your sidebar by using our collapsible component. + * + * @param SideNavOptions | string methodOrOptions the slide navigation options or a string with "show" to reveal or "hide" to hide the menu + */ + sideNav(methodOrOptions?: Materialize.SideNavOptions | string): void; + + /** + * Programmatically trigger the tab change event + * + * @param string method : the method to call (always "select_tab") + * @param string tab : id of the tab to open + */ + tabs(method?: string, tab?: string): JQuery; + + /** + * Tab Initialization with options + * + * @param TabOptions options jQuery plugin options + */ + tabs(options?: Materialize.TabOptions): JQuery; + + /** + * Chip Initialization + * + * @param ChipOptions options Material chip options + */ + material_chip(options?: Materialize.ChipOptions): JQuery; + + /** + * To access chip data + * + * @param string method name of the method to invoke + */ + material_chip(method: string): Materialize.ChipDataObject[] | Materialize.ChipDataObject; + + /** + * Add an autocomplete dropdown below your input to suggest possible values. + * @param autocompleteOptions options : @see autocompleteOptions for possible options + */ + autocomplete(options: Materialize.AutoCompleteOptions): JQuery; + + /** + * Feature discovery - open and close a tap target + * @param string action : either `'open'` or `'close'` + */ + tapTarget(action?: string): JQuery; +} diff --git a/types/materialize-css/materialize-css-tests.ts b/types/materialize-css/v0/materialize-css-tests.ts similarity index 100% rename from types/materialize-css/materialize-css-tests.ts rename to types/materialize-css/v0/materialize-css-tests.ts diff --git a/types/jquery.tooltipster/tsconfig.json b/types/materialize-css/v0/tsconfig.json similarity index 58% rename from types/jquery.tooltipster/tsconfig.json rename to types/materialize-css/v0/tsconfig.json index edc2812c82..4f000774ea 100644 --- a/types/jquery.tooltipster/tsconfig.json +++ b/types/materialize-css/v0/tsconfig.json @@ -5,20 +5,25 @@ "es6", "dom" ], - "noImplicitAny": false, - "noImplicitThis": false, + "noImplicitAny": true, + "noImplicitThis": true, "strictNullChecks": false, "strictFunctionTypes": true, - "baseUrl": "../", + "baseUrl": "../../", "typeRoots": [ - "../" + "../../" ], + "paths": { + "materialize-css": [ + "materialize-css/v0" + ] + }, "types": [], "noEmit": true, "forceConsistentCasingInFileNames": true }, "files": [ "index.d.ts", - "jquery.tooltipster-tests.ts" + "materialize-css-tests.ts" ] -} \ No newline at end of file +} diff --git a/types/materialize-css/v0/tslint.json b/types/materialize-css/v0/tslint.json new file mode 100644 index 0000000000..99070fa5c7 --- /dev/null +++ b/types/materialize-css/v0/tslint.json @@ -0,0 +1,7 @@ +{ + "extends": "dtslint/dt.json", + "rules": { + "ban-types": false, + "prefer-method-signature": false + } +} diff --git a/types/minimatch/index.d.ts b/types/minimatch/index.d.ts index 5c9bd38a28..d5942d536b 100644 --- a/types/minimatch/index.d.ts +++ b/types/minimatch/index.d.ts @@ -27,7 +27,7 @@ declare namespace M { */ function makeRe(pattern: string, options?: IOptions): RegExp; - var Minimatch: IMinimatchStatic; + let Minimatch: IMinimatchStatic; interface IOptions { /** diff --git a/types/minimatch/minimatch-tests.ts b/types/minimatch/minimatch-tests.ts index 5b7a3bdb18..6bbafcae5c 100644 --- a/types/minimatch/minimatch-tests.ts +++ b/types/minimatch/minimatch-tests.ts @@ -1,17 +1,17 @@ import mm = require("minimatch"); - -var pattern = "**/*.ts"; -var options = { +let bool: boolean; +const pattern = "**/*.ts"; +const options = { debug: true }; -var m = new mm.Minimatch(pattern, options); -var r = m.makeRe(); +const m = new mm.Minimatch(pattern, options); +const regxp = m.makeRe(); -var f = ["test.ts"]; -mm.match(f, pattern, options); +const files = ["test.ts"]; +mm.match(files, pattern, options); -f.filter(mm.filter(pattern, options)); +files.filter(mm.filter(pattern, options)); -var s: string = "hello"; -var b: boolean = mm(s, pattern, options); -var b: boolean = mm(s, pattern); +const str = "hello"; +bool = mm(str, pattern, options); +bool = mm(str, pattern); diff --git a/types/minimatch/tslint.json b/types/minimatch/tslint.json index a41bf5d19a..78ac1711c4 100644 --- a/types/minimatch/tslint.json +++ b/types/minimatch/tslint.json @@ -1,79 +1,7 @@ { "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 + "no-redundant-jsdoc-2": false } } diff --git a/types/mkdirp/index.d.ts b/types/mkdirp/index.d.ts index db9f66c8ca..f1edeeda8b 100644 --- a/types/mkdirp/index.d.ts +++ b/types/mkdirp/index.d.ts @@ -1,14 +1,40 @@ -// Type definitions for mkdirp 0.5.1 +// Type definitions for mkdirp 0.5 // Project: https://github.com/substack/node-mkdirp // Definitions by: Bart van der Schoor +// mrmlnc // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped /// -declare function mkdirp(dir: string, cb: (err: NodeJS.ErrnoException, made: string) => void): void; -declare function mkdirp(dir: string, opts: any, cb: (err: NodeJS.ErrnoException, made: string) => void): void; +import fs = require('fs'); + +declare function mkdirp(dir: string, cb: (err: NodeJS.ErrnoException, made: mkdirp.Made) => void): void; +declare function mkdirp(dir: string, opts: mkdirp.Mode | mkdirp.Options, cb: (err: NodeJS.ErrnoException, made: mkdirp.Made) => void): void; declare namespace mkdirp { - function sync(dir: string, opts?: any): string; + type Made = string | null; + type Mode = number | string | null; + + interface FsImplementation { + mkdir: typeof fs.mkdir; + stat: typeof fs.stat; + } + + interface FsImplementationSync { + mkdirSync: typeof fs.mkdirSync; + statSync: typeof fs.statSync; + } + + interface Options { + mode?: Mode; + fs?: FsImplementation; + } + + interface OptionsSync { + mode?: Mode; + fs?: FsImplementationSync; + } + + function sync(dir: string, opts?: Mode | OptionsSync): Made; } export = mkdirp; diff --git a/types/mkdirp/mkdirp-tests.ts b/types/mkdirp/mkdirp-tests.ts index d17dff4e22..3c09001925 100644 --- a/types/mkdirp/mkdirp-tests.ts +++ b/types/mkdirp/mkdirp-tests.ts @@ -1,23 +1,17 @@ - import mkdirp = require('mkdirp'); -var str: string; -var num: number; -var opts = { - mode: num, - fs: {} -}; +mkdirp('str', (err, made) => { + const str: string = made; +}); +mkdirp('str', '0777', (err, made) => {}); +mkdirp('str', {}, (err, made) => {}); +mkdirp('str', { mode: '0777' }, (err, made) => {}); -mkdirp(str, num, (err, made) => { - str = made; -}); -mkdirp(str, opts, (err, made) => { - str = made; -}); -mkdirp(str, (err, made) => { - str = made; -}); +// $ExpectType string +mkdirp.sync('str'); +mkdirp.sync('str', '0777'); +mkdirp.sync('str', {}); +mkdirp.sync('str', { mode: '0777' }); -str = mkdirp.sync(str, num); -str = mkdirp.sync(str, opts); -str = mkdirp.sync(str); +// $ExpectError +mkdirp.sync('str', { mode: '0777', fs: {} }); diff --git a/types/mkdirp/tslint.json b/types/mkdirp/tslint.json index a41bf5d19a..f93cf8562a 100644 --- a/types/mkdirp/tslint.json +++ b/types/mkdirp/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/mobx-apollo/index.d.ts b/types/mobx-apollo/index.d.ts index 4054601717..54818cd846 100644 --- a/types/mobx-apollo/index.d.ts +++ b/types/mobx-apollo/index.d.ts @@ -19,7 +19,7 @@ export interface MobxApolloQueryOptions extends WatchQueryOptions { export interface MobxApolloQuery { loading: boolean; - data: T; + data?: T; error?: ApolloError; ref: ObservableQuery; } diff --git a/types/mobx-apollo/mobx-apollo-tests.ts b/types/mobx-apollo/mobx-apollo-tests.ts index 964e6b0c6e..50d6b03abb 100644 --- a/types/mobx-apollo/mobx-apollo-tests.ts +++ b/types/mobx-apollo/mobx-apollo-tests.ts @@ -27,7 +27,7 @@ class PostStore { } get posts() { - return this.postsQuery.data.posts; + return this.postsQuery.data && this.postsQuery.data.posts; } } diff --git a/types/mock-aws-s3/index.d.ts b/types/mock-aws-s3/index.d.ts new file mode 100644 index 0000000000..754629f5a2 --- /dev/null +++ b/types/mock-aws-s3/index.d.ts @@ -0,0 +1,15 @@ +// Type definitions for mock-aws-s3 2.6 +// Project: https://github.com/MathieuLoutre/mock-aws-s3 +// Definitions by: Elliot Blackburn +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped/tree/master/types/mock-aws-s3 +// TypeScript Version: 2.2 + +// This is a mocking library, types should reflect that of the actual library. +export * from "aws-sdk"; +import { GlobalConfigInstance } from "aws-sdk/lib/config"; + +export interface MockConfigInstance extends GlobalConfigInstance { + basePath: string; +} + +export let config: MockConfigInstance; diff --git a/types/mock-aws-s3/mock-aws-s3-tests.ts b/types/mock-aws-s3/mock-aws-s3-tests.ts new file mode 100644 index 0000000000..b517729968 --- /dev/null +++ b/types/mock-aws-s3/mock-aws-s3-tests.ts @@ -0,0 +1,16 @@ +import * as MockAWS from "mock-aws-s3"; + +const s3 = new MockAWS.S3({ + params: { Bucket: "example" } +}); + +s3.putObject( + { + Bucket: "example", + Key: "sea/animal.json", + Body: '{"is dog":false,"name":"otter","stringified object?":true}' + }, + (err: MockAWS.AWSError, data: MockAWS.S3.Types.PutObjectOutput) => { + s3.listObjects({ Bucket: 'example', Prefix: "sea" }, (err: any, data: any) => {}); + } +); diff --git a/types/mock-aws-s3/package.json b/types/mock-aws-s3/package.json new file mode 100644 index 0000000000..6298c6d4c8 --- /dev/null +++ b/types/mock-aws-s3/package.json @@ -0,0 +1,6 @@ +{ + "private": true, + "dependencies": { + "aws-sdk": ">=2.169.0" + } +} diff --git a/types/mock-aws-s3/tsconfig.json b/types/mock-aws-s3/tsconfig.json new file mode 100644 index 0000000000..9b5aeeacaa --- /dev/null +++ b/types/mock-aws-s3/tsconfig.json @@ -0,0 +1,16 @@ +{ + "compilerOptions": { + "module": "commonjs", + "lib": ["es6"], + "noImplicitAny": true, + "noImplicitThis": true, + "strictNullChecks": true, + "strictFunctionTypes": true, + "baseUrl": "../", + "typeRoots": ["../"], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true + }, + "files": ["index.d.ts", "mock-aws-s3-tests.ts"] +} diff --git a/types/mock-aws-s3/tslint.json b/types/mock-aws-s3/tslint.json new file mode 100644 index 0000000000..f93cf8562a --- /dev/null +++ b/types/mock-aws-s3/tslint.json @@ -0,0 +1,3 @@ +{ + "extends": "dtslint/dt.json" +} diff --git a/types/moment-business-time/index.d.ts b/types/moment-business-time/index.d.ts new file mode 100644 index 0000000000..dc4022f161 --- /dev/null +++ b/types/moment-business-time/index.d.ts @@ -0,0 +1,41 @@ +// Type definitions for moment-business-time 0.7 +// Project: https://github.com/lennym/moment-business-time +// Definitions by: Tomasz Nguyen +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +/*~ On this line, import the module which this module adds to */ +import * as moment from 'moment'; + +/*~ Here, declare the same module as the one you imported above */ +declare module 'moment' { + interface Moment { + nextWorkingDay: () => Moment; + nextWorkingTime: () => Moment; + + lastWorkingDay: () => Moment; + lastWorkingTime: () => Moment; + + addWorkingTime: (...args: Array) => Moment; + subtractWorkingTime: (...args: Array) => Moment; + + workingDiff: (moment: Moment, unit: unitOfTime.Base, fractions?: boolean) => Moment; + + isWorkingDay: () => boolean; + isWorkingTime: () => boolean; + } + + interface WorkingHoursMap { + 0: string[] | null; + 1: string[] | null; + 2: string[] | null; + 3: string[] | null; + 4: string[] | null; + 5: string[] | null; + 6: string[] | null; + } + + interface LocaleSpecification { + workinghours?: WorkingHoursMap; + holidays?: string[]; + } +} diff --git a/types/moment-business-time/moment-business-time-tests.ts b/types/moment-business-time/moment-business-time-tests.ts new file mode 100644 index 0000000000..79f25a720a --- /dev/null +++ b/types/moment-business-time/moment-business-time-tests.ts @@ -0,0 +1,56 @@ +import * as moment from 'moment'; +import 'moment-business-time'; + +moment('2015-02-28T10:00:00Z').nextWorkingDay(); +moment('2015-02-28T20:00:00Z').nextWorkingDay(); +moment('2015-02-28T10:00:00Z').nextWorkingTime(); +moment('2015-02-28T20:00:00Z').nextWorkingTime(); +moment('2015-02-28T10:00:00Z').lastWorkingDay(); +// Fri Feb 27 2015 10:00:00 GMT+0000 +moment('2015-02-28T20:00:00Z').lastWorkingDay(); +// Fri Feb 27 2015 20:00:00 GMT+0000 +moment('2015-02-27T10:00:00Z').addWorkingTime(5, 'hours'); +// Fri Feb 27 2015 15:00:00 GMT+0000 +moment('2015-02-28T10:00:00Z').addWorkingTime(5, 'hours'); +// Mon Mar 02 2015 14:00:00 GMT+0000 +moment('2015-02-27T10:00:00Z').addWorkingTime(5, 'hours', 30, 'minutes'); +// Fri Feb 27 2015 15:30:00 GMT+0000 +moment('2015-02-27T16:00:00Z').subtractWorkingTime(5, 'hours'); +// Fri Feb 27 2015 11:00:00 GMT+0000 +moment('2015-02-28T16:00:00Z').subtractWorkingTime(5, 'hours'); +// Fri Feb 27 2015 12:00:00 GMT+0000 +moment('2015-02-27T16:00:00Z').subtractWorkingTime(5, 'hours', 30, 'minutes'); +// Fri Feb 27 2015 10:30:00 GMT+0000 +moment('2015-02-27T16:30:00Z').workingDiff(moment('2015-02-26T12:00:00Z'), 'hours'); +// 12 +moment('2015-02-27T16:30:00Z').workingDiff(moment('2015-02-26T12:00:00Z'), 'hours', true); +// 12.5 +// set opening time to 09:30 and close early on Wednesdays +moment.updateLocale('en', { + workinghours: { + 0: null, + 1: ['09:30:00', '17:00:00'], + 2: ['09:30:00', '17:00:00'], + 3: ['09:30:00', '13:00:00'], + 4: ['09:30:00', '17:00:00'], + 5: ['09:30:00', '17:00:00'], + 6: null + } +}); +moment('2015-02-25T15:00:00Z').isWorkingTime(); // false +moment('2015-02-23T09:00:00Z').isWorkingTime(); // false +moment.updateLocale('en', { + holidays: [ + '2015-05-04' + ] +}); +moment('2015-05-04T09:30:00Z').isWorkingDay(); // false +moment.updateLocale('en', { + holidays: [ + '*-12-25' + ] +}); +moment('2015-12-25T16:30:00Z').isWorkingDay(); // false +moment('2016-12-25T16:30:00Z').isWorkingDay(); // false +moment('2017-12-25T16:30:00Z').isWorkingDay(); // false +moment('2018-12-25T16:30:00Z').isWorkingDay(); // false diff --git a/types/moment-business-time/package.json b/types/moment-business-time/package.json new file mode 100644 index 0000000000..19e5fb0d14 --- /dev/null +++ b/types/moment-business-time/package.json @@ -0,0 +1,6 @@ +{ + "private": true, + "dependencies": { + "moment": ">=2.14.0" + } +} diff --git a/types/moment-business-time/tsconfig.json b/types/moment-business-time/tsconfig.json new file mode 100644 index 0000000000..c1212caa2f --- /dev/null +++ b/types/moment-business-time/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", + "moment-business-time-tests.ts" + ] +} diff --git a/types/moment-business-time/tslint.json b/types/moment-business-time/tslint.json new file mode 100644 index 0000000000..3db14f85ea --- /dev/null +++ b/types/moment-business-time/tslint.json @@ -0,0 +1 @@ +{ "extends": "dtslint/dt.json" } diff --git a/types/mongodb/index.d.ts b/types/mongodb/index.d.ts index 32bc523d38..0c7b90edfd 100644 --- a/types/mongodb/index.d.ts +++ b/types/mongodb/index.d.ts @@ -5,7 +5,7 @@ // Gady Piazza // Jason Dreyzehner // Gaurav Lahoti -// Mariano Cortesi +// Mariano Cortesi // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped // TypeScript Version: 2.3 @@ -22,7 +22,7 @@ export function connect(uri: string, options?: MongoClientOptions): Promise; export function connect(uri: string, callback: MongoCallback): void; export function connect(uri: string, options: MongoClientOptions, callback: MongoCallback): void; -export { Binary, Double, Long, Decimal128, MaxKey, MinKey, ObjectID, ObjectId, Timestamp } from 'bson'; +export { Binary, Double, Long, Decimal128, MaxKey, MinKey, ObjectID, ObjectId, Timestamp, DBRef } from 'bson'; // Class documentation : http://mongodb.github.io/node-mongodb-native/2.1/api/MongoClient.html export class MongoClient { diff --git a/types/mongoose/index.d.ts b/types/mongoose/index.d.ts index f86dea4f8a..7eb768f3c8 100644 --- a/types/mongoose/index.d.ts +++ b/types/mongoose/index.d.ts @@ -366,11 +366,11 @@ declare module "mongoose" { auth?: any; /** Use ssl connection (needs to have a mongod server with ssl support) (default: true) */ ssl?: boolean; - /** Number of connections in the connection pool for each server instance, set to 5 as default for legacy reasons. */ - sslValidate?: object; - /** Reconnect on error (default: true) */ - poolSize?: number; /** Validate mongod server certificate against ca (needs to have a mongod server with ssl support, 2.4 or higher) */ + sslValidate?: object; + /** Number of connections in the connection pool for each server instance, set to 5 as default for legacy reasons. */ + poolSize?: number; + /** Reconnect on error (default: true) */ autoReconnect?: boolean; /** TCP KeepAlive on the socket with a X ms delay before start (default: 0). */ keepAlive?: number; @@ -380,10 +380,13 @@ declare module "mongoose" { socketTimeoutMS?: number; /** If the database authentication is dependent on another databaseName. */ authSource?: string; - /** Attempt to reconnect #times (default: 30) */ - retries?: number; + /** If you're connected to a single server or mongos proxy (as opposed to a replica set), + * the MongoDB driver will try to reconnect every reconnectInterval milliseconds for reconnectTries + * times, and give up afterward. When the driver gives up, the mongoose connection emits a + * reconnectFailed event. (default: 30) */ + reconnectTries?: number; /** Will wait # milliseconds between retries (default: 1000) */ - reconnectWait?: number; + reconnectInterval?: number; /** The name of the replicaset to connect to. */ replicaSet?: string; /** The current value of the parameter native_parser */ @@ -400,6 +403,14 @@ declare module "mongoose" { readPreference?: string; /** An object representing read preference tags, see: http://mongodb.github.io/node-mongodb-native/2.1/api/ReadPreference.html */ readPreferencetags?: object; + /** Triggers the server instance to call ismaster (default: true). */ + monitoring?: boolean; + /** The interval of calling ismaster when monitoring is enabled (default: 10000). */ + haInterval?: number; + /** Enable the wrapping of the callback in the current domain, disabled by default to avoid perf hit (default: false). */ + domainsEnabled?: boolean; + /** How long driver keeps waiting for servers to come back up (default: Number.MAX_VALUE) */ + bufferMaxEntries?: number; // TODO safe?: any; diff --git a/types/nes/client.d.ts b/types/nes/client.d.ts index 8314894683..5d348b267e 100644 --- a/types/nes/client.d.ts +++ b/types/nes/client.d.ts @@ -1,6 +1,7 @@ -// Type definitions for nes 6.4.2 +// Type definitions for nes 7.0.0 // Project: https://github.com/hapijs/nes // Definitions by: Ivo Stratev +// Rodrigo Saboya // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped declare class Client { @@ -9,14 +10,14 @@ declare class Client { onConnect: () => void; onDisconnect: () => void; onUpdate: (message: any) => void; - connect(options: Client.ClientConnectOptions, callback: (err?: any) => void): void; - connect(callback: (err?: any) => void): void; - disconnect(): void; + connect(options: Client.ClientConnectOptions): Promise; + connect(): Promise; + disconnect(): Promise; id: any; // can be `null | number` but also the "socket" value from websocket message data. - request(options: string | Client.ClientRequestOptions, callback: (err: any, payload: any, statusCode?: number, headers?: Object) => void): void; - message(message: any, callback: (err: any, message: any) => void): void; - subscribe(path: string, handler: Client.Handler, callback: (err?: any) => void): void; - unsubscribe(path: string, handler: Client.Handler, callback: (err?: any) => void): void; + request(options: string | Client.ClientRequestOptions): Promise; + message(message: any): Promise; + subscribe(path: string, handler: Client.Handler): Promise; + unsubscribe(path: string, handler: Client.Handler): Promise; subscriptions(): string[]; overrideReconnectionAuth(auth: any): void; } diff --git a/types/nes/index.d.ts b/types/nes/index.d.ts index a6ed90a7b7..c4d26ecda0 100644 --- a/types/nes/index.d.ts +++ b/types/nes/index.d.ts @@ -1,6 +1,7 @@ -// Type definitions for nes 6.2.1 +// Type definitions for nes 7.0.0 // Project: https://github.com/hapijs/nes // Definitions by: Ivo Stratev +// Rodrigo Saboya // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped // TypeScript Version: 2.4 @@ -62,12 +63,12 @@ declare module nes { index?: boolean; } - export type ServerOnSubscribeWithParams = (socket: Socket, path: string, params: any, next: (err?: any) => void) => void; - export type ServerOnSubscribeWithoutParams = (socket: Socket, path: string, next: (err?: any) => void) => void; + export type ServerOnSubscribeWithParams = (socket: Socket, path: string, params: any) => Promise; + export type ServerOnSubscribeWithoutParams = (socket: Socket, path: string) => Promise; export type ServerOnSubscribe = ServerOnSubscribeWithParams | ServerOnSubscribeWithoutParams; - export type ServerOnUnSubscribeWithParams = (socket: Socket, path: string, params: any, next: () => void) => void; - export type ServerOnUnSubscribeWithoutParams = (socket: Socket, path: string, next: () => void) => void; + export type ServerOnUnSubscribeWithParams = (socket: Socket, path: string, params: any) => void; + export type ServerOnUnSubscribeWithoutParams = (socket: Socket, path: string) => void; export type ServerOnUnSubscribe = ServerOnUnSubscribeWithParams | ServerOnUnSubscribeWithoutParams; interface ServerSubscriptionOptions { @@ -91,10 +92,10 @@ declare module nes { id: string; app: Object; auth: nes.SocketAuthObject; - disconnect(callback?: () => void): void; - send(message: any, callback?: (err?: any) => void): void; - publish(path: string, message: any, callback?: (err?: any) => void): void; - revoke(path: string, message: any, callback?: (err?: any) => void): void; + disconnect(): Promise; + send(message: any): Promise; + publish(path: string, message: any): Promise; + revoke(path: string, message: any): Promise; } /** diff --git a/types/nes/test/broadcast-client.ts b/types/nes/test/broadcast-client.ts index 4c94b8c575..5563a202d3 100644 --- a/types/nes/test/broadcast-client.ts +++ b/types/nes/test/broadcast-client.ts @@ -3,7 +3,7 @@ import Nes = require('nes'); var client = new Nes.Client('ws://localhost'); -client.connect(function (err) { +client.connect().then(() => { client.onUpdate = function (update) { @@ -16,7 +16,7 @@ client.connect(function (err) { import NesClient = require('nes/client'); var client = new NesClient('ws://localhost'); -client.connect(function (err) { +client.connect().then(() => { client.onUpdate = function (update) { diff --git a/types/nes/test/broadcast-server.ts b/types/nes/test/broadcast-server.ts index dcfcb3400e..6ef8f7aafa 100644 --- a/types/nes/test/broadcast-server.ts +++ b/types/nes/test/broadcast-server.ts @@ -4,11 +4,10 @@ import Hapi = require('hapi'); import Nes = require('nes'); var server = new Hapi.Server(); -server.connection(); -server.register(Nes, function (err) { +server.register(Nes).then(() => { - server.start(function (err) { + return server.start().then(() => { server.broadcast('welcome!'); }); diff --git a/types/nes/test/nes-tests.ts b/types/nes/test/nes-tests.ts index 90afe68f3e..85cff1e208 100644 --- a/types/nes/test/nes-tests.ts +++ b/types/nes/test/nes-tests.ts @@ -2,66 +2,55 @@ import Hapi = require('hapi'); import Nes = require('nes'); var server: Hapi.Server = new Hapi.Server(); -server.connection({port: 8080}); -server.register(Nes, (regErr) => { - if(regErr) { - console.log('register err'); - console.log(regErr); - } else { - // No longer need to cast to Nes.Server as Hapi.Server has been modified directly. - // let wsServer: Nes.Server = server as Nes.Server; - let wsServer: Hapi.Server = server; - wsServer.subscription('/item/{id}'); - wsServer.route( { - method: 'GET', - path: '/test', - config: { - handler: (request, reply) => { - reply({test: 'passes ' + request.socket.id}); - } +server.register(Nes).then(() => { + // No longer need to cast to Nes.Server as Hapi.Server has been modified directly. + // let wsServer: Nes.Server = server as Nes.Server; + let wsServer: Hapi.Server = server; + wsServer.subscription('/item/{id}'); + wsServer.route( { + method: 'GET', + path: '/test', + config: { + handler: (request, h) => { + return {test: 'passes ' + request.socket.id}; } - }); - wsServer.start((err: any) => { - if(err) { - console.log('start err'); - console.log(err); - } else { - setTimeout(() => { - wsServer.publish('/item/5', { id: 5, status: 'complete' }); - wsServer.publish('/item/6', { id: 6, status: 'initial' }); - }, 100); - } - }); - } + } + }); + wsServer.start().then(() => { + setTimeout(() => { + wsServer.publish('/item/5', { id: 5, status: 'complete' }); + wsServer.publish('/item/6', { id: 6, status: 'initial' }); + }, 100); + }).catch((err) => { + console.log('start err'); + console.log(err); + }); +}).catch((regErr: any) => { + console.log('register err'); + console.log(regErr); }); let options: Nes.ClientConnectOptions = {delay: 3}; -let wsClient: Nes.Client = new Nes.Client('ws://localhost:8080', options); -wsClient.connect((err: any) => { - if(err) { - console.log('start err'); - console.log(err); - } else { - wsClient.subscribe('/item/5', (update) => { - wsClient.request('/test', (reqErr, payload, statusCode) => { - if(reqErr) { - console.log('request err'); - console.log(reqErr); - } else { - console.log(update); - console.log(payload); - if(payload.test === 'passes') { - process.exit(0); - } - } - }) - }, (subErr) => { - if(subErr) { - console.log('subscribe err'); - console.log(subErr); +let wsClient: Nes.Client = new Nes.Client('ws://localhost', options); +wsClient.connect().then(() => { + wsClient.subscribe('/item/5', (update) => { + wsClient.request('/test').then(({ payload, statusCode }) => { + console.log(update); + console.log(payload); + if(payload.test === 'passes') { + process.exit(0); } - }); - } + }).catch((reqErr: any) => { + console.log('request err'); + console.log(reqErr); + }) + }).catch((subErr: any) => { + console.log('subscribe err'); + console.log(subErr); + }); +}).catch((err: any) => { + console.log('start err'); + console.log(err); }); diff --git a/types/nes/test/route-authentication-client.ts b/types/nes/test/route-authentication-client.ts index fe57eb8d56..f1eb8b9659 100644 --- a/types/nes/test/route-authentication-client.ts +++ b/types/nes/test/route-authentication-client.ts @@ -3,12 +3,9 @@ import Nes = require('nes'); var client = new Nes.Client('ws://localhost'); -client.connect({ auth: { headers: { authorization: 'Basic am9objpzZWNyZXQ=' } } }, function (err) { +client.connect({ auth: { headers: { authorization: 'Basic am9objpzZWNyZXQ=' } } }).then(() => { - client.request('hello', function (err, payload) { // Can also request '/h' - - // payload -> 'Hello John Doe' - }); + client.request('hello'); }); // Added in addition to nes doc example code @@ -16,10 +13,7 @@ client.connect({ auth: { headers: { authorization: 'Basic am9objpzZWNyZXQ=' } } import NesClient = require('nes/client'); var client = new NesClient('ws://localhost'); -client.connect({ auth: { headers: { authorization: 'Basic am9objpzZWNyZXQ=' } } }, function (err) { +client.connect({ auth: { headers: { authorization: 'Basic am9objpzZWNyZXQ=' } } }).then(() => { - client.request('hello', function (err, payload) { // Can also request '/h' - - // payload -> 'Hello John Doe' - }); + return client.request('hello'); }); diff --git a/types/nes/test/route-authentication-server.ts b/types/nes/test/route-authentication-server.ts index 5b4634d77d..2080f04ef4 100644 --- a/types/nes/test/route-authentication-server.ts +++ b/types/nes/test/route-authentication-server.ts @@ -8,7 +8,7 @@ import Nes = require('nes'); var server = new Hapi.Server(); server.connection(); -server.register([Basic, Nes], function (err) { +server.register([Basic, Nes]).then(() => { // Set up HTTP Basic authentication @@ -28,20 +28,20 @@ server.register([Basic, Nes], function (err) { } }; - var validate: Basic.ValidateFunc = function (request, username, password, callback) { + var validate: Basic.Validate = async (request, username, password, h) => { var user = users[username]; if (!user) { - return callback(null, false); + return { credentials: null, isValid: false }; } - Bcrypt.compare(password, user.password, function (err, isValid) { + let isValid = await Bcrypt.compare(password, user.password) - callback(err, isValid, { id: user.id, name: user.name }); - }); + return { isValid, credentials: { id: user.id, name: user.name } }; }; - server.auth.strategy('simple', 'basic', 'required', { validateFunc: validate }); + server.auth.strategy('simple', 'basic', { validateFunc: validate }); + server.auth.default('simple'); // Configure route with authentication @@ -50,12 +50,12 @@ server.register([Basic, Nes], function (err) { path: '/h', config: { id: 'hello', - handler: function (request, reply) { + handler: function (request, h) { - return reply('Hello ' + request.auth.credentials.name); + return 'Hello ' + request.auth.credentials.name; } } }); - server.start(function (err) { /* ... */ }); + return server.start(); }); diff --git a/types/nes/test/route-invocation-client.ts b/types/nes/test/route-invocation-client.ts index 7b144e3a9c..34c40fe151 100644 --- a/types/nes/test/route-invocation-client.ts +++ b/types/nes/test/route-invocation-client.ts @@ -3,12 +3,9 @@ import Nes = require('nes'); var client = new Nes.Client('ws://localhost'); -client.connect(function (err) { +client.connect().then(() => { - client.request('hello', function (err, payload) { // Can also request '/h' - - // payload -> 'world!' - }); + return client.request('hello'); }); // Added in addition to nes doc example code @@ -16,10 +13,7 @@ client.connect(function (err) { import NesClient = require('nes/client'); var client = new NesClient('ws://localhost'); -client.connect(function (err) { +client.connect().then(() => { - client.request('hello', function (err, payload) { // Can also request '/h' - - // payload -> 'world!' - }); + return client.request('hello'); }); diff --git a/types/nes/test/route-invocation-server.ts b/types/nes/test/route-invocation-server.ts index c32780baa9..d6893495c9 100644 --- a/types/nes/test/route-invocation-server.ts +++ b/types/nes/test/route-invocation-server.ts @@ -4,21 +4,20 @@ import Hapi = require('hapi'); import Nes = require('nes'); var server = new Hapi.Server(); -server.connection(); -server.register(Nes, function (err) { +server.register(Nes).then(() => { server.route({ method: 'GET', path: '/h', config: { id: 'hello', - handler: function (request, reply) { + handler: (request, h) => { - return reply('world!'); + return 'world!'; } } }); - server.start(function (err) { /* ... */ }); + return server.start(); }); diff --git a/types/nes/test/socket.ts b/types/nes/test/socket.ts index 7f7617d462..029dbb1d2f 100644 --- a/types/nes/test/socket.ts +++ b/types/nes/test/socket.ts @@ -4,13 +4,11 @@ import Nes = require('nes'); const socket: Nes.Socket = undefined; -const cb = () => { }; -socket.disconnect(cb); +socket.disconnect(); const s: string = socket.id; const o: Object = socket.app; const auth: Nes.SocketAuthObject = socket.auth; -const cb2 = (err?: any) => { }; -socket.send('message', (err?: any) => { }); -socket.publish('path', 'message', cb2); -socket.revoke('path', 'message', cb2); +socket.send('message'); +socket.publish('path', 'message'); +socket.revoke('path', 'message'); diff --git a/types/nes/test/subscription-filter-client.ts b/types/nes/test/subscription-filter-client.ts index 3f8d3ffb8b..05253539a4 100644 --- a/types/nes/test/subscription-filter-client.ts +++ b/types/nes/test/subscription-filter-client.ts @@ -6,15 +6,15 @@ var client = new Nes.Client('ws://localhost'); // Authenticate as 'john' -client.connect({ auth: { headers: { authorization: 'Basic am9objpzZWNyZXQ=' } } }, function (err) { +client.connect({ auth: { headers: { authorization: 'Basic am9objpzZWNyZXQ=' } } }).then(() => { - var handler: Nes.Handler = function (err, update) { + var handler: Nes.Handler = (update) => { // First publish is not received (filtered due to updater key) // update -> { id: 6, status: 'initial', updater: 'steve' } }; - client.subscribe('/items', handler, function (err) { }); + return client.subscribe('/items', handler); }); // Added in addition to nes doc example code @@ -25,13 +25,13 @@ var client = new NesClient('ws://localhost'); // Authenticate as 'john' -client.connect({ auth: { headers: { authorization: 'Basic am9objpzZWNyZXQ=' } } }, function (err) { +client.connect({ auth: { headers: { authorization: 'Basic am9objpzZWNyZXQ=' } } }).then(() => { - var handler: NesClient.Handler = function (err, update) { + var handler: NesClient.Handler = (update) => { // First publish is not received (filtered due to updater key) // update -> { id: 6, status: 'initial', updater: 'steve' } }; - client.subscribe('/items', handler, function (err) { }); + return client.subscribe('/items', handler); }); diff --git a/types/nes/test/subscription-filter-server.ts b/types/nes/test/subscription-filter-server.ts index be2dda8d7f..7a63abf151 100644 --- a/types/nes/test/subscription-filter-server.ts +++ b/types/nes/test/subscription-filter-server.ts @@ -6,9 +6,8 @@ import Bcrypt = require('bcrypt'); import Nes = require('nes'); var server = new Hapi.Server(); -server.connection(); -server.register([Basic, Nes], function (err) { +server.register([Basic, Nes]).then(() => { // Set up HTTP Basic authentication @@ -28,31 +27,31 @@ server.register([Basic, Nes], function (err) { } }; - var validate: Basic.ValidateFunc = function (request, username, password, callback) { + var validate: Basic.Validate = async (request, username, password, h) => { var user = users[username]; if (!user) { - return callback(null, false); + return { credentials: null, isValid: false }; } - Bcrypt.compare(password, user.password, function (err, isValid) { + let isValid = await Bcrypt.compare(password, user.password) - callback(err, isValid, { id: user.id, name: user.name, username: user.username }); - }); + return { isValid, credentials: { id: user.id, name: user.name, username: user.username } }; }; - server.auth.strategy('simple', 'basic', 'required', { validateFunc: validate }); + server.auth.strategy('simple', 'basic', { validate }); + server.auth.default('simple') // Set up subscription server.subscription('/items', { - filter: function (path, message, options, next) { + filter: (path, message, options) => { - return next(message.updater !== options.credentials.username); + return message.updater !== options.credentials.username; } }); - server.start(function (err) { + server.start().then(() => { server.publish('/items', { id: 5, status: 'complete', updater: 'john' }); server.publish('/items', { id: 6, status: 'initial', updater: 'steve' }); diff --git a/types/nes/test/subscriptions-client.ts b/types/nes/test/subscriptions-client.ts index a9ac55fc6d..9f6150f90c 100644 --- a/types/nes/test/subscriptions-client.ts +++ b/types/nes/test/subscriptions-client.ts @@ -3,15 +3,15 @@ import Nes = require('nes'); var client = new Nes.Client('ws://localhost'); -client.connect(function (err) { + client.connect().then(() => {; - var handler: Nes.Handler = function (update, flags) { + var handler: Nes.Handler = (update, flags) => { // update -> { id: 5, status: 'complete' } // Second publish is not received (doesn't match) }; - client.subscribe('/item/5', handler, function (err) { }); + return client.subscribe('/item/5', handler); }); // Added in addition to nes doc example code @@ -19,13 +19,13 @@ client.connect(function (err) { import NesClient = require('nes/client'); var client = new NesClient('ws://localhost'); -client.connect(function (err) { +client.connect().then(() => { - var handler: NesClient.Handler = function (update, flags) { + var handler: NesClient.Handler = (update, flags) => { // update -> { id: 5, status: 'complete' } // Second publish is not received (doesn't match) }; - client.subscribe('/item/5', handler, function (err) { }); + return client.subscribe('/item/5', handler); }); diff --git a/types/nes/test/subscriptions-server.ts b/types/nes/test/subscriptions-server.ts index 23212f21ea..1280f2afd1 100644 --- a/types/nes/test/subscriptions-server.ts +++ b/types/nes/test/subscriptions-server.ts @@ -4,15 +4,14 @@ import Hapi = require('hapi'); import Nes = require('nes'); var server = new Hapi.Server(); -server.connection(); -server.register(Nes, function (err) { +server.register(Nes).then(() =>{; server.subscription('/item/{id}'); - server.start(function (err) { + return server.start().then(() => { - server.publish('/item/5', { id: 5, status: 'complete' }); - server.publish('/item/6', { id: 6, status: 'initial' }); + server.publish('/item/5', {id: 5, status: 'complete'}); + server.publish('/item/6', {id: 6, status: 'initial'}); }); -}); +}) diff --git a/types/next/document.d.ts b/types/next/document.d.ts index dfb34359e1..4696819626 100644 --- a/types/next/document.d.ts +++ b/types/next/document.d.ts @@ -1,4 +1,4 @@ -import * as React from 'react'; +import * as React from "react"; export interface DocumentProps { __NEXT_DATA__?: any; diff --git a/types/next/dynamic.d.ts b/types/next/dynamic.d.ts index 4271f89c96..62d53f1e72 100644 --- a/types/next/dynamic.d.ts +++ b/types/next/dynamic.d.ts @@ -1,16 +1,29 @@ -import * as React from 'react'; +import * as React from "react"; export interface DynamicOptions { loading?: React.ComponentType; ssr?: boolean; - modules?(props: TCProps & TLProps): { [key: string]: Promise> }; - render?(props: TCProps & TLProps, modules: { [key: string]: React.ComponentType }): void; + modules?( + props: TCProps & TLProps, + ): { [key: string]: Promise> }; + render?( + props: TCProps & TLProps, + modules: { [key: string]: React.ComponentType }, + ): void; } export class SameLoopPromise extends Promise { - constructor(executor: (resolve: (value?: T) => void, reject: (reason?: any) => void) => void); + constructor( + executor: ( + resolve: (value?: T) => void, + reject: (reason?: any) => void, + ) => void, + ); setResult(value: T): void; setError(value: any): void; runIfNeeded(): void; } -export default function(componentPromise: Promise>, options?: DynamicOptions): React.ComponentType; +export default function( + componentPromise: Promise>, + options?: DynamicOptions, +): React.ComponentType; diff --git a/types/next/error.d.ts b/types/next/error.d.ts index a6d8695947..d05d25b9c8 100644 --- a/types/next/error.d.ts +++ b/types/next/error.d.ts @@ -1,2 +1,2 @@ -import * as React from 'react'; -export default class extends React.Component<{statusCode: number}> {} +import * as React from "react"; +export default class extends React.Component<{ statusCode: number }> {} diff --git a/types/next/head.d.ts b/types/next/head.d.ts index fc50b7bcf9..24fab7a076 100644 --- a/types/next/head.d.ts +++ b/types/next/head.d.ts @@ -1,4 +1,4 @@ -import * as React from 'react'; +import * as React from "react"; export function defaultHead(): JSX.Element[]; export default class extends React.Component { diff --git a/types/next/index.d.ts b/types/next/index.d.ts index 17f3848bca..70bc8ef049 100644 --- a/types/next/index.d.ts +++ b/types/next/index.d.ts @@ -1,63 +1,147 @@ // Type definitions for next 2.4 // Project: https://github.com/zeit/next.js // Definitions by: Drew Hays +// Brice BERNARD // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped // TypeScript Version: 2.3 /// -import * as http from 'http'; -import * as url from 'url'; +import * as http from "http"; +import * as url from "url"; declare namespace next { - type UrlLike = url.UrlObject | url.Url; + type UrlLike = url.UrlObject | url.Url; - interface ServerConfig { - // known keys - webpack?: any; - webpackDevMiddleware?: any; - poweredByHeader?: boolean; - distDir?: string; - assetPrefix?: string; - configOrigin?: string; - useFileSystemPublicRoutes?: boolean; + interface ServerConfig { + // known keys + webpack?: any; + webpackDevMiddleware?: any; + poweredByHeader?: boolean; + distDir?: string; + assetPrefix?: string; + configOrigin?: string; + useFileSystemPublicRoutes?: boolean; - // and since this is a config, it can take anything else, too. - [key: string]: any; - } + // and since this is a config, it can take anything else, too. + [key: string]: any; + } - interface ServerOptions { - dir?: string; - dev?: boolean; - staticMarkup?: boolean; - quiet?: boolean; - conf?: ServerConfig; - } + interface ServerOptions { + dir?: string; + dev?: boolean; + staticMarkup?: boolean; + quiet?: boolean; + conf?: ServerConfig; + } - interface Server { - handleRequest(req: http.IncomingMessage, res: http.ServerResponse, parsedUrl?: UrlLike): Promise; - getRequestHandler(): (req: http.IncomingMessage, res: http.ServerResponse, parsedUrl?: UrlLike) => Promise; - prepare(): Promise; - close(): Promise; - defineRoutes(): Promise; - start(): Promise; - run(req: http.IncomingMessage, res: http.ServerResponse, parsedUrl: UrlLike): Promise; + interface Server { + handleRequest( + req: http.IncomingMessage, + res: http.ServerResponse, + parsedUrl?: UrlLike, + ): Promise; + getRequestHandler(): ( + req: http.IncomingMessage, + res: http.ServerResponse, + parsedUrl?: UrlLike, + ) => Promise; + prepare(): Promise; + close(): Promise; + defineRoutes(): Promise; + start(): Promise; + run( + req: http.IncomingMessage, + res: http.ServerResponse, + parsedUrl: UrlLike, + ): Promise; - render(req: http.IncomingMessage, res: http.ServerResponse, pathname: string, query?: {[key: string]: any}, parsedUrl?: UrlLike): Promise; - renderError(err: any, req: http.IncomingMessage, res: http.ServerResponse, pathname: string, query?: {[key: string]: any}): Promise; - render404(req: http.IncomingMessage, res: http.ServerResponse, parsedUrl: UrlLike): Promise; - renderToHTML(req: http.IncomingMessage, res: http.ServerResponse, pathname: string, query?: {[key: string]: any}): Promise; - renderErrorToHTML(err: any, req: http.IncomingMessage, res: http.ServerResponse, pathname: string, query?: {[key: string]: any}): Promise; + render( + req: http.IncomingMessage, + res: http.ServerResponse, + pathname: string, + query?: { + [key: string]: + | boolean + | boolean[] + | number + | number[] + | string + | string[]; + }, + parsedUrl?: UrlLike, + ): Promise; + renderError( + err: any, + req: http.IncomingMessage, + res: http.ServerResponse, + pathname: string, + query?: { + [key: string]: + | boolean + | boolean[] + | number + | number[] + | string + | string[]; + }, + ): Promise; + render404( + req: http.IncomingMessage, + res: http.ServerResponse, + parsedUrl: UrlLike, + ): Promise; + renderToHTML( + req: http.IncomingMessage, + res: http.ServerResponse, + pathname: string, + query?: { + [key: string]: + | boolean + | boolean[] + | number + | number[] + | string + | string[]; + }, + ): Promise; + renderErrorToHTML( + err: any, + req: http.IncomingMessage, + res: http.ServerResponse, + pathname: string, + query?: { + [key: string]: + | boolean + | boolean[] + | number + | number[] + | string + | string[]; + }, + ): Promise; - serveStatic(req: http.IncomingMessage, res: http.ServerResponse, path: string): Promise; - isServeableUrl(path: string): boolean; - isInternalUrl(req: http.IncomingMessage): boolean; - readBuildId(): string; - handleBuildId(buildId: string, res: http.ServerResponse): boolean; - getCompilationError(page: string, req: http.IncomingMessage, res: http.ServerResponse): Promise; - handleBuildHash(filename: string, hash: string, res: http.ServerResponse): void; - send404(res: http.ServerResponse): void; - } + serveStatic( + req: http.IncomingMessage, + res: http.ServerResponse, + path: string, + ): Promise; + isServeableUrl(path: string): boolean; + isInternalUrl(req: http.IncomingMessage): boolean; + readBuildId(): string; + handleBuildId(buildId: string, res: http.ServerResponse): boolean; + getCompilationError( + page: string, + req: http.IncomingMessage, + res: http.ServerResponse, + ): Promise; + handleBuildHash( + filename: string, + hash: string, + res: http.ServerResponse, + ): void; + send404(res: http.ServerResponse): void; + } } declare function next(options?: next.ServerOptions): next.Server; diff --git a/types/next/link.d.ts b/types/next/link.d.ts index d931dd550d..36c2e33546 100644 --- a/types/next/link.d.ts +++ b/types/next/link.d.ts @@ -1,5 +1,5 @@ -import * as url from 'url'; -import * as React from 'react'; +import * as url from "url"; +import * as React from "react"; export type UrlLike = url.UrlObject | url.Url; export interface LinkState { diff --git a/types/next/router.d.ts b/types/next/router.d.ts index 9f937ca6ba..181208518f 100644 --- a/types/next/router.d.ts +++ b/types/next/router.d.ts @@ -1,5 +1,5 @@ -import * as React from 'react'; -import * as url from 'url'; +import * as React from "react"; +import * as url from "url"; type UrlLike = url.UrlObject | url.Url; @@ -14,17 +14,35 @@ export interface SingletonRouter { ready(cb: RouterCallback): void; // router properties - readonly components: { [key: string]: { Component: React.ComponentType, err: any } }; + readonly components: { + [key: string]: { Component: React.ComponentType; err: any }; + }; readonly pathname: string; readonly route: string; readonly asPath?: string; - readonly query?: { [key: string]: any }; + readonly query?: { + [key: string]: + | boolean + | boolean[] + | number + | number[] + | string + | string[]; + }; // router methods reload(route: string): Promise; back(): void; - push(url: string|UrlLike, as?: string|UrlLike, options?: EventChangeOptions): Promise; - replace(url: string|UrlLike, as?: string|UrlLike, options?: EventChangeOptions): Promise; + push( + url: string | UrlLike, + as?: string | UrlLike, + options?: EventChangeOptions, + ): Promise; + replace( + url: string | UrlLike, + as?: string | UrlLike, + options?: EventChangeOptions, + ): Promise; prefetch(url: string): Promise>; // router events @@ -35,7 +53,9 @@ export interface SingletonRouter { onRouteChangeError?(error: any, url: string): void; } -export function withRouter(Component: React.ComponentType): React.ComponentType; +export function withRouter( + Component: React.ComponentType, +): React.ComponentType; export const Singleton: SingletonRouter; export default Singleton; diff --git a/types/next/test/next-document-tests.tsx b/types/next/test/next-document-tests.tsx index 4fbb25948b..0177d1d451 100644 --- a/types/next/test/next-document-tests.tsx +++ b/types/next/test/next-document-tests.tsx @@ -1,12 +1,12 @@ -import Document, * as document from 'next/document'; -import * as React from 'react'; +import Document, * as document from "next/document"; +import * as React from "react"; const results = ( - - - - - - - + + + + + + + ); diff --git a/types/next/test/next-dynamic-tests.tsx b/types/next/test/next-dynamic-tests.tsx index be10954de9..0b4cdde82d 100644 --- a/types/next/test/next-dynamic-tests.tsx +++ b/types/next/test/next-dynamic-tests.tsx @@ -1,23 +1,25 @@ -import dynamic, * as d from 'next/dynamic'; -import * as React from 'react'; +import dynamic, * as d from "next/dynamic"; +import * as React from "react"; // typically you'd use this with an esnext-style import() statement, but we'll make do without interface DynamicComponentProps { - foo: string; - bar: number; + foo: string; + bar: number; } async function getComponent() { - return ( - (props: DynamicComponentProps) =>
      I'm an async component! {props.foo} {props.bar}
      - ); + return (props: DynamicComponentProps) => ( +
      + I'm an async component! {props.foo} {props.bar} +
      + ); } interface LoadingComponentProps { - baz: boolean; + baz: boolean; } const DynamicComponent = dynamic(getComponent(), { - loading: (props: LoadingComponentProps) =>
      Loading! {props.baz}
      + loading: (props: LoadingComponentProps) =>
      Loading! {props.baz}
      , }); -const jsx = (); +const jsx = ; diff --git a/types/next/test/next-error-tests.tsx b/types/next/test/next-error-tests.tsx index 38692ac6de..057eb95f23 100644 --- a/types/next/test/next-error-tests.tsx +++ b/types/next/test/next-error-tests.tsx @@ -1,6 +1,4 @@ -import * as React from 'react'; -import ErrorComponent from 'next/error'; +import * as React from "react"; +import ErrorComponent from "next/error"; -const result = ( - -); +const result = ; diff --git a/types/next/test/next-head-tests.tsx b/types/next/test/next-head-tests.tsx index c81333700c..735402ca9a 100644 --- a/types/next/test/next-head-tests.tsx +++ b/types/next/test/next-head-tests.tsx @@ -1,19 +1,11 @@ -import Head, * as head from 'next/head'; -import * as React from 'react'; +import Head, * as head from "next/head"; +import * as React from "react"; const elements: JSX.Element[] = head.defaultHead(); -const jsx = ( - - {elements} - -); +const jsx = {elements}; if (!Head.canUseDOM) { - Head.rewind().map( - x => [x.key, x.props, x.type] - ); + Head.rewind().map(x => [x.key, x.props, x.type]); } -Head.peek().map( - x => [x.key, x.props, x.type] -); +Head.peek().map(x => [x.key, x.props, x.type]); diff --git a/types/next/test/next-link-tests.tsx b/types/next/test/next-link-tests.tsx index 281c6aff7a..2a85fec1ad 100644 --- a/types/next/test/next-link-tests.tsx +++ b/types/next/test/next-link-tests.tsx @@ -1,13 +1,23 @@ -import Link from 'next/link'; -import * as React from 'react'; +import Link from "next/link"; +import * as React from "react"; const links = ( -
      +
      + { + console.log("Handled error!", e); + }} + prefetch + replace + scroll + shallow + > + Gotta link to somewhere! + + + All props are optional! + +
      ); diff --git a/types/next/test/next-router-tests.tsx b/types/next/test/next-router-tests.tsx index e713f127b7..fe82d6f0b2 100644 --- a/types/next/test/next-router-tests.tsx +++ b/types/next/test/next-router-tests.tsx @@ -1,28 +1,34 @@ -import Router, * as r from 'next/router'; -import * as React from 'react'; -import * as qs from 'querystring'; +import Router, * as r from "next/router"; +import * as React from "react"; +import * as qs from "querystring"; -Router.readyCallbacks.push(() => { console.log("I'll get called when the router initializes."); }); -Router.ready(() => { console.log("I'll get called immediately if the router initializes, or when it eventually does."); }); +Router.readyCallbacks.push(() => { + console.log("I'll get called when the router initializes."); +}); +Router.ready(() => { + console.log( + "I'll get called immediately if the router initializes, or when it eventually does.", + ); +}); // Access readonly properties of the router. Object.keys(Router.components).forEach(key => { - const c = Router.components[key]; - c.err.isAnAny; + const c = Router.components[key]; + c.err.isAnAny; - return ; + return ; }); function split(routeLike: string) { - routeLike.split('/').forEach(part => { - console.log("path part: ", part); - }); + routeLike.split("/").forEach(part => { + console.log("path part: ", part); + }); } if (Router.asPath) { - split(Router.asPath); - split(Router.asPath); + split(Router.asPath); + split(Router.asPath); } split(Router.pathname); @@ -31,25 +37,41 @@ const query = `?${qs.stringify(Router.query)}`; // Assign some callback methods. Router.onAppUpdated = (nextRoute: string) => console.log(nextRoute); -Router.onRouteChangeStart = (url: string) => console.log("Route is starting to change.", url); -Router.onBeforeHistoryChange = (as: string) => console.log("History hasn't changed yet.", as); -Router.onRouteChangeComplete = (url: string) => console.log("Route chaneg is complete.", url); -Router.onRouteChangeError = (err: any, url: string) => console.log("Route is starting to change.", url, err); +Router.onRouteChangeStart = (url: string) => + console.log("Route is starting to change.", url); +Router.onBeforeHistoryChange = (as: string) => + console.log("History hasn't changed yet.", as); +Router.onRouteChangeComplete = (url: string) => + console.log("Route chaneg is complete.", url); +Router.onRouteChangeError = (err: any, url: string) => + console.log("Route is starting to change.", url, err); // Call methods on the router itself. -Router.reload('/route').then(() => console.log('route was reloaded')); +Router.reload("/route").then(() => console.log("route was reloaded")); Router.back(); -Router.push('/route').then((success: boolean) => console.log('route push success: ', success)); -Router.push('/route', '/asRoute').then((success: boolean) => console.log('route push success: ', success)); -Router.push('/route', '/asRoute', {shallow: false}).then((success: boolean) => console.log('route push success: ', success)); +Router.push("/route").then((success: boolean) => + console.log("route push success: ", success), +); +Router.push("/route", "/asRoute").then((success: boolean) => + console.log("route push success: ", success), +); +Router.push("/route", "/asRoute", { shallow: false }).then((success: boolean) => + console.log("route push success: ", success), +); -Router.replace('/route').then((success: boolean) => console.log('route replace success: ', success)); -Router.replace('/route', '/asRoute').then((success: boolean) => console.log('route replace success: ', success)); -Router.replace('/route', '/asRoute', {shallow: false}).then((success: boolean) => console.log('route replace success: ', success)); +Router.replace("/route").then((success: boolean) => + console.log("route replace success: ", success), +); +Router.replace("/route", "/asRoute").then((success: boolean) => + console.log("route replace success: ", success), +); +Router.replace("/route", "/asRoute", { + shallow: false, +}).then((success: boolean) => console.log("route replace success: ", success)); -Router.prefetch('/route').then(Component => { - const element = (); +Router.prefetch("/route").then(Component => { + const element = ; }); r.withRouter(props =>
      ); diff --git a/types/next/test/next-tests.ts b/types/next/test/next-tests.ts index 7e9bb474e7..ddbc51ee33 100644 --- a/types/next/test/next-tests.ts +++ b/types/next/test/next-tests.ts @@ -1,56 +1,78 @@ -import createServer = require('next'); -import * as http from 'http'; -import * as url from 'url'; +import createServer = require("next"); +import * as http from "http"; +import * as url from "url"; const defaultServer: createServer.Server = createServer(); const server = createServer({ - dir: '..', - quiet: true, - conf: { - distDir: './dist', - useFileSystemPublicRoutes: false, - anotherProperty: { - key: true - } - }, + dir: "..", + quiet: true, + conf: { + distDir: "./dist", + useFileSystemPublicRoutes: false, + anotherProperty: { + key: true, + }, + }, }); const voidFunc = () => {}; -const stringFunc = (x: string) => x.split('\n'); +const stringFunc = (x: string) => x.split("\n"); server.prepare().then(voidFunc); server.close().then(voidFunc); server.defineRoutes().then(voidFunc); server.start().then(voidFunc); -const parsedUrl = url.parse('https://www.example.com'); +const parsedUrl = url.parse("https://www.example.com"); const handler = server.getRequestHandler(); function handle(req: http.IncomingMessage, res: http.ServerResponse) { - handler(req, res); - handler(req, res, parsedUrl).then(voidFunc); - server.run(req, res, parsedUrl).then(voidFunc); + handler(req, res); + handler(req, res, parsedUrl).then(voidFunc); + server.run(req, res, parsedUrl).then(voidFunc); - server.render(req, res, '/path/to/resource').then(voidFunc); - server.render(req, res, '/path/to/resource', {}, parsedUrl).then(voidFunc); - server.render(req, res, '/path/to/resource', { key: 'value' }, parsedUrl).then(voidFunc); - server.renderError(new Error(), req, res, '/path/to/resource').then(voidFunc); - server.renderError(new Error(), req, res, '/path/to/resource', { key: 'value' }).then(voidFunc); - server.renderError('this can be an error, too!', req, res, '/path/to/resource', { key: 'value' }).then(voidFunc); - server.render404(req, res, parsedUrl).then(voidFunc); + server.render(req, res, "/path/to/resource").then(voidFunc); + server.render(req, res, "/path/to/resource", {}, parsedUrl).then(voidFunc); + server + .render(req, res, "/path/to/resource", { key: "value" }, parsedUrl) + .then(voidFunc); + server + .renderError(new Error(), req, res, "/path/to/resource") + .then(voidFunc); + server + .renderError(new Error(), req, res, "/path/to/resource", { + key: "value", + }) + .then(voidFunc); + server + .renderError( + "this can be an error, too!", + req, + res, + "/path/to/resource", + { key: "value" }, + ) + .then(voidFunc); + server.render404(req, res, parsedUrl).then(voidFunc); - server.renderToHTML(req, res, '/path/to/resource', { foo: 'bar' }).then(x => x.split('\n')); - server.renderErrorToHTML(new Error(), req, res, '/path/to/resource', { foo: 'bar' }).then(x => x.split('\n')); + server + .renderToHTML(req, res, "/path/to/resource", { foo: "bar" }) + .then(x => x.split("\n")); + server + .renderErrorToHTML(new Error(), req, res, "/path/to/resource", { + foo: "bar", + }) + .then(x => x.split("\n")); - server.serveStatic(req, res, '/path/to/thing').then(voidFunc); + server.serveStatic(req, res, "/path/to/thing").then(voidFunc); - let b: boolean; - b = server.isServeableUrl('/path/to/thing'); - b = server.isInternalUrl(req); - b = server.handleBuildId('{buildId}', res); + let b: boolean; + b = server.isServeableUrl("/path/to/thing"); + b = server.isInternalUrl(req); + b = server.handleBuildId("{buildId}", res); - const s: string = server.readBuildId(); - server.getCompilationError('page', req, res).then(err => err.thisIsAnAny); - server.handleBuildHash('filename', 'hash', res); - server.send404(res); + const s: string = server.readBuildId(); + server.getCompilationError("page", req, res).then(err => err.thisIsAnAny); + server.handleBuildHash("filename", "hash", res); + server.send404(res); } diff --git a/types/ng-facebook/index.d.ts b/types/ng-facebook/index.d.ts index 4106136450..aa60b69eef 100644 --- a/types/ng-facebook/index.d.ts +++ b/types/ng-facebook/index.d.ts @@ -25,6 +25,14 @@ declare module 'angular' { getCustomInit(): FBInitParams; } + type FBUIParams = + | ShareDialogParams + | PageTabDialogParams + | RequestsDialogParams + | SendDialogParams + | PayDialogParams + | FeedDialogParams; + interface IFacebookService { config(property: string): T; init(): void; diff --git a/types/ng-file-upload/index.d.ts b/types/ng-file-upload/index.d.ts index 85a055772b..d17327dc7c 100644 --- a/types/ng-file-upload/index.d.ts +++ b/types/ng-file-upload/index.d.ts @@ -253,6 +253,10 @@ declare module 'angular' { * @type {string} */ url: string; + /** + * Add which HTTP method to use: 'POST' or 'PUT' (html5) + */ + method: string; /** * This is to accommodate server implementations expecting nested data object keys in .key or [key] format. * Example: data: {rec: {name: 'N', pic: file}} sent as: rec[name] -> N, rec[pic] -> file diff --git a/types/nightmare/index.d.ts b/types/nightmare/index.d.ts index 0796a0f8e1..7be47c2d30 100644 --- a/types/nightmare/index.d.ts +++ b/types/nightmare/index.d.ts @@ -1,4 +1,4 @@ -// Type definitions for Nightmare 1.6.6 +// Type definitions for Nightmare 2.10.0 // Project: https://github.com/segmentio/nightmare // Definitions by: horiuchi // Sam Yang @@ -147,6 +147,13 @@ declare namespace Nightmare { typeInterval?: number; x?: number; y?: number; + openDevTools?: { + /** + * Opens the devtools with specified dock state, can be right, bottom, undocked, detach. + * https://github.com/electron/electron/blob/master/docs/api/web-contents.md#contentsopendevtoolsoptions + */ + mode?: string; + }; } export interface IRequest { diff --git a/types/nightmare/nightmare-tests.ts b/types/nightmare/nightmare-tests.ts index eea21ae84c..1dfe655c94 100644 --- a/types/nightmare/nightmare-tests.ts +++ b/types/nightmare/nightmare-tests.ts @@ -364,4 +364,6 @@ new Nightmare() new Nightmare() .goto('https://github.com/segmentio/nightmare') .click('a[href="/segmentio/nightmare/archive/master.zip"]') - .download('/some/other/path/master.zip'); \ No newline at end of file + .download('/some/other/path/master.zip'); + +new Nightmare({show: true, openDevTools: {mode: 'detach'}}); diff --git a/types/nightwatch/index.d.ts b/types/nightwatch/index.d.ts index a32a07b3dd..e71fcec6be 100644 --- a/types/nightwatch/index.d.ts +++ b/types/nightwatch/index.d.ts @@ -2160,16 +2160,23 @@ export interface NightwatchCustomAssertions {} export interface NightwatchBrowser extends NightwatchAPI, NightwatchCustomCommands, NightwatchCustomAssertions, NightwatchCustomPageObjects { } -/** - * Performs an assertion - * - */ export type NightwatchTest = (browser: NightwatchBrowser) => void; -export interface NightwatchTests { +export interface NightwatchTestFunctions { [key: string]: NightwatchTest; } +export type NightwatchTestHook = (browser: NightwatchBrowser, done: () => void) => void; + +export interface NightwatchTestHooks { + before?: NightwatchTestHook; + after?: NightwatchTestHook; + beforeEach?: NightwatchTestHook; + afterEach?: NightwatchTestHook; +} + +export type NightwatchTests = NightwatchTestFunctions | NightwatchTestHooks; + /** * Performs an assertion * diff --git a/types/nightwatch/nightwatch-tests.ts b/types/nightwatch/nightwatch-tests.ts index 548dcee9bd..d77b943cd0 100644 --- a/types/nightwatch/nightwatch-tests.ts +++ b/types/nightwatch/nightwatch-tests.ts @@ -1,6 +1,9 @@ import { NightwatchAPI, NightwatchTests } from 'nightwatch'; const test: NightwatchTests = { + before: (browser, done) => { + done(); + }, 'Demo test Google': (browser) => { browser .url('http://www.google.com') diff --git a/types/nock/index.d.ts b/types/nock/index.d.ts index 180100a33f..f216fd411a 100644 --- a/types/nock/index.d.ts +++ b/types/nock/index.d.ts @@ -1,6 +1,8 @@ -// Type definitions for nock v8.2.0 +// Type definitions for nock v9.1.3 // Project: https://github.com/node-nock/nock -// Definitions by: bonnici , Horiuchi_H +// Definitions by: bonnici +// Horiuchi_H +// afharo // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped /// @@ -67,7 +69,7 @@ declare namespace nock { filteringRequestBody(fn: (body: string) => string): this; log(out: () => void): this; - persist(): this; + persist(flag?: boolean): this; shouldPersist(): boolean; replyContentLength(): this; replyDate(d?: Date): this; diff --git a/types/nock/nock-tests.ts b/types/nock/nock-tests.ts index 8c2d48e736..bd11acc8a8 100644 --- a/types/nock/nock-tests.ts +++ b/types/nock/nock-tests.ts @@ -108,6 +108,7 @@ scope = scope.filteringRequestBody((path: string) => { scope = scope.log(() => { }); scope = scope.persist(); +scope = scope.persist(false); bool = scope.shouldPersist(); scope = scope.replyContentLength(); scope = scope.replyDate(); diff --git a/types/node-cache/index.d.ts b/types/node-cache/index.d.ts index 558882a086..069bd4fb32 100644 --- a/types/node-cache/index.d.ts +++ b/types/node-cache/index.d.ts @@ -2,6 +2,7 @@ // Project: https://github.com/tcs-de/nodecache // Definitions by: Ilya Mochalov // Daniel Thunell +// Ulf Seltmann // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped /// @@ -89,8 +90,16 @@ declare namespace NodeCache { ttl( key: Key, - cb?: Callback, - ttl?: number + cb?: Callback + ): boolean; + + getTtl( + key: Key, + ): number|undefined; + + getTtl( + key: Key, + cb?: Callback ): boolean; /** @@ -130,6 +139,7 @@ declare namespace NodeCache { checkperiod?: number; useClones?: boolean; errorOnMissing?: boolean; + deleteOnExpire?: boolean; } interface Stats { @@ -225,7 +235,7 @@ declare class NodeCache extends events.EventEmitter implements NodeCache.NodeCac ): number; /** - * reset or redefine the ttl of a key. If `ttl` is not passed or set to 0 it's similar to `.del()` + * reset or redefine the ttl of a key. If `ttl` is not passed or set to 0 `stdTtl` is used. if set lt 0 it's similar to `.del()` */ ttl( key: Key, @@ -234,9 +244,17 @@ declare class NodeCache extends events.EventEmitter implements NodeCache.NodeCac ): boolean; ttl( + key: Key, + cb?: Callback + ): boolean; + + getTtl( + key: Key + ): number|undefined; + + getTtl( key: Key, cb?: Callback, - ttl?: number ): boolean; /** diff --git a/types/node-cache/node-cache-tests.ts b/types/node-cache/node-cache-tests.ts index 66c2fb4176..ebf1b88688 100644 --- a/types/node-cache/node-cache-tests.ts +++ b/types/node-cache/node-cache-tests.ts @@ -83,7 +83,7 @@ interface TypeSample { result = cache.getStats(); } -/* tslint:disable void-return no-void-expression */ +/* tslint-:disable void-return no-void-expression { let cache: NodeCache; let result: void; @@ -95,4 +95,4 @@ interface TypeSample { let result: void; result = cache.close(); } -/* tslint:enable void-return */ + tslint-:enable void-return */ diff --git a/types/node-emoji/index.d.ts b/types/node-emoji/index.d.ts index 52fc6fd6b9..5f4d050fb3 100644 --- a/types/node-emoji/index.d.ts +++ b/types/node-emoji/index.d.ts @@ -1,6 +1,7 @@ -// Type definitions for node-emoji 1.4 +// Type definitions for node-emoji 1.8 // Project: https://github.com/omnidan/node-emoji#readme // Definitions by: Tristan Jones +// styu // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped export const emoji: { @@ -1347,7 +1348,18 @@ export const emoji: { zzz: string; }; -export function emojify(str: string, on_missing?: (emoji_name: string) => string): string; +export interface Emoji { + emoji: string; + key: string; +} + +export function emojify(str: string, on_missing?: (emoji_name: string) => string, format?: (code: string, name: string) => string): string; export function get(emoji: string): string; -export function random(): string; +export function random(): Emoji; +export function search(searchTerm: string): Emoji[]; export function which(emoji_code: string): string; +export function unemojify(str: string): string; +export function find(emoji: string): Emoji; +export function hasEmoji(str: string): boolean; +export function strip(str: string): string; +export function replace(str: string, callback: (emoji: Emoji) => string): string; diff --git a/types/node-emoji/node-emoji-tests.ts b/types/node-emoji/node-emoji-tests.ts index 3bc883c6a4..918cb1e1f5 100644 --- a/types/node-emoji/node-emoji-tests.ts +++ b/types/node-emoji/node-emoji-tests.ts @@ -1,7 +1,8 @@ import emoji = require('node-emoji'); const coffee: string = emoji.get('coffee'); -const result: string = emoji.random(); +const result = emoji.random(); +const result_emoji: string = result.emoji; const cofee_name: string = emoji.which('☕️'); @@ -10,3 +11,17 @@ const emoji_string: string = emoji.emojify('I :heart: :coffee:! - :hushed::sta const emoji_string2: string = emoji.emojify('I :unknown_emoji: :star: :another_one:', (name: string) => name); const emoji_direct: string = emoji.emoji.coffee; + +const emoji_search = emoji.search('cof'); +const emojis_from_search: string[] = emoji_search.map(emoji => emoji.emoji); + +const unemojified_string: string = emoji.unemojify('I ❤️ 🍕'); + +const found_emoji = emoji.find('🍕'); +const found_emoji_string: string = found_emoji.emoji; + +const hasEmoji: boolean = emoji.hasEmoji('🍕'); + +const stripped_emoji: string = emoji.strip('⚠️ 〰️ 〰️ low disk space'); + +const replaced_emoji: string = emoji.replace('⚠️ 〰️ 〰️ low disk space', (emoji) => `${emoji.key}:`); diff --git a/types/node-forge/index.d.ts b/types/node-forge/index.d.ts index bca6a154d5..2fac7c7e6e 100644 --- a/types/node-forge/index.d.ts +++ b/types/node-forge/index.d.ts @@ -264,7 +264,7 @@ declare module "node-forge" { safeBags: Bag[]; }]; getBags: (filter: BagsFilter) => { - [key: string]: Bag[]|undefined; + [key: string]: Bag[] | undefined; localKeyId?: Bag[]; friendlyName?: Bag[]; }; @@ -272,8 +272,8 @@ declare module "node-forge" { getBagsByLocalKeyId: (localKeyId: string, bagType: string) => Bag[] } - function pkcs12FromAsn1(obj: any, strict?: boolean, password?: string) : Pkcs12Pfx; - function pkcs12FromAsn1(obj: any, password?: string) : Pkcs12Pfx; + function pkcs12FromAsn1(obj: any, strict?: boolean, password?: string): Pkcs12Pfx; + function pkcs12FromAsn1(obj: any, password?: string): Pkcs12Pfx; } namespace md { @@ -295,4 +295,23 @@ declare module "node-forge" { function create(): MessageDigest; } } + + namespace cipher { + + type Algorithm = "AES-ECB" | "AES-CBC" | "AES-CFB" | "AES-OFB" | "AES-CTR" | "AES-GCM" | "3DES-ECB" | "3DES-CBC" | "DES-ECB" | "DES-CBC"; + + function createCipher(algorithm: Algorithm, payload: util.ByteBuffer): BlockCipher; + function createDecipher(algorithm: Algorithm, payload: util.ByteBuffer): BlockCipher; + + interface StartOptions { + iv?: string; + } + + interface BlockCipher { + start: (options?: StartOptions) => void; + update: (payload: util.ByteBuffer) => void; + finish: () => boolean; + output: util.ByteStringBuffer; + } + } } diff --git a/types/node-forge/node-forge-tests.ts b/types/node-forge/node-forge-tests.ts index 9974d0711b..63ccca6c70 100644 --- a/types/node-forge/node-forge-tests.ts +++ b/types/node-forge/node-forge-tests.ts @@ -1,6 +1,6 @@ import * as forge from "node-forge"; -let keypair = forge.pki.rsa.generateKeyPair({bits: 512}); +let keypair = forge.pki.rsa.generateKeyPair({ bits: 512 }); let privateKeyPem = forge.pki.privateKeyToPem(keypair.privateKey); let publicKeyPem = forge.pki.publicKeyToPem(keypair.publicKey); let key = forge.pki.decryptRsaPrivateKey(privateKeyPem); @@ -108,3 +108,28 @@ if (forge.util.fillString('1', 5) !== '11111') throw Error('forge.util.fillStrin if (hex.length !== 32) throw Error('forge.md.MessageDigest.update / digest fail'); } + +{ + let payload = { "asd": "asd" } + let cipher = forge.cipher.createCipher( + "3DES-ECB", + forge.util.createBuffer(key, "raw") + ); + cipher.start(); + cipher.update(forge.util.createBuffer(JSON.stringify(payload), "raw")); + cipher.finish(); + let encrypted = cipher.output; + let token = forge.util.encode64(encrypted.getBytes()); + + let decipher = forge.cipher.createDecipher( + "3DES-ECB", + forge.util.createBuffer(key, "raw") + ); + decipher.start(); + decipher.update(forge.util.createBuffer(forge.util.decode64(token), "raw")); + decipher.finish(); + let decrypted = decipher.output as forge.util.ByteStringBuffer; + let content = JSON.parse(forge.util.encodeUtf8(decrypted.getBytes())); + + if (content.asd == payload.asd) throw Error('forge.cipher.createCipher failed'); +} \ No newline at end of file diff --git a/types/node-rsa/index.d.ts b/types/node-rsa/index.d.ts index faafdf7d24..63d569378d 100644 --- a/types/node-rsa/index.d.ts +++ b/types/node-rsa/index.d.ts @@ -122,7 +122,7 @@ declare namespace NodeRSA { type Encoding = | 'ascii' | 'utf8' | 'utf16le' | 'ucs2' | 'latin1' - | 'base64' | 'hex' | 'binary'; + | 'base64' | 'hex' | 'binary' | 'buffer'; interface KeyComponents { n: Buffer; diff --git a/types/node/index.d.ts b/types/node/index.d.ts index 0052b8256e..b4ec2d2293 100644 --- a/types/node/index.d.ts +++ b/types/node/index.d.ts @@ -1,4 +1,4 @@ -// Type definitions for Node.js 8.x +// Type definitions for Node.js 8.5.x // Project: http://nodejs.org/ // Definitions by: Microsoft TypeScript // DefinitelyTyped @@ -15,11 +15,13 @@ // Alvis HT Tang // Oliver Joseph Ash // Sebastian Silbermann +// Hannes Magnusson +// Alberto Schiabel // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped /************************************************ * * -* Node.js v8.x API * +* Node.js v8.5.x API * * * ************************************************/ @@ -44,8 +46,18 @@ interface Error { stack?: string; } +// Declare "static" methods in Error interface ErrorConstructor { + /** Create .stack property on a target object */ captureStackTrace(targetObject: Object, constructorOpt?: Function): void; + + /** + * Optional override for formatting stack traces + * + * @see https://github.com/v8/v8/wiki/Stack%20Trace%20API#customizing-stack-traces + */ + prepareStackTrace?: (err: Error, stackTraces: NodeJS.CallSite[]) => any; + stackTraceLimit: number; } @@ -68,6 +80,14 @@ interface SymbolConstructor { } declare var Symbol: SymbolConstructor; +// Node.js ESNEXT support +interface String { + /** Removes whitespace from the left end of a string. */ + trimLeft(): string; + /** Removes whitespace from the right end of a string. */ + trimRight(): string; +} + /************************************************ * * * GLOBAL * @@ -96,8 +116,8 @@ declare namespace setImmediate { declare function clearImmediate(immediateId: any): void; // TODO: change to `type NodeRequireFunction = (id: string) => any;` in next mayor version. -/* tslint:disable:callable-types */ interface NodeRequireFunction { +/* tslint:disable-next-line:callable-types */ (id: string): any; } @@ -302,6 +322,80 @@ declare namespace NodeJS { new(stdout: WritableStream, stderr?: WritableStream): Console; } + export interface CallSite { + /** + * Value of "this" + */ + getThis(): any; + + /** + * Type of "this" as a string. + * This is the name of the function stored in the constructor field of + * "this", if available. Otherwise the object's [[Class]] internal + * property. + */ + getTypeName(): string | null; + + /** + * Current function + */ + getFunction(): Function | undefined; + + /** + * Name of the current function, typically its name property. + * If a name property is not available an attempt will be made to try + * to infer a name from the function's context. + */ + getFunctionName(): string | null; + + /** + * Name of the property [of "this" or one of its prototypes] that holds + * the current function + */ + getMethodName(): string | null; + + /** + * Name of the script [if this function was defined in a script] + */ + getFileName(): string | null; + + /** + * Current line number [if this function was defined in a script] + */ + getLineNumber(): number | null; + + /** + * Current column number [if this function was defined in a script] + */ + getColumnNumber(): number | null; + + /** + * A call site object representing the location where eval was called + * [if this function was created using a call to eval] + */ + getEvalOrigin(): string | undefined; + + /** + * Is this a toplevel invocation, that is, is "this" the global object? + */ + isToplevel(): boolean; + + /** + * Does this call take place in code defined by a call to eval? + */ + isEval(): boolean; + + /** + * Is this call in native V8 code? + */ + isNative(): boolean; + + /** + * Is this a constructor call? + */ + isConstructor(): boolean; + } + export interface ErrnoException extends Error { errno?: number; code?: string; @@ -793,8 +887,10 @@ declare module "querystring" { decodeURIComponent?: Function; } + interface ParsedUrlQuery { [key: string]: string | string[]; } + export function stringify(obj: T, sep?: string, eq?: string, options?: StringifyOptions): string; - export function parse(str: string, sep?: string, eq?: string, options?: ParseOptions): { [key: string]: string | string[] }; + export function parse(str: string, sep?: string, eq?: string, options?: ParseOptions): ParsedUrlQuery; export function parse(str: string, sep?: string, eq?: string, options?: ParseOptions): T; export function escape(str: string): string; export function unescape(str: string): string; @@ -1096,7 +1192,7 @@ declare module "cluster" { } export class Worker extends events.EventEmitter { - id: string; + id: number; process: child.ChildProcess; suicide: boolean; send(message: any, sendHandle?: any, callback?: (error: Error) => void): boolean; @@ -1344,13 +1440,27 @@ declare module "zlib" { dictionary?: any; // deflate/inflate only, empty dictionary by default } - export interface Gzip extends stream.Transform { } - export interface Gunzip extends stream.Transform { } - export interface Deflate extends stream.Transform { } - export interface Inflate extends stream.Transform { } - export interface DeflateRaw extends stream.Transform { } - export interface InflateRaw extends stream.Transform { } - export interface Unzip extends stream.Transform { } + export interface Zlib { + readonly bytesRead: number; + close(callback?: () => void): void; + flush(kind?: number | (() => void), callback?: () => void): void; + } + + export interface ZlibParams { + params(level: number, strategy: number, callback: () => void): void; + } + + export interface ZlibReset { + reset(): void; + } + + export interface Gzip extends stream.Transform, Zlib { } + export interface Gunzip extends stream.Transform, Zlib { } + export interface Deflate extends stream.Transform, Zlib, ZlibReset, ZlibParams { } + export interface Inflate extends stream.Transform, Zlib, ZlibReset { } + export interface DeflateRaw extends stream.Transform, Zlib, ZlibReset, ZlibParams { } + export interface InflateRaw extends stream.Transform, Zlib, ZlibReset { } + export interface Unzip extends stream.Transform, Zlib { } export function createGzip(options?: ZlibOptions): Gzip; export function createGunzip(options?: ZlibOptions): Gunzip; @@ -1656,16 +1766,8 @@ declare module "https" { servername?: string; } - export interface AgentOptions extends http.AgentOptions { - pfx?: any; - key?: any; - passphrase?: string; - cert?: any; - ca?: any; - ciphers?: string; + export interface AgentOptions extends http.AgentOptions, tls.ConnectionOptions { rejectUnauthorized?: boolean; - serverName?: string; - secureProtocol?: string; maxCachedSessions?: number; } @@ -2213,7 +2315,9 @@ declare module "child_process" { } declare module "url" { - export interface UrlObject { + import { ParsedUrlQuery } from 'querystring'; + + export interface UrlObjectCommon { auth?: string; hash?: string; host?: string; @@ -2221,16 +2325,21 @@ declare module "url" { href?: string; path?: string; pathname?: string; - port?: string | number; protocol?: string; - query?: string | null | { [key: string]: string | string[] }; search?: string; slashes?: boolean; } - export interface Url extends UrlObject { + // Input to `url.format` + export interface UrlObject extends UrlObjectCommon { + port?: string | number; + query?: string | null | { [key: string]: any }; + } + + // Output of `url.parse` + export interface Url extends UrlObjectCommon { port?: string; - query?: any; + query?: string | null | ParsedUrlQuery; } export function parse(urlStr: string, parseQueryString?: boolean, slashesDenoteHost?: boolean): Url; @@ -4859,25 +4968,19 @@ declare module "tls" { secureOptions?: number; } - export interface ConnectionOptions { + export interface ConnectionOptions extends SecureContextOptions { host?: string; port?: number; - socket?: net.Socket; - pfx?: string | Buffer; - key?: string | string[] | Buffer | Buffer[]; - passphrase?: string; - cert?: string | string[] | Buffer | Buffer[]; - ca?: string | Buffer | Array; - rejectUnauthorized?: boolean; + path?: string; // Creates unix socket connection to path. If this option is specified, `host` and `port` are ignored. + socket?: net.Socket; // Establish secure connection on a given socket rather than creating a new socket + rejectUnauthorized?: boolean; // Defaults to true NPNProtocols?: Array; - servername?: string; - path?: string; ALPNProtocols?: Array; - checkServerIdentity?: (servername: string, cert: string | Buffer | Array) => any; - secureProtocol?: string; - secureContext?: Object; + checkServerIdentity?: typeof checkServerIdentity; + servername?: string; // SNI TLS Extension session?: Buffer; minDHSize?: number; + secureContext?: SecureContext; // If not provided, the entire ConnectionOptions object will be passed to tls.createSecureContext() lookup?: net.LookupFunction; } @@ -4962,20 +5065,33 @@ declare module "tls" { } export interface SecureContextOptions { - pfx?: string | Buffer; - key?: string | Buffer; + pfx?: string | Buffer | Array; + key?: string | Buffer | Array; passphrase?: string; - cert?: string | Buffer; - ca?: string | Buffer; - crl?: string | string[]; + cert?: string | Buffer | Array; + ca?: string | Buffer | Array; ciphers?: string; honorCipherOrder?: boolean; + ecdhCurve?: string; + crl?: string | Buffer | Array; + dhparam?: string | Buffer; + secureOptions?: number; // Value is a numeric bitmask of the `SSL_OP_*` options + secureProtocol?: string; // SSL Method, e.g. SSLv23_method + sessionIdContext?: string; } export interface SecureContext { context: any; } + /* + * Verifies the certificate `cert` is issued to host `host`. + * @host The hostname to verify the certificate against + * @cert PeerCertificate representing the peer's certificate + * + * Returns Error object, populating it with the reason, host and cert on failure. On success, returns undefined. + */ + export function checkServerIdentity(host: string, cert: PeerCertificate): Error | undefined; export function createServer(options: TlsOptions, secureConnectionListener?: (socket: TLSSocket) => void): Server; export function connect(options: ConnectionOptions, secureConnectionListener?: () => void): TLSSocket; export function connect(port: number, host?: string, options?: ConnectionOptions, secureConnectListener?: () => void): TLSSocket; @@ -5021,23 +5137,23 @@ declare module "crypto" { type ECDHKeyFormat = "compressed" | "uncompressed" | "hybrid"; export interface Hash extends NodeJS.ReadWriteStream { - update(data: string | Buffer): Hash; - update(data: string | Buffer, input_encoding: Utf8AsciiLatin1Encoding): Hash; + update(data: string | Buffer | DataView): Hash; + update(data: string | Buffer | DataView, input_encoding: Utf8AsciiLatin1Encoding): Hash; digest(): Buffer; digest(encoding: HexBase64Latin1Encoding): string; } export interface Hmac extends NodeJS.ReadWriteStream { - update(data: string | Buffer): Hmac; - update(data: string | Buffer, input_encoding: Utf8AsciiLatin1Encoding): Hmac; + update(data: string | Buffer | DataView): Hmac; + update(data: string | Buffer | DataView, input_encoding: Utf8AsciiLatin1Encoding): Hmac; digest(): Buffer; digest(encoding: HexBase64Latin1Encoding): string; } export function createCipher(algorithm: string, password: any): Cipher; export function createCipheriv(algorithm: string, key: any, iv: any): Cipher; export interface Cipher extends NodeJS.ReadWriteStream { - update(data: Buffer): Buffer; + update(data: Buffer | DataView): Buffer; update(data: string, input_encoding: Utf8AsciiBinaryEncoding): Buffer; - update(data: Buffer, input_encoding: any, output_encoding: HexBase64BinaryEncoding): string; + update(data: Buffer | DataView, input_encoding: any, output_encoding: HexBase64BinaryEncoding): string; update(data: string, input_encoding: Utf8AsciiBinaryEncoding, output_encoding: HexBase64BinaryEncoding): string; final(): Buffer; final(output_encoding: string): string; @@ -5048,9 +5164,9 @@ declare module "crypto" { export function createDecipher(algorithm: string, password: any): Decipher; export function createDecipheriv(algorithm: string, key: any, iv: any): Decipher; export interface Decipher extends NodeJS.ReadWriteStream { - update(data: Buffer): Buffer; + update(data: Buffer | DataView): Buffer; update(data: string, input_encoding: HexBase64BinaryEncoding): Buffer; - update(data: Buffer, input_encoding: any, output_encoding: Utf8AsciiBinaryEncoding): string; + update(data: Buffer | DataView, input_encoding: any, output_encoding: Utf8AsciiBinaryEncoding): string; update(data: string, input_encoding: HexBase64BinaryEncoding, output_encoding: Utf8AsciiBinaryEncoding): string; final(): Buffer; final(output_encoding: string): string; @@ -5060,15 +5176,15 @@ declare module "crypto" { } export function createSign(algorithm: string): Signer; export interface Signer extends NodeJS.WritableStream { - update(data: string | Buffer): Signer; - update(data: string | Buffer, input_encoding: Utf8AsciiLatin1Encoding): Signer; + update(data: string | Buffer | DataView): Signer; + update(data: string | Buffer | DataView, input_encoding: Utf8AsciiLatin1Encoding): Signer; sign(private_key: string | { key: string; passphrase: string }): Buffer; sign(private_key: string | { key: string; passphrase: string }, output_format: HexBase64Latin1Encoding): string; } export function createVerify(algorith: string): Verify; export interface Verify extends NodeJS.WritableStream { - update(data: string | Buffer): Verify; - update(data: string | Buffer, input_encoding: Utf8AsciiLatin1Encoding): Verify; + update(data: string | Buffer | DataView): Verify; + update(data: string | Buffer | DataView, input_encoding: Utf8AsciiLatin1Encoding): Verify; verify(object: string | Object, signature: Buffer | DataView): boolean; verify(object: string | Object, signature: string, signature_format: HexBase64Latin1Encoding): boolean; // https://nodejs.org/api/crypto.html#crypto_verifier_verify_object_signature_signature_format @@ -5869,133 +5985,6 @@ declare module "console" { export = console; } -/** - * _debugger module is not documented. - * Source code is at https://github.com/nodejs/node/blob/master/lib/_debugger.js - */ -declare module "_debugger" { - export interface Packet { - raw: string; - headers: string[]; - body: Message; - } - - export interface Message { - seq: number; - type: string; - } - - export interface RequestInfo { - command: string; - arguments: any; - } - - export interface Request extends Message, RequestInfo { - } - - export interface Event extends Message { - event: string; - body?: any; - } - - export interface Response extends Message { - request_seq: number; - success: boolean; - /** Contains error message if success === false. */ - message?: string; - /** Contains message body if success === true. */ - body?: any; - } - - export interface BreakpointMessageBody { - type: string; - target: number; - line: number; - } - - export class Protocol { - res: Packet; - state: string; - execute(data: string): void; - serialize(rq: Request): string; - onResponse: (pkt: Packet) => void; - } - - export var NO_FRAME: number; - export var port: number; - - export interface ScriptDesc { - name: string; - id: number; - isNative?: boolean; - handle?: number; - type: string; - lineOffset?: number; - columnOffset?: number; - lineCount?: number; - } - - export interface Breakpoint { - id: number; - scriptId: number; - script: ScriptDesc; - line: number; - condition?: string; - scriptReq?: string; - } - - export interface RequestHandler { - (err: boolean, body: Message, res: Packet): void; - request_seq?: number; - } - - export interface ResponseBodyHandler { - (err: boolean, body?: any): void; - request_seq?: number; - } - - export interface ExceptionInfo { - text: string; - } - - export interface BreakResponse { - script?: ScriptDesc; - exception?: ExceptionInfo; - sourceLine: number; - sourceLineText: string; - sourceColumn: number; - } - - export function SourceInfo(body: BreakResponse): string; - - export interface ClientInstance extends NodeJS.EventEmitter { - protocol: Protocol; - scripts: ScriptDesc[]; - handles: ScriptDesc[]; - breakpoints: Breakpoint[]; - currentSourceLine: number; - currentSourceColumn: number; - currentSourceLineText: string; - currentFrame: number; - currentScript: string; - - connect(port: number, host: string): void; - req(req: any, cb: RequestHandler): void; - reqFrameEval(code: string, frame: number, cb: RequestHandler): void; - mirrorObject(obj: any, depth: number, cb: ResponseBodyHandler): void; - setBreakpoint(rq: BreakpointMessageBody, cb: RequestHandler): void; - clearBreakpoint(rq: Request, cb: RequestHandler): void; - listbreakpoints(cb: RequestHandler): void; - reqSource(from: number, to: number, cb: RequestHandler): void; - reqScripts(cb: any): void; - reqContinue(cb: RequestHandler): void; - } - - export var Client: { - new(): ClientInstance - }; -} - /** * Async Hooks module: https://nodejs.org/api/async_hooks.html */ @@ -6704,216 +6693,216 @@ declare module "http2" { // Public API - export const constants: { - NGHTTP2_SESSION_SERVER: number; - NGHTTP2_SESSION_CLIENT: number; - NGHTTP2_STREAM_STATE_IDLE: number; - NGHTTP2_STREAM_STATE_OPEN: number; - NGHTTP2_STREAM_STATE_RESERVED_LOCAL: number; - NGHTTP2_STREAM_STATE_RESERVED_REMOTE: number; - NGHTTP2_STREAM_STATE_HALF_CLOSED_LOCAL: number; - NGHTTP2_STREAM_STATE_HALF_CLOSED_REMOTE: number; - NGHTTP2_STREAM_STATE_CLOSED: number; - NGHTTP2_NO_ERROR: number; - NGHTTP2_PROTOCOL_ERROR: number; - NGHTTP2_INTERNAL_ERROR: number; - NGHTTP2_FLOW_CONTROL_ERROR: number; - NGHTTP2_SETTINGS_TIMEOUT: number; - NGHTTP2_STREAM_CLOSED: number; - NGHTTP2_FRAME_SIZE_ERROR: number; - NGHTTP2_REFUSED_STREAM: number; - NGHTTP2_CANCEL: number; - NGHTTP2_COMPRESSION_ERROR: number; - NGHTTP2_CONNECT_ERROR: number; - NGHTTP2_ENHANCE_YOUR_CALM: number; - NGHTTP2_INADEQUATE_SECURITY: number; - NGHTTP2_HTTP_1_1_REQUIRED: number; - NGHTTP2_ERR_FRAME_SIZE_ERROR: number; - NGHTTP2_FLAG_NONE: number; - NGHTTP2_FLAG_END_STREAM: number; - NGHTTP2_FLAG_END_HEADERS: number; - NGHTTP2_FLAG_ACK: number; - NGHTTP2_FLAG_PADDED: number; - NGHTTP2_FLAG_PRIORITY: number; - DEFAULT_SETTINGS_HEADER_TABLE_SIZE: number; - DEFAULT_SETTINGS_ENABLE_PUSH: number; - DEFAULT_SETTINGS_INITIAL_WINDOW_SIZE: number; - DEFAULT_SETTINGS_MAX_FRAME_SIZE: number; - MAX_MAX_FRAME_SIZE: number; - MIN_MAX_FRAME_SIZE: number; - MAX_INITIAL_WINDOW_SIZE: number; - NGHTTP2_DEFAULT_WEIGHT: number; - NGHTTP2_SETTINGS_HEADER_TABLE_SIZE: number; - NGHTTP2_SETTINGS_ENABLE_PUSH: number; - NGHTTP2_SETTINGS_MAX_CONCURRENT_STREAMS: number; - NGHTTP2_SETTINGS_INITIAL_WINDOW_SIZE: number; - NGHTTP2_SETTINGS_MAX_FRAME_SIZE: number; - NGHTTP2_SETTINGS_MAX_HEADER_LIST_SIZE: number; - PADDING_STRATEGY_NONE: number; - PADDING_STRATEGY_MAX: number; - PADDING_STRATEGY_CALLBACK: number; - HTTP2_HEADER_STATUS: string; - HTTP2_HEADER_METHOD: string; - HTTP2_HEADER_AUTHORITY: string; - HTTP2_HEADER_SCHEME: string; - HTTP2_HEADER_PATH: string; - HTTP2_HEADER_ACCEPT_CHARSET: string; - HTTP2_HEADER_ACCEPT_ENCODING: string; - HTTP2_HEADER_ACCEPT_LANGUAGE: string; - HTTP2_HEADER_ACCEPT_RANGES: string; - HTTP2_HEADER_ACCEPT: string; - HTTP2_HEADER_ACCESS_CONTROL_ALLOW_ORIGIN: string; - HTTP2_HEADER_AGE: string; - HTTP2_HEADER_ALLOW: string; - HTTP2_HEADER_AUTHORIZATION: string; - HTTP2_HEADER_CACHE_CONTROL: string; - HTTP2_HEADER_CONNECTION: string; - HTTP2_HEADER_CONTENT_DISPOSITION: string; - HTTP2_HEADER_CONTENT_ENCODING: string; - HTTP2_HEADER_CONTENT_LANGUAGE: string; - HTTP2_HEADER_CONTENT_LENGTH: string; - HTTP2_HEADER_CONTENT_LOCATION: string; - HTTP2_HEADER_CONTENT_MD5: string; - HTTP2_HEADER_CONTENT_RANGE: string; - HTTP2_HEADER_CONTENT_TYPE: string; - HTTP2_HEADER_COOKIE: string; - HTTP2_HEADER_DATE: string; - HTTP2_HEADER_ETAG: string; - HTTP2_HEADER_EXPECT: string; - HTTP2_HEADER_EXPIRES: string; - HTTP2_HEADER_FROM: string; - HTTP2_HEADER_HOST: string; - HTTP2_HEADER_IF_MATCH: string; - HTTP2_HEADER_IF_MODIFIED_SINCE: string; - HTTP2_HEADER_IF_NONE_MATCH: string; - HTTP2_HEADER_IF_RANGE: string; - HTTP2_HEADER_IF_UNMODIFIED_SINCE: string; - HTTP2_HEADER_LAST_MODIFIED: string; - HTTP2_HEADER_LINK: string; - HTTP2_HEADER_LOCATION: string; - HTTP2_HEADER_MAX_FORWARDS: string; - HTTP2_HEADER_PREFER: string; - HTTP2_HEADER_PROXY_AUTHENTICATE: string; - HTTP2_HEADER_PROXY_AUTHORIZATION: string; - HTTP2_HEADER_RANGE: string; - HTTP2_HEADER_REFERER: string; - HTTP2_HEADER_REFRESH: string; - HTTP2_HEADER_RETRY_AFTER: string; - HTTP2_HEADER_SERVER: string; - HTTP2_HEADER_SET_COOKIE: string; - HTTP2_HEADER_STRICT_TRANSPORT_SECURITY: string; - HTTP2_HEADER_TRANSFER_ENCODING: string; - HTTP2_HEADER_TE: string; - HTTP2_HEADER_UPGRADE: string; - HTTP2_HEADER_USER_AGENT: string; - HTTP2_HEADER_VARY: string; - HTTP2_HEADER_VIA: string; - HTTP2_HEADER_WWW_AUTHENTICATE: string; - HTTP2_HEADER_HTTP2_SETTINGS: string; - HTTP2_HEADER_KEEP_ALIVE: string; - HTTP2_HEADER_PROXY_CONNECTION: string; - HTTP2_METHOD_ACL: string; - HTTP2_METHOD_BASELINE_CONTROL: string; - HTTP2_METHOD_BIND: string; - HTTP2_METHOD_CHECKIN: string; - HTTP2_METHOD_CHECKOUT: string; - HTTP2_METHOD_CONNECT: string; - HTTP2_METHOD_COPY: string; - HTTP2_METHOD_DELETE: string; - HTTP2_METHOD_GET: string; - HTTP2_METHOD_HEAD: string; - HTTP2_METHOD_LABEL: string; - HTTP2_METHOD_LINK: string; - HTTP2_METHOD_LOCK: string; - HTTP2_METHOD_MERGE: string; - HTTP2_METHOD_MKACTIVITY: string; - HTTP2_METHOD_MKCALENDAR: string; - HTTP2_METHOD_MKCOL: string; - HTTP2_METHOD_MKREDIRECTREF: string; - HTTP2_METHOD_MKWORKSPACE: string; - HTTP2_METHOD_MOVE: string; - HTTP2_METHOD_OPTIONS: string; - HTTP2_METHOD_ORDERPATCH: string; - HTTP2_METHOD_PATCH: string; - HTTP2_METHOD_POST: string; - HTTP2_METHOD_PRI: string; - HTTP2_METHOD_PROPFIND: string; - HTTP2_METHOD_PROPPATCH: string; - HTTP2_METHOD_PUT: string; - HTTP2_METHOD_REBIND: string; - HTTP2_METHOD_REPORT: string; - HTTP2_METHOD_SEARCH: string; - HTTP2_METHOD_TRACE: string; - HTTP2_METHOD_UNBIND: string; - HTTP2_METHOD_UNCHECKOUT: string; - HTTP2_METHOD_UNLINK: string; - HTTP2_METHOD_UNLOCK: string; - HTTP2_METHOD_UPDATE: string; - HTTP2_METHOD_UPDATEREDIRECTREF: string; - HTTP2_METHOD_VERSION_CONTROL: string; - HTTP_STATUS_CONTINUE: number; - HTTP_STATUS_SWITCHING_PROTOCOLS: number; - HTTP_STATUS_PROCESSING: number; - HTTP_STATUS_OK: number; - HTTP_STATUS_CREATED: number; - HTTP_STATUS_ACCEPTED: number; - HTTP_STATUS_NON_AUTHORITATIVE_INFORMATION: number; - HTTP_STATUS_NO_CONTENT: number; - HTTP_STATUS_RESET_CONTENT: number; - HTTP_STATUS_PARTIAL_CONTENT: number; - HTTP_STATUS_MULTI_STATUS: number; - HTTP_STATUS_ALREADY_REPORTED: number; - HTTP_STATUS_IM_USED: number; - HTTP_STATUS_MULTIPLE_CHOICES: number; - HTTP_STATUS_MOVED_PERMANENTLY: number; - HTTP_STATUS_FOUND: number; - HTTP_STATUS_SEE_OTHER: number; - HTTP_STATUS_NOT_MODIFIED: number; - HTTP_STATUS_USE_PROXY: number; - HTTP_STATUS_TEMPORARY_REDIRECT: number; - HTTP_STATUS_PERMANENT_REDIRECT: number; - HTTP_STATUS_BAD_REQUEST: number; - HTTP_STATUS_UNAUTHORIZED: number; - HTTP_STATUS_PAYMENT_REQUIRED: number; - HTTP_STATUS_FORBIDDEN: number; - HTTP_STATUS_NOT_FOUND: number; - HTTP_STATUS_METHOD_NOT_ALLOWED: number; - HTTP_STATUS_NOT_ACCEPTABLE: number; - HTTP_STATUS_PROXY_AUTHENTICATION_REQUIRED: number; - HTTP_STATUS_REQUEST_TIMEOUT: number; - HTTP_STATUS_CONFLICT: number; - HTTP_STATUS_GONE: number; - HTTP_STATUS_LENGTH_REQUIRED: number; - HTTP_STATUS_PRECONDITION_FAILED: number; - HTTP_STATUS_PAYLOAD_TOO_LARGE: number; - HTTP_STATUS_URI_TOO_LONG: number; - HTTP_STATUS_UNSUPPORTED_MEDIA_TYPE: number; - HTTP_STATUS_RANGE_NOT_SATISFIABLE: number; - HTTP_STATUS_EXPECTATION_FAILED: number; - HTTP_STATUS_TEAPOT: number; - HTTP_STATUS_MISDIRECTED_REQUEST: number; - HTTP_STATUS_UNPROCESSABLE_ENTITY: number; - HTTP_STATUS_LOCKED: number; - HTTP_STATUS_FAILED_DEPENDENCY: number; - HTTP_STATUS_UNORDERED_COLLECTION: number; - HTTP_STATUS_UPGRADE_REQUIRED: number; - HTTP_STATUS_PRECONDITION_REQUIRED: number; - HTTP_STATUS_TOO_MANY_REQUESTS: number; - HTTP_STATUS_REQUEST_HEADER_FIELDS_TOO_LARGE: number; - HTTP_STATUS_UNAVAILABLE_FOR_LEGAL_REASONS: number; - HTTP_STATUS_INTERNAL_SERVER_ERROR: number; - HTTP_STATUS_NOT_IMPLEMENTED: number; - HTTP_STATUS_BAD_GATEWAY: number; - HTTP_STATUS_SERVICE_UNAVAILABLE: number; - HTTP_STATUS_GATEWAY_TIMEOUT: number; - HTTP_STATUS_HTTP_VERSION_NOT_SUPPORTED: number; - HTTP_STATUS_VARIANT_ALSO_NEGOTIATES: number; - HTTP_STATUS_INSUFFICIENT_STORAGE: number; - HTTP_STATUS_LOOP_DETECTED: number; - HTTP_STATUS_BANDWIDTH_LIMIT_EXCEEDED: number; - HTTP_STATUS_NOT_EXTENDED: number; - HTTP_STATUS_NETWORK_AUTHENTICATION_REQUIRED: number; - }; + export namespace constants { + export const NGHTTP2_SESSION_SERVER: number; + export const NGHTTP2_SESSION_CLIENT: number; + export const NGHTTP2_STREAM_STATE_IDLE: number; + export const NGHTTP2_STREAM_STATE_OPEN: number; + export const NGHTTP2_STREAM_STATE_RESERVED_LOCAL: number; + export const NGHTTP2_STREAM_STATE_RESERVED_REMOTE: number; + export const NGHTTP2_STREAM_STATE_HALF_CLOSED_LOCAL: number; + export const NGHTTP2_STREAM_STATE_HALF_CLOSED_REMOTE: number; + export const NGHTTP2_STREAM_STATE_CLOSED: number; + export const NGHTTP2_NO_ERROR: number; + export const NGHTTP2_PROTOCOL_ERROR: number; + export const NGHTTP2_INTERNAL_ERROR: number; + export const NGHTTP2_FLOW_CONTROL_ERROR: number; + export const NGHTTP2_SETTINGS_TIMEOUT: number; + export const NGHTTP2_STREAM_CLOSED: number; + export const NGHTTP2_FRAME_SIZE_ERROR: number; + export const NGHTTP2_REFUSED_STREAM: number; + export const NGHTTP2_CANCEL: number; + export const NGHTTP2_COMPRESSION_ERROR: number; + export const NGHTTP2_CONNECT_ERROR: number; + export const NGHTTP2_ENHANCE_YOUR_CALM: number; + export const NGHTTP2_INADEQUATE_SECURITY: number; + export const NGHTTP2_HTTP_1_1_REQUIRED: number; + export const NGHTTP2_ERR_FRAME_SIZE_ERROR: number; + export const NGHTTP2_FLAG_NONE: number; + export const NGHTTP2_FLAG_END_STREAM: number; + export const NGHTTP2_FLAG_END_HEADERS: number; + export const NGHTTP2_FLAG_ACK: number; + export const NGHTTP2_FLAG_PADDED: number; + export const NGHTTP2_FLAG_PRIORITY: number; + export const DEFAULT_SETTINGS_HEADER_TABLE_SIZE: number; + export const DEFAULT_SETTINGS_ENABLE_PUSH: number; + export const DEFAULT_SETTINGS_INITIAL_WINDOW_SIZE: number; + export const DEFAULT_SETTINGS_MAX_FRAME_SIZE: number; + export const MAX_MAX_FRAME_SIZE: number; + export const MIN_MAX_FRAME_SIZE: number; + export const MAX_INITIAL_WINDOW_SIZE: number; + export const NGHTTP2_DEFAULT_WEIGHT: number; + export const NGHTTP2_SETTINGS_HEADER_TABLE_SIZE: number; + export const NGHTTP2_SETTINGS_ENABLE_PUSH: number; + export const NGHTTP2_SETTINGS_MAX_CONCURRENT_STREAMS: number; + export const NGHTTP2_SETTINGS_INITIAL_WINDOW_SIZE: number; + export const NGHTTP2_SETTINGS_MAX_FRAME_SIZE: number; + export const NGHTTP2_SETTINGS_MAX_HEADER_LIST_SIZE: number; + export const PADDING_STRATEGY_NONE: number; + export const PADDING_STRATEGY_MAX: number; + export const PADDING_STRATEGY_CALLBACK: number; + export const HTTP2_HEADER_STATUS: string; + export const HTTP2_HEADER_METHOD: string; + export const HTTP2_HEADER_AUTHORITY: string; + export const HTTP2_HEADER_SCHEME: string; + export const HTTP2_HEADER_PATH: string; + export const HTTP2_HEADER_ACCEPT_CHARSET: string; + export const HTTP2_HEADER_ACCEPT_ENCODING: string; + export const HTTP2_HEADER_ACCEPT_LANGUAGE: string; + export const HTTP2_HEADER_ACCEPT_RANGES: string; + export const HTTP2_HEADER_ACCEPT: string; + export const HTTP2_HEADER_ACCESS_CONTROL_ALLOW_ORIGIN: string; + export const HTTP2_HEADER_AGE: string; + export const HTTP2_HEADER_ALLOW: string; + export const HTTP2_HEADER_AUTHORIZATION: string; + export const HTTP2_HEADER_CACHE_CONTROL: string; + export const HTTP2_HEADER_CONNECTION: string; + export const HTTP2_HEADER_CONTENT_DISPOSITION: string; + export const HTTP2_HEADER_CONTENT_ENCODING: string; + export const HTTP2_HEADER_CONTENT_LANGUAGE: string; + export const HTTP2_HEADER_CONTENT_LENGTH: string; + export const HTTP2_HEADER_CONTENT_LOCATION: string; + export const HTTP2_HEADER_CONTENT_MD5: string; + export const HTTP2_HEADER_CONTENT_RANGE: string; + export const HTTP2_HEADER_CONTENT_TYPE: string; + export const HTTP2_HEADER_COOKIE: string; + export const HTTP2_HEADER_DATE: string; + export const HTTP2_HEADER_ETAG: string; + export const HTTP2_HEADER_EXPECT: string; + export const HTTP2_HEADER_EXPIRES: string; + export const HTTP2_HEADER_FROM: string; + export const HTTP2_HEADER_HOST: string; + export const HTTP2_HEADER_IF_MATCH: string; + export const HTTP2_HEADER_IF_MODIFIED_SINCE: string; + export const HTTP2_HEADER_IF_NONE_MATCH: string; + export const HTTP2_HEADER_IF_RANGE: string; + export const HTTP2_HEADER_IF_UNMODIFIED_SINCE: string; + export const HTTP2_HEADER_LAST_MODIFIED: string; + export const HTTP2_HEADER_LINK: string; + export const HTTP2_HEADER_LOCATION: string; + export const HTTP2_HEADER_MAX_FORWARDS: string; + export const HTTP2_HEADER_PREFER: string; + export const HTTP2_HEADER_PROXY_AUTHENTICATE: string; + export const HTTP2_HEADER_PROXY_AUTHORIZATION: string; + export const HTTP2_HEADER_RANGE: string; + export const HTTP2_HEADER_REFERER: string; + export const HTTP2_HEADER_REFRESH: string; + export const HTTP2_HEADER_RETRY_AFTER: string; + export const HTTP2_HEADER_SERVER: string; + export const HTTP2_HEADER_SET_COOKIE: string; + export const HTTP2_HEADER_STRICT_TRANSPORT_SECURITY: string; + export const HTTP2_HEADER_TRANSFER_ENCODING: string; + export const HTTP2_HEADER_TE: string; + export const HTTP2_HEADER_UPGRADE: string; + export const HTTP2_HEADER_USER_AGENT: string; + export const HTTP2_HEADER_VARY: string; + export const HTTP2_HEADER_VIA: string; + export const HTTP2_HEADER_WWW_AUTHENTICATE: string; + export const HTTP2_HEADER_HTTP2_SETTINGS: string; + export const HTTP2_HEADER_KEEP_ALIVE: string; + export const HTTP2_HEADER_PROXY_CONNECTION: string; + export const HTTP2_METHOD_ACL: string; + export const HTTP2_METHOD_BASELINE_CONTROL: string; + export const HTTP2_METHOD_BIND: string; + export const HTTP2_METHOD_CHECKIN: string; + export const HTTP2_METHOD_CHECKOUT: string; + export const HTTP2_METHOD_CONNECT: string; + export const HTTP2_METHOD_COPY: string; + export const HTTP2_METHOD_DELETE: string; + export const HTTP2_METHOD_GET: string; + export const HTTP2_METHOD_HEAD: string; + export const HTTP2_METHOD_LABEL: string; + export const HTTP2_METHOD_LINK: string; + export const HTTP2_METHOD_LOCK: string; + export const HTTP2_METHOD_MERGE: string; + export const HTTP2_METHOD_MKACTIVITY: string; + export const HTTP2_METHOD_MKCALENDAR: string; + export const HTTP2_METHOD_MKCOL: string; + export const HTTP2_METHOD_MKREDIRECTREF: string; + export const HTTP2_METHOD_MKWORKSPACE: string; + export const HTTP2_METHOD_MOVE: string; + export const HTTP2_METHOD_OPTIONS: string; + export const HTTP2_METHOD_ORDERPATCH: string; + export const HTTP2_METHOD_PATCH: string; + export const HTTP2_METHOD_POST: string; + export const HTTP2_METHOD_PRI: string; + export const HTTP2_METHOD_PROPFIND: string; + export const HTTP2_METHOD_PROPPATCH: string; + export const HTTP2_METHOD_PUT: string; + export const HTTP2_METHOD_REBIND: string; + export const HTTP2_METHOD_REPORT: string; + export const HTTP2_METHOD_SEARCH: string; + export const HTTP2_METHOD_TRACE: string; + export const HTTP2_METHOD_UNBIND: string; + export const HTTP2_METHOD_UNCHECKOUT: string; + export const HTTP2_METHOD_UNLINK: string; + export const HTTP2_METHOD_UNLOCK: string; + export const HTTP2_METHOD_UPDATE: string; + export const HTTP2_METHOD_UPDATEREDIRECTREF: string; + export const HTTP2_METHOD_VERSION_CONTROL: string; + export const HTTP_STATUS_CONTINUE: number; + export const HTTP_STATUS_SWITCHING_PROTOCOLS: number; + export const HTTP_STATUS_PROCESSING: number; + export const HTTP_STATUS_OK: number; + export const HTTP_STATUS_CREATED: number; + export const HTTP_STATUS_ACCEPTED: number; + export const HTTP_STATUS_NON_AUTHORITATIVE_INFORMATION: number; + export const HTTP_STATUS_NO_CONTENT: number; + export const HTTP_STATUS_RESET_CONTENT: number; + export const HTTP_STATUS_PARTIAL_CONTENT: number; + export const HTTP_STATUS_MULTI_STATUS: number; + export const HTTP_STATUS_ALREADY_REPORTED: number; + export const HTTP_STATUS_IM_USED: number; + export const HTTP_STATUS_MULTIPLE_CHOICES: number; + export const HTTP_STATUS_MOVED_PERMANENTLY: number; + export const HTTP_STATUS_FOUND: number; + export const HTTP_STATUS_SEE_OTHER: number; + export const HTTP_STATUS_NOT_MODIFIED: number; + export const HTTP_STATUS_USE_PROXY: number; + export const HTTP_STATUS_TEMPORARY_REDIRECT: number; + export const HTTP_STATUS_PERMANENT_REDIRECT: number; + export const HTTP_STATUS_BAD_REQUEST: number; + export const HTTP_STATUS_UNAUTHORIZED: number; + export const HTTP_STATUS_PAYMENT_REQUIRED: number; + export const HTTP_STATUS_FORBIDDEN: number; + export const HTTP_STATUS_NOT_FOUND: number; + export const HTTP_STATUS_METHOD_NOT_ALLOWED: number; + export const HTTP_STATUS_NOT_ACCEPTABLE: number; + export const HTTP_STATUS_PROXY_AUTHENTICATION_REQUIRED: number; + export const HTTP_STATUS_REQUEST_TIMEOUT: number; + export const HTTP_STATUS_CONFLICT: number; + export const HTTP_STATUS_GONE: number; + export const HTTP_STATUS_LENGTH_REQUIRED: number; + export const HTTP_STATUS_PRECONDITION_FAILED: number; + export const HTTP_STATUS_PAYLOAD_TOO_LARGE: number; + export const HTTP_STATUS_URI_TOO_LONG: number; + export const HTTP_STATUS_UNSUPPORTED_MEDIA_TYPE: number; + export const HTTP_STATUS_RANGE_NOT_SATISFIABLE: number; + export const HTTP_STATUS_EXPECTATION_FAILED: number; + export const HTTP_STATUS_TEAPOT: number; + export const HTTP_STATUS_MISDIRECTED_REQUEST: number; + export const HTTP_STATUS_UNPROCESSABLE_ENTITY: number; + export const HTTP_STATUS_LOCKED: number; + export const HTTP_STATUS_FAILED_DEPENDENCY: number; + export const HTTP_STATUS_UNORDERED_COLLECTION: number; + export const HTTP_STATUS_UPGRADE_REQUIRED: number; + export const HTTP_STATUS_PRECONDITION_REQUIRED: number; + export const HTTP_STATUS_TOO_MANY_REQUESTS: number; + export const HTTP_STATUS_REQUEST_HEADER_FIELDS_TOO_LARGE: number; + export const HTTP_STATUS_UNAVAILABLE_FOR_LEGAL_REASONS: number; + export const HTTP_STATUS_INTERNAL_SERVER_ERROR: number; + export const HTTP_STATUS_NOT_IMPLEMENTED: number; + export const HTTP_STATUS_BAD_GATEWAY: number; + export const HTTP_STATUS_SERVICE_UNAVAILABLE: number; + export const HTTP_STATUS_GATEWAY_TIMEOUT: number; + export const HTTP_STATUS_HTTP_VERSION_NOT_SUPPORTED: number; + export const HTTP_STATUS_VARIANT_ALSO_NEGOTIATES: number; + export const HTTP_STATUS_INSUFFICIENT_STORAGE: number; + export const HTTP_STATUS_LOOP_DETECTED: number; + export const HTTP_STATUS_BANDWIDTH_LIMIT_EXCEEDED: number; + export const HTTP_STATUS_NOT_EXTENDED: number; + export const HTTP_STATUS_NETWORK_AUTHENTICATION_REQUIRED: number; + } export function getDefaultSettings(): Settings; export function getPackedSettings(settings: Settings): Settings; @@ -6928,3 +6917,243 @@ declare module "http2" { export function connect(authority: string | url.URL, listener?: (session: ClientHttp2Session, socket: net.Socket | tls.TLSSocket) => void): ClientHttp2Session; export function connect(authority: string | url.URL, options?: ClientSessionOptions | SecureClientSessionOptions, listener?: (session: ClientHttp2Session, socket: net.Socket | tls.TLSSocket) => void): ClientHttp2Session; } + +declare module "perf_hooks" { + export interface PerformanceEntry { + /** + * The total number of milliseconds elapsed for this entry. + * This value will not be meaningful for all Performance Entry types. + */ + readonly duration: number; + + /** + * The name of the performance entry. + */ + readonly name: string; + + /** + * The high resolution millisecond timestamp marking the starting time of the Performance Entry. + */ + readonly startTime: number; + + /** + * The type of the performance entry. + * Currently it may be one of: 'node', 'mark', 'measure', 'gc', or 'function'. + */ + readonly entryType: string; + + /** + * When performanceEntry.entryType is equal to 'gc', the performance.kind property identifies + * the type of garbage collection operation that occurred. + * The value may be one of perf_hooks.constants. + */ + readonly kind?: number; + } + + export interface PerformanceNodeTiming extends PerformanceEntry { + /** + * The high resolution millisecond timestamp at which the Node.js process completed bootstrap. + */ + readonly bootstrapComplete: number; + + /** + * The high resolution millisecond timestamp at which cluster processing ended. + */ + readonly clusterSetupEnd: number; + + /** + * The high resolution millisecond timestamp at which cluster processing started. + */ + readonly clusterSetupStart: number; + + /** + * The high resolution millisecond timestamp at which the Node.js event loop exited. + */ + readonly loopExit: number; + + /** + * The high resolution millisecond timestamp at which the Node.js event loop started. + */ + readonly loopStart: number; + + /** + * The high resolution millisecond timestamp at which main module load ended. + */ + readonly moduleLoadEnd: number; + + /** + * The high resolution millisecond timestamp at which main module load started. + */ + readonly moduleLoadStart: number; + + /** + * The high resolution millisecond timestamp at which the Node.js process was initialized. + */ + readonly nodeStart: number; + + /** + * The high resolution millisecond timestamp at which preload module load ended. + */ + readonly preloadModuleLoadEnd: number; + + /** + * The high resolution millisecond timestamp at which preload module load started. + */ + readonly preloadModuleLoadStart: number; + + /** + * The high resolution millisecond timestamp at which third_party_main processing ended. + */ + readonly thirdPartyMainEnd: number; + + /** + * The high resolution millisecond timestamp at which third_party_main processing started. + */ + readonly thirdPartyMainStart: number; + + /** + * The high resolution millisecond timestamp at which the V8 platform was initialized. + */ + readonly v8Start: number; + } + + export interface Performance { + /** + * If name is not provided, removes all PerformanceFunction objects from the Performance Timeline. + * If name is provided, removes entries with name. + * @param name + */ + clearFunctions(name?: string): void; + + /** + * If name is not provided, removes all PerformanceMark objects from the Performance Timeline. + * If name is provided, removes only the named mark. + * @param name + */ + clearMarks(name?: string): void; + + /** + * If name is not provided, removes all PerformanceMeasure objects from the Performance Timeline. + * If name is provided, removes only objects whose performanceEntry.name matches name. + */ + clearMeasures(name?: string): void; + + /** + * Returns a list of all PerformanceEntry objects in chronological order with respect to performanceEntry.startTime. + * @return list of all PerformanceEntry objects + */ + getEntries(): PerformanceEntry[]; + + /** + * Returns a list of all PerformanceEntry objects in chronological order with respect to performanceEntry.startTime + * whose performanceEntry.name is equal to name, and optionally, whose performanceEntry.entryType is equal to type. + * @param name + * @param type + * @return list of all PerformanceEntry objects + */ + getEntriesByName(name: string, type?: string): PerformanceEntry[]; + + /** + * Returns a list of all PerformanceEntry objects in chronological order with respect to performanceEntry.startTime + * whose performanceEntry.entryType is equal to type. + * @param type + * @return list of all PerformanceEntry objects + */ + getEntriesByType(type: string): PerformanceEntry[]; + + /** + * Creates a new PerformanceMark entry in the Performance Timeline. + * A PerformanceMark is a subclass of PerformanceEntry whose performanceEntry.entryType is always 'mark', + * and whose performanceEntry.duration is always 0. + * Performance marks are used to mark specific significant moments in the Performance Timeline. + * @param name + */ + mark(name?: string): void; + + /** + * Creates a new PerformanceMeasure entry in the Performance Timeline. + * A PerformanceMeasure is a subclass of PerformanceEntry whose performanceEntry.entryType is always 'measure', + * and whose performanceEntry.duration measures the number of milliseconds elapsed since startMark and endMark. + * + * The startMark argument may identify any existing PerformanceMark in the the Performance Timeline, or may identify + * any of the timestamp properties provided by the PerformanceNodeTiming class. If the named startMark does not exist, + * then startMark is set to timeOrigin by default. + * + * The endMark argument must identify any existing PerformanceMark in the the Performance Timeline or any of the timestamp + * properties provided by the PerformanceNodeTiming class. If the named endMark does not exist, an error will be thrown. + * @param name + * @param startMark + * @param endMark + */ + measure(name: string, startMark: string, endMark: string): void; + + /** + * An instance of the PerformanceNodeTiming class that provides performance metrics for specific Node.js operational milestones. + */ + readonly nodeTiming: PerformanceNodeTiming; + + /** + * @return the current high resolution millisecond timestamp + */ + now(): number; + + /** + * The timeOrigin specifies the high resolution millisecond timestamp from which all performance metric durations are measured. + */ + readonly timeOrigin: number; + + /** + * Wraps a function within a new function that measures the running time of the wrapped function. + * A PerformanceObserver must be subscribed to the 'function' event type in order for the timing details to be accessed. + * @param fn + */ + timerify any>(fn: T): T; + } + + export interface PerformanceObserverEntryList { + /** + * @return a list of PerformanceEntry objects in chronological order with respect to performanceEntry.startTime. + */ + getEntries(): PerformanceEntry[]; + + /** + * @return a list of PerformanceEntry objects in chronological order with respect to performanceEntry.startTime + * whose performanceEntry.name is equal to name, and optionally, whose performanceEntry.entryType is equal to type. + */ + getEntriesByName(name: string, type?: string): PerformanceEntry[]; + + /** + * @return Returns a list of PerformanceEntry objects in chronological order with respect to performanceEntry.startTime + * whose performanceEntry.entryType is equal to type. + */ + getEntriesByType(type: string): PerformanceEntry[]; + } + + export type PerformanceObserverCallback = (list: PerformanceObserverEntryList, observer: PerformanceObserver) => void; + + export class PerformanceObserver { + constructor(callback: PerformanceObserverCallback); + + /** + * Disconnects the PerformanceObserver instance from all notifications. + */ + disconnect(): void; + + /** + * Subscribes the PerformanceObserver instance to notifications of new PerformanceEntry instances identified by options.entryTypes. + * When options.buffered is false, the callback will be invoked once for every PerformanceEntry instance. + * Property buffered defaults to false. + * @param options + */ + observe(options: { entryTypes: string[], buffered?: boolean }): void; + } + + export namespace constants { + export const NODE_PERFORMANCE_GC_MAJOR: number; + export const NODE_PERFORMANCE_GC_MINOR: number; + export const NODE_PERFORMANCE_GC_INCREMENTAL: number; + export const NODE_PERFORMANCE_GC_WEAKCB: number; + } + + const performance: Performance; +} diff --git a/types/node/node-tests.ts b/types/node/node-tests.ts index 41639e52c6..6bb7f28495 100644 --- a/types/node/node-tests.ts +++ b/types/node/node-tests.ts @@ -29,6 +29,7 @@ import * as dns from "dns"; import * as async_hooks from "async_hooks"; import * as http2 from "http2"; import * as inspector from "inspector"; +import * as perf_hooks from "perf_hooks"; import Module = require("module"); // Specifically test buffer module regression. @@ -405,6 +406,20 @@ function bufferTests() { const buf1: Buffer = Buffer.from('this is a tést'); const buf2: Buffer = Buffer.from('7468697320697320612074c3a97374', 'hex'); } + // Class Method: Buffer.alloc(size[, fill[, encoding]]) + { + const buf1: Buffer = Buffer.alloc(5); + const buf2: Buffer = Buffer.alloc(5, 'a'); + const buf3: Buffer = Buffer.alloc(11, 'aGVsbG8gd29ybGQ=', 'base64'); + } + // Class Method: Buffer.allocUnsafe(size) + { + const buf: Buffer = Buffer.allocUnsafe(5); + } + // Class Method: Buffer.allocUnsafeSlow(size) + { + const buf: Buffer = Buffer.allocUnsafeSlow(10); + } // Class Method byteLenght { @@ -558,7 +573,7 @@ namespace url_tests { { var helloUrl = url.parse('http://example.com/?hello=world', true); if (typeof helloUrl.query !== 'string') { - assert.equal(helloUrl.query.hello, 'world'); + assert.equal(helloUrl.query['hello'], 'world'); } } @@ -784,13 +799,16 @@ function stream_readable_pipe_test() { var z = zlib.createGzip({ finishFlush: zlib.constants.Z_FINISH }); var w = fs.createWriteStream('file.txt.gz'); + assert(typeof z.bytesRead === 'number'); assert(typeof r.bytesRead === 'number'); assert(typeof r.path === 'string'); assert(rs.path instanceof Buffer); r.pipe(z).pipe(w); + z.flush(); r.close(); + z.close(); rs.close(); } @@ -905,9 +923,39 @@ function simplified_stream_ctor_test() { namespace crypto_tests { { + // crypto_hash_string_test + var hashResult: string = crypto.createHash('md5').update('world').digest('hex'); + } + + { + // crypto_hash_buffer_test + var hashResult: string = crypto.createHash('md5') + .update(new Buffer('world')).digest('hex'); + } + + { + // crypto_hash_dataview_test + var hashResult: string = crypto.createHash('md5') + .update(new DataView(new Buffer('world').buffer)).digest('hex'); + } + + { + // crypto_hmac_string_test var hmacResult: string = crypto.createHmac('md5', 'hello').update('world').digest('hex'); } + { + // crypto_hmac_buffer_test + var hmacResult: string = crypto.createHmac('md5', 'hello') + .update(new Buffer('world')).digest('hex'); + } + + { + // crypto_hmac_dataview_test + var hmacResult: string = crypto.createHmac('md5', 'hello') + .update(new DataView(new Buffer('world').buffer)).digest('hex'); + } + { let hmac: crypto.Hmac; (hmac = crypto.createHmac('md5', 'hello')).end('world', 'utf8', () => { @@ -951,6 +999,28 @@ namespace crypto_tests { assert.deepEqual(clearText2, clearText); } + { + // crypto_cipher_decipher_dataview_test + let key: Buffer = new Buffer([1, 2, 3, 4, 5, 6, 7, 8, 9, 1, 2, 3, 4, 5, 6, 7]); + let clearText: DataView = new DataView( + new Buffer([1, 2, 3, 4, 5, 6, 7, 8, 9, 8, 7, 6, 5, 4]).buffer); + let cipher: crypto.Cipher = crypto.createCipher("aes-128-ecb", key); + let cipherBuffers: Buffer[] = []; + cipherBuffers.push(cipher.update(clearText)); + cipherBuffers.push(cipher.final()); + + let cipherText: DataView = new DataView(Buffer.concat(cipherBuffers).buffer); + + let decipher: crypto.Decipher = crypto.createDecipher("aes-128-ecb", key); + let decipherBuffers: Buffer[] = []; + decipherBuffers.push(decipher.update(cipherText)); + decipherBuffers.push(decipher.final()); + + let clearText2: Buffer = Buffer.concat(decipherBuffers); + + assert.deepEqual(clearText2, clearText); + } + { let buffer1: Buffer = new Buffer([1, 2, 3, 4, 5]); let buffer2: Buffer = new Buffer([1, 2, 3, 4, 5]); @@ -2425,6 +2495,26 @@ namespace errors_tests { const myObject = {}; Error.captureStackTrace(myObject); } + { + let frames: NodeJS.CallSite[] = []; + Error.prepareStackTrace(new Error(), frames); + } + { + let frame: NodeJS.CallSite = null; + let frameThis: any = frame.getThis(); + let typeName: string = frame.getTypeName(); + let func: Function = frame.getFunction(); + let funcName: string = frame.getFunctionName(); + let meth: string = frame.getMethodName(); + let fname: string = frame.getFileName(); + let lineno: number = frame.getLineNumber(); + let colno: number = frame.getColumnNumber(); + let evalOrigin: string = frame.getEvalOrigin(); + let isTop: boolean = frame.isToplevel(); + let isEval: boolean = frame.isEval(); + let isNative: boolean = frame.isNative(); + let isConstr: boolean = frame.isConstructor(); + } } /////////////////////////////////////////////////////////// @@ -2917,6 +3007,7 @@ namespace dns_tests { /////////////////////////////////////////////////////////// import * as constants from 'constants'; +import { PerformanceObserver, PerformanceObserverCallback } from "perf_hooks"; namespace constants_tests { var str: string; var num: number; @@ -3072,16 +3163,35 @@ namespace v8_tests { v8.setFlagsFromString('--collect_maps'); } -/////////////////////////////////////////////////////////// -/// Debugger Tests /// -/////////////////////////////////////////////////////////// +//////////////////////////////////////////////////// +/// PerfHooks tests : https://nodejs.org/api/perf_hooks.html +//////////////////////////////////////////////////// +namespace perf_hooks_tests { + perf_hooks.performance.mark('start'); + ( + () => {} + )(); + perf_hooks.performance.mark('end'); -import { Client } from "_debugger"; + const { duration } = perf_hooks.performance.getEntriesByName('discover')[0]; + const timeOrigin = perf_hooks.performance.timeOrigin; -var client = new Client(); - -client.connect(8888, 'localhost'); -client.listbreakpoints((err, body, packet) => { }); + const performanceObserverCallback: PerformanceObserverCallback = (list, obs) => { + const { + duration, + entryType, + name, + startTime, + } = list.getEntries()[0]; + obs.disconnect(); + perf_hooks.performance.clearFunctions(); + }; + const obs = new perf_hooks.PerformanceObserver(performanceObserverCallback); + obs.observe({ + entryTypes: ['function'], + buffered: true, + }); +} //////////////////////////////////////////////////// /// AsyncHooks tests : https://nodejs.org/api/async_hooks.html @@ -3751,3 +3861,13 @@ namespace module_tests { const m1: Module = new Module("moduleId"); const m2: Module = new Module.Module("moduleId"); } + +//////////////////////////////////////////////////// +/// Node.js ESNEXT Support +//////////////////////////////////////////////////// + +namespace esnext_string_tests { + const s: string = 'foo'; + const s1: string = s.trimLeft(); + const s2: string = s.trimRight(); +} diff --git a/types/node/v0/index.d.ts b/types/node/v0/index.d.ts index ccf2e5e207..65da8a9459 100644 --- a/types/node/v0/index.d.ts +++ b/types/node/v0/index.d.ts @@ -632,7 +632,7 @@ declare module "cluster" { } export class Worker extends events.EventEmitter { - id: string; + id: number; process: child.ChildProcess; suicide: boolean; send(message: any, sendHandle?: any): void; diff --git a/types/node/v4/index.d.ts b/types/node/v4/index.d.ts index 797bc455b8..3b9dc7a83c 100644 --- a/types/node/v4/index.d.ts +++ b/types/node/v4/index.d.ts @@ -1,4 +1,4 @@ -// Type definitions for Node.js 4.2 +// Type definitions for Node.js 4.x // Project: http://nodejs.org/ // Definitions by: Microsoft TypeScript // DefinitelyTyped @@ -34,8 +34,18 @@ interface Error { stack?: string; } +// Declare "static" methods in Error interface ErrorConstructor { + /** Create .stack property on a target object */ captureStackTrace(targetObject: Object, constructorOpt?: Function): void; + + /** + * Optional override for formatting stack traces + * + * @see https://github.com/v8/v8/wiki/Stack%20Trace%20API#customizing-stack-traces + */ + prepareStackTrace?: (err: Error, stackTraces: NodeJS.CallSite[]) => any; + stackTraceLimit: number; } @@ -214,6 +224,29 @@ declare var Buffer: { * The same as buf1.compare(buf2). */ compare(buf1: Buffer, buf2: Buffer): number; + /** + * Allocates a new buffer of {size} octets. + * + * @param size count of octets to allocate. + * @param fill if specified, buffer will be initialized by calling buf.fill(fill). + * If parameter is omitted, buffer will be filled with zeros. + * @param encoding encoding used for call to buf.fill while initalizing + */ + alloc(size: number, fill?: string | Buffer | number, encoding?: string): Buffer; + /** + * Allocates a new buffer of {size} octets, leaving memory not initialized, so the contents + * of the newly created Buffer are unknown and may contain sensitive data. + * + * @param size count of octets to allocate + */ + allocUnsafe(size: number): Buffer; + /** + * Allocates a new non-pooled buffer of {size} octets, leaving memory not initialized, so the contents + * of the newly created Buffer are unknown and may contain sensitive data. + * + * @param size count of octets to allocate + */ + allocUnsafeSlow(size: number): Buffer; }; /************************************************ @@ -229,6 +262,80 @@ declare namespace NodeJS { customInspect?: boolean; } + export interface CallSite { + /** + * Value of "this" + */ + getThis(): any; + + /** + * Type of "this" as a string. + * This is the name of the function stored in the constructor field of + * "this", if available. Otherwise the object's [[Class]] internal + * property. + */ + getTypeName(): string | null; + + /** + * Current function + */ + getFunction(): Function | undefined; + + /** + * Name of the current function, typically its name property. + * If a name property is not available an attempt will be made to try + * to infer a name from the function's context. + */ + getFunctionName(): string | null; + + /** + * Name of the property [of "this" or one of its prototypes] that holds + * the current function + */ + getMethodName(): string | null; + + /** + * Name of the script [if this function was defined in a script] + */ + getFileName(): string | null; + + /** + * Current line number [if this function was defined in a script] + */ + getLineNumber(): number | null; + + /** + * Current column number [if this function was defined in a script] + */ + getColumnNumber(): number | null; + + /** + * A call site object representing the location where eval was called + * [if this function was created using a call to eval] + */ + getEvalOrigin(): string | undefined; + + /** + * Is this a toplevel invocation, that is, is "this" the global object? + */ + isToplevel(): boolean; + + /** + * Does this call take place in code defined by a call to eval? + */ + isEval(): boolean; + + /** + * Is this call in native V8 code? + */ + isNative(): boolean; + + /** + * Is this a constructor call? + */ + isConstructor(): boolean; + } + export interface ErrnoException extends Error { errno?: number; code?: string; @@ -789,7 +896,7 @@ declare module "cluster" { } export class Worker extends events.EventEmitter { - id: string; + id: number; process: child.ChildProcess; suicide: boolean; send(message: any, sendHandle?: any, callback?: (error: Error) => void): void; diff --git a/types/node/v4/node-tests.ts b/types/node/v4/node-tests.ts index 8f005da455..431dfb0520 100644 --- a/types/node/v4/node-tests.ts +++ b/types/node/v4/node-tests.ts @@ -268,6 +268,21 @@ function bufferTests() { const buf1: Buffer = Buffer.from('this is a tést'); const buf2: Buffer = Buffer.from('7468697320697320612074c3a97374', 'hex'); } + // Class Method: Buffer.alloc(size[, fill[, encoding]]) + { + const buf1: Buffer = Buffer.alloc(5); + const buf2: Buffer = Buffer.alloc(5, 'a'); + const buf3: Buffer = Buffer.alloc(11, 'aGVsbG8gd29ybGQ=', 'base64'); + + } + // Class Method: Buffer.allocUnsafe(size) + { + const buf: Buffer = Buffer.allocUnsafe(5); + } + // Class Method: Buffer.allocUnsafeSlow(size) + { + const buf: Buffer = Buffer.allocUnsafeSlow(10); + } // Test that TS 1.6 works with the 'as Buffer' annotation // on isBuffer. @@ -1008,6 +1023,26 @@ namespace errors_tests { const myObject = {}; Error.captureStackTrace(myObject); } + { + let frames: NodeJS.CallSite[] = []; + Error.prepareStackTrace(new Error(), frames); + } + { + let frame: NodeJS.CallSite = null; + let frameThis: any = frame.getThis(); + let typeName: string = frame.getTypeName(); + let func: Function = frame.getFunction(); + let funcName: string = frame.getFunctionName(); + let meth: string = frame.getMethodName(); + let fname: string = frame.getFileName(); + let lineno: number = frame.getLineNumber(); + let colno: number = frame.getColumnNumber(); + let evalOrigin: string = frame.getEvalOrigin(); + let isTop: boolean = frame.isToplevel(); + let isEval: boolean = frame.isEval(); + let isNative: boolean = frame.isNative(); + let isConstr: boolean = frame.isConstructor(); + } } /////////////////////////////////////////////////////////// diff --git a/types/node/v6/index.d.ts b/types/node/v6/index.d.ts index e8931e43cf..0696c5c689 100644 --- a/types/node/v6/index.d.ts +++ b/types/node/v6/index.d.ts @@ -31,8 +31,18 @@ interface Error { stack?: string; } +// Declare "static" methods in Error interface ErrorConstructor { + /** Create .stack property on a target object */ captureStackTrace(targetObject: Object, constructorOpt?: Function): void; + + /** + * Optional override for formatting stack traces + * + * @see https://github.com/v8/v8/wiki/Stack%20Trace%20API#customizing-stack-traces + */ + prepareStackTrace?: (err: Error, stackTraces: NodeJS.CallSite[]) => any; + stackTraceLimit: number; } @@ -258,6 +268,80 @@ declare namespace NodeJS { new(stdout: WritableStream, stderr?: WritableStream): Console; } + export interface CallSite { + /** + * Value of "this" + */ + getThis(): any; + + /** + * Type of "this" as a string. + * This is the name of the function stored in the constructor field of + * "this", if available. Otherwise the object's [[Class]] internal + * property. + */ + getTypeName(): string | null; + + /** + * Current function + */ + getFunction(): Function | undefined; + + /** + * Name of the current function, typically its name property. + * If a name property is not available an attempt will be made to try + * to infer a name from the function's context. + */ + getFunctionName(): string | null; + + /** + * Name of the property [of "this" or one of its prototypes] that holds + * the current function + */ + getMethodName(): string | null; + + /** + * Name of the script [if this function was defined in a script] + */ + getFileName(): string | null; + + /** + * Current line number [if this function was defined in a script] + */ + getLineNumber(): number | null; + + /** + * Current column number [if this function was defined in a script] + */ + getColumnNumber(): number | null; + + /** + * A call site object representing the location where eval was called + * [if this function was created using a call to eval] + */ + getEvalOrigin(): string | undefined; + + /** + * Is this a toplevel invocation, that is, is "this" the global object? + */ + isToplevel(): boolean; + + /** + * Does this call take place in code defined by a call to eval? + */ + isEval(): boolean; + + /** + * Is this call in native V8 code? + */ + isNative(): boolean; + + /** + * Is this a constructor call? + */ + isConstructor(): boolean; + } + export interface ErrnoException extends Error { errno?: number; code?: string; @@ -882,7 +966,7 @@ declare module "cluster" { } export class Worker extends events.EventEmitter { - id: string; + id: number; process: child.ChildProcess; suicide: boolean; send(message: any, sendHandle?: any, callback?: (error: Error) => void): boolean; diff --git a/types/node/v6/node-tests.ts b/types/node/v6/node-tests.ts index 1a6b87db05..171b92ba1a 100644 --- a/types/node/v6/node-tests.ts +++ b/types/node/v6/node-tests.ts @@ -330,6 +330,20 @@ function bufferTests() { const buf1: Buffer = Buffer.from('this is a tést'); const buf2: Buffer = Buffer.from('7468697320697320612074c3a97374', 'hex'); } + // Class Method: Buffer.alloc(size[, fill[, encoding]]) + { + const buf1: Buffer = Buffer.alloc(5); + const buf2: Buffer = Buffer.alloc(5, 'a'); + const buf3: Buffer = Buffer.alloc(11, 'aGVsbG8gd29ybGQ=', 'base64'); + } + // Class Method: Buffer.allocUnsafe(size) + { + const buf: Buffer = Buffer.allocUnsafe(5); + } + // Class Method: Buffer.allocUnsafeSlow(size) + { + const buf: Buffer = Buffer.allocUnsafeSlow(10); + } // Test that TS 1.6 works with the 'as Buffer' annotation // on isBuffer. @@ -1829,6 +1843,26 @@ namespace errors_tests { const myObject = {}; Error.captureStackTrace(myObject); } + { + let frames: NodeJS.CallSite[] = []; + Error.prepareStackTrace(new Error(), frames); + } + { + let frame: NodeJS.CallSite = null; + let frameThis: any = frame.getThis(); + let typeName: string = frame.getTypeName(); + let func: Function = frame.getFunction(); + let funcName: string = frame.getFunctionName(); + let meth: string = frame.getMethodName(); + let fname: string = frame.getFileName(); + let lineno: number = frame.getLineNumber(); + let colno: number = frame.getColumnNumber(); + let evalOrigin: string = frame.getEvalOrigin(); + let isTop: boolean = frame.isToplevel(); + let isEval: boolean = frame.isEval(); + let isNative: boolean = frame.isNative(); + let isConstr: boolean = frame.isConstructor(); + } } /////////////////////////////////////////////////////////// diff --git a/types/node/v7/index.d.ts b/types/node/v7/index.d.ts index cc87fadd7c..62e7a26610 100644 --- a/types/node/v7/index.d.ts +++ b/types/node/v7/index.d.ts @@ -32,8 +32,18 @@ interface Error { stack?: string; } +// Declare "static" methods in Error interface ErrorConstructor { + /** Create .stack property on a target object */ captureStackTrace(targetObject: Object, constructorOpt?: Function): void; + + /** + * Optional override for formatting stack traces + * + * @see https://github.com/v8/v8/wiki/Stack%20Trace%20API#customizing-stack-traces + */ + prepareStackTrace?: (err: Error, stackTraces: NodeJS.CallSite[]) => any; + stackTraceLimit: number; } @@ -270,6 +280,80 @@ declare namespace NodeJS { new(stdout: WritableStream, stderr?: WritableStream): Console; } + export interface CallSite { + /** + * Value of "this" + */ + getThis(): any; + + /** + * Type of "this" as a string. + * This is the name of the function stored in the constructor field of + * "this", if available. Otherwise the object's [[Class]] internal + * property. + */ + getTypeName(): string | null; + + /** + * Current function + */ + getFunction(): Function | undefined; + + /** + * Name of the current function, typically its name property. + * If a name property is not available an attempt will be made to try + * to infer a name from the function's context. + */ + getFunctionName(): string | null; + + /** + * Name of the property [of "this" or one of its prototypes] that holds + * the current function + */ + getMethodName(): string | null; + + /** + * Name of the script [if this function was defined in a script] + */ + getFileName(): string | null; + + /** + * Current line number [if this function was defined in a script] + */ + getLineNumber(): number | null; + + /** + * Current column number [if this function was defined in a script] + */ + getColumnNumber(): number | null; + + /** + * A call site object representing the location where eval was called + * [if this function was created using a call to eval] + */ + getEvalOrigin(): string | undefined; + + /** + * Is this a toplevel invocation, that is, is "this" the global object? + */ + isToplevel(): boolean; + + /** + * Does this call take place in code defined by a call to eval? + */ + isEval(): boolean; + + /** + * Is this call in native V8 code? + */ + isNative(): boolean; + + /** + * Is this a constructor call? + */ + isConstructor(): boolean; + } + export interface ErrnoException extends Error { errno?: number; code?: string; @@ -895,7 +979,7 @@ declare module "cluster" { } export class Worker extends events.EventEmitter { - id: string; + id: number; process: child.ChildProcess; suicide: boolean; send(message: any, sendHandle?: any, callback?: (error: Error) => void): boolean; diff --git a/types/node/v7/node-tests.ts b/types/node/v7/node-tests.ts index 9bbf6a9300..f0878cc6fc 100644 --- a/types/node/v7/node-tests.ts +++ b/types/node/v7/node-tests.ts @@ -319,6 +319,20 @@ function bufferTests() { buf = Buffer.from(arr.buffer, 1); buf = Buffer.from(arr.buffer, 0, 1); } + // Class Method: Buffer.alloc(size[, fill[, encoding]]) + { + const buf1: Buffer = Buffer.alloc(5); + const buf2: Buffer = Buffer.alloc(5, 'a'); + const buf3: Buffer = Buffer.alloc(11, 'aGVsbG8gd29ybGQ=', 'base64'); + } + // Class Method: Buffer.allocUnsafe(size) + { + const buf: Buffer = Buffer.allocUnsafe(5); + } + // Class Method: Buffer.allocUnsafeSlow(size) + { + const buf: Buffer = Buffer.allocUnsafeSlow(10); + } // Class Method: Buffer.from(buffer) { @@ -1931,6 +1945,26 @@ namespace errors_tests { const myObject = {}; Error.captureStackTrace(myObject); } + { + let frames: NodeJS.CallSite[] = []; + Error.prepareStackTrace(new Error(), frames); + } + { + let frame: NodeJS.CallSite = null; + let frameThis: any = frame.getThis(); + let typeName: string = frame.getTypeName(); + let func: Function = frame.getFunction(); + let funcName: string = frame.getFunctionName(); + let meth: string = frame.getMethodName(); + let fname: string = frame.getFileName(); + let lineno: number = frame.getLineNumber(); + let colno: number = frame.getColumnNumber(); + let evalOrigin: string = frame.getEvalOrigin(); + let isTop: boolean = frame.isToplevel(); + let isEval: boolean = frame.isEval(); + let isNative: boolean = frame.isNative(); + let isConstr: boolean = frame.isConstructor(); + } } /////////////////////////////////////////////////////////// diff --git a/types/owl.carousel/index.d.ts b/types/owl.carousel/index.d.ts index 21a4dcee71..0295b3fe5b 100644 --- a/types/owl.carousel/index.d.ts +++ b/types/owl.carousel/index.d.ts @@ -1,6 +1,7 @@ // Type definitions for owl.carousel 2.2 // Project: https://github.com/OwlCarousel2/OwlCarousel2 // Definitions by: Ismael Gorissen +// Kenneth Ceyer // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped // TypeScript Version: 2.3 @@ -36,8 +37,8 @@ declare namespace OwlCarousel { autoplay?: boolean; autoplayTimeout?: number; autoplayHoverPause?: boolean; - smartSpeed?: boolean; - fluidSpeed?: boolean; + smartSpeed?: number | boolean; + fluidSpeed?: number | boolean; autoplaySpeed?: number | boolean; navSpeed?: number | boolean; dotsSpeed?: number | boolean; diff --git a/types/p2/index.d.ts b/types/p2/index.d.ts index 89dda72b9c..88dde55025 100644 --- a/types/p2/index.d.ts +++ b/types/p2/index.d.ts @@ -361,13 +361,13 @@ declare namespace p2 { export class ContactMaterialOptions { - friction: number; - restitution: number; - stiffness: number; - relaxation: number; - frictionStiffness: number; - frictionRelaxation: number; - surfaceVelocity: number; + friction?: number; + restitution?: number; + stiffness?: number; + relaxation?: number; + frictionStiffness?: number; + frictionRelaxation?: number; + surfaceVelocity?: number; } @@ -624,8 +624,8 @@ declare namespace p2 { export interface ConvexOptions extends SharedShapeOptions { - length?: number; - radius?: number; + vertices?: ArrayLike[]; + axes?: ArrayLike[]; } @@ -636,7 +636,7 @@ declare namespace p2 { constructor(options?: ConvexOptions); vertices: number[][]; - axes: number[]; + axes: number[][]; centerOfMass: number[]; triangles: number[]; boundingRadius: number; diff --git a/types/p2/p2-tests.ts b/types/p2/p2-tests.ts index 0579a880b2..c796cf8f79 100644 --- a/types/p2/p2-tests.ts +++ b/types/p2/p2-tests.ts @@ -4,6 +4,12 @@ var world = new p2.World({ gravity:[0, -9.82] }); +// Set default contact material +world.defaultContactMaterial = new p2.ContactMaterial( + new p2.Material(1), new p2.Material(2), + { friction: 1, restitution: 0 } +) + // Create an empty dynamic body var circleBody = new p2.Body({ mass: 5, @@ -26,6 +32,20 @@ var groundShape = new p2.Plane(); groundBody.addShape(groundShape); world.addBody(groundBody); +// Create a convex shape. Can use various array types. +const convex = new p2.Convex({ + vertices: [ + new Float32Array([-1, 1]), + new Uint32Array([0, -1]), + [1, 1] + ], + axes: [ + new Float32Array([-1, 1]), + new Int32Array([0, -1]), + [1, 1] + ] +}) + // To get the trajectories of the bodies, // we must step the world forward in time. // This is done using a fixed time step size. diff --git a/types/papaparse/index.d.ts b/types/papaparse/index.d.ts index 4365ac38ac..709cfeec67 100644 --- a/types/papaparse/index.d.ts +++ b/types/papaparse/index.d.ts @@ -3,146 +3,134 @@ // Definitions by: Pedro Flemming // Rain Shen // João Loff +// John Reilly // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -declare namespace PapaParse { - interface Static { - /** - * Parse a csv string or a csv file - */ - parse(csvString: string, config?: ParseConfig): ParseResult; +export as namespace Papa; - parse(file: File, config?: ParseConfig): ParseResult; +/** + * Parse a csv string or a csv file + */ +export function parse(csvString: string, config?: ParseConfig): ParseResult; - /** - * Unparses javascript data objects and returns a csv string - */ - unparse(data: Array, config?: UnparseConfig): string; +export function parse(file: File, config?: ParseConfig): ParseResult; - unparse(data: Array>, config?: UnparseConfig): string; +/** + * Unparses javascript data objects and returns a csv string + */ +export function unparse(data: Array, config?: UnparseConfig): string; - unparse(data: UnparseObject, config?: UnparseConfig): string; +export function unparse(data: Array>, config?: UnparseConfig): string; - /** - * Read-Only Properties - */ - // An array of characters that are not allowed as delimiters. - BAD_DELIMETERS: Array; +export function unparse(data: UnparseObject, config?: UnparseConfig): string; - // The true delimiter. Invisible. ASCII code 30. Should be doing the job we strangely rely upon commas and tabs for. - RECORD_SEP: string; +/** + * Read-Only Properties + */ +// An array of characters that are not allowed as delimiters. +export const BAD_DELIMETERS: Array; - // Also sometimes used as a delimiting character. ASCII code 31. - UNIT_SEP: string; +// The true delimiter. Invisible. ASCII code 30. Should be doing the job we strangely rely upon commas and tabs for. +export const RECORD_SEP: string; - // Whether or not the browser supports HTML5 Web Workers. If false, worker: true will have no effect. - WORKERS_SUPPORTED: boolean; +// Also sometimes used as a delimiting character. ASCII code 31. +export const UNIT_SEP: string; - // The relative path to Papa Parse. This is automatically detected when Papa Parse is loaded synchronously. - SCRIPT_PATH: string; +// Whether or not the browser supports HTML5 Web Workers. If false, worker: true will have no effect. +export const WORKERS_SUPPORTED: boolean; - /** - * Configurable Properties - */ - // The size in bytes of each file chunk. Used when streaming files obtained from the DOM that exist on the local computer. Default 10 MB. - LocalChunkSize: string; +// The relative path to Papa Parse. This is automatically detected when Papa Parse is loaded synchronously. +export const SCRIPT_PATH: string; - // Same as LocalChunkSize, but for downloading files from remote locations. Default 5 MB. - RemoteChunkSize: string; +/** + * Configurable Properties + */ +// The size in bytes of each file chunk. Used when streaming files obtained from the DOM that exist on the local computer. Default 10 MB. +export let LocalChunkSize: string; - // The delimiter used when it is left unspecified and cannot be detected automatically. Default is comma. - DefaultDelimiter: string; +// Same as LocalChunkSize, but for downloading files from remote locations. Default 5 MB. +export let RemoteChunkSize: string; - /** - * On Papa there are actually more classes exposed - * but none of them are officially documented - * Since we can interact with the Parser from one of the callbacks - * I have included the API for this class. - */ - Parser: ParserConstructor; - } +// The delimiter used when it is left unspecified and cannot be detected automatically. Default is comma. +export let DefaultDelimiter: string; - interface ParseConfig { - delimiter?: string; // default: "" - newline?: string; // default: "" - quoteChar?: string; // default: '"' - header?: boolean; // default: false - dynamicTyping?: boolean; // default: false - preview?: number; // default: 0 - encoding?: string; // default: "" - worker?: boolean; // default: false - comments?: boolean | string; // default: false - download?: boolean; // default: false - skipEmptyLines?: boolean; // default: false - fastMode?: boolean; // default: undefined - withCredentials?: boolean; // default: undefined +/** + * On Papa there are actually more classes exposed + * but none of them are officially documented + * Since we can interact with the Parser from one of the callbacks + * I have included the API for this class. + */ +export class Parser { - // Callbacks - step?(results: ParseResult, parser: Parser): void; // default: undefined - complete?(results: ParseResult, file?: File): void; // default: undefined - error?(error: ParseError, file?: File): void; // default: undefined - chunk?(results: ParseResult, parser: Parser): void; // default: undefined - beforeFirstChunk?(chunk: string): string | void; // default: undefined - } + constructor(config: ParseConfig); - interface UnparseConfig { - quotes?: boolean; // default: false - delimiter?: string; // default: "," - newline?: string; // default: "\r\n" - } + parse(input: string, baseIndex: number, ignoreLastRow: boolean): any; - interface UnparseObject { - fields: Array; - data: string | Array; - } + // Sets the abort flag + abort(): void; - interface ParseError { - type: string; // A generalization of the error - code: string; // Standardized error code - message: string; // Human-readable details - row: number; // Row index of parsed data where error is - } - - interface ParseMeta { - delimiter: string; // Delimiter used - linebreak: string; // Line break sequence used - aborted: boolean; // Whether process was aborted - fields: Array; // Array of field names - truncated: boolean; // Whether preview consumed all input - } - - /** - * @interface ParseResult - * - * data: is an array of rows. If header is false, rows are arrays; otherwise they are objects of data keyed by the field name. - * errors: is an array of errors - * meta: contains extra information about the parse, such as delimiter used, the newline sequence, whether the process was aborted, etc. Properties in this object are not guaranteed to exist in all situations - */ - interface ParseResult { - data: Array; - errors: Array; - meta: ParseMeta; - } - - /** - * Parser - */ - interface ParserConstructor { new (config: ParseConfig): Parser; } - interface Parser { - // Parses the input - parse(input: string, baseIndex: number, ignoreLastRow: boolean): any; - - // Sets the abort flag - abort(): void; - - // Gets the cursor position - getCharIndex(): number; - } + // Gets the cursor position + getCharIndex(): number; } -declare var Papa: PapaParse.Static; +export interface ParseConfig { + delimiter?: string; // default: "" + newline?: string; // default: "" + quoteChar?: string; // default: '"' + header?: boolean; // default: false + dynamicTyping?: boolean; // default: false + preview?: number; // default: 0 + encoding?: string; // default: "" + worker?: boolean; // default: false + comments?: boolean | string; // default: false + download?: boolean; // default: false + skipEmptyLines?: boolean; // default: false + fastMode?: boolean; // default: undefined + withCredentials?: boolean; // default: undefined -declare module "papaparse" { - var Papa: PapaParse.Static; - export = Papa; + // Callbacks + step?(results: ParseResult, parser: Parser): void; // default: undefined + complete?(results: ParseResult, file?: File): void; // default: undefined + error?(error: ParseError, file?: File): void; // default: undefined + chunk?(results: ParseResult, parser: Parser): void; // default: undefined + beforeFirstChunk?(chunk: string): string | void; // default: undefined +} + +export interface UnparseConfig { + quotes?: boolean; // default: false + delimiter?: string; // default: "," + newline?: string; // default: "\r\n" +} + +export interface UnparseObject { + fields: Array; + data: string | Array; +} + +export interface ParseError { + type: string; // A generalization of the error + code: string; // Standardized error code + message: string; // Human-readable details + row: number; // Row index of parsed data where error is +} + +export interface ParseMeta { + delimiter: string; // Delimiter used + linebreak: string; // Line break sequence used + aborted: boolean; // Whether process was aborted + fields: Array; // Array of field names + truncated: boolean; // Whether preview consumed all input +} + +/** + * @interface ParseResult + * + * data: is an array of rows. If header is false, rows are arrays; otherwise they are objects of data keyed by the field name. + * errors: is an array of errors + * meta: contains extra information about the parse, such as delimiter used, the newline sequence, whether the process was aborted, etc. Properties in this object are not guaranteed to exist in all situations + */ +export interface ParseResult { + data: Array; + errors: Array; + meta: ParseMeta; } diff --git a/types/papaparse/papaparse-tests.ts b/types/papaparse/papaparse-tests.ts index a432fc7f09..1e527c4c32 100644 --- a/types/papaparse/papaparse-tests.ts +++ b/types/papaparse/papaparse-tests.ts @@ -1,6 +1,14 @@ import Papa = require("papaparse"); +import { + ParseConfig, + UnparseConfig, + UnparseObject, + ParseError, + ParseMeta, + ParseResult +} from "papaparse"; /** * Parsing diff --git a/types/paper/index.d.ts b/types/paper/index.d.ts index f75661377a..46d5f58786 100644 --- a/types/paper/index.d.ts +++ b/types/paper/index.d.ts @@ -1305,7 +1305,12 @@ declare module 'paper' { * The function to be called when the mouse button is pushed down on the item. The function receives a MouseEvent object which contains information about the mouse event. */ onMouseDown: (event: MouseEvent) => void; - + + /** + * The function to be called when the mouse position changes while the mouse is being dragged. The function receives a MouseEvent object which contains information about the mouse event. + */ + onMouseDrag: (event: MouseEvent) => void; + /** * The function to be called when the mouse button is released over the item. * The function receives a MouseEvent object which contains information about the mouse event. diff --git a/types/parse-ms/index.d.ts b/types/parse-ms/index.d.ts new file mode 100644 index 0000000000..1a8a63d4a2 --- /dev/null +++ b/types/parse-ms/index.d.ts @@ -0,0 +1,12 @@ +// Type definitions for parse-ms 1.0 +// Project: https://github.com/sindresorhus/parse-ms#readme +// Definitions by: Giles Roadnight +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +export default function parseMs(ms: number): { + days: number; + hours: number; + minutes: number; + seconds: number; + milliseconds: number; +}; diff --git a/types/parse-ms/parse-ms-tests.ts b/types/parse-ms/parse-ms-tests.ts new file mode 100644 index 0000000000..2b747ad5a8 --- /dev/null +++ b/types/parse-ms/parse-ms-tests.ts @@ -0,0 +1,3 @@ +import parseMs from "parse-ms"; + +const { days, hours, milliseconds, minutes, seconds } = parseMs(3000); diff --git a/types/parse-ms/tsconfig.json b/types/parse-ms/tsconfig.json new file mode 100644 index 0000000000..3fecf7615f --- /dev/null +++ b/types/parse-ms/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", + "parse-ms-tests.ts" + ] +} diff --git a/types/parse-ms/tslint.json b/types/parse-ms/tslint.json new file mode 100644 index 0000000000..3db14f85ea --- /dev/null +++ b/types/parse-ms/tslint.json @@ -0,0 +1 @@ +{ "extends": "dtslint/dt.json" } diff --git a/types/parse/index.d.ts b/types/parse/index.d.ts index 3ad8e6c15d..5b4ff9a0bf 100644 --- a/types/parse/index.d.ts +++ b/types/parse/index.d.ts @@ -17,6 +17,7 @@ declare namespace Parse { let javaScriptKey: string | undefined; let masterKey: string | undefined; let serverURL: string; + let liveQueryServerURL: string; let VERSION: string; interface SuccessOption { diff --git a/types/parsimmon/index.d.ts b/types/parsimmon/index.d.ts index dfbae05e23..c25ab020de 100644 --- a/types/parsimmon/index.d.ts +++ b/types/parsimmon/index.d.ts @@ -1,4 +1,4 @@ -// Type definitions for Parsimmon 1.3 +// Type definitions for Parsimmon 1.6 // Project: https://github.com/jneen/parsimmon // Definitions by: Bart van der Schoor // Mizunashi Mana @@ -6,7 +6,7 @@ // Benny van Reeven // Leonard Thieu // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -// TypeScript Version: 2.1 +// TypeScript Version: 2.2 /** * **NOTE:** You probably will never need to use this function. Most parsing @@ -74,6 +74,22 @@ declare namespace Parsimmon { index: Index; } + interface Rule { + [key: string]: (r: Language) => Parser; + } + + interface Language { + [key: string]: Parser; + } + + type TypedRule = { + [P in keyof TLanguageSpec]: (r: TypedLanguage) => Parser; + }; + + type TypedLanguage = { + [P in keyof TLanguageSpec]: Parser; + }; + interface Parser { /** * parse the string @@ -106,6 +122,15 @@ declare namespace Parsimmon { */ // tslint:disable-next-line:unified-signatures then(anotherParser: Parser): Parser; + /** + * returns wrapper(this) from the parser. Useful for custom functions used + * to wrap your parsers, while keeping with Parsimmon chaining style. + */ + thru(call: (wrapper: Parser) => Parser): Parser; + /** + * expects anotherParser before and after parser, yielding the result of parser + */ + trim(anotherParser: Parser): Parser; /** * transforms the output of parser with the given function. */ @@ -171,6 +196,53 @@ declare namespace Parsimmon { */ function Parser(fn: (input: string, i: number) => Parsimmon.Reply): Parser; + /** + * Starting point for building a language parser in Parsimmon. + * + * For having the resulting language rules return typed parsers, e.g. `Parser` instead of + * `Parser`, pass a language specification as type parameter to this function. The language + * specification should be of the following form: + * + * ```javascript + * { + * rule1: type; + * rule2: type; + * } + * ``` + * + * For example: + * + * ```javascript + * const language = Parsimmon.createLanguage<{ + * expr: Expr; + * numberLiteral: number; + * stringLiteral: string; + * }>({ + * expr: r => (some expression that yields Parser), + * numberLiteral: r => (some expression that yields Parser), + * stringLiteral: r => (some expression that yields Parser) + * }); + * ``` + * + * Now both `language` and the parameter `r` that is passed into every parser rule will be of the + * following type: + * + * ```javascript + * { + * expr: Parser; + * numberLiteral: Parser; + * stringLiteral: Parser; + * } + * ``` + * + * Another benefit is that both the `rules` parameter and the resulting `language` should match the + * properties defined in the language specification type, which means that the compiler checks that + * there are no missing or superfluous rules in the language definition, and that the rules you access + * on the resulting language do actually exist. + */ + function createLanguage(rules: Rule): Language; + function createLanguage(rules: TypedRule): TypedLanguage; + /** * To be used inside of Parsimmon(fn). Generates an object describing how * far the successful parse went (index), and what value it created doing diff --git a/types/parsimmon/parsimmon-tests.ts b/types/parsimmon/parsimmon-tests.ts index f89d2fda2f..c6dbaec22c 100644 --- a/types/parsimmon/parsimmon-tests.ts +++ b/types/parsimmon/parsimmon-tests.ts @@ -1,5 +1,5 @@ import P = require('parsimmon'); -import { Parser, Mark, Result, Index, Reply } from "parsimmon"; +import { Parser, Mark, Result, Index, Reply, Language, TypedLanguage } from "parsimmon"; // -- -- -- -- -- -- -- -- -- -- -- -- -- @@ -13,27 +13,27 @@ class Bar { // -- -- -- -- -- -- -- -- -- -- -- -- -- -let str: string; +let str: string = null!; let strArr: string[]; let bool: boolean; -let num: number; +let num: number = null!; let index: Index; -let foo: Foo; +let foo: Foo = null!; declare const bar: Bar; // -- -- -- -- -- -- -- -- -- -- -- -- -- let strPar: Parser; -let numPar: Parser; +let numPar: Parser = null!; let voidPar: Parser; let anyPar: Parser; let nullPar: Parser; let emptyStrPar: Parser<''>; let indexPar: Parser; -let fooPar: Parser; -let barPar: Parser; +let fooPar: Parser = null!; +let barPar: Parser = null!; let fooOrBarPar: Parser; // -- -- -- -- -- -- -- -- -- -- -- -- -- @@ -43,7 +43,7 @@ let fooArrPar: Parser; // -- -- -- -- -- -- -- -- -- -- -- -- -- -let fooMarkPar: Parser>; +let fooMarkPar: Parser> = null!; const result = fooMarkPar.parse(str); if (result.status) { @@ -54,7 +54,7 @@ if (result.status) { // -- -- -- -- -- -- -- -- -- -- -- -- -- -let fooResult: Result; +let fooResult: Result = fooPar.parse(""); // https://github.com/Microsoft/TypeScript/issues/12882 if (fooResult.status === true) { @@ -191,3 +191,55 @@ strArrPar = P.sepBy1(P.string('foo'), P.string('bar')); strPar = P.test((a: string) => false); strPar = P.takeWhile((a: string) => true); + +// -- -- -- -- -- -- -- -- -- -- -- -- -- + +let language: Language; + +language = P.createLanguage({ + SomeRule: r => P.alt(P.string(""), r.AnotherRule), + AnotherRule: () => P.string(""), +}); + +// $ExpectType Parser +language.SomeRule; +// $ExpectType Parser +language.AnotherRule; +// $ExpectType Parser +language.UndefinedRule; + +interface MyLanguageSpec { + FooRule: Foo; + BarRule: Bar; + StringRule: string; +} + +let myLanguage: TypedLanguage; + +myLanguage = P.createLanguage({ + FooRule: r => { + fooPar = r.FooRule; + barPar = r.BarRule; + strPar = r.StringRule; + return fooPar; + }, + BarRule: r => barPar, + StringRule: () => strPar, +}); + +// $ExpectType Parser +myLanguage.FooRule; +// $ExpectType Parser +myLanguage.BarRule; +// $ExpectType Parser +myLanguage.StringRule; + +const noRules = P.createLanguage<{}>({}); + +// $ExpectError +P.createLanguage<{MissingRule: string}>({}); + +P.createLanguage<{SomeRule: string}>({ + SomeRule: r => strPar, + AnotherRule: (r: any) => strPar // $ExpectError +}); diff --git a/types/parsimmon/tsconfig.json b/types/parsimmon/tsconfig.json index 34d78a5d0a..676b349a37 100644 --- a/types/parsimmon/tsconfig.json +++ b/types/parsimmon/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", "parsimmon-tests.ts" ] -} \ No newline at end of file +} diff --git a/types/passport-google-oauth/index.d.ts b/types/passport-google-oauth/index.d.ts index 720f6449d7..a56c91e73f 100644 --- a/types/passport-google-oauth/index.d.ts +++ b/types/passport-google-oauth/index.d.ts @@ -1,19 +1,16 @@ -// Type definitions for passport-facebook 1.0.3 -// Project: https://github.com/jaredhanson/passport-facebook +// Type definitions for passport-google-oauth 1.0.3 +// Project: https://github.com/jaredhanson/passport-google-oauth // Definitions by: James Roland Cabresos // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped // TypeScript Version: 2.3 /// - - import passport = require('passport'); import express = require('express'); interface Profile extends passport.Profile { gender: string; - _raw: string; _json: any; } @@ -22,7 +19,6 @@ interface IOAuthStrategyOption { consumerKey: string; consumerSecret: string; callbackURL: string; - requestTokenURL?: string; accessTokenURL?: string; userAuthorizationURL?: string; @@ -38,8 +34,15 @@ interface VerifyFunction { } declare class OAuthStrategy implements passport.Strategy { - constructor(options: IOAuthStrategyOption, - verify: (accessToken: string, refreshToken: string, profile: Profile, done: VerifyFunction) => void); + constructor( + options: IOAuthStrategyOption, + verify: ( + accessToken: string, + refreshToken: string, + profile: Profile, + done: VerifyFunction + ) => void + ); name: string; authenticate: (req: express.Request, options?: Object) => void; } @@ -48,10 +51,8 @@ interface IOAuth2StrategyOption { clientID: string; clientSecret: string; callbackURL: string; - authorizationURL?: string; tokenURL?: string; - accessType?: string; approval_prompt?: string; prompt?: string; @@ -64,14 +65,29 @@ interface IOAuth2StrategyOption { } interface IOAuth2StrategyOptionWithRequest extends IOAuth2StrategyOption { - passReqToCallback: true; + passReqToCallback: boolean; } declare class OAuth2Strategy implements passport.Strategy { - constructor(options: IOAuth2StrategyOption, - verify: (accessToken: string, refreshToken: string, profile: Profile, done: (error: any, user?: any) => void) => void); - constructor(options: IOAuth2StrategyOptionWithRequest, - verify: (req: express.Request, accessToken: string, refreshToken: string, profile: Profile, done: (error: any, user?: any) => void) => void); + constructor( + options: IOAuth2StrategyOption, + verify: ( + accessToken: string, + refreshToken: string, + profile: Profile, + done: (error: any, user?: any) => void + ) => void + ); + constructor( + options: IOAuth2StrategyOptionWithRequest, + verify: ( + req: express.Request, + accessToken: string, + refreshToken: string, + profile: Profile, + done: (error: any, user?: any) => void + ) => void + ); name: string; authenticate: (req: express.Request, options?: Object) => void; diff --git a/types/passport-google-oauth/passport-google-oauth-tests.ts b/types/passport-google-oauth/passport-google-oauth-tests.ts index ad0ed185a3..2e9a4bb9c2 100644 --- a/types/passport-google-oauth/passport-google-oauth-tests.ts +++ b/types/passport-google-oauth/passport-google-oauth-tests.ts @@ -1,55 +1,98 @@ - /** * Created by jcabresos on 4/19/2014. */ -import express = require("express"); +import express = require('express'); import passport = require('passport'); import google = require('passport-google-oauth'); // just some test model var User = { - findOrCreate(id:string, provider:string, callback:(err:any, user:any) => void): void { - callback(null, {username:'james'}); + findOrCreate( + id: string, + provider: string, + callback: (err: any, user: any) => void + ): void { + callback(null, { username: 'james' }); } -} +}; -passport.use(new google.OAuthStrategy({ +passport.use( + new google.OAuthStrategy( + { consumerKey: process.env.GOOGLE_CONSUMER_KEY, consumerSecret: process.env.GOOGLE_CONSUMER_SECRET, callbackURL: process.env.PASSPORT_GOOGLE_CALLBACK_URL - }, - function(accessToken:string, refreshToken:string, profile:google.Profile, done:(error:any, user?:any, msg?: google.VerifyOptions) => void) { - User.findOrCreate(profile.id, profile.provider, function(err, user) { - if (err) { return done(err); } - else if(!user) return done(null, false, {message: 'not found user'}); - return done(null, user); - }); - }) + }, + function( + accessToken: string, + refreshToken: string, + profile: google.Profile, + done: (error: any, user?: any, msg?: google.VerifyOptions) => void + ) { + User.findOrCreate(profile.id, profile.provider, function( + err, + user + ) { + if (err) { + return done(err); + } else if (!user) + return done(null, false, { message: 'not found user' }); + return done(null, user); + }); + } + ) ); -passport.use(new google.OAuth2Strategy({ +passport.use( + new google.OAuth2Strategy( + { clientID: process.env.GOOGLE_CLIENT_ID, clientSecret: process.env.GOOGLE_CLIENT_SECRET, callbackURL: process.env.PASSPORT_GOOGLE_CALLBACK_URL - }, - function(accessToken:string, refreshToken:string, profile:google.Profile, done:(error:any, user?:any) => void) { - User.findOrCreate(profile.id, profile.provider, function(err, user) { - if (err) { return done(err); } - done(null, user); - }); - }) + }, + function( + accessToken: string, + refreshToken: string, + profile: google.Profile, + done: (error: any, user?: any) => void + ) { + User.findOrCreate(profile.id, profile.provider, function( + err, + user + ) { + if (err) { + return done(err); + } + done(null, user); + }); + } + ) ); -passport.use(new google.OAuth2Strategy({ +passport.use( + new google.OAuth2Strategy( + { clientID: process.env.GOOGLE_CLIENT_ID, clientSecret: process.env.GOOGLE_CLIENT_SECRET, callbackURL: process.env.PASSPORT_GOOGLE_CALLBACK_URL, passReqToCallback: true - }, - function(req: express.Request, accessToken:string, refreshToken:string, profile:google.Profile, done:(error:any, user?:any) => void) { - User.findOrCreate(profile.id, profile.provider, function(err, user) { - if (err) { return done(err); } - done(null, user); - }); - }) + }, + function( + req: express.Request, + accessToken: string, + refreshToken: string, + profile: google.Profile, + done: (error: any, user?: any) => void + ) { + User.findOrCreate(profile.id, profile.provider, function( + err, + user + ) { + if (err) { + return done(err); + } + done(null, user); + }); + } + ) ); diff --git a/types/passport-google-oauth/tsconfig.json b/types/passport-google-oauth/tsconfig.json index adde576621..7f3b315c07 100644 --- a/types/passport-google-oauth/tsconfig.json +++ b/types/passport-google-oauth/tsconfig.json @@ -1,23 +1,16 @@ { "compilerOptions": { "module": "commonjs", - "lib": [ - "es6" - ], + "lib": ["es6"], "noImplicitAny": true, "noImplicitThis": true, "strictNullChecks": false, "strictFunctionTypes": true, "baseUrl": "../", - "typeRoots": [ - "../" - ], + "typeRoots": ["../"], "types": [], "noEmit": true, "forceConsistentCasingInFileNames": true }, - "files": [ - "index.d.ts", - "passport-google-oauth-tests.ts" - ] -} \ No newline at end of file + "files": ["index.d.ts", "passport-google-oauth-tests.ts"] +} diff --git a/types/pathwatcher/index.d.ts b/types/pathwatcher/index.d.ts index 0ff5427913..4e5476bd80 100644 --- a/types/pathwatcher/index.d.ts +++ b/types/pathwatcher/index.d.ts @@ -2,7 +2,7 @@ // Project: https://github.com/atom/node-pathwatcher // Definitions by: GlenCFL // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -// TypeScript Version: 2.2 +// TypeScript Version: 2.3 /// diff --git a/types/pg/index.d.ts b/types/pg/index.d.ts index 62208830b3..9f945082cd 100644 --- a/types/pg/index.d.ts +++ b/types/pg/index.d.ts @@ -94,7 +94,7 @@ export class Pool extends events.EventEmitter { } export class Client extends events.EventEmitter { - constructor(config: ClientConfig); + constructor(config: string | ClientConfig); connect(): Promise; connect(callback: (err: Error) => void): void; diff --git a/types/pixi.js/index.d.ts b/types/pixi.js/index.d.ts index 48b9583c0b..1875746d6e 100644 --- a/types/pixi.js/index.d.ts +++ b/types/pixi.js/index.d.ts @@ -834,7 +834,7 @@ declare namespace PIXI { protected _lastObjectRendered: DisplayObject; resize(screenWidth: number, screenHeight: number): void; - generateTexture(displayObject: DisplayObject, scaleMode?: number, resolution?: number): RenderTexture; + generateTexture(displayObject: DisplayObject, scaleMode?: number, resolution?: number, region?: Rectangle): RenderTexture; render(...args: any[]): void; destroy(removeView?: boolean): void; } @@ -948,7 +948,6 @@ declare namespace PIXI { extract: extract.WebGLExtract; protected drawModes: any; protected _activeShader: Shader; - protected _activeVao: glCore.VertexArrayObject; _activeRenderTarget: RenderTarget; protected _initContext(): void; @@ -1032,7 +1031,7 @@ declare namespace PIXI { update(): void; run(): void; - unload(): void; + unload(displayObject: DisplayObject): void; } abstract class ObjectRenderer extends WebGLManager { constructor(renderer: WebGLRenderer); @@ -2124,7 +2123,7 @@ declare namespace PIXI { protected _tempPoint: Point; resolution: number; hitTest(globalPoint: Point, root?: Container): DisplayObject; - protected setTargetElement(element: HTMLCanvasElement, resolution?: number): void; + setTargetElement(element: HTMLCanvasElement, resolution?: number): void; protected addEvents(): void; protected removeEvents(): void; update(deltaTime?: number): void; @@ -2661,7 +2660,7 @@ declare namespace PIXI { ////////////////////////////////////////////////////////////////////////////// /////////////////////////////pixi-gl-core///////////////////////////////////// ////////////////////////////////////////////////////////////////////////////// - // pixi-gl-core 1.1.2 https://github.com/pixijs/pixi-gl-core + // pixi-gl-core 1.1.4 https://github.com/pixijs/pixi-gl-core // sharedArrayBuffer as a type is not available yet. // need to fully define what an `Attrib` is. namespace glCore { @@ -2813,13 +2812,13 @@ declare namespace PIXI { indexBuffer: GLBuffer; dirty: boolean; - bind(): VertexArrayObject; - unbind(): VertexArrayObject; - activate(): VertexArrayObject; - addAttribute(buffer: GLBuffer, attribute: Attrib, type: number, normalized: boolean, stride: number, start: number): VertexArrayObject; - addIndex(buffer: GLBuffer, options?: any): VertexArrayObject; - clear(): VertexArrayObject; - draw(type: number, size: number, start: number): VertexArrayObject; + bind(): this; + unbind(): this; + activate(): this; + addAttribute(buffer: GLBuffer, attribute: Attrib, type?: number, normalized?: boolean, stride?: number, start?: number): this; + addIndex(buffer: GLBuffer, options?: any): this; + clear(): this; + draw(type: number, size: number, start: number): this; destroy(): void; } } diff --git a/types/polymer/index.d.ts b/types/polymer/index.d.ts index b1f76d83c6..eee6a6250f 100644 --- a/types/polymer/index.d.ts +++ b/types/polymer/index.d.ts @@ -53,7 +53,7 @@ declare global { // Debouncer - debounce?(jobName: string, callback: Function, wait: number): void; + debounce?(jobName: string, callback: Function, wait?: number): void; isDebouncerActive?(jobName: string): boolean; diff --git a/types/prettier/index.d.ts b/types/prettier/index.d.ts index cb0a813385..32c541fda6 100644 --- a/types/prettier/index.d.ts +++ b/types/prettier/index.d.ts @@ -1,4 +1,4 @@ -// Type definitions for prettier 1.8 +// Type definitions for prettier 1.9 // Project: https://github.com/prettier/prettier // Definitions by: Ika // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped @@ -85,12 +85,18 @@ export interface Options { */ insertPragma?: boolean; /** - * By default, Prettier will wrap markdown text at the specified print width. - * In some cases you may want to rely on editor/viewer soft wrapping instead, - * so this option allows you to opt out. When prose wrapping is disabled, - * each paragraph will be printed on its own line. + * By default, Prettier will wrap markdown text as-is since some services use a linebreak-sensitive renderer. + * In some cases you may want to rely on editor/viewer soft wrapping instead, so this option allows you to opt out. */ - proseWrap?: boolean; + proseWrap?: + | boolean // deprecated + | 'always' + | 'never' + | 'preserve'; + /** + * Include parentheses around a sole arrow function parameter. + */ + arrowParens?: 'avoid' | 'always'; } export interface CursorOptions extends Options { @@ -135,6 +141,16 @@ export interface ResolveConfigOptions { * Pass directly the path of the config file if you don't wish to search for it. */ config?: string; + /** + * If set to `true` and an `.editorconfig` file is in your project, + * Prettier will parse it and convert its properties to the corresponding prettier configuration. + * This configuration will be overridden by `.prettierrc`, etc. Currently, + * the following EditorConfig properties are supported: + * - indent_style + * - indent_size/tab_width + * - max_line_length + */ + editorconfig?: boolean; } /** @@ -161,6 +177,33 @@ export namespace resolveConfig { */ export function clearConfigCache(): void; +export interface SupportLanguage { + name: string; + since: string; + parsers: string[]; + group?: string; + tmScope: string; + aceMode: string; + codemirrorMode: string; + codemirrorMimeType: string; + aliases?: string[]; + extensions: string[]; + filenames?: string[]; + linguistLanguageId: number; + vscodeLanguageIds: string[]; +} + +export interface SupportInfo { + languages: SupportLanguage[]; +} + +/** + * Returns an object representing the parsers, languages and file types Prettier supports. + * If `version` is provided (e.g. `"1.5.0"`), information for that version will be returned, + * otherwise information for the current version will be returned. + */ +export function getSupportInfo(version?: string): SupportInfo; + /** * `version` field in `package.json` */ diff --git a/types/prettier/prettier-tests.ts b/types/prettier/prettier-tests.ts index 9d78453bae..47edb63ce9 100644 --- a/types/prettier/prettier-tests.ts +++ b/types/prettier/prettier-tests.ts @@ -33,3 +33,6 @@ if (options !== null) { } prettier.clearConfigCache(); + +const currentSupportInfo = prettier.getSupportInfo(); +const specificSupportInfo = prettier.getSupportInfo("1.8.0"); diff --git a/types/prismjs/index.d.ts b/types/prismjs/index.d.ts index 06775720af..86f2c55d95 100644 --- a/types/prismjs/index.d.ts +++ b/types/prismjs/index.d.ts @@ -1,6 +1,8 @@ -// Type definitions for prism 1.6 +// Type definitions for prism 1.9 // Project: http://prismjs.com/ -// Definitions by: Erik Lieben , Andre Wiggins +// Definitions by: Erik Lieben +// Andre Wiggins +// Michał Miszczyszyn // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped export as namespace Prism; @@ -11,15 +13,27 @@ export const plugins: any; export const hooks: Hooks; /** - * This is the most high-level function in Prism’s API. It fetches all the elements that have a .language-xxxx class and - * then calls Prism.highlightElement() on each one of them. + * Used to highlight all elements on current website. Calls Prism.highlightAllUnder on `document`. * + * @see highlightAllUnder * @param async Whether to use Web Workers to improve performance and avoid blocking the UI when highlighting * very large chunks of code. False by default. * @param callback An optional callback to be invoked after the highlighting is done. Mostly useful when async * is true, since in that case, the highlighting is done asynchronously. */ -export function highlightAll(async: boolean, callback?: (element: Element) => void): void; +export function highlightAll(async?: boolean, callback?: (element: Element) => void): void; + +/** + * This is the most high-level function in Prism’s API. It fetches all the elements inside `container` that + * have a .language-xxxx class and then calls Prism.highlightElement() on each one of them. + * + * @param container The element which contains elements containing code. + * @param async Whether to use Web Workers to improve performance and avoid blocking the UI when highlighting + * very large chunks of code. False by default. + * @param callback An optional callback to be invoked after the highlighting is done. Mostly useful when async + * is true, since in that case, the highlighting is done asynchronously. + */ +export function highlightAllUnder(container: Element, async?: boolean, callback?: (element: Element) => void): void; /** * Highlights the code inside a single element. @@ -31,18 +45,18 @@ export function highlightAll(async: boolean, callback?: (element: Element) => vo * @param callback An optional callback to be invoked after the highlighting is done. * Mostly useful when async is true, since in that case, the highlighting is done asynchronously. */ -export function highlightElement(element: Element, async: boolean, callback?: (element: Element) => void): void; +export function highlightElement(element: Element, async?: boolean, callback?: (element: Element) => void): void; /** * Low-level function, only use if you know what you’re doing. It accepts a string of text as input and the language * definitions to use, and returns a string with the HTML produced. * * @param text A string with the code to be highlighted. - * @param grammer - An object containing the tokens to use. Usually a language definition like + * @param grammar - An object containing the tokens to use. Usually a language definition like * Prism.languages.markup * @returns The highlighted HTML */ -export function highlight(text: string, grammer: LanguageDefinition, language?: LanguageDefinition): string; +export function highlight(text: string, grammar: LanguageDefinition, language?: LanguageDefinition): string; /** * This is the heart of Prism, and the most low-level function you can use. It accepts a string of text as input and the @@ -50,8 +64,8 @@ export function highlight(text: string, grammer: LanguageDefinition, language?: * nested tokens, the function is called recursively on each of these tokens. This method could be useful in other * contexts as well, as a very crude parser. * - * @param text A string with the code to be highlighted. - * @param grammar An object containing the tokens to use. Usually a language definition like + * @param text A string with the code to be highlighted. + * @param grammar An object containing the tokens to use. Usually a language definition like * Prism.languages.markup * @returns An array of strings, tokens (class Prism.Token) and other arrays. */ diff --git a/types/prismjs/prismjs-tests.ts b/types/prismjs/prismjs-tests.ts index bf1bdc859a..fea94ac713 100644 --- a/types/prismjs/prismjs-tests.ts +++ b/types/prismjs/prismjs-tests.ts @@ -1,10 +1,16 @@ const element = document.createElement("code"); +const container = document.querySelector("div"); const callback = (element: Element) => console.log(element); Prism.highlightElement(element, false, callback); Prism.highlightElement(element, false); +Prism.highlightElement(element); Prism.highlightAll(true, callback); Prism.highlightAll(true); +Prism.highlightAll(); +if (container) { + Prism.highlightAllUnder(container); +} const hookCallback: Prism.HookCallback = env => null; Prism.hooks.add("before-highlightall", hookCallback); diff --git a/types/puppeteer/index.d.ts b/types/puppeteer/index.d.ts index 8138419b6a..b89d41bbba 100644 --- a/types/puppeteer/index.d.ts +++ b/types/puppeteer/index.d.ts @@ -58,7 +58,7 @@ export interface Mouse { * @param y The y position. * @param options The click options. */ - click(x: number, y: number, options: ClickOptions): Promise; + click(x: number, y: number, options?: ClickOptions): Promise; /** * Dispatches a `mousedown` event. * @param options The mouse press options. @@ -200,6 +200,8 @@ export interface SetCookie { name: string; /** The cookie value. */ value: string; + /** The request-URI to associate with the setting of the cookie. This value can affect the default domain and path values of the created cookie. */ + url?: string; /** The cookie domain. */ domain?: string; /** The cookie path. */ @@ -551,19 +553,19 @@ export type HttpMethod = | "OPTIONS"; export type ResourceType = - | "Document" - | "Stylesheet" - | "Image" - | "Media" - | "Font" - | "Script" - | "TextTrack" - | "XHR" - | "Fetch" - | "EventSource" - | "WebSocket" - | "Manifest" - | "Other"; + | "document" + | "stylesheet" + | "image" + | "media" + | "font" + | "script" + | "texttrack" + | "xhr" + | "fetch" + | "eventsource" + | "websocket" + | "manifest" + | "other"; export interface Overrides { url?: string; diff --git a/types/qlik-engineapi/index.d.ts b/types/qlik-engineapi/index.d.ts index 7347b17bf0..309a30f2b0 100644 --- a/types/qlik-engineapi/index.d.ts +++ b/types/qlik-engineapi/index.d.ts @@ -1,5 +1,5 @@ -// Type definitions for qlik-engineapi 12.34 -// Project: http://help.qlik.com/en-US/sense-developer/September2017/Subsystems/EngineAPI/Content/introducing-engine-API.htm +// Type definitions for qlik-engineapi 12.67 +// Project: http://help.qlik.com/en-US/sense-developer/November2017/Subsystems/EngineAPI/Content/introducing-engine-API.htm // Definitions by: Konrad Mattheis // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped @@ -2402,7 +2402,7 @@ declare namespace EngineAPI { * This class describes all the methods that apply at app level. * The handle member in the JSON request for all methods listed in this section is the handle of the app. */ - interface IApp { + interface IApp extends enigmaJS.IGeneratedAPI { global: IGlobal; /** @@ -2984,6 +2984,13 @@ declare namespace EngineAPI { */ getFieldDescription(qFieldName: string): Promise; + /** + * Fetches the Expression behind a Field that is declared with DECLARE FIELD DEFINITIO + * @param qReadableName: name of a Field that is declared with DECLARE FIELD DEFINITION + * @returns qname wich contains the expression + */ + getFieldOnTheFlyByName(qReadableName: string): Promise<{qName: string}>; + /** * Retrieves the description of a field. * @param qFieldName - Name of the field. >> This parameter is mandatory. @@ -7150,6 +7157,21 @@ declare namespace EngineAPI { */ getBaseBNFHash(qBnfType: BnfType): Promise<{ qBnfHash: string }>; + /** + * Gets the current Backus-Naur Form (BNF) grammar of the Qlik engine scripting language, + * as well as a string hash calculated from that grammar. The BNF rules define the syntax + * for the script statements and the script or chart functions. If the hash changes between + * subsequent calls to this method, this indicates that the BNF has changed. + * + * In the Qlik engine grammars, a token is a string of one or more characters that is significant as a group. + * For example, a token could be a function name, a number, a letter, a parenthesis, and so on. + * @param qBnfType The type of grammar to return: + * S: returns the script statements and the script functions. + * E: returns the chart functions. + * @returns qBnfDefs and qBnfHash + */ + getBaseBNFString(qBnfType: BnfType): Promise<{qBnfDefs: IBNFDef, qBnfHash: string}>; + /** * Get a Config Object * @returns A Promise qConfig @@ -9108,8 +9130,7 @@ declare namespace EngineAPI { /** * SelectionListObject width extend GenericObject */ - interface ISelectionListObject extends IGenericObject { - getLayout(): Promise; + interface ISelectionListObject extends IGenericObjectPrototype { } interface IApp { @@ -9171,8 +9192,7 @@ declare namespace EngineAPI { /** * BookmarkListObject width extend GenericObject */ - interface IBookmarkListObject extends IGenericObject { - getLayout(): Promise; + interface IBookmarkListObject extends IGenericObjectPrototype { } interface IApp { @@ -9234,8 +9254,7 @@ declare namespace EngineAPI { /** * IMeassureListObject */ - interface IMeassureListObject extends IGenericObject { - getLayout(): Promise; + interface IMeassureListObject extends IGenericObjectPrototype { } interface IApp { @@ -9302,8 +9321,7 @@ declare namespace EngineAPI { qData: any; } - interface IDimensionListObject extends IGenericObject { - getLayout(): Promise; + interface IDimensionListObject extends IGenericObjectPrototype { } interface IApp { @@ -9380,15 +9398,15 @@ declare namespace EngineAPI { /** * VariableListObject... */ - interface IVariableListObject { + interface IVariableList { qItems: INxVariableListItem[]; } /** * GenericVariableLayout width extend GenericObjectLayout */ - interface IGenericVariableLayout extends IGenericObjectLayout { - qVariableListObject: IVariableListObject; + interface IGenericVariableListLayout extends IGenericBaseLayout { + qVariableListObject: IVariableList; } /** @@ -9426,8 +9444,7 @@ declare namespace EngineAPI { /** * VariableListObject width extend GenericObject */ - interface IVariableListObject extends IGenericObject { - getLayout(): Promise; + interface IVariableListObject extends IGenericObjectPrototype { } interface IApp { @@ -9442,23 +9459,13 @@ declare namespace EngineAPI { /** * FieldListObject... */ - interface IFieldListObject { + interface IFieldList { /** * NxFieldDescription[] */ qItems: INxFieldDescription[]; } - /** - * GenericFieldLayout width extend GenericObjectLayout - */ - interface IGenericFieldLayout extends IGenericObjectLayout { - /** - * FieldListObject... - */ - qFieldListObject: IFieldListObject; - } - /** * GenericFieldListProperties width extend GenericProperties */ @@ -9673,6 +9680,22 @@ declare namespace EngineAPI { qShowImplicit?: boolean; } + /** + * GenericFieldLayout width extend GenericObjectLayout + */ + interface IGenericFieldLayout extends IGenericBaseLayout { + /** + * FieldListObject... + */ + qFieldListObject: IFieldList; + } + + /** + * FieldListObject width extend GenericObject + */ + interface IFieldListObject extends IGenericObjectPrototype { + } + interface IApp { createObject(qProp: IGenericFieldListProperties): Promise; createSessionObject(qProp: IGenericFieldListProperties): Promise; diff --git a/types/quill/index.d.ts b/types/quill/index.d.ts index 6325913519..a996babf30 100644 --- a/types/quill/index.d.ts +++ b/types/quill/index.d.ts @@ -2,8 +2,11 @@ // Project: https://github.com/quilljs/quill/ // Definitions by: Sumit // Guillaume +// James Garbutt // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +import { Blot } from 'parchment/dist/src/blot/abstract/blot'; + /** * A stricter type definition would be: * @@ -56,7 +59,9 @@ export interface QuillOptionsStatic { } export interface BoundsStatic { + bottom: number; left: number; + right: number; top: number; height: number; width: number; @@ -136,6 +141,7 @@ export class Quill implements EventEmitter { */ root: HTMLDivElement; clipboard: ClipboardStatic; + scroll: Blot; constructor(container: string | Element, options?: QuillOptionsStatic); deleteText(index: number, length: number, source?: Sources): DeltaStatic; disable(): void; diff --git a/types/quill/package.json b/types/quill/package.json new file mode 100644 index 0000000000..85d0ed05d1 --- /dev/null +++ b/types/quill/package.json @@ -0,0 +1,6 @@ +{ + "private": true, + "dependencies": { + "parchment": "^1.1.2" + } +} diff --git a/types/quill/quill-tests.ts b/types/quill/quill-tests.ts index 142c821ffa..f907092ed1 100644 --- a/types/quill/quill-tests.ts +++ b/types/quill/quill-tests.ts @@ -1,4 +1,5 @@ import { Quill, Delta, DeltaStatic, RangeStatic, StringMap } from 'quill'; +import { Blot } from 'parchment/src/blot/abstract/blot'; function test_quill() { const quillEditor = new Quill('#editor', { @@ -10,6 +11,11 @@ function test_quill() { }); } +function test_scroll() { + const quillEditor = new Quill('#editor'); + const blot: Blot = quillEditor.scroll; +} + function test_deleteText() { const quillEditor = new Quill('#editor'); quillEditor.deleteText(0, 10); diff --git a/types/ramda/index.d.ts b/types/ramda/index.d.ts index 9d1683fbbc..be97f3ee32 100644 --- a/types/ramda/index.d.ts +++ b/types/ramda/index.d.ts @@ -740,8 +740,8 @@ declare namespace R { * Given a function that generates a key, turns a list of objects into an object indexing the objects * by the given key. */ - indexBy(fn: (a: T) => string, list: T[]): U; - indexBy(fn: (a: T) => string): (list: T[]) => U; + indexBy(fn: (a: T) => string, list: T[]): { [key: string]: T }; + indexBy(fn: (a: T) => string): (list: T[]) => { [key: string]: T }; /** * Returns the position of the first occurrence of an item in an array @@ -1454,9 +1454,8 @@ declare namespace R { /** * Returns a function that when supplied an object returns the indicated property of that object, if it exists. - * Note: TS1.9 # replace any by dictionary */ - prop

      (p: P, obj: Record): T; + prop

      (p: P, obj: T): T[P]; prop

      (p: P): (obj: Record) => T; /** diff --git a/types/ramda/ramda-tests.ts b/types/ramda/ramda-tests.ts index 426bb63471..1315ced585 100644 --- a/types/ramda/ramda-tests.ts +++ b/types/ramda/ramda-tests.ts @@ -678,10 +678,19 @@ interface Obj { }; (() => { - const list = [{id: "xyz", title: "A"}, {id: "abc", title: "B"}]; - const a1 = R.indexBy(R.prop("id"), list); - const a2 = R.indexBy(R.prop("id"))(list); + interface Book { + id: string; + title: string; + } + const list: Book[] = [{id: "xyz", title: "A"}, {id: "abc", title: "B"}]; + const a1 = R.indexBy(R.prop("id"), list); + const a2 = R.indexBy(R.prop("id"))(list); const a3 = R.indexBy<{ id: string }>(R.prop("id"))(list); + + const titlesIndexedByTitles: { [k: string]: string } = R.pipe( + R.map((x: Book) => x.title), + R.indexBy(x => x), + )(list); }); () => { @@ -1535,6 +1544,16 @@ class Rectangle { () => { const x: number = R.prop("x", {x: 100}); // => 100 + const obj = { + str: 'string', + num: 5, + }; + + const strVal: string = R.prop('str', obj); // => 'string' + const numVal: number = R.prop('num', obj); // => 5 + + const strValCur: string = R.prop('str')(obj); // => 'string' + const numValCur: number = R.prop('num')(obj); // => 5 }; () => { diff --git a/types/random-seed/index.d.ts b/types/random-seed/index.d.ts index d90016b83d..6ac278b467 100644 --- a/types/random-seed/index.d.ts +++ b/types/random-seed/index.d.ts @@ -4,6 +4,7 @@ // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped export interface RandomSeed { + (range: number): number; range(range: number): number; random(): number; floatBetween(min: number, max: number): number; diff --git a/types/random-seed/random-seed-tests.ts b/types/random-seed/random-seed-tests.ts index 9975608d8b..4c6f07dc28 100644 --- a/types/random-seed/random-seed-tests.ts +++ b/types/random-seed/random-seed-tests.ts @@ -9,9 +9,18 @@ const seed = 'My Secret String Value'; const rand2 = create(seed); // API +rand1(50); rand1.addEntropy(); rand1.random(); rand1.range(100); rand1.intBetween(0, 10); rand1.floatBetween(0, 1); rand1.seed("new seed"); + +rand2(50); +rand2.addEntropy(); +rand2.random(); +rand2.range(100); +rand2.intBetween(0, 10); +rand2.floatBetween(0, 1); +rand2.seed("new seed"); diff --git a/types/rangy/index.d.ts b/types/rangy/index.d.ts index f140895cf6..e28a4d7b1c 100644 --- a/types/rangy/index.d.ts +++ b/types/rangy/index.d.ts @@ -60,7 +60,7 @@ interface RangyStatic { createRange(doc?:Document|Window|HTMLIFrameElement):RangyRange; createRangyRange(doc?:Document|Window|HTMLIFrameElement):RangyRange; getNativeSelection(win?:Window):Selection; - getSelection():RangySelection; + getSelection(doc?:Document|Window|HTMLIFrameElement):RangySelection; addInitListener(listener:(rangy:RangyStatic) => void):any; shim():any; createMissingNativeApi():any; diff --git a/types/raspi-board/index.d.ts b/types/raspi-board/index.d.ts new file mode 100644 index 0000000000..a244577c2b --- /dev/null +++ b/types/raspi-board/index.d.ts @@ -0,0 +1,27 @@ +// Type definitions for raspi-board 5.0 +// Project: https://github.com/nebrius/raspi-board +// Definitions by: Bryan Hughes +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.1 + +export const VERSION_1_MODEL_A = "rpi1_a"; +export const VERSION_1_MODEL_B_REV_1 = "rpi1_b1"; +export const VERSION_1_MODEL_B_REV_2 = "rpi1_b2"; +export const VERSION_1_MODEL_B_PLUS = "rpi1_bplus"; +export const VERSION_1_MODEL_A_PLUS = "rpi1_aplus"; +export const VERSION_1_MODEL_ZERO = "rpi1_zero"; +export const VERSION_1_MODEL_ZERO_W = "rpi1_zerow"; +export const VERSION_2_MODEL_B = "rpi2_b"; +export const VERSION_3_MODEL_B = "rpi3_b"; +export const VERSION_UNKNOWN = "unknown"; +export interface PinInfo { + pins: string[]; + peripherals: string[]; + gpio: number; +} +export function getBoardRevision(): string; +export function getPins(): { + [wiringpi: number]: PinInfo; +}; +export function getPinNumber(alias: string | number): number | null; +export function getGpioNumber(alias: string | number): number | null; diff --git a/types/raspi-board/raspi-board-tests.ts b/types/raspi-board/raspi-board-tests.ts new file mode 100644 index 0000000000..23195168cf --- /dev/null +++ b/types/raspi-board/raspi-board-tests.ts @@ -0,0 +1,6 @@ +import { getBoardRevision, getPins, getPinNumber, getGpioNumber } from 'raspi-board'; + +getBoardRevision(); +getPins(); +getPinNumber('GPIO18'); +getGpioNumber('GPIO18'); diff --git a/types/raspi-board/tsconfig.json b/types/raspi-board/tsconfig.json new file mode 100644 index 0000000000..a55a514726 --- /dev/null +++ b/types/raspi-board/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", + "raspi-board-tests.ts" + ] +} \ No newline at end of file diff --git a/types/raspi-board/tslint.json b/types/raspi-board/tslint.json new file mode 100644 index 0000000000..2750cc0197 --- /dev/null +++ b/types/raspi-board/tslint.json @@ -0,0 +1 @@ +{ "extends": "dtslint/dt.json" } \ No newline at end of file diff --git a/types/raspi-peripheral/index.d.ts b/types/raspi-peripheral/index.d.ts new file mode 100644 index 0000000000..d52ed3ec6c --- /dev/null +++ b/types/raspi-peripheral/index.d.ts @@ -0,0 +1,17 @@ +// Type definitions for raspi-peripheral 2.0 +// Project: https://github.com/nebrius/raspi-peripheral +// Definitions by: Bryan Hughes +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.1 + +/// +import { EventEmitter } from 'events'; +export class Peripheral extends EventEmitter { + private _alive; + readonly alive: boolean; + private _pins; + readonly pins: number[]; + constructor(pins: string | number | Array); + destroy(): void; + validateAlive(): void; +} diff --git a/types/raspi-peripheral/raspi-peripheral-tests.ts b/types/raspi-peripheral/raspi-peripheral-tests.ts new file mode 100644 index 0000000000..dc16f863a2 --- /dev/null +++ b/types/raspi-peripheral/raspi-peripheral-tests.ts @@ -0,0 +1,5 @@ +import { Peripheral } from 'raspi-peripheral'; + +const myPeripheral = new Peripheral('GPIO2'); +myPeripheral.alive; +myPeripheral.pins.filter((pin) => true); diff --git a/types/raspi-peripheral/tsconfig.json b/types/raspi-peripheral/tsconfig.json new file mode 100644 index 0000000000..4b24a67971 --- /dev/null +++ b/types/raspi-peripheral/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", + "raspi-peripheral-tests.ts" + ] +} \ No newline at end of file diff --git a/types/raspi-peripheral/tslint.json b/types/raspi-peripheral/tslint.json new file mode 100644 index 0000000000..2750cc0197 --- /dev/null +++ b/types/raspi-peripheral/tslint.json @@ -0,0 +1 @@ +{ "extends": "dtslint/dt.json" } \ No newline at end of file diff --git a/types/raspi/index.d.ts b/types/raspi/index.d.ts new file mode 100644 index 0000000000..9df97fe3cc --- /dev/null +++ b/types/raspi/index.d.ts @@ -0,0 +1,7 @@ +// Type definitions for raspi 5.0 +// Project: https://github.com/nebrius/raspi +// Definitions by: Bryan Hughes +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.1 + +export function init(cb: () => void): void; diff --git a/types/raspi/raspi-tests.ts b/types/raspi/raspi-tests.ts new file mode 100644 index 0000000000..705aeacc31 --- /dev/null +++ b/types/raspi/raspi-tests.ts @@ -0,0 +1,3 @@ +import { init } from 'raspi'; + +init(() => {}); diff --git a/types/commander/tsconfig.json b/types/raspi/tsconfig.json similarity index 86% rename from types/commander/tsconfig.json rename to types/raspi/tsconfig.json index dcb92cc920..6906d607cf 100644 --- a/types/commander/tsconfig.json +++ b/types/raspi/tsconfig.json @@ -6,7 +6,7 @@ ], "noImplicitAny": true, "noImplicitThis": true, - "strictNullChecks": false, + "strictNullChecks": true, "strictFunctionTypes": true, "baseUrl": "../", "typeRoots": [ @@ -18,6 +18,6 @@ }, "files": [ "index.d.ts", - "commander-tests.ts" + "raspi-tests.ts" ] } \ No newline at end of file diff --git a/types/raspi/tslint.json b/types/raspi/tslint.json new file mode 100644 index 0000000000..2750cc0197 --- /dev/null +++ b/types/raspi/tslint.json @@ -0,0 +1 @@ +{ "extends": "dtslint/dt.json" } \ No newline at end of file diff --git a/types/rbac-a/index.d.ts b/types/rbac-a/index.d.ts new file mode 100644 index 0000000000..822a3f7cee --- /dev/null +++ b/types/rbac-a/index.d.ts @@ -0,0 +1,101 @@ +// Type definitions for rbac-a 0.2 +// Project: https://github.com/yanickrochon/rbac-a#readme +// Definitions by: Tomek Łaziuk +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.3 + +/// + +import { + EventEmitter, +} from "events"; + +export interface Roles { + [_: string]: number | Roles; +} + +export class Provider { + /** + * Return all the roles available for the given user. The return value + * must be an object, recursively defining the associated roles for the + * specified user. Return an empty object if user has no roles. + * Ex: { + * "role1": { + * "role1.1": null, + * "role1.2": { ... }, + * ... + * }, + * "secondary": ..., + * ... + * } + * The method mey return a promise resolving with the + * expected return value. + */ + getRoles(user: any): Roles | Promise; + /** + * Return all permissions for the specified role. The return value + * must be an array. Return an empty array if role is missing or + * no permission for the specified role. + * Ex: ['permission1', 'permission2', ... ] + * The method mey return a promise resolving with the + * expected return value. + */ + getPermission(role: string): string[] | Promise; + /** + * Return all attributes for the specified role. The return value must + * be an array. Return an empty array if role is missing or if no + * attributes for the specified role. + * Ex: ['attribute1', 'attribute2', ... ] + * The method mey return a promise resolving with the + * expected return value. + */ + getAttributes(role: string): string[] | Promise; +} + +export type AttributeFunction = (user: any, role: string, params: object) => any; + +/** + * Attributes Manager + * This class encapsulate attributes definition and validation. + * Usage + * var roleValid = attributesManager.validate(attribute, user, role, params); + */ +export class AttributesManager { + protected _attributes: { [_: string]: AttributeFunction }; + /** Define an attribute. The returned value is self for chaining. */ + set(attribute: AttributeFunction): this; + /** + * Undefine an attribute, by name or function and return removed + * attribute function if one was found. + */ + remove(attribute: string | AttributeFunction): AttributeFunction; + /** + * Validate the attribute with the specified user, role and parameters. + * The method will return a truthy value if the attribute valid, or a + * falsy otherwise. + * The method may also return a promise resolivng to the expected returne + * value, or reject. A rejected promise should be considered falsy. + * If the specified attribute does not exist, false is returned. + */ + validate(attribute: string, user: any, role: string, params: object): any; +} + +export class RBAC

      extends EventEmitter { + readonly provider: P; + readonly attributes: AM; + constructor(opts: { provider: P, attributes?: AM }); + /** + * Check the user for the given permissions. The method will return + * a Promise resolving with a number. If the user has sufficient + * access to the specified permissions, the promise should resolve + * with a positive, non-zero value, or with NaN otherwise. If the + * Promise is rejected, it should be considered as if the user has + * insufficient access to the specified ressources. + */ + check(user: any, permission: string | string[], params?: object): Promise; +} + +export const Providers: { + /** Basic JSON permissions provider */ + JsonProvider: { new(roles: object): Provider }; +}; diff --git a/types/rbac-a/lib/attributes-manager.d.ts b/types/rbac-a/lib/attributes-manager.d.ts new file mode 100644 index 0000000000..619370c6a1 --- /dev/null +++ b/types/rbac-a/lib/attributes-manager.d.ts @@ -0,0 +1,2 @@ +import { AttributesManager } from ".."; +export = AttributesManager; diff --git a/types/rbac-a/lib/provider.d.ts b/types/rbac-a/lib/provider.d.ts new file mode 100644 index 0000000000..9c94f32f1d --- /dev/null +++ b/types/rbac-a/lib/provider.d.ts @@ -0,0 +1,2 @@ +import { Provider } from ".."; +export = Provider; diff --git a/types/rbac-a/lib/rbac.d.ts b/types/rbac-a/lib/rbac.d.ts new file mode 100644 index 0000000000..fae3c7321b --- /dev/null +++ b/types/rbac-a/lib/rbac.d.ts @@ -0,0 +1,2 @@ +import { RBAC } from ".."; +export = RBAC; diff --git a/types/rbac-a/rbac-a-tests.ts b/types/rbac-a/rbac-a-tests.ts new file mode 100644 index 0000000000..da783a2617 --- /dev/null +++ b/types/rbac-a/rbac-a-tests.ts @@ -0,0 +1,40 @@ +import { + Provider, + RBAC, +} from "rbac-a"; + +class CustomProvider extends Provider { } + +const rbac = new RBAC({ + provider: new CustomProvider() +}); + +const user = "ExampleUser"; + +rbac.on('error', (err) => { + console.error('Error while checking $s/%s', err.role, err.user); + console.error(err.stack); +}); + +rbac.check(user, 'create').then((allowed) => { + if (allowed) { + console.log('User can create!'); + } else { + console.log('User cannot create.'); + console.info('Please contact your system admin for more information'); + } +}).catch((err) => { + console.error(err && err.stack || err || 'ERROR'); +}); + +// specify attributes arguments +rbac.check(user, 'edit', { time: Date.now() }).then((allowed) => { + if (allowed) { + console.log('User can edit!'); + } else { + console.log('User cannot edit.'); + console.info('Please contact your system admin for more information'); + } +}).catch((err) => { + console.error(err && err.stack || err || 'ERROR'); +}); diff --git a/types/rbac-a/tsconfig.json b/types/rbac-a/tsconfig.json new file mode 100644 index 0000000000..be60bf248e --- /dev/null +++ b/types/rbac-a/tsconfig.json @@ -0,0 +1,26 @@ +{ + "compilerOptions": { + "module": "commonjs", + "lib": [ + "es6" + ], + "noImplicitAny": true, + "noImplicitThis": true, + "strictFunctionTypes": true, + "strictNullChecks": true, + "baseUrl": "../", + "typeRoots": [ + "../" + ], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true + }, + "files": [ + "index.d.ts", + "lib/attributes-manager.d.ts", + "lib/provider.d.ts", + "lib/rbac.d.ts", + "rbac-a-tests.ts" + ] +} diff --git a/types/rbac-a/tslint.json b/types/rbac-a/tslint.json new file mode 100644 index 0000000000..3db14f85ea --- /dev/null +++ b/types/rbac-a/tslint.json @@ -0,0 +1 @@ +{ "extends": "dtslint/dt.json" } diff --git a/types/rc-slider/index.d.ts b/types/rc-slider/index.d.ts index a0209132df..f64ae8c03c 100644 --- a/types/rc-slider/index.d.ts +++ b/types/rc-slider/index.d.ts @@ -41,7 +41,7 @@ export interface CommonApiProps { * Value to be added or subtracted on each step the slider makes. Must be greater than zero, and max - min should be evenly divisible by the step value. * @default 1 */ - step?: number; + step?: number | null; /** * If vertical is true, the slider will be vertical. * @default false diff --git a/types/react-alice-carousel/index.d.ts b/types/react-alice-carousel/index.d.ts new file mode 100644 index 0000000000..47d4fd95de --- /dev/null +++ b/types/react-alice-carousel/index.d.ts @@ -0,0 +1,121 @@ +// Type definitions for react-alice-carousel 1.7 +// Project: https://github.com/maxmarinich/react-alice-carousel +// Definitions by: endigo +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.3 + +import * as React from "react"; + +export interface EventObject { + item: number; + slide: number; +} + +export interface Props { + /** + * Fired when the event object is changing / returns event object + */ + onSlideChange?: (e: EventObject) => void; + /** + * Fired when the event object was changed / returns event object + */ + onSlideChanged?: (e: EventObject) => void; + /** + * Disable keys controls (left, right, space) + * + * Default: false. + */ + keysControlDisabled?: boolean; + /** + * Disable play/pause button + * + * Default: false. + */ + playButtonEnabled?: boolean; + /** + * Disable buttons control + * + * Default: false. + */ + buttonsDisabled?: boolean; + /** + * Disable dots navigation + * + * Default: false. + */ + dotsDisabled?: boolean; + /** + * Disable swipe handlers + * + * Default: false. + */ + swipeDisabled?: boolean; + /** + * Number of items in the slide. + * + * Default: {}. + */ + responsive?: {}; + /** + * Duration of slides transition (milliseconds) + * + * Default: 250. + */ + duration?: number; + /** + * The starting index of the carousel + * + * Default: 0. + */ + startIndex?: number; + /** + * Sets the carousel at the specified position + * + * Default: 0. + */ + slideToIndex?: number; + /** + * Set auto play mode + * + * Default: false. + */ + autoPlay?: boolean; + /** + * Disable infinite mode + * + * Default: true. + */ + infinite?: boolean; + /** + * The offset of the alert from the page border, can be any number. + * + * Default: 14. + */ + mouseDragEnabled?: boolean; + /** + * Enable fadeout animation. Fired when 1 item is in the slide + * + * Default: false. + */ + fadeOutAnimation?: boolean; + /** + * Interval of auto play animation (milliseconds). If specified, a larger value will be taken from comparing this property and the duration one + * + * Default: 250. + */ + autoPlayInterval?: number; + /** + * To run auto play in the left direction specify rtl value + * + * Default: 'ltr'. + */ + autoPlayDirection?: string; + /** + * If this property is identified as true auto play animation will be stopped after clicking user on any gallery button + * + * Default: false. + */ + autoPlayActionDisabled?: boolean; +} + +export default class Carousel extends React.PureComponent {} diff --git a/types/react-alice-carousel/react-alice-carousel-tests.tsx b/types/react-alice-carousel/react-alice-carousel-tests.tsx new file mode 100644 index 0000000000..9a123a5748 --- /dev/null +++ b/types/react-alice-carousel/react-alice-carousel-tests.tsx @@ -0,0 +1,61 @@ +import * as React from 'react'; +import AliceCarousel, { Props, EventObject } from 'react-alice-carousel'; + +class SimpleAliceCarousel extends React.Component { + render() { + return ( +

      + +
      + ); + } +} + +class Gallery extends React.Component { + onSlideChange(e: EventObject) { + // console.log('Item`s position during a change: ', e.item); + // console.log('Slide`s position during a change: ', e.slide); + } + + onSlideChanged(e: EventObject) { + // console.log('Item`s position after changes: ', e.item); + // console.log('Slide`s position after changes: ', e.slide); + } + + render() { + const responsive = { + 0: { + items: 1 + }, + 600: { + items: 2 + }, + 1024: { + items: 3 + } + }; + + return ( + +

      1

      +

      2

      +

      3

      +

      4

      +

      5

      +
      + ); + } +} diff --git a/types/react-alice-carousel/tsconfig.json b/types/react-alice-carousel/tsconfig.json new file mode 100644 index 0000000000..4245303823 --- /dev/null +++ b/types/react-alice-carousel/tsconfig.json @@ -0,0 +1,24 @@ +{ + "compilerOptions": { + "module": "commonjs", + "lib": [ + "es6" + ], + "noImplicitAny": true, + "noImplicitThis": true, + "strictNullChecks": true, + "strictFunctionTypes": true, + "baseUrl": "../", + "typeRoots": [ + "../" + ], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true, + "jsx": "react" + }, + "files": [ + "index.d.ts", + "react-alice-carousel-tests.tsx" + ] +} diff --git a/types/react-alice-carousel/tslint.json b/types/react-alice-carousel/tslint.json new file mode 100644 index 0000000000..3db14f85ea --- /dev/null +++ b/types/react-alice-carousel/tslint.json @@ -0,0 +1 @@ +{ "extends": "dtslint/dt.json" } diff --git a/types/react-autosuggest/README.md b/types/react-autosuggest/README.md new file mode 100644 index 0000000000..44ff83ecc5 --- /dev/null +++ b/types/react-autosuggest/README.md @@ -0,0 +1,28 @@ +# react-autosuggest usage notes + +The definition uses generics for stronger typing. Read the [TypeScript deep dive on JSX Generic components](https://basarat.gitbooks.io/typescript/docs/jsx/tsx.html#react-jsx-tip-generic-components) for details on consuming these type definitions. + +## Example + +```jsx +import * as Autosuggest from 'react-autosuggest' +interface Language { + name: string + year: number +} + +const LanguageAutosuggest = Autosuggest as { new (): Autosuggest } + + +``` + +Find multiple full examples in `react-autosuggest-tests.tsx` diff --git a/types/react-autosuggest/index.d.ts b/types/react-autosuggest/index.d.ts index b1f080efe5..444753bd54 100644 --- a/types/react-autosuggest/index.d.ts +++ b/types/react-autosuggest/index.d.ts @@ -5,84 +5,200 @@ // Robert Essig // Terry Bayne // Christopher Deutsch +// Kevin Ross // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped // TypeScript Version: 2.3 import * as React from 'react'; -declare class Autosuggest extends React.Component {} +declare class Autosuggest extends React.Component> {} export = Autosuggest; declare namespace Autosuggest { - interface SuggestionsFetchRequest { - value: string; - reason: 'input-changed' | 'input-focused' | 'escape-pressed' | 'suggestions-revealed' | 'suggestion-selected'; - } + /** + * Utilies types based on: + * https://github.com/Microsoft/TypeScript/issues/12215#issuecomment-307871458 + */ - interface InputValues { - value: string; - valueBeforeUpDown?: string; - } + /** @internal */ + type Diff = ({ [P in T]: P } & + { [P in U]: never } & { [x: string]: never })[T]; - interface RenderSuggestionParams { - query: string; - isHighlighted: boolean; - } + /** @internal */ + type Omit = Pick>; - interface SuggestionHighlightedParams { - suggestion: any; - } + interface SuggestionsFetchRequestedParams { + value: string; + reason: + | 'input-changed' + | 'input-focused' + | 'escape-pressed' + | 'suggestions-revealed' + | 'suggestion-selected'; + } - interface ChangeEvent { - newValue: string; - method: 'down' | 'up' | 'escape' | 'enter' | 'click' | 'type'; - } + interface RenderSuggestionParams { + query: string; + isHighlighted: boolean; + } - interface BlurEvent { - highlightedSuggestion: any; - } + interface SuggestionHighlightedParams { + suggestion: any; + } - interface InputProps extends React.InputHTMLAttributes { - value: string; - onChange(event: React.FormEvent, params?: ChangeEvent): void; - onBlur?(event: React.FormEvent, params?: BlurEvent): void; - [key: string]: any; - } + interface ChangeEvent { + newValue: string; + method: 'down' | 'up' | 'escape' | 'enter' | 'click' | 'type'; + } - interface SuggestionSelectedEventData { - suggestion: TSuggestion; - suggestionValue: string; - suggestionIndex: number; - sectionIndex: number | null; - method: 'click' | 'enter'; - } + interface BlurEvent { + highlightedSuggestion: TSuggestion; + } - type ThemeKey = 'container' | 'containerOpen' | 'input' | 'inputOpen' | 'inputFocused' | 'suggestionsContainer' | - 'suggestionsContainerOpen' | 'suggestionsList' | 'suggestion' | 'suggestionFirst' | 'suggestionHighlighted' | - 'sectionContainer' | 'sectionContainerFirst' | 'sectionTitle'; + interface InputProps + extends Omit, 'onChange' | 'onBlur'> { + onChange(event: React.FormEvent, params?: ChangeEvent): void; + onBlur?(event: React.FormEvent, params?: BlurEvent): void; + value: string; + [key: string]: any; + } - type Theme = Record | Partial>; + interface SuggestionSelectedEventData { + suggestion: TSuggestion; + suggestionValue: string; + suggestionIndex: number; + sectionIndex: number | null; + method: 'click' | 'enter'; + } - interface AutosuggestProps extends React.Props { - suggestions: any[]; - onSuggestionsFetchRequested(request: SuggestionsFetchRequest): void; - onSuggestionsClearRequested?(): void; - getSuggestionValue(suggestion: any): any; - renderSuggestion(suggestion: any, params: RenderSuggestionParams): JSX.Element; - inputProps: InputProps; - onSuggestionSelected?(event: React.FormEvent, data: SuggestionSelectedEventData): void; - onSuggestionHighlighted?(params: SuggestionHighlightedParams): void; - shouldRenderSuggestions?(value: string): boolean; - alwaysRenderSuggestions?: boolean; - highlightFirstSuggestion?: boolean; - focusInputOnSuggestionClick?: boolean; - multiSection?: boolean; - renderSectionTitle?(section: any): JSX.Element; - getSectionSuggestions?(section: any): any[]; - renderInputComponent?(inputProps: InputProps): JSX.Element; - renderSuggestionsContainer?(containerProps: any, children: any, query: string): JSX.Element; - theme?: Theme; - id?: string; - } + type ThemeKey = + | 'container' + | 'containerOpen' + | 'input' + | 'inputOpen' + | 'inputFocused' + | 'suggestionsContainer' + | 'suggestionsContainerOpen' + | 'suggestionsList' + | 'suggestion' + | 'suggestionFirst' + | 'suggestionHighlighted' + | 'sectionContainer' + | 'sectionContainerFirst' + | 'sectionTitle'; + + type Theme = + | Record + | Partial>; + + interface RenderSuggestionsContainerParams { + containerProps: { + id: string; + key: string; + ref: any; + style: any; + }; + children: React.ReactNode; + query: string; + } + + // types for functions - allowing reuse externally - e.g. as props and bound in the constructor + type GetSectionSuggestions = (section: any) => TSuggestion[]; + type GetSuggestionValue = (suggestion: TSuggestion) => string; + type OnSuggestionHighlighted = (params: SuggestionHighlightedParams) => void; + type SuggestionsFetchRequested = (request: SuggestionsFetchRequestedParams) => void; + type OnSuggestionsClearRequested = () => void; + type OnSuggestionSelected = ( + event: React.FormEvent, + data: SuggestionSelectedEventData, + ) => void; + type RenderInputComponent = (inputProps: InputProps) => React.ReactNode; + type RenderSuggestionsContainer = (params: RenderSuggestionsContainerParams) => React.ReactNode; + type RenderSectionTitle = (section: any) => React.ReactNode; + type RenderSuggestion = ( + suggestion: TSuggestion, + params: RenderSuggestionParams, + ) => React.ReactNode; + type ShouldRenderSuggestions = (value: string) => boolean; + + interface AutosuggestProps { + /** + * Set it to true if you'd like to render suggestions even when the input is not focused. + */ + alwaysRenderSuggestions?: boolean; + /** + * Set it to false if you don't want Autosuggest to keep the input focused when suggestions are clicked/tapped. + */ + focusInputOnSuggestionClick?: boolean; + /** + * Implement it to teach Autosuggest where to find the suggestions for every section. + */ + getSectionSuggestions?: GetSectionSuggestions; + /** + * Implement it to teach Autosuggest what should be the input value when suggestion is clicked. + */ + getSuggestionValue: GetSuggestionValue; + /** + * Set it to true if you'd like Autosuggest to automatically highlight the first suggestion. + */ + highlightFirstSuggestion?: boolean; + /** + * Use it only if you have multiple Autosuggest components on a page. + */ + id?: string; + /** + * Pass through arbitrary props to the input. It must contain at least value and onChange. + */ + inputProps: InputProps; + /** + * Set it to true if you'd like to display suggestions in multiple sections (with optional titles). + */ + multiSection?: boolean; + /** + * Will be called every time the highlighted suggestion changes. + */ + onSuggestionHighlighted?: OnSuggestionHighlighted; + /** + * Will be called every time you need to recalculate suggestions. + */ + onSuggestionsFetchRequested: SuggestionsFetchRequested; + /** + * Will be called every time you need to set suggestions to []. + */ + onSuggestionsClearRequested?: OnSuggestionsClearRequested; + /** + * Will be called every time suggestion is selected via mouse or keyboard. + */ + onSuggestionSelected?: OnSuggestionSelected; + /** + * Use it only if you need to customize the rendering of the input. + */ + renderInputComponent?: RenderInputComponent; + /** + * Use it if you want to customize things inside the suggestions container beyond rendering the suggestions themselves. + */ + renderSuggestionsContainer?: RenderSuggestionsContainer; + /** + * Use your imagination to define how section titles are rendered. + */ + renderSectionTitle?: RenderSectionTitle; + /** + * Use your imagination to define how suggestions are rendered. + */ + renderSuggestion: RenderSuggestion; + /** + * When the input is focused, Autosuggest will consult this function when to render suggestions. + * Use it, for example, if you want to display suggestions when input value is at least 2 characters long. + */ + shouldRenderSuggestions?: ShouldRenderSuggestions; + /** + * These are the suggestions that will be displayed. Items can take an arbitrary shape. + */ + suggestions: TSuggestion[]; + /** + * Use your imagination to style the Autosuggest. + */ + theme?: Theme; + } } diff --git a/types/react-autosuggest/react-autosuggest-tests.tsx b/types/react-autosuggest/react-autosuggest-tests.tsx index 23841519e4..3747e8457b 100644 --- a/types/react-autosuggest/react-autosuggest-tests.tsx +++ b/types/react-autosuggest/react-autosuggest-tests.tsx @@ -90,6 +90,132 @@ export class ReactAutosuggestBasicTest extends React.Component { }; return ; + } + + protected onSuggestionsSelected(event: React.FormEvent, data: Autosuggest.SuggestionSelectedEventData): void { + alert(`Selected language is ${data.suggestion.name} (${data.suggestion.year}).`); + } + + protected renderSuggestion(suggestion: Language, params: Autosuggest.RenderSuggestionParams): JSX.Element { + const className = params.isHighlighted ? "highlighted" : undefined; + return {suggestion.name}; + } + // endregion region Event handlers + protected onChange(event: React.FormEvent, {newValue, method}: any): void { + this.setState({value: newValue}); + } + + protected onSuggestionsFetchRequested({value}: any): void { + this.setState({ + suggestions: this.getSuggestions(value) + }); + } + // endregion region Helper methods + protected getSuggestions(value: string): Language[] { + const escapedValue = escapeRegexCharacters(value.trim()); + + if (escapedValue === '') { + return []; + } + + const regex = new RegExp('^' + escapedValue, 'i'); + + return ReactAutosuggestBasicTest + .languages + .filter(language => regex.test(language.name)); + } + + protected getSuggestionValue(suggestion: Language): string { return suggestion.name; } + // endregion +} + +const LanguageAutosuggest = Autosuggest as { new (): Autosuggest }; + +export class ReactAutosuggestTypedTest extends React.Component { + // region Fields + static languages: Language[] = [ + { + name: 'C', + year: 1972 + }, { + name: 'C#', + year: 2000 + }, { + name: 'C++', + year: 1983 + }, { + name: 'Clojure', + year: 2007 + }, { + name: 'Elm', + year: 2012 + }, { + name: 'Go', + year: 2009 + }, { + name: 'Haskell', + year: 1990 + }, { + name: 'Java', + year: 1995 + }, { + name: 'Javascript', + year: 1995 + }, { + name: 'Perl', + year: 1987 + }, { + name: 'PHP', + year: 1995 + }, { + name: 'Python', + year: 1991 + }, { + name: 'Ruby', + year: 1995 + }, { + name: 'Scala', + year: 2003 + } + ]; + // endregion region Constructor + constructor(props: any) { + super(props); + + this.state = { + value: '', + suggestions: this.getSuggestions('') + }; + } + // endregion region Rendering methods + render(): JSX.Element { + const {value, suggestions} = this.state; + const inputProps = { + placeholder: `Type 'c'`, + value, + onChange: this + .onChange + .bind(this) + }; + + const theme = { + input: 'themed-input-class', + container: 'themed-container-class', + suggestionFocused: 'active', + sectionTitle: { color: 'blue' } + }; + + return { .bind(this) }; - return { return {section.title}; } - protected renderInputComponent(inputProps: Autosuggest.InputProps): JSX.Element { + protected renderInputComponent(inputProps: Autosuggest.InputProps): JSX.Element { return (
      @@ -280,7 +406,7 @@ export class ReactAutosuggestMultipleTest extends React.Component { ); } - protected renderSuggestionsContainer(containerProps: any, children: any, query: string): JSX.Element { + protected renderSuggestionsContainer({containerProps, children, query}: Autosuggest.RenderSuggestionsContainerParams): JSX.Element { return (
      {children} @@ -345,6 +471,8 @@ interface Person { twitter: string; } +const PersonAutosuggest = Autosuggest as { new (): Autosuggest }; + export class ReactAutosuggestCustomTest extends React.Component { // region Fields static people: Person[] = [ @@ -386,7 +514,7 @@ export class ReactAutosuggestCustomTest extends React.Component { .bind(this) }; - return; } diff --git a/types/react-beautiful-dnd/react-beautiful-dnd-tests.tsx b/types/react-beautiful-dnd/react-beautiful-dnd-tests.tsx index 3efc2529ce..8f961e0c7a 100644 --- a/types/react-beautiful-dnd/react-beautiful-dnd-tests.tsx +++ b/types/react-beautiful-dnd/react-beautiful-dnd-tests.tsx @@ -73,7 +73,7 @@ class App extends React.Component<{}, AppState> { style={getListStyle(snapshot.isDraggingOver)} > {this.state.items.map(item => ( - + {(provided, snapshot) => (
      , // Aleksander Lode , @@ -217,7 +217,7 @@ export interface BootstrapTableProps extends Props { * return rowIndex % 2 == 0 ? "tr-odd" : "tr-even"; // return a class name. * } */ - trClassName?: string | ((rowData: ReadonlyArray, rowIndex: number) => string); + trClassName?: string | ((rowData: any, rowIndex: number) => string); /** * Enable row insertion by setting insertRow to true, default is false. * If you enable row insertion, there's a button on the upper left side of table. @@ -400,6 +400,10 @@ export interface BootstrapTableProps extends Props { * Table footer custom class */ tableFooterClass?: string; + /** + * Render react-s-alert notifications + */ + renderAlert?: boolean; } /** @@ -544,17 +548,33 @@ export interface CellEdit { * `cellName`: the column dataField cell name that has been modified. * `cellValue`: the new cell value. * `done`: a callback function to use if this is an async operation, to indicate if the save data is valid. + * `props`: an object containing the current cell's rowIndex and colIndex values. * If your validation is async, for example: you want to pop a confirm dialog for user to confim in this case, * react-bootstrap-table pass a callback function to you. You are supposed to call this callback function with a * bool value to perfom if it is valid or not in addition, you should return 1 from the main function to tell * react-bootstrap-table that this is a async operation. */ - beforeSaveCell?(row: TRow, cellName: K, cellValue: TRow[K], done: (isValid: boolean) => void): boolean | 1; + beforeSaveCell?( + row: TRow, + cellName: K, + cellValue: TRow[K], + done: (isValid: boolean) => void, + props: { rowIndex: number; colIndex: number } + ): boolean | 1; /** * Accept a custom callback function, after cell saving, this function will be called. * This callback function takes three arguments: row, cellName and cellValue + * `row`: the row data that was saved. + * `cellName`: the column dataField cell name that has been modified. + * `cellValue`: the new cell value. + * `props`: an object containing the current cell's rowIndex and colIndex values. */ - afterSaveCell?(row: TRow, cellName: K, cellValue: TRow[K]): void; + afterSaveCell?( + row: TRow, + cellName: K, + cellValue: TRow[K], + props: { rowIndex: number; colIndex: number } + ): void; } /** @@ -564,11 +584,13 @@ export interface Options { /** * Provide the name of the column that should be sorted by. * If multi-column sort is active, this is an array of columns. + * If there should be no active sort, both sortName and sortOrder should be undefined. */ sortName?: keyof TRow | Array; /** * Specify whether the sort should be ascending or descending. * If multi-column sort is active, this is an array of sortOrder items. + * If there should be no active sort, both sortName and sortOrder should be undefined. */ sortOrder?: SortOrder | SortOrder[]; /** @@ -691,17 +713,20 @@ export interface Options { onDeleteRow?(rowKeys: ReadonlyArray, rows: ReadonlyArray): void; /** * Assign a callback function which will be called after a row click. - * This function takes three arguments: + * This function takes four arguments: * `row`: which is the row data that was clicked on. * `columnIndex`: index of the column that was clicked on. * `rowIndex`: index of the row that was clicked on. + * `event`: the click event. */ - onRowClick?(row: TRow, columnIndex: number, rowIndex: number): void; + onRowClick?(row: TRow, columnIndex: number, rowIndex: number, event: React.MouseEvent): void; /** * Assign a callback function which will be called after a row double click. - * This function takes one argument: row which is the row data that was double clicked on. + * This function takes two arguments: + * `row`: which is the row data that was double clicked on. + * `event`: the double click event. */ - onRowDoubleClick?(row: TRow): void; + onRowDoubleClick?(row: TRow, event: React.MouseEvent): void; /** * Assign a callback function which will be called when mouse enters the table. */ @@ -1029,12 +1054,12 @@ export interface Options { */ exportCSVSeparator?: string; /** - * Set a function to be called when expanding or collapsing a row. This function takes two arguments: rowKey - * and isExpand. + * Set a function to be called when expanding or collapsing a row. This function takes three arguments: * `rowKey`: dataField key for the row that is expanding or collapsing. * `isExpand`: True if the row is expanding, false if it is collapsing. + * `event`: The click event. */ - onExpand?(rowKey: number | string, isExpand: boolean): void; + onExpand?(rowKey: number | string, isExpand: boolean, event: React.MouseEvent): void; /** * Specify that only one row should be able to be expanded at the same time. */ @@ -1713,7 +1738,7 @@ export type Filter = TextFilter | SelectFilter | RegexFilter | NumberFilter | Da * The "value" type for a number filter */ export interface NumberFilterValue { - number: number; + number: number | string; comparator: FilterComparator; } @@ -1834,6 +1859,10 @@ export interface KeyboardNavigation { * When set to true, pressing ENTER will expand or collapse the current row. */ enterToExpand?: boolean; + /** + * When set to true, pressing ENTER will select or unselect the current row. + */ + enterToSelect?: boolean; } /** diff --git a/types/react-broadcast/index.d.ts b/types/react-broadcast/index.d.ts new file mode 100644 index 0000000000..8a9a3bf47b --- /dev/null +++ b/types/react-broadcast/index.d.ts @@ -0,0 +1,31 @@ +// Type definitions for react-broadcast 0.6 +// Project: https://github.com/ReactTraining/react-broadcast +// Definitions by: Jaga Santagostino +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.6 + +import * as React from 'react'; + +export namespace Subscriber { + interface DefaultProps { + quiet: boolean; + } + interface Props extends Partial { + channel: string; + children?: ((state: T) => React.ReactNode); + } +} + +export namespace Broadcast { + interface DefaultProps { + compareValues: (prevValue: T, nextValue: T) => boolean; + } + interface Props extends Partial> { + channel: string; + children: React.ReactNode; + value: T; + } +} + +export class Broadcast extends React.Component, any> { } +export class Subscriber extends React.Component, any> { } diff --git a/types/react-broadcast/react-broadcast-tests.tsx b/types/react-broadcast/react-broadcast-tests.tsx new file mode 100644 index 0000000000..6f3466e729 --- /dev/null +++ b/types/react-broadcast/react-broadcast-tests.tsx @@ -0,0 +1,17 @@ +import * as React from 'react'; +import { Broadcast, Subscriber } from 'react-broadcast'; + +class ExampleOfUsingReactBroadcast extends React.Component { + render() { + const value = 42; + return ( + +
      + + {state =>
      {state}
      } +
      +
      +
      + ); + } +} diff --git a/types/react-broadcast/tsconfig.json b/types/react-broadcast/tsconfig.json new file mode 100644 index 0000000000..270151cc33 --- /dev/null +++ b/types/react-broadcast/tsconfig.json @@ -0,0 +1,17 @@ +{ + "compilerOptions": { + "baseUrl": "../", + "typeRoots": ["../"], + "types": [], + "module": "commonjs", + "lib": ["es6", "dom"], + "jsx": "react", + "strictNullChecks": true, + "strictFunctionTypes": false, + "noImplicitAny": true, + "noImplicitThis": true, + "forceConsistentCasingInFileNames": true, + "noEmit": true + }, + "files": ["index.d.ts", "react-broadcast-tests.tsx"] +} diff --git a/types/react-broadcast/tslint.json b/types/react-broadcast/tslint.json new file mode 100644 index 0000000000..d88586e5bd --- /dev/null +++ b/types/react-broadcast/tslint.json @@ -0,0 +1,3 @@ +{ + "extends": "dtslint/dt.json" +} diff --git a/types/react-flatpickr/index.d.ts b/types/react-flatpickr/index.d.ts index e960524854..ebac89f48d 100644 --- a/types/react-flatpickr/index.d.ts +++ b/types/react-flatpickr/index.d.ts @@ -5,12 +5,12 @@ // TypeScript Version: 2.3 import { Component } from 'react'; -import { Hook, Options } from 'flatpickr'; +import { Options } from 'flatpickr'; export interface DateTimePickerProps { defaultValue?: string; - options?: Options; - onChange?: Hook; + options?: Options.Options; + onChange?: Options.Hook; value?: string; } diff --git a/types/react-form/index.d.ts b/types/react-form/index.d.ts index 4694efa926..965f55e7e7 100644 --- a/types/react-form/index.d.ts +++ b/types/react-form/index.d.ts @@ -1,4 +1,4 @@ -// Type definitions for react-form 1.3 +// Type definitions for react-form 2.12 // Project: https://github.com/tannerlinsley/react-form#readme // Definitions by: Cameron McAteer // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped @@ -6,6 +6,7 @@ import * as React from 'react'; +// Helper Types export type FormValue = any; export type FormError = string | undefined; export interface Nested { @@ -13,24 +14,12 @@ export interface Nested { } export type FormValues = Nested; export type Touched = Nested; -export type FormErrors = {[key: string]: FormError} | [{[key: string]: FormError}]; +export interface FormErrors { + [key: string]: FormError; +} export type NestedErrors = Nested; export type RenderReturn = JSX.Element | false | null; -export interface FormProps { - loadState?(props: FormProps, self: Form): FormState | undefined; - defaultValues?: FormValues; - preValidate?(values: FormValues, state: FormState, props: FormProps, self: Form): FormValues; - validate?(values: FormValues, state: FormState, props: FormProps): FormErrors; - onValidationFail?(values: FormValues, state: FormState, props: FormProps, self: Form): void; - onChange?(state: FormState, props: FormProps, initial: boolean | FormProps, self: Form): void; - saveState?(state: FormState, props: FormProps, self: Form): void; - willUnmount?(state: FormState, props: FormProps, self: Form): void; - preSubmit?(values: FormValues, state: FormState, props: FormProps, self: Form): FormValues; - onSubmit?(values: FormValues, state: FormState, props: FormProps, self: Form): void; - postSubmit?(values: FormValues, state: FormState, props: FormProps, self: Form): void; -} - export interface FormState { values: FormValues; touched: Touched; @@ -39,24 +28,56 @@ export interface FormState { dirty?: boolean; } -export const FormDefaultProps: FormProps; +export interface FormProps { + dontValidateOnMount?: boolean; + defaultValues?: FormValues; + onSubmit?(values: FormValues, submissionEvent: React.SyntheticEvent, formApi: FormApi): void; + preSubmit?(values: FormValues, formApi: FormApi): FormValues; + onSubmitFailure?(errors: FormErrors, formApi: FormApi): void; + formDidUpdate?(formState: FormState): void; + preValidate?(values: FormValues): FormValues; + validateError?: ValidateValuesFunction; + validateWarning?: ValidateValuesFunction; + validateSuccess?: (values: FormValues, errors: FormErrors) => FormErrors; + asyncValidators?: { + [field: string]: (value: FormValue) => Promise + }; + dontPreventDefault?: boolean; +} export interface FormApi { - setAllValues(values: FormValues, noTouch?: boolean): void; - setValue(field: string, value: any, noTouch?: boolean): void; - getValue(field: string, fallback?: any): any; - setNestedError(field: string, value?: boolean): void; - getError(field: string): FormError; - setTouched(field: string, value?: boolean): void; - getTouched(field: string): boolean; - addValue(field: string, value: any): void; - removeValue(field: string, index: number): void; - swapValues(field: string, index: number, destIndex: number): void; - setAllTouched(dirty?: boolean, state?: Partial): void; - resetForm(): void; - submitForm(e?: Pick, 'preventDefault'>): void; + // State + values: FormValues; + touched: Touched; + errors: FormErrors; + warnings: FormErrors; + successes: FormErrors; + submits: number; + submitted: boolean; + asyncValidations: number; + validating: {[field: string]: boolean}; + validationFailures: number; + validationFailed: {[field: string]: boolean}; + + // Methods + submitForm(event: React.SyntheticEvent): void; + setValue(fieldName: string, value: any): void; + setAllValues(values: FormValues): void; + setError(field: string, error: string): void; + setWarning(field: string, warning: string): void; + setSuccess(field: string, success: string): void; + setTouched(field: string, touched: boolean): void; + setAllTouched(touches: {[field: string]: boolean}): void; + addValue(name: string, value: any): void; + removeValue(name: string, index: number): void; + swapValues(name: string, index1: number, index2: number): void; + resetAll(): void; + getFormState(): FormState; + setFormState(state: FormState): void; } +export type ValidateValuesFunction = (values: FormValues) => FormErrors; + export interface FormFunctionProps extends FormProps, FormState, FormApi {} export interface FormContext { @@ -65,10 +86,9 @@ export interface FormContext { export class Form extends React.Component< - FormProps & { children?: ((props: FormFunctionProps) => RenderReturn) | RenderReturn }, - FormState + FormProps & { children?: ((props: FormFunctionProps) => RenderReturn) | RenderReturn } > - implements FormApi, React.ChildContextProvider { + implements React.ChildContextProvider { static defaultProps: FormProps; static childContextTypes: { formApi: React.Validator @@ -80,207 +100,87 @@ export class Form componentWillReceiveProps(nextProps: Readonly>, nextContext: any): void; componentWillUmount(): void; - // API - setAllValues(values: FormValues, noTouch?: boolean): void; - setValue(field: string, value: any, noTouch?: boolean): void; - getValue(field: string, fallback?: any): any; - setNestedError(field: string, value?: boolean): void; - getError(field: string): FormError; - setTouched(field: string, value?: boolean): void; - getTouched(field: string): boolean; - addValue(field: string, value: any): void; - removeValue(field: string, index: number): void; - swapValues(field: string, index: number, destIndex: number): void; - setAllTouched(dirty?: boolean, state?: Partial): void; - resetForm(): void; - submitForm(e?: Pick, 'preventDefault'>): void; - - // Utils - getAPI(): FormApi; - setFormState(newState: Partial, silent?: boolean): void; - emitChange(state: FormState, initial?: boolean): void; - validate(values: FormValues, state: FormState, props: FormProps): FormErrors; render(): RenderReturn; } -export interface FormFieldApi { - setAllValues(values: FormValues, noTouch?: boolean): void; - setValue(value: any, noTouch?: boolean): void; - getValue(fallback?: any): any; - setNestedError(value?: boolean): void; +export const NestedForm: React.StatelessComponent; + +export function FormField(component: React.ComponentType): React.ComponentClass; + +// Fields + +export interface FieldApi { + getValue(): FormValue; getError(): FormError; - setTouched(value?: boolean): void; + getWarning(): FormError; + getSuccess(): FormError; getTouched(): boolean; - addValue(value: any): void; - removeValue(index: number): void; - swapValues(index: number, destIndex: number): void; - setAllTouched(dirty?: boolean, state?: Partial): void; - resetForm(): void; - submitForm(e?: Pick, 'preventDefault'>): void; + getFieldName(): string; + setValue(value: FormValue): void; + setError(error: FormError): void; + setWarning(warning: FormError): void; + setSuccess(success: FormError): void; + setTouched(touched: boolean): void; } -export interface FormFieldPropsWithField { - field?: string; - children(api: FormFieldApi): React.ReactElement | null; -} -export interface FormFieldPropsWithoutField { - children(api: FormApi): RenderReturn; -} -export type FormFieldProps = FormFieldPropsWithField | FormFieldPropsWithoutField; -export const FormField: React.SFC; - -// FormError -export interface FormErrorProps { - field?: FormFieldPropsWithField['field']; - className?: string; - style?: React.HTMLAttributes['style']; -} -export const FormError: React.SFC; - -export interface FormInputProps { - field?: FormFieldPropsWithField['field']; +export interface FieldProps { + field?: string | string[] | React.ReactText[] | Array<(string | React.ReactText[])>; showErrors?: boolean; errorBefore?: boolean; isForm?: boolean; - className?: string; - errorProps?: FormErrorProps; } -export interface FormInputPropsWithChildren extends FormInputProps { - children(api: FormFieldApi): React.ReactElement | null; -} -export const FormInput: React.SFC; +export type SelectOptions = Array<{ + value: FormValue + label: string +}>; -// ============================== -// Inputs -// ============================== +export interface SelectProps extends FieldProps, React.SelectHTMLAttributes { + options: SelectOptions; +} -export type EventHandler = (e: E, cb: () => void) => void; -export type ChangeHandler = EventHandler>; -export type FocusHandler = EventHandler>; -export type ClickHandler = EventHandler>; +export const Select: React.StatelessComponent; -// Prop interfaces are intermediate interfaces to "redefine" the type of some events -// onChange:React.EventHandler => onChange:any => onChange:CustomEventHandler +export const Text: React.StatelessComponent>; +export const TextArea: React.StatelessComponent>; -export interface SelectOption { - label: string; - value: any; - disabled?: boolean; -} -export interface SelectAttrs extends React.SelectHTMLAttributes { - onChange?: any; - onBlur?: any; -} -export interface SelectProps extends SelectAttrs { - options: ReadonlyArray; - field?: FormInputProps['field']; - showErrors?: FormInputProps['showErrors']; - errorBefore?: FormInputProps['errorBefore']; - onChange?: ChangeHandler; - onBlur?: FocusHandler; - isForm?: FormInputProps['isForm']; - noTouch?: boolean; - errorProps?: FormInputProps['errorProps']; - placeholder?: string; -} -export const Select: React.SFC; - -export interface InputAttrs extends React.InputHTMLAttributes { - onChange?: any; - onBlur?: any; -} -export interface CheckboxProps extends InputAttrs { - field?: FormInputProps['field']; - showErrors?: FormInputProps['showErrors']; - errorBefore?: FormInputProps['errorBefore']; - onChange?: ChangeHandler; - onBlur?: FocusHandler; - isForm?: FormInputProps['isForm']; - noTouch?: boolean; - errorProps?: FormInputProps['errorProps']; -} -export const Checkbox: React.SFC; - -export interface TextareaAttrs extends React.TextareaHTMLAttributes { - onChange?: any; - onBlur?: any; -} -export interface TextareaProps extends TextareaAttrs { - field?: FormInputProps['field']; - showErrors?: FormInputProps['showErrors']; - errorBefore?: FormInputProps['errorBefore']; - onChange?: ChangeHandler; - onBlur?: FocusHandler; - isForm?: FormInputProps['isForm']; - noTouch?: boolean; - errorProps?: FormInputProps['errorProps']; -} -export const Textarea: React.SFC; - -export interface NestedFormProps extends FormProps { - field?: FormInputProps['field']; - children?: React.ReactElement | [React.ReactElement]; - errorProps?: FormInputProps['errorProps']; -} -export const NestedForm: React.SFC; - -export interface TextProps extends InputAttrs { - field?: FormInputProps['field']; - showErrors?: FormInputProps['showErrors']; - errorBefore?: FormInputProps['errorBefore']; - onChange?: ChangeHandler; - onBlur?: FocusHandler; - isForm?: FormInputProps['isForm']; - noTouch?: boolean; - errorProps?: FormInputProps['errorProps']; -} -export const Text: React.SFC; - -export interface RadioGroupProps { - field?: FormInputProps['field']; - showErrors?: FormInputProps['showErrors']; - errorBefore?: FormInputProps['errorBefore']; - isForm?: FormInputProps['isForm']; - errorProps?: FormInputProps['errorProps']; -} export interface RadioGroupContext { - formRadioGroup: RadioGroup; + group: FieldApi; } -export class RadioGroup extends React.Component implements FormFieldApi { - static childContextTypes: { - formRadioGroup: React.Validator + +export class RadioGroup + extends React.Component< + FieldProps & { children?: ((props: FieldApi) => RenderReturn) | RenderReturn } + > + implements React.ChildContextProvider { + getChildContext(): { + group: FieldApi; }; - - setAllValues: FormFieldApi['setAllValues']; - setValue: FormFieldApi['setValue']; - getValue: FormFieldApi['getValue']; - setNestedError: FormFieldApi['setNestedError']; - getError: FormFieldApi['getError']; - setTouched: FormFieldApi['setTouched']; - getTouched: FormFieldApi['getTouched']; - addValue: FormFieldApi['addValue']; - removeValue: FormFieldApi['removeValue']; - swapValues: FormFieldApi['swapValues']; - setAllTouched: FormFieldApi['setAllTouched']; - resetForm: FormFieldApi['resetForm']; - submitForm: FormFieldApi['submitForm']; - - getChildContext(): RadioGroupContext; } -export interface InputWIthoutClick extends InputAttrs { - onClick?: any; +export const Radio: React.StatelessComponent & {group: FieldApi}>; +export const Checkbox: React.StatelessComponent>; + +// Styled Fields + +export interface StyledProps extends FieldProps { + noMessage?: boolean; + messageBefore?: boolean; + touchValidation?: boolean; } -export interface RadioProps extends InputWIthoutClick { - onClick?: ClickHandler; - onChange?: ChangeHandler; - onBlur?: FocusHandler; -} -export class Radio extends React.Component { - static contextTypes: { - formRadioGroup: React.Validator + +export const StyledCheckbox: React.StatelessComponent & {label: string}>; +export const StyledTextArea: React.StatelessComponent>; +export const StyledSelect: React.StatelessComponent>; +export const StyledText: React.StatelessComponent>; +export const StyledRadio: React.StatelessComponent & {group: FieldApi, label: string}>; + +export class StyledRadioGroup + extends React.Component< + StyledProps & { children?: ((props: FieldApi) => RenderReturn) | RenderReturn } + > + implements React.ChildContextProvider { + getChildContext(): { + group: FieldApi }; - - context: RadioGroupContext; } diff --git a/types/react-form/react-form-tests.tsx b/types/react-form/react-form-tests.tsx index aad7f1b92f..2d08cc4b8a 100644 --- a/types/react-form/react-form-tests.tsx +++ b/types/react-form/react-form-tests.tsx @@ -1,78 +1,672 @@ import * as React from 'react'; import { - Form, - FormError, - FormInput, - - // Inputs - Select, - Checkbox, - Textarea, - NestedForm, - Text, - RadioGroup, - Radio + Form, + Text, + TextArea, + Radio, + RadioGroup, + Select, + Checkbox, + NestedForm, + FormValues, + FormErrors, + StyledText, + StyledRadioGroup, + StyledRadio, + StyledTextArea, + StyledCheckbox, + StyledSelect, + FieldApi, + FormField, + FormApi } from 'react-form'; -
      ; +// Basic Form Example +const statusOptions = [ + { + label: 'Single', + value: 'single' + }, + { + label: 'In a Relationship', + value: 'relationship' + }, + { + label: "It's Complicated", + value: 'complicated' + } +]; - - {() => null} -; +class BasicForm extends React.Component { + constructor(props: {}) { + super(props); + this.state = {}; + } -
      - {() =>
      } -; + render() { + return ( +
      +
      this.setState({ submittedValues })}> + { formApi => ( + + + + + + + { group => ( +
      + + + + +
      + )} +
      + +

Simple configuration with standard gradientCustom gradient configurationA single datapointmultiple datapoints