diff --git a/types/ace/index.d.ts b/types/ace/index.d.ts index 456727756c..822c394a32 100644 --- a/types/ace/index.d.ts +++ b/types/ace/index.d.ts @@ -345,18 +345,47 @@ declare namespace AceAjax { insert(position: Position, text: string): any; /** - * Inserts the elements in `lines` into the document, starting at the row index given by `row`. This method also triggers the `'change'` event. - * @param row The index of the row to insert at - * @param lines An array of strings - **/ + * @deprecated Use the insertFullLines method instead. + */ insertLines(row: number, lines: string[]): any; /** - * Inserts a new line into the document at the current row's `position`. This method also triggers the `'change'` event. - * @param position The position to insert at - **/ + * Inserts the elements in `lines` into the document as full lines (does not merge with existing line), starting at the row index given by `row`. This method also triggers the `"change"` event. + * @param {Number} row The index of the row to insert at + * @param {Array} lines An array of strings + * @returns {Object} Contains the final row and column, like this: + * ``` + * {row: endRow, column: 0} + * ``` + * If `lines` is empty, this function returns an object containing the current row, and column, like this: + * ``` + * {row: row, column: 0} + * ``` + * + **/ + insertFullLines(row: number, lines: string[]): any; + + /** + * @deprecated Use insertMergedLines(position, ['', '']) instead. + */ insertNewLine(position: Position): any; + /** + * Inserts the elements in `lines` into the document, starting at the position index given by `row`. This method also triggers the `"change"` event. + * @param {Number} row The index of the row to insert at + * @param {Array} lines An array of strings + * @returns {Object} Contains the final row and column, like this: + * ``` + * {row: endRow, column: 0} + * ``` + * If `lines` is empty, this function returns an object containing the current row, and column, like this: + * ``` + * {row: row, column: 0} + * ``` + * + **/ + insertMergedLines(row: number, lines: string[]): any; + /** * Inserts `text` into the `position` at the current row. This method also triggers the `'change'` event. * @param position The position to insert at @@ -379,12 +408,19 @@ declare namespace AceAjax { removeInLine(row: number, startColumn: number, endColumn: number): any; /** - * Removes a range of full lines. This method also triggers the `'change'` event. - * @param firstRow The first row to be removed - * @param lastRow The last row to be removed - **/ + * @deprecated Use the removeFullLines method instead. + */ removeLines(firstRow: number, lastRow: number): string[]; + /** + * Removes a range of full lines. This method also triggers the `"change"` event. + * @param {Number} firstRow The first row to be removed + * @param {Number} lastRow The last row to be removed + * @returns {[String]} Returns all the removed lines. + * + **/ + removeFullLines(firstRow: number, lastRow: number): string[]; + /** * Removes the new line between `row` and the row immediately following it. This method also triggers the `'change'` event. * @param row The row to check @@ -474,9 +510,9 @@ declare namespace AceAjax { removeFold(arg: any): void; expandFold(arg: any): void; - + foldAll(startRow?: number, endRow?: number, depth?: number): void - + unfold(arg1: any, arg2: boolean): void; screenToDocumentColumn(row: number, column: number): void; @@ -2659,9 +2695,9 @@ declare namespace AceAjax { characterWidth: number; lineHeight: number; - + setScrollMargin(top:number, bottom:number, left: number, right: number): void; - + screenToTextCoordinates(left: number, top: number): void; /** diff --git a/types/actions-on-google/actions-sdk-app.d.ts b/types/actions-on-google/actions-sdk-app.d.ts index 8de0de0cfb..09a4fbe0ad 100644 --- a/types/actions-on-google/actions-sdk-app.d.ts +++ b/types/actions-on-google/actions-sdk-app.d.ts @@ -35,6 +35,7 @@ export class ActionsSdkApp extends AssistantApp { constructor(options: ActionsSdkAppOptions); /** + * @deprecated * Validates whether request is from Assistant through signature verification. * Uses Google-Auth-Library to verify authorization token against given * Google Cloud Project ID. Auth token is given in request header with key, @@ -58,6 +59,30 @@ export class ActionsSdkApp extends AssistantApp { */ isRequestFromAssistant(projectId: string): Promise; + /** + * Validates whether request is from Google through signature verification. + * Uses Google-Auth-Library to verify authorization token against given + * Google Cloud Project ID. Auth token is given in request header with key, + * "Authorization". + * + * @example + * const app = new ActionsSdkApp({request, response}); + * app.isRequestFromGoogle('nodejs-cloud-test-project-1234') + * .then(() => { + * app.ask('Hey there, thanks for stopping by!'); + * }) + * .catch(err => { + * response.status(400).send(); + * }); + * + * @param projectId Google Cloud Project ID for the Assistant app. + * @return Promise resolving with google-auth-library LoginTicket + * if request is from a valid source, otherwise rejects with the error reason + * for an invalid token. + * @actionssdk + */ + isRequestFromGoogle(projectId: string): Promise; + /** * Gets the request Conversation API version. * diff --git a/types/actions-on-google/assistant-app.d.ts b/types/actions-on-google/assistant-app.d.ts index d33f447a2e..caed5cf6cb 100644 --- a/types/actions-on-google/assistant-app.d.ts +++ b/types/actions-on-google/assistant-app.d.ts @@ -10,58 +10,36 @@ import { ActionPaymentTransactionConfig, Cart, GooglePaymentTransactionConfig, L * @dialogflow */ export enum StandardIntents { - /** - * App fires MAIN intent for queries like [talk to $app]. - */ + /** App fires MAIN intent for queries like [talk to $app]. */ MAIN, - /** - * App fires TEXT intent when action issues ask intent. - */ + /** App fires TEXT intent when action issues ask intent. */ TEXT, - /** - * App fires PERMISSION intent when action invokes askForPermission. - */ + /** App fires PERMISSION intent when action invokes askForPermission. */ PERMISSION, - /** - * App fires OPTION intent when user chooses from options provided. - */ + /** App fires OPTION intent when user chooses from options provided. */ OPTION, - /** - * App fires TRANSACTION_REQUIREMENTS_CHECK intent when action sets up transaction. - */ + /** App fires TRANSACTION_REQUIREMENTS_CHECK intent when action sets up transaction. */ TRANSACTION_REQUIREMENTS_CHECK, - /** - * App fires DELIVERY_ADDRESS intent when action asks for delivery address. - */ + /** App fires DELIVERY_ADDRESS intent when action asks for delivery address. */ DELIVERY_ADDRESS, - /** - * App fires TRANSACTION_DECISION intent when action asks for transaction decision. - */ + /** App fires TRANSACTION_DECISION intent when action asks for transaction decision. */ TRANSACTION_DECISION, - /** - * App fires CONFIRMATION intent when requesting affirmation from user. - */ + /** App fires CONFIRMATION intent when requesting affirmation from user. */ CONFIRMATION, - /** - * App fires DATETIME intent when requesting date/time from user. - */ + /** App fires DATETIME intent when requesting date/time from user. */ DATETIME, - /** - * App fires SIGN_IN intent when requesting sign-in from user. - */ + /** App fires SIGN_IN intent when requesting sign-in from user. */ SIGN_IN, - /** - * App fires NO_INPUT intent when user doesn't provide input. - */ + /** App fires NO_INPUT intent when user doesn't provide input. */ NO_INPUT, - /** - * App fires CANCEL intent when user exits app mid-dialog. - */ + /** App fires CANCEL intent when user exits app mid-dialog. */ CANCEL, - /** - * App fires NEW_SURFACE intent when requesting handoff to a new surface from user. - */ + /** App fires NEW_SURFACE intent when requesting handoff to a new surface from user. */ NEW_SURFACE, + /** App fires REGISTER_UPDATE intent when requesting the user to register for proactive updates. */ + REGISTER_UPDATE, + /** App receives CONFIGURE_UPDATES intent to indicate a custom REGISTER_UPDATE intent should be sent. */ + CONFIGURE_UPDATES } /** @@ -85,6 +63,10 @@ export enum SupportedPermissions { * {@link https://developers.google.com/actions/reference/conversation#Location|Location object}. */ DEVICE_COARSE_LOCATION, + /** + * Confirmation to receive proactive content at any time from the app. + */ + UPDATE } /** @@ -137,6 +119,8 @@ export enum BuiltInArgNames { * New surface value argument. */ NEW_SURFACE, + /** Update registration value argument. */ + REGISTER_UPDATE } /** @@ -144,8 +128,17 @@ export enum BuiltInArgNames { * {@link https://developers.google.com/actions/reference/conversation#Conversation|Conversation object}. * @actionssdk * @dialogflow + * @deprecated Use {@link ConversationTypes} instead. */ -export enum ConversationStages { +export type ConversationStages = ConversationTypes; + +/** + * List of possible conversation types, as defined in the + * {@link https://developers.google.com/actions/reference/conversation#Conversation|Conversation object}. + * @actionssdk + * @dialogflow + */ +export enum ConversationTypes { /** * Unspecified conversation state. */ @@ -224,6 +217,13 @@ export enum SignInStatus { ERROR } +/** + * Possible update trigger time context frequencies. + */ +export enum TimeContextFrequency { + DAILY +} + /** * User provided date/time info. */ @@ -277,6 +277,17 @@ export interface User { userName: UserName; /** Unique Oauth2 token. Only available with account linking. */ accessToken: string; + /** + * Timestamp for the last access from the user. + * Retrieve using app.getLastSeen() to get a Date object or null if never seen. + */ + lastSeen: string; + /** + * A string persistent across sessions. + * Retrieved and set using app.userStorage which allows you to store it like an JSON object + * which is abstracted for convenience by the client library. + */ + userStorage: string; } /** @@ -295,6 +306,17 @@ export interface Capability { name: string; } +/** + * Intent Argument. For incoming intents, the argument value can be retrieved + * using {@link AssistantApp#getArgument}. + */ +export interface IntentArgument { + /** Name of the argument. */ + name: string; + /** Text value of the argument. */ + textValue: string; +} + /** * The Actions on Google client library AssistantApp base class. * @@ -313,6 +335,20 @@ export class AssistantApp { */ data: object; + /** + * The data persistent across sessions in JSON format. + * It exists in the same context as getUser().userId + * + * @example + * // Actions SDK + * const app = new ActionsSdkApp({request: request, response: response}); + * app.userStorage.someProperty = 'someValue'; + * // Dialogflow + * const app = new DialogflowApp({request: request, response: response}); + * app.userStorage.someProperty = 'someValue'; + */ + userStorage: object; + /** * List of standard intents that the app provides. * @actionssdk @@ -339,8 +375,17 @@ export class AssistantApp { * {@link https://developers.google.com/actions/reference/conversation#Conversation|Conversation object}. * @actionssdk * @dialogflow + * @deprecated Use {@link ConversationTypes} instead. */ - readonly ConversationStages: typeof ConversationStages; + readonly ConversationStages: typeof ConversationTypes; + + /** + * List of possible conversation types, as defined in the + * {@link https://developers.google.com/actions/reference/conversation#Conversation|Conversation object}. + * @actionssdk + * @dialogflow + */ + readonly ConversationTypes: typeof ConversationTypes; /** * List of surface capabilities supported by the app. @@ -368,6 +413,11 @@ export class AssistantApp { */ readonly Transactions: typeof TransactionValues; + /** + * Possible update trigger time context frequencies. + */ + readonly TimeContextFrequency: typeof TimeContextFrequency; + // --------------------------------------------------------------------------- // Public APIs // --------------------------------------------------------------------------- @@ -477,7 +527,7 @@ export class AssistantApp { * @param permissions Array of permissions App supports, each of * which comes from AssistantApp.SupportedPermissions. * @param dialogState JSON object the app uses to hold dialog state that - * will be circulated back by Assistant. Used in {@link ActionsSdkAssistant}. + * will be circulated back by Assistant. Used in {@link ActionsSdkApp}. * @return A response is sent to Assistant to ask for the user's permission; for any * invalid input, we return null. * @actionssdk @@ -485,6 +535,58 @@ export class AssistantApp { */ askForPermissions(context: string, permissions: string[], dialogState?: object): express.Response | null; + /** + * Prompts the user for permission to send proactive updates at any time. + * + * @example + * const app = new DialogflowApp({request, response}); + * const REQUEST_PERMISSION_ACTION = 'request.permission'; + * const PERMISSION_REQUESTED = 'permission.requested'; + * const SHOW_IMAGE = 'show.image'; + * + * function requestPermission (app) { + * app.askForUpdatePermission('show.image', [ + * { + * name: 'image_to_show', + * textValue: 'image_type_1' + * } + * ]); + * } + * + * function checkPermission (app) { + * if (app.isPermissionGranted()) { + * app.tell(`Great, I'll send an update whenever I notice a change`); + * } else { + * // Response shows that user did not grant permission + * app.tell('Alright, just let me know whenever you need the weather!'); + * } + * } + * + * function showImage (app) { + * showPicture(app.getArgument('image_to_show')); + * } + * + * const actionMap = new Map(); + * actionMap.set(REQUEST_PERMISSION_ACTION, requestPermission); + * actionMap.set(PERMISSION_REQUESTED, checkPermission); + * actionMap.set(SHOW_IMAGE, showImage); + * app.handleRequest(actionMap); + * + * @param intent If using Dialogflow, the action name of the intent + * to be triggered when the update is received. If using Actions SDK, the + * intent name to be triggered when the update is received. + * @param intentArguments The necessary arguments + * to fulfill the intent triggered on update. These can be retrieved using + * {@link AssistantApp#getArgument}. + * @param dialogState JSON object the app uses to hold dialog state that + * will be circulated back by Assistant. Used in {@link ActionsSdkApp}. + * @return A response is sent to Assistant to ask for the user's permission; for any + * invalid input, we return null. + * @actionssdk + * @dialogflow + */ + askForUpdatePermission(intent: string, intentArguments: IntentArgument[], dialogState?: object): express.Response | null; + /** * Checks whether user is in transactable state. * @@ -520,7 +622,7 @@ export class AssistantApp { * options and order options. Optional if order has no payment or * delivery. * @param dialogState JSON object the app uses to hold dialog state that - * will be circulated back by Assistant. Used in {@link ActionsSdkAssistant}. + * will be circulated back by Assistant. Used in {@link ActionsSdkApp}. * @return HTTP response. * @actionssdk * @dialogflow @@ -562,7 +664,7 @@ export class AssistantApp { * transactionConfig Configuration for the transaction. Includes payment * options and order options. * @param dialogState JSON object the app uses to hold dialog state that - * will be circulated back by Assistant. Used in {@link ActionsSdkAssistant}. + * will be circulated back by Assistant. Used in {@link ActionsSdkApp}. * @return HTTP response * @dialogflow */ @@ -737,7 +839,7 @@ export class AssistantApp { * query for an affirmative or negative response. If undefined or null, * Google will use a generic yes/no prompt. * @param dialogState JSON object the app uses to hold dialog state that - * will be circulated back by Assistant. Used in {@link ActionsSdkAssistant}. + * will be circulated back by Assistant. Used in {@link ActionsSdkApp}. * @return HTTP response. * @actionssdk * @dialogflow @@ -782,7 +884,7 @@ export class AssistantApp { * time if not provided by user. If undefined or null, Google will use a * generic prompt. * @param dialogState JSON object the app uses to hold dialog state that - * will be circulated back by Assistant. Used in {@link ActionsSdkAssistant}. + * will be circulated back by Assistant. Used in {@link ActionsSdkApp}. * @return HTTP response. * @actionssdk * @dialogflow @@ -795,11 +897,6 @@ export class AssistantApp { * Retrieve the access token in subsequent intents using * app.getUser().accessToken. * - * Note: Currently this API requires enabling the app for Transactions APIs. - * To do this, fill out the App Info section of the Actions Console project - * and check the box indicating the use of Transactions under "Privacy and - * consent". - * * @example * const app = new DialogflowApp({ request, response }); * const WELCOME_INTENT = 'input.welcome'; @@ -824,7 +921,7 @@ export class AssistantApp { * app.handleRequest(actionMap); * * @param dialogState JSON object the app uses to hold dialog state that - * will be circulated back by Assistant. Used in {@link ActionsSdkAssistant}. + * will be circulated back by Assistant. Used in {@link ActionsSdkApp}. * @return HTTP response. * @actionssdk * @dialogflow @@ -872,13 +969,53 @@ export class AssistantApp { * @param capabilities The list of capabilities required in * the surface. * @param dialogState JSON object the app uses to hold dialog state that - * will be circulated back by Assistant. Used in {@link ActionsSdkAssistant}. + * will be circulated back by Assistant. Used in {@link ActionsSdkApp}. * @return HTTP response. * @dialogflow * @actionssdk */ askForNewSurface(context: string, notificationTitle: string, capabilities: SurfaceCapabilities[], dialogState?: object): express.Response | null; + /** + * Requests the user to register for daily updates. + * + * @example + * const app = new DialogflowApp({ request, response }); + * const WELCOME_INTENT = 'input.welcome'; + * const SHOW_IMAGE = 'show.image'; + * + * function welcomeIntent (app) { + * app.askToRegisterDailyUpdate('show.image', [ + * { + * name: 'image_to_show', + * textValue: 'image_type_1' + * } + * ]); + * } + * + * function showImage (app) { + * showPicture(app.getArgument('image_to_show')); + * } + * + * const actionMap = new Map(); + * actionMap.set(WELCOME_INTENT, welcomeIntent); + * actionMap.set(SHOW_IMAGE, showImage); + * app.handleRequest(actionMap); + * + * @param intent If using Dialogflow, the action name of the intent + * to be triggered when the update is received. If using Actions SDK, the + * intent name to be triggered when the update is received. + * @param intentArguments The necessary arguments + * to fulfill the intent triggered on update. These can be retrieved using + * {@link AssistantApp#getArgument}. + * @param dialogState JSON object the app uses to hold dialog state that + * will be circulated back by Assistant. Used in {@link ActionsSdkApp}. + * @return HTTP response. + * @dialogflow + * @actionssdk + */ + askToRegisterDailyUpdate(intent: string, intentArguments: IntentArgument[], dialogState?: object): express.Response | null; + /** * Gets the {@link User} object. * The user object contains information about the user, including @@ -945,6 +1082,18 @@ export class AssistantApp { */ getUserLocale(): string; + /** + * Get the user's last seen time as a Date object. + * Not supported in V1. + * + * @example + * const app = new DialogflowApp({request, response}); + * const lastSeen = app.getLastSeen(); + * + * @return User's last seen date or null if never seen + */ + getLastSeen(): Date | null; + /** * If granted permission to device's location in previous intent, returns device's * location (see {@link AssistantApp#askForPermissions|askForPermissions}). @@ -1225,6 +1374,16 @@ export class AssistantApp { */ isFinalReprompt(): boolean; + /** + * Returns true if user accepted update registration request. Used with + * {@link AssistantApp#askToRegisterDailyUpdate} + * + * @return True if user accepted update registration request. + * @dialogflow + * @actionssdk + */ + isUpdateRegistered(): boolean; + // --------------------------------------------------------------------------- // Response Builders // --------------------------------------------------------------------------- diff --git a/types/actions-on-google/index.d.ts b/types/actions-on-google/index.d.ts index 5f7baba3b8..378604411f 100644 --- a/types/actions-on-google/index.d.ts +++ b/types/actions-on-google/index.d.ts @@ -1,4 +1,4 @@ -// Type definitions for actions-on-google 1.5 +// Type definitions for actions-on-google 1.6 // Project: https://github.com/actions-on-google/actions-on-google-nodejs // Definitions by: Joel Hegg // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped diff --git a/types/actions-on-google/response-builder.d.ts b/types/actions-on-google/response-builder.d.ts index 1e11984551..5b6e3d7522 100644 --- a/types/actions-on-google/response-builder.d.ts +++ b/types/actions-on-google/response-builder.d.ts @@ -70,6 +70,24 @@ export interface OptionInfo { synonyms: string[]; } +export interface StructuredResponse { + orderUpdate: OrderUpdate; +} + +export interface RichResponseItemBasicCard { + basicCard: BasicCard; +} + +export interface RichResponseItemSimpleResponse { + simpleResponse: SimpleResponse; +} + +export interface RichResponseItemStructuredResponse { + structuredResponse: StructuredResponse; +} + +export type RichResponseItem = RichResponseItemBasicCard | RichResponseItemSimpleResponse | RichResponseItemStructuredResponse; + /** * Class for initializing and constructing Rich Responses with chainable interface. */ @@ -85,7 +103,7 @@ export class RichResponse { * Ordered list of either SimpleResponse objects or BasicCard objects. * First item must be SimpleResponse. There can be at most one card. */ - items: Array; + items: RichResponseItem[]; /** * Ordered list of text suggestions to display. Optional. diff --git a/types/actions-on-google/transactions.d.ts b/types/actions-on-google/transactions.d.ts index 8cc26165db..b4a4285fe9 100644 --- a/types/actions-on-google/transactions.d.ts +++ b/types/actions-on-google/transactions.d.ts @@ -25,8 +25,8 @@ export interface Price { * Order rejection info. */ export interface RejectionInfo { - /** One of Transaction.RejectionType. */ - type: RejectionType; + /** One of Transaction.ReasonType. */ + type: ReasonType; /** Reason for the order rejection. */ reason: string; } @@ -51,26 +51,16 @@ export interface CancellationInfo { * Order transit info. */ export interface TransitInfo { - /** UTC timestamp of the transit update. */ - updatedTime: { - /** Seconds since Unix epoch. */ - seconds: number; - /** Partial seconds since Unix epoch. */ - nanos?: number; - }; + /** UTC timestamp of the transit update as an RFC 3339 string. */ + updatedTime: string; } /** * Order fulfillment info. */ export interface FulfillmentInfo { - /** UTC timestamp of the fulfillment update. */ - deliveryTime: { - /** Seconds since Unix epoch. */ - seconds: number; - /** Partial seconds since Unix epoch. */ - nanos?: number; - }; + /** UTC timestamp of the fulfillment update as an RFC 3339 string. */ + deliveryTime: string; } /** @@ -140,7 +130,7 @@ export interface Location { */ export interface TransactionDecision { /** One of Transactions.ConfirmationDecision. */ - userDecision: ConfirmationDecision; + userDecision: TransactionUserDecision; checkResult: { /** One of Transactions.ResultType. */ resultType: ResultType; @@ -175,32 +165,61 @@ export interface TransactionDecision { export const TransactionValues: { /** List of transaction card networks available when paying with Google. */ readonly CardNetwork: typeof CardNetwork; + /** + * List of possible item types. + * @deprecated Use {@link TransactionValues.LineItemType} instead. + */ + readonly ItemType: typeof LineItemType; /** List of possible item types. */ - readonly ItemType: typeof ItemType; + readonly LineItemType: typeof LineItemType; /** List of price types. */ readonly PriceType: typeof PriceType; /** List of possible item types. */ readonly PaymentType: typeof PaymentType; /** List of customer information properties that can be requested. */ readonly CustomerInfoProperties: typeof CustomerInfoProperties; + /** + * List of possible order confirmation user decisions + * @deprecated Use {@link TransactionValues.TransactionUserDecision} instead. + */ + readonly ConfirmationDecision: typeof TransactionUserDecision; /** List of possible order confirmation user decisions */ - readonly ConfirmationDecision: typeof ConfirmationDecision; + readonly TransactionUserDecision: typeof TransactionUserDecision; /** List of possible order states. */ readonly OrderState: typeof OrderState; + /** + * List of possible actions to take on the order. + * @deprecated Use {@link TransactionValues.ActionType} instead. + */ + readonly OrderAction: typeof ActionType; /** List of possible actions to take on the order. */ - readonly OrderAction: typeof OrderAction; + readonly ActionType: typeof ActionType; + /** + * List of possible types of order rejection. + * @deprecated Use {@link TransactionValues.ReasonType} instead. + */ + readonly RejectionType: typeof ReasonType; /** List of possible types of order rejection. */ - readonly RejectionType: typeof RejectionType; + readonly ReasonType: typeof ReasonType; /** List of possible order state objects. */ readonly OrderStateInfo: typeof OrderStateInfo; /** List of possible order transaction requirements check result types. */ readonly ResultType: typeof ResultType; /** List of possible user decisions to give delivery address. */ - readonly DeliveryAddressDecision: typeof DeliveryAddressDecision; + readonly DeliveryAddressDecision: typeof DeliveryAddressUserDecision; + /** List of possible user decisions to give delivery address. */ + readonly DeliveryAddressUserDecision: typeof DeliveryAddressUserDecision; + /** + * List of possible order location types. + * @deprecated Use {@link TransactionValues.OrderLocationType} instead. + */ + readonly LocationType: typeof OrderLocationType; /** List of possible order location types. */ - readonly LocationType: typeof LocationType; + readonly OrderLocationType: typeof OrderLocationType; /** List of possible order time types. */ readonly TimeType: typeof TimeType; + /** List of possible tokenization types for the payment method */ + readonly PaymentMethodTokenizationType: typeof PaymentMethodTokenizationType; }; /** @@ -235,8 +254,14 @@ export enum CardNetwork { /** * List of possible item types. + * @deprecated Use {@link TransactionValues.LineItemType} instead. */ -export enum ItemType { +export type ItemType = LineItemType; + +/** + * List of possible item types. + */ +export enum LineItemType { /** * Unspecified. */ @@ -323,13 +348,24 @@ export enum PaymentType { * List of customer information properties that can be requested. */ export enum CustomerInfoProperties { + CUSTOMER_INFO_PROPERTY_UNSPECIFIED, EMAIL } /** * List of possible order confirmation user decisions + * @deprecated Use {@link TransactionValues.TransactionUserDecision} instead. */ -export enum ConfirmationDecision { +export type ConfirmationDecision = TransactionUserDecision; + +/** + * List of possible order confirmation user decisions + */ +export enum TransactionUserDecision { + /** + * Unspecified user decision. + */ + UNKNOWN_USER_DECISION, /** * Order was approved by user. */ @@ -353,6 +389,10 @@ export enum ConfirmationDecision { * List of possible order states. */ export enum OrderState { + /** + * Order was created at the integrator's system. + */ + CREATED, /** * Order was rejected. */ @@ -381,8 +421,18 @@ export enum OrderState { /** * List of possible actions to take on the order. + * @deprecated Use {@link TransactionValues.ActionType} instead. */ -export enum OrderAction { +export type OrderAction = ActionType; + +/** + * List of possible actions to take on the order. + */ +export enum ActionType { + /** + * Unknown action. + */ + UNKNOWN, /** * View details. */ @@ -418,13 +468,23 @@ export enum OrderAction { /** * Review. */ - REVIEW + REVIEW, + /** + * Customer Service. + */ + CUSTOMER_SERVICE } /** * List of possible types of order rejection. + * @deprecated Use {@link TransactionValues.ReasonType} instead. */ -export enum RejectionType { +export type RejectionType = ReasonType; + +/** + * List of possible types of order rejection. + */ +export enum ReasonType { /** * Unknown */ @@ -494,8 +554,14 @@ export enum ResultType { /** * List of possible user decisions to give delivery address. + * @deprecated Use {@link TransactionValues.DeliveryAddressUserDecision} instead. */ -export enum DeliveryAddressDecision { +export type DeliveryAddressDecision = DeliveryAddressUserDecision; + +/** + * List of possible user decisions to give delivery address. + */ +export enum DeliveryAddressUserDecision { /** * Unknown. */ @@ -512,8 +578,14 @@ export enum DeliveryAddressDecision { /** * List of possible order location types. + * @deprecated Use {@link TransactionValues.OrderLocationType} instead. */ -export enum LocationType { +export type LocationType = OrderLocationType; + +/** + * List of possible order location types. + */ +export enum OrderLocationType { /** * Unknown. */ @@ -533,7 +605,11 @@ export enum LocationType { /** * Destination of the order. */ - DESTINATION + DESTINATION, + /** + * Pick up location of the order. + */ + PICK_UP } /** @@ -558,6 +634,20 @@ export enum TimeType { RESERVATION_SLOT } +/** + * List of possible tokenization types for the payment method + */ +export enum PaymentMethodTokenizationType { + /** + * Unspecified tokenization type. + */ + UNSPECIFIED_TOKENIZATION_TYPE, + /** + * Use external payment gateway tokenization API to tokenize selected payment method. + */ + PAYMENT_GATEWAY +} + /** * Class for initializing and constructing Order with chainable interface. */ @@ -655,11 +745,11 @@ export class Order { /** * Adds an associated location to the order. Up to 2 locations can be added. * - * @param type One of TransactionValues.LocationType. + * @param type One of TransactionValues.OrderLocationType. * @param location Location to add. * @return Returns current constructed Order. */ - addLocation(type: LocationType, location: Location): Order; + addLocation(type: OrderLocationType, location: Location): Order; /** * Sets an associated time to the order. @@ -780,9 +870,9 @@ export class LineItem { image?: Image; /** - * Type of the item. One of TransactionValues.ItemType. + * Type of the item. One of TransactionValues.LineItemType. */ - type?: ItemType; + type?: LineItemType; /** * Quantity of the item. @@ -834,10 +924,10 @@ export class LineItem { /** * Set the type of the item. * - * @param type Type of the item. One of TransactionValues.ItemType. + * @param type Type of the item. One of TransactionValues.LineItemType. * @return Returns current constructed LineItem. */ - setType(type: ItemType): LineItem; + setType(type: LineItemType): LineItem; /** * Set the quantity of the item. @@ -898,9 +988,9 @@ export class OrderUpdate { lineItemUpdates: object; /** - * UTC timestamp of the order update. + * UTC timestamp of the order update as an RFC 3339 string. */ - updateTime?: object; + updateTime?: string; /** * Actionable items presented to the user to manage the order. @@ -946,7 +1036,7 @@ export class OrderUpdate { * Set the update time of the order. * * @param seconds Seconds since Unix epoch. - * @param nanos Partial time units. + * @param nanos Partial time units. It is rounded to the nearest millisecond. * @return Returns current constructed OrderUpdate. */ setUpdateTime(seconds: number, nanos?: number): OrderUpdate; @@ -974,12 +1064,12 @@ export class OrderUpdate { /** * Adds an actionable item for the user to manage the order. * - * @param type One of TransactionValues.OrderActions. + * @param type One of TransactionValues.ActionType. * @param label Button label. * @param url URL to open when button is clicked. * @return Returns current constructed OrderUpdate. */ - addOrderManagementAction(type: OrderAction, label: string, url: string): OrderUpdate; + addOrderManagementAction(type: ActionType, label: string, url: string): OrderUpdate; /** * Adds a single price update for a particular line item in the order. diff --git a/types/aframe/aframe-tests.ts b/types/aframe/aframe-tests.ts index 439d314f4a..5af66a09d1 100644 --- a/types/aframe/aframe-tests.ts +++ b/types/aframe/aframe-tests.ts @@ -1,5 +1,4 @@ // Global - const threeCamera = new AFRAME.THREE.Camera(); AFRAME.TWEEN.Easing; @@ -42,9 +41,18 @@ entity.addEventListener('child-detached', (event) => { const Component = AFRAME.registerComponent('test', {}); // Scene - const scene = document.querySelector('a-scene'); scene.hasLoaded; // System const system = scene.systems['systemName']; + +// Register Custom Geometry +AFRAME.registerGeometry('a-test-geometry', { + schema: { + groupIndex: { default: 0 } + }, + init(data) { + this.geometry = new THREE.Geometry(); + } +}); diff --git a/types/aframe/index.d.ts b/types/aframe/index.d.ts index f1f5cd7a20..803318a754 100644 --- a/types/aframe/index.d.ts +++ b/types/aframe/index.d.ts @@ -1,6 +1,7 @@ -// Type definitions for AFRAME 0.5 +// Type definitions for AFRAME 0.7 // Project: https://aframe.io/ // Definitions by: Paul Shannon +// Roberto Ritger // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped // TypeScript Version: 2.3 @@ -40,7 +41,7 @@ declare namespace AFrame { primitives: { [ key: string ]: Entity }; registerComponent(name: string, component: ComponentDefinition): ComponentConstructor; registerElement(name: string, element: ANode): void; - registerGeometry(name: string, geometery: THREE.Geometry): Geometry; + registerGeometry(name: string, geometry: GeometryDefinition): Geometry; registerPrimitive(name: string, primitive: PrimitiveDefinition): void; registerShader(name: string, shader: any): void; registerSystem(name: string, definition: SystemDefinition): void; @@ -101,7 +102,7 @@ declare namespace AFrame { name: string; schema: Schema; - init(): void; + init(data?: any): void; pause(): void; play(): void; remove(): void; @@ -124,7 +125,7 @@ declare namespace AFrame { multiple?: boolean; schema?: Schema; - init?(): void; + init?(data?: any): void; pause?(): void; play?(): void; remove?(): void; @@ -222,6 +223,10 @@ declare namespace AFrame { [ key: string ]: any; } + interface GeometryDefinition extends ComponentDefinition { + geometry?: THREE.Geometry; + } + interface GeometryDescriptor { Geometry: Geometry; schema: Schema; diff --git a/types/amcharts/index.d.ts b/types/amcharts/index.d.ts index 85abd11f5c..0dae492a76 100644 --- a/types/amcharts/index.d.ts +++ b/types/amcharts/index.d.ts @@ -2191,27 +2191,45 @@ If you do not set properties such as dashLength, lineAlpha, lineColor, etc - val chart.addGraph(graph); */ class AmGraph { + /** Text which screen readers will read if user rolls-over the bullet/column or sets focus using tab key (this is possible only if tabIndex property of AmGraph is set to some number). Text is added as aria-label tag. Note - not all screen readers and browsers support this. + @default "[[title]] [[category]] [[value]]" + */ + accessibleLabel: string; /** Name of the alpha field in your dataProvider. */ alphaField: string; + /** If you set this to true before chart is drawn, the animation of this graph won't be played. + @default false + */ + animationPlayed: boolean; + /** Allows customizing graphs balloons individually (only when ChartCursor is used). Note: the balloon object is not created automatically, you should create it before setting properties */ + balloon: AmBalloon; /** Value balloon color. Will use graph or data item color if not set. */ balloonColor: string; - /** If you set some function, the graph will call it and pass GraphDataItem and AmGraph object to it. This function should return a string which will be displayed in a balloon. */ + /** If you set some function, the graph will call it and pass GraphDataItem and AmGraph objects to it. This function should return a string which will be displayed in a balloon. */ balloonFunction(graphDataItem: GraphDataItem, amGraph: AmGraph): string; - /** Balloon text. You can use tags like [[value]], [[description]], [[percents]], [[open]], [[category]] [[value]] */ + /** Balloon text. You can use tags like [[value]], [[description]], [[percents]], [[open]], [[category]] or any other field name from your data provider. HTML tags can also be used. + @default [[value]] + */ balloonText: string; - /** Specifies if the line graph should be placed behind column graphs */ + /** Specifies if the line graph should be placed behind column graphs + @default false + */ behindColumns: boolean; - /** Type of the bullets. Possible values are: "none", "round", "square", "triangleUp", "triangleDown", "bubble", "custom". none */ + /** Type of the bullets. Possible values are: "none", "round", "square", "triangleUp", "triangleDown", "triangleLeft", "triangleRight", "bubble", "diamond", "xError", "yError" and "custom". + @default "none" + */ bullet: string; /** Opacity of bullets. Value range is 0 - 1. @default 1 */ bulletAlpha: number; + /** bulletAxis value is used when you are building error chart. Error chart is a regular serial or XY chart with bullet type set to "xError" or "yError". The graph should know which axis should be used to determine the size of this bullet - that's when bulletAxis should be set. Besides that, you should also set graph.errorField. You can also use other bullet types with this feature too. For example, if you set bulletAxis for XY chart, the size of a bullet will change as you zoom the chart. */ + bulletAxis: ValueAxis; /** Bullet border opacity. - @default 1 + @default 0 */ bulletBorderAlpha: number; - /** Bullet border color. Will use lineColor if not set. */ + /** Bullet border color. Will use lineColor if not set. */ bulletBorderColor: string; /** Bullet border thickness. @default 2 @@ -2221,7 +2239,11 @@ If you do not set properties such as dashLength, lineAlpha, lineColor, etc - val bulletColor: string; /** Name of the bullet field in your dataProvider. */ bulletField: string; - /** Bullet offset. Distance from the actual data point to the bullet. Can be used to place custom bullets above the columns. */ + /** Useful for touch devices - if you set it to 20 or so, the bullets of a graph will have invisible circle around the actual bullet (bullets should still be enabled), which will be easier to touch (bullets usually are smaller and hard to hit). */ + bulletHitAreaSize: number; + /** Bullet offset. Distance from the actual data point to the bullet. Can be used to place custom bullets above the columns. + @default 0 + */ bulletOffset: number; /** Bullet size. @default 8 @@ -2229,17 +2251,31 @@ If you do not set properties such as dashLength, lineAlpha, lineColor, etc - val bulletSize: number; /** Name of the bullet size field in your dataProvider. */ bulletSizeField: string; + /** If this field is set and addClassNames is enabled, the chart will look for a class name string in data using this setting and apply additional class names to elements of the particular data points, such as bullets. */ + classNameField: string; /** Name of the close field (used by candlesticks and ohlc) in your dataProvider. */ closeField: string; + /** In case you want to place this graph's columns in front of other columns, set this to false. In case "true", the columns will be clustered next to each other. + + NOTE: clustering works only for graphs of type "column". + @default true + */ + clustered: boolean; /** Color of value labels. Will use chart's color if not set. */ color: string; /** Name of the color field in your dataProvider. */ colorField: string; - /** Specifies whether to connect data points if data is missing. The default value is true. + /** You can use this property with non-stacked column graphs and specify order of columns of each category (starting from 0). Important: this feature does not work in stacked columns scenarios as well as with graph toggling enabled in legend. */ + columnIndexField: string; + /** You can specify custom column width for each graph individually. Value range is 0 - 1 (we set relative width, not pixel width here). */ + columnWidth: number; + /** Specifies whether to connect data points if data is missing. The default value is true. This feature does not work with XY chart. @default true */ connect: boolean; - /** Corner radius of column. It can be set both in pixels or in percents. The chart's depth and angle styles must be set to 0. The default value is 0. Note, cornerRadiusTop will be applied for all corners of the column, JavaScript charts do not have a possibility to set separate corner radius for top and bottom. As we want all the property names to be the same both on JS and Flex, we didn't change this too. */ + /** Corner radius of column. It can be set both in pixels or in percents. The chart's depth and angle styles must be set to 0. The default value is 0. Note, cornerRadiusTop will be applied for all corners of the column, JavaScript charts do not have a possibility to set separate corner radius for top and bottom. As we want all the property names to be the same both on JS and Flex, we didn't change this too. + @default 0 + */ cornerRadiusTop: number; /** If bulletsEnabled of ChartCurosor is true, a bullet on each graph follows the cursor. You can set opacity of each graphs bullet. In case you want to disable these bullets for a certain graph, set opacity to 0. @default 1 @@ -2249,55 +2285,108 @@ If you do not set properties such as dashLength, lineAlpha, lineColor, etc - val customBullet: string; /** Name of the custom bullet field in your dataProvider. */ customBulletField: string; - /** Dash length. If you set it to a value greater than 0, the graph line will be dashed. */ + /** Path to the image for legend marker. */ + customMarker: string; + /** Dash length. If you set it to a value greater than 0, the graph line (or columns border) will be dashed. + @default 0 + */ dashLength: number; + /** Name of the dash length field in your dataProvider. This property adds a possibility to change graphs’ line from solid to dashed on any data point. You can also make columns border dashed using this setting. Note, this won't work with smoothedLineGraph. */ + dashLengthField: string; + /** Used to format balloons if value axis is date-based. + @default "MMM DD, YYYY" + */ + dateFormat: string; /** Name of the description field in your dataProvider. */ descriptionField: string; - /** Opacity of fill. Plural form is used to keep the same property names as our Flex charts'. Flex charts can accept array of numbers to generate gradients. Although you can set array here, only first value of this array will be used. */ + /** Name of error value field in your data provider. */ + errorField: string; + /** Opacity of fill. Plural form is used to keep the same property names as our Flex charts'. Flex charts can accept array of numbers to generate gradients. Although you can set array here, only first value of this array will be used. + @default 0 + */ fillAlphas: number; - /** Fill color. Will use lineColor if not set. */ - fillColors: any; - /** Name of the fill colors field in your dataProvider. */ + /** Fill color. Will use lineColor if not set. You can also set array of colors here. */ + fillColors: string; + /** Name of the fill colors field in your dataProvider. This property adds a possibility to change line graphs’ fill color on any data point to create highlighted sections of the graph. Works only with AmSerialChart. */ fillColorsField: string; - /** You can set another graph here and if fillAlpha is >0, the area from this graph to fillToGraph will be filled (instead of filling the area to the X axis). */ + /** XY chart only. If you set this property to id or reference of your X or Y axis, and the fillAlphas is > 0, the area between graph and axis will be filled with color, like in this demo. */ + fillToAxis: ValueAxis; + /** You can set another graph here and if fillAlpha is >0, the area from this graph to fillToGraph will be filled (instead of filling the area to the X axis). This feature is not supported by smoothedLine graphs and Radar chart. */ fillToGraph: AmGraph; + /** Column width in pixels. If you set this property, columns will be of a fixed width and won't adjust to the available space. */ + fixedColumnWidth: number; /** Size of value labels text. Will use chart's fontSize if not set. */ - fontSize: string; - /** Orientation of the gradient fills (only for "column" graph type). Possible values are "vertical" and "horizontal". vertical */ + fontSize: number; + /** If this is set `true`, the graph will always break the line if the distance in time between two adjacent data points is bigger than `gapPeriod x minPeriod`, even if `connect` is set to `true`. + @default false + */ + forceGap: boolean; + /** Name of the gap field in your dataProvider. You can force graph to show gap at a desired data point using this feature. This feature does not work with XY chart. */ + gapField: string; + /** Using this property you can specify when graph should display gap - if the time difference between data points is bigger than duration of minPeriod * gapPeriod, and connect property of a graph is set to false, graph will display gap. + @default 1.1 + */ + gapPeriod: number; + /** Orientation of the gradient fills (only for "column" graph type). Possible values are "vertical" and "horizontal". + @default "vertical" + */ gradientOrientation: string; - /** Specifies whether the graph is hidden. Do not use this to show/hide the graph, use hideGraph(graph) and showGraph(graph) methods instead. */ + /** Specifies whether the graph is hidden. Do not use this to show/hide the graph, use hideGraph(graph) and showGraph(graph) methods instead. + @default false + */ hidden: boolean; - /** If there are more data points than hideBulletsCount, the bullets will not be shown. 0 means the bullets will always be visible. */ + /** If there are more data points than hideBulletsCount, the bullets will not be shown. 0 means the bullets will always be visible. + @default 0 + */ hideBulletsCount: number; /** Name of the high field (used by candlesticks and ohlc) in your dataProvider. */ highField: string; - - /** Unique id of a graph. It is not required to set one, unless you want to use this graph for as your scrollbar's graph and need to indicate which graph should be used.*/ - id?: string; - + /** Unique id of a graph. It is not required to set one, unless you want to use this graph for as your scrollbar's graph and need to indicate which graph should be used. */ + id: string; /** Whether to include this graph when calculating min and max value of the axis. @default true */ includeInMinMax: boolean; + /** Data label text anchor. + @default "auto" + */ + labelAnchor: string; /** Name of label color field in data provider. */ labelColorField: string; - /** Position of value label. Possible values are: "bottom", "top", "right", "left", "inside", "middle". Sometimes position is changed by the chart, depending on a graph type, rotation, etc. top */ + /** You can use it to format labels of data items in any way you want. Graph will call this function and pass reference to GraphDataItem and formatted text as attributes. This function should return string which will be displayed as label. */ + labelFunction(value: number, valueText: string, valueAxis: ValueAxis): string; + labelFunction(valueText: string, data: Date, valueAxis: ValueAxis): string; + /** Offset of data label. + @default 0 + */ + labelOffset: number; + /** Position of value label. Possible values are: "bottom", "top", "right", "left", "inside", "middle". Sometimes position is changed by the chart, depending on a graph type, rotation, etc. + @default "top" + */ labelPosition: string; + /** Rotation of a data label. + @default 0 + */ + labelRotation: number; /** Value label text. You can use tags like [[value]], [[description]], [[percents]], [[open]], [[category]]. */ labelText: string; /** Legend marker opacity. Will use lineAlpha if not set. Value range is 0 - 1. */ legendAlpha: number; /** Legend marker color. Will use lineColor if not set. */ legendColor: string; + /** It is called and the following attributes are passed: dataItem, formattedText, periodValues, periodPercentValues. It should return hex color code which will be used for legend marker. */ + legendColorFunction: Object; + /** The text which will be displayed in the value portion of the legend when user is not hovering above any data point. The tags should be made out of two parts - the name of a field (value / open / close / high / low) and the value of the period you want to be show - open / close / high / low / sum / average / count. For example: [[value.sum]] means that sum of all data points of value field in the selected period will be displayed. */ + legendPeriodValueText: string; /** Legend value text. You can use tags like [[value]], [[description]], [[percents]], [[open]], [[category]] You can also use custom fields from your dataProvider. If not set, uses Legend's valueText. */ legendValueText: string; /** Opacity of the line (or column border). Value range is 0 - 1. @default 1 */ lineAlpha: number; - /** Color of the line (or column border). If you do not set any, the color from [[AmCoordinateChart */ + /** Color of the line (or column border). If you do not set any, the color from AmCoordinateChart.colors array will be used for each subsequent graph. */ lineColor: string; - /** Name of the line color field (used by columns and candlesticks only) in your dataProvider. */ + /** Name of the line color field in your dataProvider. This property adds a possibility to change graphs’ line color on any data point to create highlighted sections of the graph. Works only with AmSerialChart. */ lineColorField: string; /** Specifies thickness of the graph line (or column border). @default 1 @@ -2305,55 +2394,125 @@ If you do not set properties such as dashLength, lineAlpha, lineColor, etc - val lineThickness: number; /** Name of the low field (used by candlesticks and ohlc) in your dataProvider. */ lowField: string; - /** Legend marker type. You can set legend marker (key) type for individual graphs. Possible values are: "square", "circle", "line", "dashedLine", "triangleUp", "triangleDown", "bubble". */ + /** Legend marker type. You can set legend marker (key) type for individual graphs. Possible values are: square, circle, diamond, triangleUp, triangleDown, triangleLeft, triangleDown, bubble, line, none. */ markerType: string; /** Specifies size of the bullet which value is the biggest (XY chart). @default 50 */ maxBulletSize: number; - /** Specifies minimum size of the bullet (XY chart). */ + /** Specifies minimum size of the bullet (XY chart). + @default 4 + */ minBulletSize: number; - /** If you use different colors for your negative values, a graph below zero line is filled with negativeColor. With this property you can define a different base value at which colors should be changed to negative colors. */ + /** It is useful if you have really lots of data points. Based on this property the graph will omit some of the lines (if the distance between points is less that minDistance, in pixels). This will not affect the bullets or indicator in anyway, so the user will not see any difference (unless you set minValue to a bigger value, let say 5), but will increase performance as less lines will be drawn. By setting value to a bigger number you can also make your lines look less jagged. + @default 1 + */ + minDistance: number; + /** If you use different colors for your negative values, a graph below zero line is filled with negativeColor. With this property you can define a different base value at which colors should be changed to negative colors. + @default 0 + */ negativeBase: number; /** Fill opacity of negative part of the graph. Will use fillAlphas if not set. */ negativeFillAlphas: number; /** Fill color of negative part of the graph. Will use fillColors if not set. */ - negativeFillColors: any; //String /Array; + negativeFillColors: string; + /** Opacity of the negative portion of the line (or column border). Value range is 0 - 1. + @default 1 + */ + negativeLineAlpha: number; /** Color of the line (or column) when the values are negative. In case the graph type is candlestick or ohlc, negativeLineColor is used when close value is less then open value. */ negativeLineColor: string; - /** Example: {precision:-1, decimalSeparator:'.', thousandsSeparator:','}. The graph uses this object's values to format the numbers. Uses chart's numberFormatter if not defined. */ - numberFormatter: Object; - /** If you set it to true, column chart will begin new stack. This allows having Clustered and Stacked column/bar chart. */ - newStack: boolean; - /** Name of the open field (used by floating columns, candlesticks and ohlc) in your dataProvider. - @default 50 + /** If you set it to true, column chart will begin new stack. This allows having Clustered and Stacked column/bar chart. + @default false */ + newStack: boolean; + /** In case you want to have a step line graph without risers, you should set this to true. + @default false + */ + noStepRisers: boolean; + /** Name of the open field (used by floating columns, candlesticks and ohlc) in your dataProvider. */ openField: string; - /**Precision of values. Will use chart's precision if not set any.*/ - precision: number; - /** Specifies where data points should be placed - on the beginning of the period (day, hour, etc) or in the middle (only when parseDates property of categoryAxis is set to true). This setting affects Serial chart only. Possible values are "start" and "middle". middle */ + /** Value of pattern should be object with url, width, height of an image, optionally it might have x, y, randomX and randomY values. For example: {"url":"../amcharts/patterns/black/pattern1.png", "width":4, "height":4}. If you want to have individual patterns for each column, define patterns in data provider and set graph.patternField property. Check amcharts/patterns folder for some patterns. You can create your own patterns and use them. Note, x, y, randomX and randomY properties won't work with IE8 and older. 3D bar/Pie charts won't work properly with patterns. */ + pattern: Object; + /** Field name in your data provider which holds pattern information. Value of pattern should be object with url, width, height of an image, optionally it might have x, y, randomX and randomY values. For example: {"url":"../amcharts/patterns/black/pattern1.png", "width":4, "height":4}. Check amcharts/patterns folder for some patterns. You can create your own patterns and use them. Note, x, y, randomX and randomY properties won't work with IE8 and older. 3D bar/Pie charts won't work properly with patterns. */ + patternField: string; + /** This property can be used by step graphs - you can set how many periods one horizontal line should span. + @default 1 + */ + periodSpan: number; + /** Specifies where data points should be placed - on the beginning of the period (day, hour, etc) or in the middle (only when parseDates property of categoryAxis is set to true). This setting affects Serial chart only. Possible values are "start", "middle" and "end" + @default "middle" + */ pointPosition: string; - /** If graph's type is column and labelText is set, graph hides labels which do not fit into the column's space. If you don't want these labels to be hidden, set this to true. */ + /** Precision of values. Will use chart's precision if not set any. */ + precision: number; + /** If this is set to true, candlesticks will be colored in a different manner - if current close is less than current open, the candlestick will be empty, otherwise - filled with color. If previous close is less than current close, the candlestick will use positive color, otherwise - negative color. + @default false + */ + proCandlesticks: boolean; + /** Gantt chart only. Contains unmodified segment object from data provider. */ + segmentData: Object; + /** If graph's type is column and labelText is set, graph hides labels which do not fit into the column's space or go outside plot area. If you don't want these labels to be hidden, set this to true. + @default false + */ showAllValueLabels: boolean; /** Specifies whether the value balloon of this graph is shown when mouse is over data item or chart's indicator is over some series. @default true */ showBalloon: boolean; - /** Specifies graphs value at which cursor is showed. This is only important for candlestick and ohlc charts, also if column chart has "open" value. Possible values are: "open", "close", "high", "low". close */ + /** Specifies graphs value at which cursor is showed. This is only important for candlestick and ohlc charts, also if column chart has "open" value. Possible values are: "open", "close", "high", "low". "top" and "bottom" values will glue the balloon to top/bottom of the plot area. + @default "close" + */ showBalloonAt: string; + /** Works with candlestick graph type, you can set it to open, close, high, low. If you set it to high, the events will be shown at the tip of the high line. + @default "close" + */ + showBulletsAt: string; + /** If you want mouse pointer to change to hand when hovering the graph, set this property to true. + @default false + */ + showHandOnHover: boolean; + /** It can only be used together with topRadius (when columns look like cylinders). If you set it to true, the cylinder will be lowered down so that the center of it's bottom circle would be right on category axis. + @default false + */ + showOnAxis: boolean; /** If the value axis of this graph has stack types like "regular" or "100%" You can exclude this graph from stacking. @default true */ stackable: boolean; + /** Step graph only. Specifies to which direction step should be drawn. + @default "right" + */ + stepDirection: string; + /** If you set it to false, the graph will not be hidden when user clicks on legend entry. + @default true + */ + switchable: boolean; + /** In case you set it to some number, the chart will set focus on bullet/column (starting from first) when user clicks tab key. When a focus is set, screen readers like NVDA Screen reader will read label which is set using accessibleLabel property of AmGraph. Note, not all browsers and readers support this. */ + tabIndex: number; /** Graph title. */ title: string; - /** Type of the graph. Possible values are: "line", "column", "step", "smoothedLine", "candlestick", "ohlc". XY and Radar charts can only display "line" type graphs. line */ + /** If you set this to 1, columns will become cylinders (must set depth3D and angle properties of a chart to >0 values in order this to be visible). you can make columns look like cones (set topRadius to 0) or even like some glasses (set to bigger than 1). We strongly recommend setting grid opacity to 0 in order this to look good. */ + topRadius: number; + /** Type of the graph. Possible values are: "line", "column", "step", "smoothedLine", "candlestick", "ohlc". XY and Radar charts can only display "line" type graphs. + @default "line" + */ type: string; /** Name of the url field in your dataProvider. */ urlField: string; /** Target to open URLs in, i.e. _blank, _top, etc. */ urlTarget: string; - /** Specifies which value axis the graph will use. Will use the first value axis if not set. */ + /** If set to true, the bullet border will take the same color as graph line. + @default false + */ + useLineColorForBulletBorder: boolean; + /** If negativeLineColor and/or negativeFillColors are set and useNegativeColorIfDown is set to true (default is false), the line, step and column graphs will use these colors for lines, bullets or columns if previous value is bigger than current value. In case you set openField for the graph, the graph will compare current value with openField value instead of comparing to previous value. Here is a demo. + @default false + */ + useNegativeColorIfDown: boolean; + /** Specifies which value axis the graph will use. Will use the first value axis if not set. You can use reference to the real ValueAxis object or set value axis id. + @default ValueAxis + */ valueAxis: ValueAxis; /** Name of the value field in your dataProvider. */ valueField: string; @@ -2361,11 +2520,15 @@ If you do not set properties such as dashLength, lineAlpha, lineColor, etc - val @default true */ visibleInLegend: boolean; - /** XY chart only. A horizontal value axis object to attach graph to. */ + /** XY chart only. A horizontal value axis object to attach graph to. + @default ValueAxis + */ xAxis: ValueAxis; /** XY chart only. Name of the x field in your dataProvider. */ xField: string; - /** XY chart only. A vertical value axis object to attach graph to. */ + /** XY chart only. A vertical value axis object to attach graph to. + @default ValueAxis + */ yAxis: ValueAxis; /** XY chart only. Name of the y field in your dataProvider. */ yField: string; diff --git a/types/amqplib/index.d.ts b/types/amqplib/index.d.ts index 91060d23b0..2d5cb3ba99 100644 --- a/types/amqplib/index.d.ts +++ b/types/amqplib/index.d.ts @@ -63,4 +63,4 @@ export interface ConfirmChannel extends Channel { waitForConfirms(): Promise; } -export function connect(url: string, socketOptions?: any): Promise; +export function connect(url: string | Options.Connect, socketOptions?: any): Promise; diff --git a/types/amqplib/properties.d.ts b/types/amqplib/properties.d.ts index 12514d7810..af90909d8c 100644 --- a/types/amqplib/properties.d.ts +++ b/types/amqplib/properties.d.ts @@ -21,6 +21,64 @@ export namespace Replies { } export namespace Options { + interface Connect { + /** + * The to be used protocol + * + * Default value: 'amqp' + */ + protocol?: string; + /** + * Hostname used for connecting to the server. + * + * Default value: 'localhost' + */ + hostname?: string; + /** + * Port used for connecting to the server. + * + * Default value: 5672 + */ + port?: number; + /** + * Username used for authenticating against the server. + * + * Default value: 'guest' + */ + username?: string; + /** + * Password used for authenticating against the server. + * + * Default value: 'guest' + */ + password?: string; + /** + * The desired locale for error messages. RabbitMQ only ever uses en_US + * + * Default value: 'en_US' + */ + locale?: string; + /** + * The size in bytes of the maximum frame allowed over the connection. 0 means + * no limit (but since frames have a size field which is an unsigned 32 bit integer, it’s perforce 2^32 - 1). + * + * Default value: 0x1000 (4kb) - That's the allowed minimum, it will fit many purposes + */ + frameMax?: number; + /** + * The period of the connection heartbeat in seconds. + * + * Default value: 0 + */ + heartbeat?: number; + /** + * What VHost shall be used. + * + * Default value: '/' + */ + vhost?: string; + } + interface AssertQueue { exclusive?: boolean; durable?: boolean; @@ -85,4 +143,4 @@ export interface Message { content: Buffer; fields: any; properties: any; -} \ No newline at end of file +} diff --git a/types/angular-material/angular-material-tests.ts b/types/angular-material/angular-material-tests.ts index ce5a9bf71e..ac4a1386cd 100644 --- a/types/angular-material/angular-material-tests.ts +++ b/types/angular-material/angular-material-tests.ts @@ -140,6 +140,9 @@ myApp.controller('DialogController', ($scope: TestScope, $mdDialog: ng.material. $scope['promptDialog'] = () => { $mdDialog.show($mdDialog.prompt().initialValue('Buddy')); }; + $scope['promptDialog'] = () => { + $mdDialog.show($mdDialog.prompt().required(true)); + }; $scope['prerenderedDialog'] = () => { $mdDialog.show({ template: 'Hello!', diff --git a/types/angular-material/index.d.ts b/types/angular-material/index.d.ts index 2dca0c66da..92f6d46751 100644 --- a/types/angular-material/index.d.ts +++ b/types/angular-material/index.d.ts @@ -80,6 +80,7 @@ declare module 'angular' { interface IPromptDialog extends IPresetDialog { cancel(cancel: string): IPromptDialog; + required(required: boolean): IPromptDialog; // default: false placeholder(placeholder: string): IPromptDialog; initialValue(initialValue: string): IPromptDialog; } diff --git a/types/angular-sanitize/angular-sanitize-tests.ts b/types/angular-sanitize/angular-sanitize-tests.ts index b093f2bbb0..51d48db90d 100644 --- a/types/angular-sanitize/angular-sanitize-tests.ts +++ b/types/angular-sanitize/angular-sanitize-tests.ts @@ -4,5 +4,6 @@ declare var $sanitizeService: ng.sanitize.ISanitizeService; shouldBeString = $sanitizeService(shouldBeString); declare var $linky: ng.sanitize.filter.ILinky; +shouldBeString = $linky(shouldBeString); shouldBeString = $linky(shouldBeString, "target"); shouldBeString = $linky(shouldBeString, shouldBeString); diff --git a/types/angular-sanitize/index.d.ts b/types/angular-sanitize/index.d.ts index ad42ec362e..b9d16aaeb2 100644 --- a/types/angular-sanitize/index.d.ts +++ b/types/angular-sanitize/index.d.ts @@ -36,7 +36,7 @@ declare module 'angular' { * see https://docs.angularjs.org/api/ngSanitize/filter/linky */ interface ILinky { - (text: string, target: string, attributes?: { [attribute: string]: string } | ((url: string) => { [attribute: string]: string })): string; + (text: string, target?: string, attributes?: { [attribute: string]: string } | ((url: string) => { [attribute: string]: string })): string; } } diff --git a/types/applicationinsights-js/index.d.ts b/types/applicationinsights-js/index.d.ts index 17137d67dd..4214837ddf 100644 --- a/types/applicationinsights-js/index.d.ts +++ b/types/applicationinsights-js/index.d.ts @@ -777,7 +777,7 @@ declare module Microsoft.ApplicationInsights { * @param authenticatedUserId {string} - The authenticated user id. A unique and persistent string that represents each authenticated user in the service. * @param accountId {string} - An optional string to represent the account associated with the authenticated user. */ - setAuthenticatedUserContext(authenticatedUserId: string, accountId?: string): any; + setAuthenticatedUserContext(authenticatedUserId: string, accountId?: string, storeInCookie?: boolean): any; /** * Clears the authenticated user id and the account id from the user context. */ diff --git a/types/atom/index.d.ts b/types/atom/index.d.ts index 0db2ab0002..2a13373b7d 100644 --- a/types/atom/index.d.ts +++ b/types/atom/index.d.ts @@ -5265,7 +5265,7 @@ export interface CursorPositionChangedEvent { newBufferPosition: Point; newScreenPosition: Point; textChanged: boolean; - Cursor: Cursor; + cursor: Cursor; } export interface DecorationPropsChangedEvent { diff --git a/types/autobahn/index.d.ts b/types/autobahn/index.d.ts index 7f01a53e3a..969c703478 100644 --- a/types/autobahn/index.d.ts +++ b/types/autobahn/index.d.ts @@ -1,6 +1,6 @@ // Type definitions for AutobahnJS v0.9.7 // Project: http://autobahn.ws/js/ -// Definitions by: Elad Zelingher , Andy Hawkins , Wladimir Totino +// Definitions by: Elad Zelingher , Andy Hawkins , Wladimir Totino , Mathias Teier // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped /// @@ -179,6 +179,7 @@ declare namespace autobahn { interface ISubscribeOptions { match?: string; + get_retained?: boolean; } interface IRegisterOptions { diff --git a/types/babel-traverse/index.d.ts b/types/babel-traverse/index.d.ts index 682550b161..df420c17bd 100644 --- a/types/babel-traverse/index.d.ts +++ b/types/babel-traverse/index.d.ts @@ -600,185 +600,185 @@ export class NodePath { addComments(type: string, comments: any[]): void; // ------------------------- isXXX ------------------------- - isArrayExpression(opts?: object): boolean; - isAssignmentExpression(opts?: object): boolean; - isBinaryExpression(opts?: object): boolean; - isDirective(opts?: object): boolean; - isDirectiveLiteral(opts?: object): boolean; - isBlockStatement(opts?: object): boolean; - isBreakStatement(opts?: object): boolean; - isCallExpression(opts?: object): boolean; - isCatchClause(opts?: object): boolean; - isConditionalExpression(opts?: object): boolean; - isContinueStatement(opts?: object): boolean; - isDebuggerStatement(opts?: object): boolean; - isDoWhileStatement(opts?: object): boolean; - isEmptyStatement(opts?: object): boolean; - isExpressionStatement(opts?: object): boolean; - isFile(opts?: object): boolean; - isForInStatement(opts?: object): boolean; - isForStatement(opts?: object): boolean; - isFunctionDeclaration(opts?: object): boolean; - isFunctionExpression(opts?: object): boolean; - isIdentifier(opts?: object): boolean; - isIfStatement(opts?: object): boolean; - isLabeledStatement(opts?: object): boolean; - isStringLiteral(opts?: object): boolean; - isNumericLiteral(opts?: object): boolean; - isNullLiteral(opts?: object): boolean; - isBooleanLiteral(opts?: object): boolean; - isRegExpLiteral(opts?: object): boolean; - isLogicalExpression(opts?: object): boolean; - isMemberExpression(opts?: object): boolean; - isNewExpression(opts?: object): boolean; - isProgram(opts?: object): boolean; - isObjectExpression(opts?: object): boolean; - isObjectMethod(opts?: object): boolean; - isObjectProperty(opts?: object): boolean; - isRestElement(opts?: object): boolean; - isReturnStatement(opts?: object): boolean; - isSequenceExpression(opts?: object): boolean; - isSwitchCase(opts?: object): boolean; - isSwitchStatement(opts?: object): boolean; - isThisExpression(opts?: object): boolean; - isThrowStatement(opts?: object): boolean; - isTryStatement(opts?: object): boolean; - isUnaryExpression(opts?: object): boolean; - isUpdateExpression(opts?: object): boolean; - isVariableDeclaration(opts?: object): boolean; - isVariableDeclarator(opts?: object): boolean; - isWhileStatement(opts?: object): boolean; - isWithStatement(opts?: object): boolean; - isAssignmentPattern(opts?: object): boolean; - isArrayPattern(opts?: object): boolean; - isArrowFunctionExpression(opts?: object): boolean; - isClassBody(opts?: object): boolean; - isClassDeclaration(opts?: object): boolean; - isClassExpression(opts?: object): boolean; - isExportAllDeclaration(opts?: object): boolean; - isExportDefaultDeclaration(opts?: object): boolean; - isExportNamedDeclaration(opts?: object): boolean; - isExportSpecifier(opts?: object): boolean; - isForOfStatement(opts?: object): boolean; - isImportDeclaration(opts?: object): boolean; - isImportDefaultSpecifier(opts?: object): boolean; - isImportNamespaceSpecifier(opts?: object): boolean; - isImportSpecifier(opts?: object): boolean; - isMetaProperty(opts?: object): boolean; - isClassMethod(opts?: object): boolean; - isObjectPattern(opts?: object): boolean; - isSpreadElement(opts?: object): boolean; - isSuper(opts?: object): boolean; - isTaggedTemplateExpression(opts?: object): boolean; - isTemplateElement(opts?: object): boolean; - isTemplateLiteral(opts?: object): boolean; - isYieldExpression(opts?: object): boolean; - isAnyTypeAnnotation(opts?: object): boolean; - isArrayTypeAnnotation(opts?: object): boolean; - isBooleanTypeAnnotation(opts?: object): boolean; - isBooleanLiteralTypeAnnotation(opts?: object): boolean; - isNullLiteralTypeAnnotation(opts?: object): boolean; - isClassImplements(opts?: object): boolean; - isClassProperty(opts?: object): boolean; - isDeclareClass(opts?: object): boolean; - isDeclareFunction(opts?: object): boolean; - isDeclareInterface(opts?: object): boolean; - isDeclareModule(opts?: object): boolean; - isDeclareTypeAlias(opts?: object): boolean; - isDeclareVariable(opts?: object): boolean; - isExistentialTypeParam(opts?: object): boolean; - isFunctionTypeAnnotation(opts?: object): boolean; - isFunctionTypeParam(opts?: object): boolean; - isGenericTypeAnnotation(opts?: object): boolean; - isInterfaceExtends(opts?: object): boolean; - isInterfaceDeclaration(opts?: object): boolean; - isIntersectionTypeAnnotation(opts?: object): boolean; - isMixedTypeAnnotation(opts?: object): boolean; - isNullableTypeAnnotation(opts?: object): boolean; - isNumericLiteralTypeAnnotation(opts?: object): boolean; - isNumberTypeAnnotation(opts?: object): boolean; - isStringLiteralTypeAnnotation(opts?: object): boolean; - isStringTypeAnnotation(opts?: object): boolean; - isThisTypeAnnotation(opts?: object): boolean; - isTupleTypeAnnotation(opts?: object): boolean; - isTypeofTypeAnnotation(opts?: object): boolean; - isTypeAlias(opts?: object): boolean; - isTypeAnnotation(opts?: object): boolean; - isTypeCastExpression(opts?: object): boolean; - isTypeParameterDeclaration(opts?: object): boolean; - isTypeParameterInstantiation(opts?: object): boolean; - isObjectTypeAnnotation(opts?: object): boolean; - isObjectTypeCallProperty(opts?: object): boolean; - isObjectTypeIndexer(opts?: object): boolean; - isObjectTypeProperty(opts?: object): boolean; - isQualifiedTypeIdentifier(opts?: object): boolean; - isUnionTypeAnnotation(opts?: object): boolean; - isVoidTypeAnnotation(opts?: object): boolean; - isJSXAttribute(opts?: object): boolean; - isJSXClosingElement(opts?: object): boolean; - isJSXElement(opts?: object): boolean; - isJSXEmptyExpression(opts?: object): boolean; - isJSXExpressionContainer(opts?: object): boolean; - isJSXIdentifier(opts?: object): boolean; - isJSXMemberExpression(opts?: object): boolean; - isJSXNamespacedName(opts?: object): boolean; - isJSXOpeningElement(opts?: object): boolean; - isJSXSpreadAttribute(opts?: object): boolean; - isJSXText(opts?: object): boolean; - isNoop(opts?: object): boolean; - isParenthesizedExpression(opts?: object): boolean; - isAwaitExpression(opts?: object): boolean; - isBindExpression(opts?: object): boolean; - isDecorator(opts?: object): boolean; - isDoExpression(opts?: object): boolean; - isExportDefaultSpecifier(opts?: object): boolean; - isExportNamespaceSpecifier(opts?: object): boolean; - isRestProperty(opts?: object): boolean; - isSpreadProperty(opts?: object): boolean; - isExpression(opts?: object): boolean; - isBinary(opts?: object): boolean; - isScopable(opts?: object): boolean; - isBlockParent(opts?: object): boolean; - isBlock(opts?: object): boolean; - isStatement(opts?: object): boolean; - isTerminatorless(opts?: object): boolean; - isCompletionStatement(opts?: object): boolean; - isConditional(opts?: object): boolean; - isLoop(opts?: object): boolean; - isWhile(opts?: object): boolean; - isExpressionWrapper(opts?: object): boolean; - isFor(opts?: object): boolean; - isForXStatement(opts?: object): boolean; - isFunction(opts?: object): boolean; - isFunctionParent(opts?: object): boolean; - isPureish(opts?: object): boolean; - isDeclaration(opts?: object): boolean; - isLVal(opts?: object): boolean; - isLiteral(opts?: object): boolean; - isImmutable(opts?: object): boolean; - isUserWhitespacable(opts?: object): boolean; - isMethod(opts?: object): boolean; - isObjectMember(opts?: object): boolean; - isProperty(opts?: object): boolean; - isUnaryLike(opts?: object): boolean; - isPattern(opts?: object): boolean; - isClass(opts?: object): boolean; - isModuleDeclaration(opts?: object): boolean; - isExportDeclaration(opts?: object): boolean; - isModuleSpecifier(opts?: object): boolean; - isFlow(opts?: object): boolean; - isFlowBaseAnnotation(opts?: object): boolean; - isFlowDeclaration(opts?: object): boolean; - isJSX(opts?: object): boolean; - isNumberLiteral(opts?: object): boolean; - isRegexLiteral(opts?: object): boolean; - isReferencedIdentifier(opts?: object): boolean; - isReferencedMemberExpression(opts?: object): boolean; - isBindingIdentifier(opts?: object): boolean; - isScope(opts?: object): boolean; + isArrayExpression(opts?: object): this is NodePath ; + isAssignmentExpression(opts?: object): this is NodePath; + isBinaryExpression(opts?: object): this is NodePath; + isDirective(opts?: object): this is NodePath; + isDirectiveLiteral(opts?: object): this is NodePath; + isBlockStatement(opts?: object): this is NodePath; + isBreakStatement(opts?: object): this is NodePath; + isCallExpression(opts?: object): this is NodePath; + isCatchClause(opts?: object): this is NodePath; + isConditionalExpression(opts?: object): this is NodePath; + isContinueStatement(opts?: object): this is NodePath; + isDebuggerStatement(opts?: object): this is NodePath; + isDoWhileStatement(opts?: object): this is NodePath; + isEmptyStatement(opts?: object): this is NodePath; + isExpressionStatement(opts?: object): this is NodePath; + isFile(opts?: object): this is NodePath; + isForInStatement(opts?: object): this is NodePath; + isForStatement(opts?: object): this is NodePath; + isFunctionDeclaration(opts?: object): this is NodePath; + isFunctionExpression(opts?: object): this is NodePath; + isIdentifier(opts?: object): this is NodePath; + isIfStatement(opts?: object): this is NodePath; + isLabeledStatement(opts?: object): this is NodePath; + isStringLiteral(opts?: object): this is NodePath; + isNumericLiteral(opts?: object): this is NodePath; + isNullLiteral(opts?: object): this is NodePath; + isBooleanLiteral(opts?: object): this is NodePath; + isRegExpLiteral(opts?: object): this is NodePath; + isLogicalExpression(opts?: object): this is NodePath; + isMemberExpression(opts?: object): this is NodePath; + isNewExpression(opts?: object): this is NodePath; + isProgram(opts?: object): this is NodePath; + isObjectExpression(opts?: object): this is NodePath; + isObjectMethod(opts?: object): this is NodePath; + isObjectProperty(opts?: object): this is NodePath; + isRestElement(opts?: object): this is NodePath; + isReturnStatement(opts?: object): this is NodePath; + isSequenceExpression(opts?: object): this is NodePath; + isSwitchCase(opts?: object): this is NodePath; + isSwitchStatement(opts?: object): this is NodePath; + isThisExpression(opts?: object): this is NodePath; + isThrowStatement(opts?: object): this is NodePath; + isTryStatement(opts?: object): this is NodePath; + isUnaryExpression(opts?: object): this is NodePath; + isUpdateExpression(opts?: object): this is NodePath; + isVariableDeclaration(opts?: object): this is NodePath; + isVariableDeclarator(opts?: object): this is NodePath; + isWhileStatement(opts?: object): this is NodePath; + isWithStatement(opts?: object): this is NodePath; + isAssignmentPattern(opts?: object): this is NodePath; + isArrayPattern(opts?: object): this is NodePath; + isArrowFunctionExpression(opts?: object): this is NodePath; + isClassBody(opts?: object): this is NodePath; + isClassDeclaration(opts?: object): this is NodePath; + isClassExpression(opts?: object): this is NodePath; + isExportAllDeclaration(opts?: object): this is NodePath; + isExportDefaultDeclaration(opts?: object): this is NodePath; + isExportNamedDeclaration(opts?: object): this is NodePath; + isExportSpecifier(opts?: object): this is NodePath; + isForOfStatement(opts?: object): this is NodePath; + isImportDeclaration(opts?: object): this is NodePath; + isImportDefaultSpecifier(opts?: object): this is NodePath; + isImportNamespaceSpecifier(opts?: object): this is NodePath; + isImportSpecifier(opts?: object): this is NodePath; + isMetaProperty(opts?: object): this is NodePath; + isClassMethod(opts?: object): this is NodePath; + isObjectPattern(opts?: object): this is NodePath; + isSpreadElement(opts?: object): this is NodePath; + isSuper(opts?: object): this is NodePath; + isTaggedTemplateExpression(opts?: object): this is NodePath; + isTemplateElement(opts?: object): this is NodePath; + isTemplateLiteral(opts?: object): this is NodePath; + isYieldExpression(opts?: object): this is NodePath; + isAnyTypeAnnotation(opts?: object): this is NodePath; + isArrayTypeAnnotation(opts?: object): this is NodePath; + isBooleanTypeAnnotation(opts?: object): this is NodePath; + isBooleanLiteralTypeAnnotation(opts?: object): this is NodePath; + isNullLiteralTypeAnnotation(opts?: object): this is NodePath; + isClassImplements(opts?: object): this is NodePath; + isClassProperty(opts?: object): this is NodePath; + isDeclareClass(opts?: object): this is NodePath; + isDeclareFunction(opts?: object): this is NodePath; + isDeclareInterface(opts?: object): this is NodePath; + isDeclareModule(opts?: object): this is NodePath; + isDeclareTypeAlias(opts?: object): this is NodePath; + isDeclareVariable(opts?: object): this is NodePath; + isExistentialTypeParam(opts?: object): this is NodePath; + isFunctionTypeAnnotation(opts?: object): this is NodePath; + isFunctionTypeParam(opts?: object): this is NodePath; + isGenericTypeAnnotation(opts?: object): this is NodePath; + isInterfaceExtends(opts?: object): this is NodePath; + isInterfaceDeclaration(opts?: object): this is NodePath; + isIntersectionTypeAnnotation(opts?: object): this is NodePath; + isMixedTypeAnnotation(opts?: object): this is NodePath; + isNullableTypeAnnotation(opts?: object): this is NodePath; + isNumericLiteralTypeAnnotation(opts?: object): this is NodePath; + isNumberTypeAnnotation(opts?: object): this is NodePath; + isStringLiteralTypeAnnotation(opts?: object): this is NodePath; + isStringTypeAnnotation(opts?: object): this is NodePath; + isThisTypeAnnotation(opts?: object): this is NodePath; + isTupleTypeAnnotation(opts?: object): this is NodePath; + isTypeofTypeAnnotation(opts?: object): this is NodePath; + isTypeAlias(opts?: object): this is NodePath; + isTypeAnnotation(opts?: object): this is NodePath; + isTypeCastExpression(opts?: object): this is NodePath; + isTypeParameterDeclaration(opts?: object): this is NodePath; + isTypeParameterInstantiation(opts?: object): this is NodePath; + isObjectTypeAnnotation(opts?: object): this is NodePath; + isObjectTypeCallProperty(opts?: object): this is NodePath; + isObjectTypeIndexer(opts?: object): this is NodePath; + isObjectTypeProperty(opts?: object): this is NodePath; + isQualifiedTypeIdentifier(opts?: object): this is NodePath; + isUnionTypeAnnotation(opts?: object): this is NodePath; + isVoidTypeAnnotation(opts?: object): this is NodePath; + isJSXAttribute(opts?: object): this is NodePath; + isJSXClosingElement(opts?: object): this is NodePath; + isJSXElement(opts?: object): this is NodePath; + isJSXEmptyExpression(opts?: object): this is NodePath; + isJSXExpressionContainer(opts?: object): this is NodePath; + isJSXIdentifier(opts?: object): this is NodePath; + isJSXMemberExpression(opts?: object): this is NodePath; + isJSXNamespacedName(opts?: object): this is NodePath; + isJSXOpeningElement(opts?: object): this is NodePath; + isJSXSpreadAttribute(opts?: object): this is NodePath; + isJSXText(opts?: object): this is NodePath; + isNoop(opts?: object): this is NodePath; + isParenthesizedExpression(opts?: object): this is NodePath; + isAwaitExpression(opts?: object): this is NodePath; + isBindExpression(opts?: object): this is NodePath; + isDecorator(opts?: object): this is NodePath; + isDoExpression(opts?: object): this is NodePath; + isExportDefaultSpecifier(opts?: object): this is NodePath; + isExportNamespaceSpecifier(opts?: object): this is NodePath; + isRestProperty(opts?: object): this is NodePath; + isSpreadProperty(opts?: object): this is NodePath; + isExpression(opts?: object): this is NodePath; + isBinary(opts?: object): this is NodePath; + isScopable(opts?: object): this is NodePath; + isBlockParent(opts?: object): this is NodePath; + isBlock(opts?: object): this is NodePath; + isStatement(opts?: object): this is NodePath; + isTerminatorless(opts?: object): this is NodePath; + isCompletionStatement(opts?: object): this is NodePath; + isConditional(opts?: object): this is NodePath; + isLoop(opts?: object): this is NodePath; + isWhile(opts?: object): this is NodePath; + isExpressionWrapper(opts?: object): this is NodePath; + isFor(opts?: object): this is NodePath; + isForXStatement(opts?: object): this is NodePath; + isFunction(opts?: object): this is NodePath; + isFunctionParent(opts?: object): this is NodePath; + isPureish(opts?: object): this is NodePath; + isDeclaration(opts?: object): this is NodePath; + isLVal(opts?: object): this is NodePath; + isLiteral(opts?: object): this is NodePath; + isImmutable(opts?: object): this is NodePath; + isUserWhitespacable(opts?: object): this is NodePath; + isMethod(opts?: object): this is NodePath; + isObjectMember(opts?: object): this is NodePath; + isProperty(opts?: object): this is NodePath; + isUnaryLike(opts?: object): this is NodePath; + isPattern(opts?: object): this is NodePath; + isClass(opts?: object): this is NodePath; + isModuleDeclaration(opts?: object): this is NodePath; + isExportDeclaration(opts?: object): this is NodePath; + isModuleSpecifier(opts?: object): this is NodePath; + isFlow(opts?: object): this is NodePath; + isFlowBaseAnnotation(opts?: object): this is NodePath; + isFlowDeclaration(opts?: object): this is NodePath; + isJSX(opts?: object): this is NodePath; + isNumberLiteral(opts?: object): this is NodePath; + isRegexLiteral(opts?: object): this is NodePath; + isReferencedIdentifier(opts?: object): this is NodePath; + isReferencedMemberExpression(opts?: object): this is NodePath; + isBindingIdentifier(opts?: object): this is NodePath; + isScope(opts?: object): this is NodePath; isReferenced(opts?: object): boolean; - isBlockScoped(opts?: object): boolean; - isVar(opts?: object): boolean; + isBlockScoped(opts?: object): this is NodePath; + isVar(opts?: object): this is NodePath; isUser(opts?: object): boolean; isGenerated(opts?: object): boolean; isPure(opts?: object): boolean; diff --git a/types/babel-types/index.d.ts b/types/babel-types/index.d.ts index 1879c81e85..a49909ed4a 100644 --- a/types/babel-types/index.d.ts +++ b/types/babel-types/index.d.ts @@ -1265,13 +1265,13 @@ export function isJSX(node: object, opts?: object): node is JSX; export function isNumberLiteral(node: object, opts?: object): node is NumericLiteral; export function isRegexLiteral(node: object, opts?: object): node is RegExpLiteral; -export function isReferencedIdentifier(node: object, opts?: object): boolean; -export function isReferencedMemberExpression(node: object, opts?: object): boolean; -export function isBindingIdentifier(node: object, opts?: object): boolean; -export function isScope(node: object, opts?: object): boolean; +export function isReferencedIdentifier(node: object, opts?: object): node is Identifier | JSXIdentifier; +export function isReferencedMemberExpression(node: object, opts?: object): node is MemberExpression; +export function isBindingIdentifier(node: object, opts?: object): node is Identifier; +export function isScope(node: object, opts?: object): node is Scopable; export function isReferenced(node: object, opts?: object): boolean; -export function isBlockScoped(node: object, opts?: object): boolean; -export function isVar(node: object, opts?: object): boolean; +export function isBlockScoped(node: object, opts?: object): node is FunctionDeclaration | ClassDeclaration | VariableDeclaration; +export function isVar(node: object, opts?: object): node is VariableDeclaration; export function isUser(node: object, opts?: object): boolean; export function isGenerated(node: object, opts?: object): boolean; export function isPure(node: object, opts?: object): boolean; diff --git a/types/backbone/index.d.ts b/types/backbone/index.d.ts index 607f6413fc..1a186d9924 100644 --- a/types/backbone/index.d.ts +++ b/types/backbone/index.d.ts @@ -460,8 +460,7 @@ declare namespace Backbone { } // SYNC - function sync(method: string, model: Model, options?: JQueryAjaxSettings): any; - function sync(method: string, collection: Collection, options?: JQueryAjaxSettings): any; + function sync(method: string, model: Model | Collection, options?: JQueryAjaxSettings): any; function ajax(options?: JQueryAjaxSettings): JQueryXHR; var emulateHTTP: boolean; var emulateJSON: boolean; diff --git a/types/beats/beats-tests.ts b/types/beats/beats-tests.ts new file mode 100644 index 0000000000..00659af2e5 --- /dev/null +++ b/types/beats/beats-tests.ts @@ -0,0 +1,11 @@ +import beats = require('beats'); + +const bins: beats.Bin[] = [ + { lo: 0, hi: 512, threshold: 0, decay: 0.005 }, + { lo: 512, hi: 1024, threshold: 0, decay: 0.005 }, +]; + +const detect = beats(bins, 1); + +const frequencies = new Uint8Array(1024); +const result = detect(frequencies); diff --git a/types/beats/index.d.ts b/types/beats/index.d.ts new file mode 100644 index 0000000000..e95f008c1f --- /dev/null +++ b/types/beats/index.d.ts @@ -0,0 +1,17 @@ +// Type definitions for beats 0.0 +// Project: https://github.com/hughsk/beats/ +// Definitions by: Uri Shaked +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +export = beats; + +declare function beats(bins: ReadonlyArray, minSeparation?: number): (frequencies: Uint8Array | Float32Array | ReadonlyArray, dt?: number) => Float32Array; + +declare namespace beats { + interface Bin { + lo: number; + hi: number; + threshold: number; + decay: number; + } +} diff --git a/types/beats/tsconfig.json b/types/beats/tsconfig.json new file mode 100644 index 0000000000..89bd0b5995 --- /dev/null +++ b/types/beats/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", + "beats-tests.ts" + ] +} diff --git a/types/beats/tslint.json b/types/beats/tslint.json new file mode 100644 index 0000000000..3db14f85ea --- /dev/null +++ b/types/beats/tslint.json @@ -0,0 +1 @@ +{ "extends": "dtslint/dt.json" } diff --git a/types/chai/chai-tests.ts b/types/chai/chai-tests.ts index 0076396422..401e5f468a 100644 --- a/types/chai/chai-tests.ts +++ b/types/chai/chai-tests.ts @@ -1357,6 +1357,56 @@ suite('assert', () => { assert.notInclude(undefined, 'bar'); }); + test('deepInclude', () => { + assert.deepInclude('foobar', 'bar'); + assert.deepInclude([1, 2, 3], 3); + assert.deepInclude('foobar', 'baz'); + assert.deepInclude(undefined, 'bar'); + }); + + test('notDeepInclude', () => { + assert.notDeepInclude('foobar', 'baz'); + assert.notDeepInclude([1, 2, 3], 4); + assert.notDeepInclude('foobar', 'bar'); + assert.notDeepInclude(undefined, 'bar'); + }); + + test('nestedInclude', () => { + 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'}); + }); + + test('deepNestedInclude', () => { + assert.deepNestedInclude({a: {b: [{x: 1}]}}, {'a.b[0]': {x: 1}}); + assert.deepNestedInclude({'.a': {'[b]': {x: 1}}}, {'\\.a.\\[b\\]': {x: 1}}); + }); + + test('notDeepNestedInclude', () => { + assert.notDeepNestedInclude({a: {b: [{x: 1}]}}, {'a.b[0]': {y: 1}}) + assert.notDeepNestedInclude({'.a': {'[b]': {x: 1}}}, {'\\.a.\\[b\\]': {y: 2}}); + }); + + test('ownInclude', () => { + assert.ownInclude({ a: 1 }, { a: 1 }); + }); + + test('notOwnInclude', () => { + assert.notOwnInclude({ a: 1 }, { a: 1 }); + }); + + test('deepOwnInclude', () => { + assert.deepOwnInclude({a: {b: 2}}, {a: {b: 2}}); + }); + + test('notDeepOwnInclude', () => { + assert.notDeepOwnInclude({a: {b: 2}}, {a: {c: 3}}); + }); + test('lengthOf', () => { assert.lengthOf([1, 2, 3], 3); assert.lengthOf('foobar', 6); diff --git a/types/chai/index.d.ts b/types/chai/index.d.ts index 340d69f7cd..faafa3b2a8 100644 --- a/types/chai/index.d.ts +++ b/types/chai/index.d.ts @@ -7,6 +7,7 @@ // Matt Wistrand , // Josh Goldberg // Shaun Luttin +// Gintautas Miselis // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped // @@ -706,13 +707,145 @@ declare namespace Chai { /** * Asserts that haystack does not include needle. * - * @type T Type of values in haystack. * @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; + + /** + * 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. + * + * @param haystack Container string. + * @param needle Potential expected substring of haystack. + * @param message Message to display on error. + */ + deepInclude(haystack: string, needle: string, 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. + * + * @param haystack + * @param needle + * @param message Message to display on error. + */ + deepInclude(haystack: any, 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 Container string. + * @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; + + /** + * Asserts that ‘haystack’ includes ‘needle’. Can be used to assert the inclusion of a subset of properties in an object. + * + * Enables the use of dot- and bracket-notation for referencing nested properties. + * ‘[]’ and ‘.’ in property names can be escaped using double backslashes.Asserts that ‘haystack’ includes ‘needle’. + * Can be used to assert the inclusion of a subset of properties in an object. + * Enables the use of dot- and bracket-notation for referencing nested properties. + * ‘[]’ and ‘.’ in property names can be escaped using double backslashes. + * + * @param haystack + * @param needle + * @param message Message to display on error. + */ + nestedInclude(haystack: any, needle: any, message?: string): void; + + /** + * Asserts that ‘haystack’ does not include ‘needle’. Can be used to assert the absence of a subset of properties in an object. + * + * Enables the use of dot- and bracket-notation for referencing nested properties. + * ‘[]’ and ‘.’ in property names can be escaped using double backslashes.Asserts that ‘haystack’ includes ‘needle’. + * Can be used to assert the inclusion of a subset of properties in an object. + * Enables the use of dot- and bracket-notation for referencing nested properties. + * ‘[]’ and ‘.’ in property names can be escaped using double backslashes. + * + * @param haystack + * @param needle + * @param message Message to display on error. + */ + notNestedInclude(haystack: 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 while checking for deep equality + * + * Enables the use of dot- and bracket-notation for referencing nested properties. + * ‘[]’ and ‘.’ in property names can be escaped using double backslashes.Asserts that ‘haystack’ includes ‘needle’. + * Can be used to assert the inclusion of a subset of properties in an object. + * Enables the use of dot- and bracket-notation for referencing nested properties. + * ‘[]’ and ‘.’ in property names can be escaped using double backslashes. + * + * @param haystack + * @param needle + * @param message Message to display on error. + */ + deepNestedInclude(haystack: any, needle: any, message?: string): void; + + /** + * Asserts that ‘haystack’ does not include ‘needle’. Can be used to assert the absence of a subset of properties in an object while checking for deep equality. + * + * Enables the use of dot- and bracket-notation for referencing nested properties. + * ‘[]’ and ‘.’ in property names can be escaped using double backslashes.Asserts that ‘haystack’ includes ‘needle’. + * Can be used to assert the inclusion of a subset of properties in an object. + * Enables the use of dot- and bracket-notation for referencing nested properties. + * ‘[]’ and ‘.’ in property names can be escaped using double backslashes. + * + * @param haystack + * @param needle + * @param message Message to display on error. + */ + notDeepNestedInclude(haystack: 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 while ignoring inherited properties. + * + * @param haystack + * @param needle + * @param message Message to display on error. + */ + ownInclude(haystack: any, needle: any, message?: string): void; + + /** + * Asserts that ‘haystack’ includes ‘needle’. Can be used to assert the absence of a subset of properties in an object while ignoring inherited properties. + * + * @param haystack + * @param needle + * @param message Message to display on error. + */ + notOwnInclude(haystack: 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 while ignoring inherited properties and checking for deep + * + * @param haystack + * @param needle + * @param message Message to display on error. + */ + deepOwnInclude(haystack: any, needle: any, message?: string): void; + + /** + * Asserts that ‘haystack’ includes ‘needle’. Can be used to assert the absence of a subset of properties in an object while ignoring inherited properties and checking for deep equality. + * + * @param haystack + * @param needle + * @param message Message to display on error. + */ + notDeepOwnInclude(haystack: any, needle: any, message?: string): void; + /** * Asserts that value matches the regular expression regexp. * diff --git a/types/chart.js/index.d.ts b/types/chart.js/index.d.ts index f4f4bda40d..049488f8db 100644 --- a/types/chart.js/index.d.ts +++ b/types/chart.js/index.d.ts @@ -159,6 +159,7 @@ declare namespace Chart { interface ChartOptions { responsive?: boolean; responsiveAnimationDuration?: number; + aspectRatio?: number; maintainAspectRatio?: boolean; events?: string[]; onClick?(event?: MouseEvent, activeElements?: Array<{}>): any; diff --git a/types/cheerio/index.d.ts b/types/cheerio/index.d.ts index 511fce354d..8250848374 100644 --- a/types/cheerio/index.d.ts +++ b/types/cheerio/index.d.ts @@ -263,6 +263,7 @@ interface CheerioElement { parent: CheerioElement; parentNode: CheerioElement; nodeValue: string; + data?: string; } interface CheerioAPI extends CheerioSelector, CheerioStatic { diff --git a/types/ckeditor/index.d.ts b/types/ckeditor/index.d.ts index f26a08a725..20882269fd 100644 --- a/types/ckeditor/index.d.ts +++ b/types/ckeditor/index.d.ts @@ -602,13 +602,17 @@ declare namespace CKEDITOR { browserContextMenuOnCtrl?: boolean; clipboard_defaultContentType?: string; // html | text + clipboard_notificationDuration?: number; codeSnippet_codeClass?: string; codeSnippet_languages?: Object; coceSnippet_theme?: string; colorButton_backStyle?: config.styleObject; colorButton_colors?: string; + colorButton_colorsPerRow?: number; + colorButton_enableAutomatic?: boolean; colorButton_enableMore?: boolean; colorButton_foreStyle?: config.styleObject; + colorButton_normalizeBackground?: boolean; contentsCss?: string | string[]; contentsLangDirection?: string; contentsLanguage?: string; diff --git a/types/codemirror/index.d.ts b/types/codemirror/index.d.ts index 126eafe013..4f479b29d0 100644 --- a/types/codemirror/index.d.ts +++ b/types/codemirror/index.d.ts @@ -105,9 +105,9 @@ declare namespace CodeMirror { function signal(target: any, name: string, ...args: any[]): void; type DOMEvent = 'mousedown' | 'dblclick' | 'touchstart' | 'contextmenu' | 'keydown' | 'keypress' | 'keyup' | 'cut' | 'copy' | 'paste' | 'dragstart' | 'dragenter' | 'dragover' | 'dragleave' | 'drop'; - + type CoordsMode = 'window' | 'page' | 'local'; - + interface Token { /** The character(on the given line) at which the token starts. */ start: number; @@ -202,10 +202,10 @@ declare namespace CodeMirror { /** Compute the line at the given pixel height. mode is the relative element to use to compute this line, it may be "window", "page" (the default), or "local" */ lineAtHeight(height: number, mode?: CoordsMode): number; - - /** Computes the height of the top of a line, in the coordinate system specified by mode, it may be "window", - "page" (the default), or "local". When a line below the bottom of the document is specified, the returned value - is the bottom of the last line in the document. By default, the position of the actual text is returned. + + /** Computes the height of the top of a line, in the coordinate system specified by mode, it may be "window", + "page" (the default), or "local". When a line below the bottom of the document is specified, the returned value + is the bottom of the last line in the document. By default, the position of the actual text is returned. If includeWidgets is true and the line has line widgets, the position above the first line widget is returned. */ heightAtLine(line: any, mode?: CoordsMode, includeWidgets?: boolean): number; @@ -292,7 +292,7 @@ declare namespace CodeMirror { charCoords(pos: CodeMirror.Position, mode?: CoordsMode): { left: number; right: number; top: number; bottom: number; }; /** Given an { left , top } object , returns the { line , ch } position that corresponds to it. - The optional mode parameter determines relative to what the coordinates are interpreted. + The optional mode parameter determines relative to what the coordinates are interpreted. It may be "window", "page" (the default), or "local". */ coordsChar(object: { left: number; top: number; }, mode?: CoordsMode): CodeMirror.Position; @@ -512,7 +512,7 @@ declare namespace CodeMirror { /** Get the currently selected code. */ getSelection(): string; - + /** Returns an array containing a string for each selection, representing the content of the selections. */ getSelections(lineSep?: string): Array; @@ -535,8 +535,14 @@ declare namespace CodeMirror { /** Set the cursor position.You can either pass a single { line , ch } object , or the line and the character as two separate parameters. */ setCursor(pos: CodeMirror.Position): void; - /** Set the selection range.anchor and head should be { line , ch } objects.head defaults to anchor when not given. */ - setSelection(anchor: CodeMirror.Position, head: CodeMirror.Position): void; + /** Set a single selection range. anchor and head should be {line, ch} objects. head defaults to anchor when not given. */ + setSelection(anchor: CodeMirror.Position, head: CodeMirror.Position, options?: { bias?: number, origin?: string, scroll?: boolean }): void; + + /** Sets a new set of selections. There must be at least one selection in the given array. When primary is a + number, it determines which selection is the primary one. When it is not given, the primary index is taken from + the previous selection, or set to the last range if the previous selection had less ranges than the new one. + Supports the same options as setSelection. */ + setSelections(ranges: Array<{ anchor: CodeMirror.Position, head: CodeMirror.Position }>, primary?: number, options?: { bias?: number, origin?: string, scroll?: boolean }): void; /** Similar to setSelection , but will, if shift is held or the extending flag is set, move the head of the selection while leaving the anchor at its current place. @@ -779,7 +785,7 @@ declare namespace CodeMirror { /** Determines whether the gutter scrolls along with the content horizontally (false) or whether it stays fixed during horizontal scrolling (true, the default). */ fixedGutter?: boolean; - + /** * Chooses a scrollbar implementation. The default is "native", showing native scrollbars. The core library also * provides the "null" style, which completely hides the scrollbars. Addons can implement additional scrollbar models. @@ -1141,6 +1147,7 @@ declare namespace CodeMirror { interface LintStateOptions { async: boolean; hasGutters: boolean; + onUpdateLinting?: (annotationsNotSorted: Annotation[], annotations: Annotation[], codeMirror: Editor) => void; } /** diff --git a/types/cordova-plugin-device/index.d.ts b/types/cordova-plugin-device/index.d.ts index cb75703d1a..0451afb4de 100644 --- a/types/cordova-plugin-device/index.d.ts +++ b/types/cordova-plugin-device/index.d.ts @@ -2,9 +2,9 @@ // Project: https://github.com/apache/cordova-plugin-device // Definitions by: Microsoft Open Technologies Inc // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -// +// // Copyright (c) Microsoft Open Technologies Inc -// Licensed under the MIT license +// Licensed under the MIT license /** * This plugin defines a global device object, which describes the device's hardware and software. @@ -26,11 +26,16 @@ interface Device { uuid: string; /** Get the operating system version. */ version: string; - /** Get the device's manufacturer. */ - manufacturer: string; - /** Whether the device is running on a simulator. */ - isVirtual: boolean; - /** Get the device hardware serial number. */ - serial: string;} + /** Get the device's manufacturer. */ + manufacturer: string; + /** Whether the device is running on a simulator. */ + isVirtual: boolean; + /** Get the device hardware serial number. */ + serial: string; +} + +interface Window { + device: Device; +} declare var device: Device; diff --git a/types/cordova-plugin-keyboard/cordova-plugin-keyboard-tests.ts b/types/cordova-plugin-keyboard/cordova-plugin-keyboard-tests.ts index 767eaa6ed2..fa5cf72a30 100644 --- a/types/cordova-plugin-keyboard/cordova-plugin-keyboard-tests.ts +++ b/types/cordova-plugin-keyboard/cordova-plugin-keyboard-tests.ts @@ -1,23 +1,31 @@ Keyboard.shrinkView(true); Keyboard.shrinkView(false); +Keyboard.shrinkView(null, (currentValue) => console.log(currentValue)); + Keyboard.hideFormAccessoryBar(true); Keyboard.hideFormAccessoryBar(false); +Keyboard.hideFormAccessoryBar(null, (currentValue) => console.log(currentValue)); + Keyboard.disableScrollingInShrinkView(true); Keyboard.disableScrollingInShrinkView(false); +Keyboard.disableScrollingInShrinkView(null, (currentValue) => console.log(currentValue)); + +Keyboard.hide(); + +Keyboard.show(); + if (Keyboard.isVisible) { console.log('Keyboard is visible'); } -Keyboard.automaticScrollToTopOnHiding = true; -Keyboard.onshow = function () { - console.log('onshow'); -}; -Keyboard.onhide = function () { - console.log('onhide'); -}; -Keyboard.onshowing = function () { - console.log('onshowing'); -}; -Keyboard.onhiding= function () { - console.log('onhiding'); -}; +Keyboard.automaticScrollToTopOnHiding = true; + +window.addEventListener('keyboardDidShow', () => console.log('keyboardDidShow')); + +window.addEventListener('keyboardDidHide', () => console.log('keyboardDidHide')); + +window.addEventListener('keyboardWillShow', () => console.log('keyboardWillShow')); + +window.addEventListener('keyboardWillHide', () => console.log('keyboardWillHide')); + +window.addEventListener('keyboardHeightWillChange', (event: CordovaKeyboardEvent) => console.log(`keyboardHeightWillChange - keyboard height: ${event.keyboardHeight}`)); diff --git a/types/cordova-plugin-keyboard/index.d.ts b/types/cordova-plugin-keyboard/index.d.ts index 427a5425e5..af880d732a 100644 --- a/types/cordova-plugin-keyboard/index.d.ts +++ b/types/cordova-plugin-keyboard/index.d.ts @@ -1,32 +1,9 @@ -// Type definitions for Apache Cordova Keyboard plugin v0.1.2 -// Project: https://github.com/apache/cordova-plugins/tree/master/keyboard -// Definitions by: Dan Manastireanu +// Type definitions for Apache Cordova Keyboard plugin v1.2.0 +// Project: https://github.com/cjpearson/cordova-plugin-keyboard +// Definitions by: Dan Manastireanu +// Jochen Becker // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -/** - * The Keyboard object provides some functions to customize the iOS keyboard. - * - * Supported Platforms: iOS - * - * This plugin has only been tested in Cordova 3.2 or greater, - * and its use in previous Cordova versions is not recommended - * (potential conflict with keyboard customization code present in the core in previous Cordova versions). - * - * If you do use this plugin in an older Cordova version (again, not recommended), - * you have to make sure the HideKeyboardFormAccessoryBar and KeyboardShrinksView preference values are always false, - * and only use the API functions to turn things on/off. - * - * This plugin supports the HideKeyboardFormAccessoryBar (boolean) - * and KeyboardShrinksView (boolean) preferences in config.xml. - * - * Permissions in config.xml - * - * - * - * - * - * - */ interface Keyboard { // Methods @@ -39,15 +16,20 @@ interface Keyboard { * This applies to apps that position their elements relative to the bottom of the WebView. * This is the default behaviour on Android, and makes a lot of sense when building apps as opposed to webpages. * + * Supported Platforms: + * - iOS + * * Example: * * Keyboard.shrinkView(true); * Keyboard.shrinkView(false); + * Keyboard.shrinkView(null, function (currentValue) { console.log(currentValue); }); * * * @param shrink + * @param successCallback A success callbackfunction */ - shrinkView(shrink:boolean): void, + shrinkView(shrink: boolean, successCallback?: (currentValue: any) => void): void, /** * Hide the keyboard toolbar. @@ -55,21 +37,29 @@ interface Keyboard { * Set to true to hide the additional toolbar that is on top of the keyboard. * This toolbar features the Prev, Next, and Done buttons. * + * Supported Platforms: + * - iOS + * * Example: * * Keyboard.hideFormAccessoryBar(true); * Keyboard.hideFormAccessoryBar(false); + * Keyboard.hideFormAccessoryBar(null, function (currentValue) { console.log(currentValue); }); * * * @param hide + * @param successCallback A success callbackfunction */ - hideFormAccessoryBar(hide:boolean): void, + hideFormAccessoryBar(hide: boolean, successCallback?: (currentValue: any) => void): void, /** * Disable scrolling when the the WebView is shrunk. * * Set to true to disable scrolling when the WebView is shrunk. * + * Supported Platforms: + * - iOS + * * Example: * * Keyboard.disableScrollingInShrinkView(true); @@ -77,8 +67,40 @@ interface Keyboard { * * * @param disable + * @param successCallback A success callbackfunction */ - disableScrollingInShrinkView(disable:boolean): void, + disableScrollingInShrinkView(disable: boolean, successCallback?: (currentValue: any) => void): void, + + /** + * Hide the keyboard + * + * Call this method to hide the keyboard + * + * Supported Platforms: + * - iOS + * - Android + * + * Example: + * + * Keyboard.hide(); + * + */ + hide(): void, + + /** + * Show the keyboard + * + * Call this method to show the keyboard. + * + * Supported Platforms: + * - Android + * + * Example: + * + * Keyboard.show(); + * + */ + show(): void, // Properties @@ -87,6 +109,9 @@ interface Keyboard { * * Read this property to determine if the keyboard is visible. * + * Supported Platforms: + * - iOS + * * Example: * * if (Keyboard.isVisible) { @@ -102,6 +127,9 @@ interface Keyboard { * Set this to true if you need that page scroll to beginning when keyboard is hiding. * This is allows to fix issue with elements declared with position: fixed, after keyboard is hiding. * + * Supported Platforms: + * - iOS + * * Example: * * Keyboard.automaticScrollToTopOnHiding = true; @@ -110,65 +138,48 @@ interface Keyboard { */ automaticScrollToTopOnHiding: boolean, - // Events + /** + * Deprecated Events + */ + onshow(): void, - /** - * If defined, this function is fired when keyboard fully shown. - * - * Attach handler to this event to be able to receive notification when keyboard is shown. - * - * Example: - * - * Keyboard.onshow = function () { - * // Describe your logic which will be run each time keyboard is shown. - * } - * - * - */ - onshow():void, - /** - * If defined, this function is fired when keyboard fully closed. - * - * Attach handler to this event to be able to receive notification when keyboard is closed. - * - * Example: - * - * Keyboard.onhide = function () { - * // Describe your logic which will be run each time keyboard is closed. - * } - * - * - */ - onhide():void, - /** - * If defined, this function is fired before keyboard will be shown. - * - * Attach handler to this event to be able to receive notification when keyboard is about to be shown on the screen. - * - * Example: - * - * Keyboard.onshowing = function () { - * // Describe your logic which will be run each time when keyboard is about to be shown. - * } - * - * - */ - onshowing():void, - /** - * If defined, this function is fired when keyboard is about to be closed. - * - * Attach handler to this event to be able to receive notification when keyboard is about to be closed. - * - * Example: - * - * Keyboard.onhiding = function () { - * // Describe your logic which will be run each time when keyboard is about to be closed. - * } - * - * - */ - onhiding():void, + onhide(): void, + onhiding(): void, + + onshowing(): void } -declare var Keyboard:Keyboard; +interface CordovaKeyboardEvent extends Event { + /** The height of the keyboard */ + keyboardHeight: number; +} + +interface WindowEventMap { + /** + * This event is fired when keyboard fully shown. + */ + 'keyboardDidShow': Event, + + /** + * This event is fired when the keyboard is fully closed. + */ + 'keyboardDidHide': Event, + + /** + * This event fires before keyboard will be shown. + */ + 'keyboardWillShow': Event, + + /** + * This event is fired when the keyboard is fully closed. + */ + 'keyboardWillHide': Event, + + /** + * This event is fired when the keyboard is fully closed. + */ + 'keyboardHeightWillChange': CordovaKeyboardEvent + } + +declare var Keyboard: Keyboard; diff --git a/types/css/index.d.ts b/types/css/index.d.ts index c892d5c3a2..be8f1323a0 100644 --- a/types/css/index.d.ts +++ b/types/css/index.d.ts @@ -112,7 +112,7 @@ export interface Comment extends Node { /** * The @charset at-rule. */ -export interface Charset { +export interface Charset extends Node { /** The part following @charset. */ charset?: string; } @@ -120,7 +120,7 @@ export interface Charset { /** * The @custom-media at-rule */ -export interface CustomMedia { +export interface CustomMedia extends Node { /** The ---prefixed name. */ name?: string; /** The part following the name. */ @@ -130,7 +130,7 @@ export interface CustomMedia { /** * The @document at-rule. */ -export interface Document { +export interface Document extends Node { /** The part following @document. */ document?: string; /** The vendor prefix in @document, or undefined if there is none. */ @@ -142,7 +142,7 @@ export interface Document { /** * The @font-face at-rule. */ -export interface FontFace { +export interface FontFace extends Node { /** Array of nodes with the types declaration and comment. */ declarations?: Array; } @@ -150,7 +150,7 @@ export interface FontFace { /** * The @host at-rule. */ -export interface Host { +export interface Host extends Node { /** Array of nodes with the types rule, comment and any of the at-rule types. */ rules?: Array; } @@ -158,7 +158,7 @@ export interface Host { /** * The @import at-rule. */ -export interface Import { +export interface Import extends Node { /** The part following @import. */ import?: string; } @@ -166,7 +166,7 @@ export interface Import { /** * The @keyframes at-rule. */ -export interface KeyFrames { +export interface KeyFrames extends Node { /** The name of the keyframes rule. */ name?: string; /** The vendor prefix in @keyframes, or undefined if there is none. */ @@ -175,7 +175,7 @@ export interface KeyFrames { keyframes?: Array; } -export interface KeyFrame { +export interface KeyFrame extends Node { /** The list of "selectors" of the keyframe rule, split on commas. Each “selector” is trimmed from whitespace. */ values?: Array; /** Array of nodes with the types declaration and comment. */ @@ -185,7 +185,7 @@ export interface KeyFrame { /** * The @media at-rule. */ -export interface Media { +export interface Media extends Node { /** The part following @media. */ media?: string; /** Array of nodes with the types rule, comment and any of the at-rule types. */ @@ -195,7 +195,7 @@ export interface Media { /** * The @namespace at-rule. */ -export interface Namespace { +export interface Namespace extends Node { /** The part following @namespace. */ namespace?: string; } @@ -203,7 +203,7 @@ export interface Namespace { /** * The @page at-rule. */ -export interface Page { +export interface Page extends Node { /** The list of selectors of the rule, split on commas. Each selector is trimmed from whitespace and comments. */ selectors?: Array; /** Array of nodes with the types declaration and comment. */ @@ -213,7 +213,7 @@ export interface Page { /** * The @supports at-rule. */ -export interface Supports { +export interface Supports extends Node { /** The part following @supports. */ supports?: string; /** Array of nodes with the types rule, comment and any of the at-rule types. */ @@ -223,16 +223,21 @@ export interface Supports { /** All at-rules. */ export type AtRule = Charset | CustomMedia | Document | FontFace | Host | Import | KeyFrames | Media | Namespace | Page | Supports; +/** + * A collection of rules + */ +export interface StyleRules { + /** Array of nodes with the types rule, comment and any of the at-rule types. */ + rules: Array; + /** Array of Errors. Errors collected during parsing when option silent is true. */ + parsingErrors?: Array +} + /** * The root node returned by css.parse. */ export interface Stylesheet extends Node { - stylesheet?: { - /** Array of nodes with the types rule, comment and any of the at-rule types. */ - rules?: Array; - /** Array of Errors. Errors collected during parsing when option silent is true. */ - parsingErrors?: Array - }; + stylesheet?: StyleRules; } // --------------------------------------------------------------------------------- diff --git a/types/d3-selection/d3-selection-tests.ts b/types/d3-selection/d3-selection-tests.ts index 96d421f828..6019084be2 100644 --- a/types/d3-selection/d3-selection-tests.ts +++ b/types/d3-selection/d3-selection-tests.ts @@ -1036,6 +1036,19 @@ positions = d3Selection.touches(svg, changedTouches); positions = d3Selection.touches(g, changedTouches); positions = d3Selection.touches(h, changedTouches); +// clientPoint() --------------------------------------------------------------------- + +let clientPoint: [number, number]; +declare let mEvt: MouseEvent; +declare let tEvt: Touch; +declare let msgEvt: MSGestureEvent; +declare let customEvt: {clientX: number, clientY: number}; // minimally conforming object + +clientPoint = d3Selection.clientPoint(svg, mEvt); +clientPoint = d3Selection.clientPoint(g, tEvt); +clientPoint = d3Selection.clientPoint(h, msgEvt); +clientPoint = d3Selection.clientPoint(h, customEvt); + // --------------------------------------------------------------------------------------- // Tests of style // --------------------------------------------------------------------------------------- diff --git a/types/d3-selection/index.d.ts b/types/d3-selection/index.d.ts index abbb14db0f..b5231f37c2 100644 --- a/types/d3-selection/index.d.ts +++ b/types/d3-selection/index.d.ts @@ -1,9 +1,9 @@ -// Type definitions for D3JS d3-selection module 1.1 +// Type definitions for D3JS d3-selection module 1.2 // Project: https://github.com/d3/d3-selection/ // Definitions by: Tom Wanzek , Alex Ford , Boris Yankov // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -// Last module patch version validated against: 1.1 +// Last module patch version validated against: 1.2.0 // -------------------------------------------------------------------------- // Shared Type Definitions and Interfaces @@ -44,6 +44,14 @@ export interface EnterElement { */ export type ContainerElement = HTMLElement | SVGSVGElement | SVGGElement; +/** + * A User interface event (e.g. mouse event, touch or MSGestureEvent) with captured clientX and clientY properties. + */ +export interface ClientPointEvent { + clientX: number; + clientY: number; +} + /** * Interface for optional parameters map, when dispatching custom events * on a selection @@ -670,7 +678,8 @@ export interface Selection; /** - * Return the exit selection: existing DOM elements in the selection for which no new datum was found. - * The exit selection is determined by the previous selection.data, and is thus empty until the selection is - * joined to data. If the exit selection is retrieved more than once after a data join, subsequent calls return - * the empty selection. + * Returns the exit selection: existing DOM elements in the selection for which no new datum was found. + * (The exit selection is empty for selections not returned by selection.data.) * * IMPORTANT: The generic refers to the type of the old datum associated with the exit selection elements. * Ensure you set the generic to the correct type, if you need to access the data on the exit selection in @@ -972,6 +979,16 @@ export function touch(container: ContainerElement, touches: TouchList, identifie */ export function touches(container: ContainerElement, touches?: TouchList): Array<[number, number]>; +/** + * Returns the x and y coordinates of the specified event relative to the specified container. + * (The event may also be a touch.) The container may be an HTML or SVG container element, such as a G element or an SVG element. + * The coordinates are returned as a two-element array of numbers [x, y]. + * + * @param container Container element relative to which coordinates are calculated. + * @param event A User interface event (e.g. mouse event, touch or MSGestureEvent) with captured clientX and clientY properties. + */ +export function clientPoint(container: ContainerElement, event: ClientPointEvent): [number, number]; + // --------------------------------------------------------------------------- // style // --------------------------------------------------------------------------- diff --git a/types/d3/index.d.ts b/types/d3/index.d.ts index cb48077985..de522828ff 100644 --- a/types/d3/index.d.ts +++ b/types/d3/index.d.ts @@ -1,4 +1,4 @@ -// Type definitions for D3JS d3 standard bundle 4.11 +// Type definitions for D3JS d3 standard bundle 4.12 // Project: https://github.com/d3/d3 // Definitions by: Tom Wanzek , Alex Ford , Boris Yankov // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped diff --git a/types/dagre/dagre-tests.ts b/types/dagre/dagre-tests.ts index ae81c2c896..a29cf0128a 100644 --- a/types/dagre/dagre-tests.ts +++ b/types/dagre/dagre-tests.ts @@ -1,8 +1,39 @@ -const gDagre = new dagre.graphlib.Graph(); +const gDagre = new dagre.graphlib.Graph({compound: true, multigraph: false}); gDagre.setGraph({}) .setDefaultEdgeLabel(() => ({})) + .setDefaultNodeLabel(() => ({})) .setNode("a", {}) .setEdge("b", "c") .setEdge("c", "d", {class: "class"}); dagre.layout(gDagre); + +gDagre.edge({v: 'b', w: 'c'}); +gDagre.hasEdge({v: 'b', w: 'c'}); +gDagre.inEdges('c'); +gDagre.outEdges('c'); + +gDagre.setParent('a', 'b'); +gDagre.children('b'); +gDagre.hasNode('d'); +gDagre.neighbors('c'); +gDagre.node({}); +gDagre.parent('a'); +gDagre.predecessors('d'); +gDagre.successors('b'); + +gDagre.removeEdge('c', 'd').removeNode('d'); + +dagre.graphlib.json.read(dagre.graphlib.json.write(gDagre)); + +dagre.graphlib.alg.components(gDagre); +dagre.graphlib.alg.dijkstra(gDagre, 'a', (edge) => 5); +dagre.graphlib.alg.dijkstraAll(gDagre); +dagre.graphlib.alg.findCycles(gDagre); +dagre.graphlib.alg.floydWarchall(gDagre); +dagre.graphlib.alg.isAcyclic(gDagre); +dagre.graphlib.alg.postorder(gDagre, 'a'); +dagre.graphlib.alg.preorder(gDagre, ['b', 'c']); +dagre.graphlib.alg.prim(gDagre); +dagre.graphlib.alg.tarjam(gDagre); +dagre.graphlib.alg.topsort(gDagre); diff --git a/types/dagre/index.d.ts b/types/dagre/index.d.ts index 852fe33973..6c5e5e00ec 100644 --- a/types/dagre/index.d.ts +++ b/types/dagre/index.d.ts @@ -41,7 +41,7 @@ export namespace graphlib { predecessors(name: string): Node[]|undefined; removeNode(name: string): Graph; setDefaultNodeLabel(callback: string|((nodeId: string) => string|Label)): Graph; - setNode(id: string, node: NodeConfig): Graph; + setNode(name: string, label: string|Label): Graph; setParent(childName: string, parentName: string): void; sinks(): Node[]; sources(): Node[]; diff --git a/types/docker-file-parser/docker-file-parser-tests.ts b/types/docker-file-parser/docker-file-parser-tests.ts new file mode 100644 index 0000000000..21cd715f47 --- /dev/null +++ b/types/docker-file-parser/docker-file-parser-tests.ts @@ -0,0 +1,25 @@ +import { parse, CommandEntry, ParseOptions } from 'docker-file-parser'; + +const file = ` +FROM node:8 + +ADD . /opt/ +WORKDIR /opt + +RUN npm install --production + +EXPOSE 8080 +VOLUME /opt/scripts + +CMD ["npm", "start"] +`; + +const options: ParseOptions = { + includeComments: false +}; + +const result: CommandEntry[] = parse(file, options); +const line1Name = result[0].name; +const line1Number = result[0].lineno; +const line1Args = result[0].args; +const line1Raw = result[0].raw; diff --git a/types/docker-file-parser/index.d.ts b/types/docker-file-parser/index.d.ts new file mode 100644 index 0000000000..5263ef3353 --- /dev/null +++ b/types/docker-file-parser/index.d.ts @@ -0,0 +1,21 @@ +// Type definitions for docker-file-parser 1.0 +// Project: https://github.com/joyent/docker-file-parse +// Definitions by: Yash Kulshrestha +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +export interface CommandEntry { + name: string; + args: string[]; + lineno: number; + raw: string; + error?: string; +} + +export interface ParseOptions { + includeComments: boolean; +} + +export function parse( + contents: string, + options?: ParseOptions +): CommandEntry[]; diff --git a/types/docker-file-parser/tsconfig.json b/types/docker-file-parser/tsconfig.json new file mode 100644 index 0000000000..7c529341c4 --- /dev/null +++ b/types/docker-file-parser/tsconfig.json @@ -0,0 +1,23 @@ +{ + "compilerOptions": { + "module": "commonjs", + "lib": [ + "es6" + ], + "noImplicitAny": true, + "noImplicitThis": true, + "strictNullChecks": true, + "baseUrl": "../", + "typeRoots": [ + "../" + ], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true, + "strictFunctionTypes": true + }, + "files": [ + "index.d.ts", + "docker-file-parser-tests.ts" + ] +} diff --git a/types/docker-file-parser/tslint.json b/types/docker-file-parser/tslint.json new file mode 100644 index 0000000000..3db14f85ea --- /dev/null +++ b/types/docker-file-parser/tslint.json @@ -0,0 +1 @@ +{ "extends": "dtslint/dt.json" } diff --git a/types/download/download-tests.ts b/types/download/download-tests.ts new file mode 100644 index 0000000000..7a498ef0dd --- /dev/null +++ b/types/download/download-tests.ts @@ -0,0 +1,30 @@ +import * as fs from 'fs'; +import download = require('download'); + +download('http://unicorn.com/foo.jpg', 'dist').then(() => { + console.log('done!'); +}); + +download('http://unicorn.com/foo.jpg').then(data => { + fs.writeFileSync('dist/foo.jpg', data); +}); + +download('unicorn.com/foo.jpg').pipe(fs.createWriteStream('dist/foo.jpg')); + +download('unicorn.com/foo.jpg', 'dest', { + body: '', + decompress: true, + encoding: 'utf8', + extract: true, + filename: 'filename', + followRedirect: true, + proxy: '', + query: '', + retries: (retry: number, error: any) => 4, + timeout: { + connect: 20, + request: 20, + socket: 20 + }, + useElectronNet: true +}); diff --git a/types/download/index.d.ts b/types/download/index.d.ts new file mode 100644 index 0000000000..f3af9778bf --- /dev/null +++ b/types/download/index.d.ts @@ -0,0 +1,41 @@ +// Type definitions for download 6.2 +// Project: https://github.com/kevva/download +// Definitions by: Nico Jansen +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.2 + +/// + +interface TimeoutOptions { + connect?: number; + socket?: number; + request?: number; +} +type RetryFunction = (retry: number, error: any) => number; + +interface DownloadOptions { + body?: string | Buffer | NodeJS.ReadableStream; + encoding?: string | null; + query?: string | object; + timeout?: number | TimeoutOptions; + retries?: number | RetryFunction; + followRedirect?: boolean; + decompress?: boolean; + useElectronNet?: boolean; + /** + * If set to true, try extracting the file using decompress. + */ + extract?: boolean; + /** + * Name of the saved file. + */ + filename?: string; + /** + * Proxy endpoint + */ + proxy?: string; +} + +declare function download(url: string, destination?: string, options?: DownloadOptions): Promise & NodeJS.WritableStream & NodeJS.ReadableStream; + +export = download; diff --git a/types/download/tsconfig.json b/types/download/tsconfig.json new file mode 100644 index 0000000000..634ae5ab32 --- /dev/null +++ b/types/download/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", + "download-tests.ts" + ] +} diff --git a/types/download/tslint.json b/types/download/tslint.json new file mode 100644 index 0000000000..3db14f85ea --- /dev/null +++ b/types/download/tslint.json @@ -0,0 +1 @@ +{ "extends": "dtslint/dt.json" } diff --git a/types/draft-js/draft-js-tests.tsx b/types/draft-js/draft-js-tests.tsx index 87172d9471..63821eda98 100644 --- a/types/draft-js/draft-js-tests.tsx +++ b/types/draft-js/draft-js-tests.tsx @@ -12,7 +12,17 @@ import { SelectionState, getDefaultKeyBinding, ContentState, - convertFromHTML + RawDraftInlineStyleRange, + RawDraftEntityRange, + RawDraftEntity, + RawDraftContentBlock, + RawDraftContentState, + DraftBlockType, + DraftInlineStyleType, + DraftEntityMutability, + DraftEntityType, + convertFromHTML, + convertToRaw } from 'draft-js'; const SPLIT_HEADER_BLOCK = 'split-header-block'; @@ -274,7 +284,7 @@ var INLINE_STYLES = [ const InlineStyleControls = (props: {editorState: EditorState, onToggle: (blockType: string) => void}) => { var currentStyle = props.editorState.getCurrentInlineStyle(); - return ( + return (
{INLINE_STYLES.map(type => , document.getElementById('target') ); + +const editorState = EditorState.createEmpty(); +const contentState = editorState.getCurrentContent(); +const rawContentState: RawDraftContentState = convertToRaw(contentState); + +rawContentState.blocks.forEach((block: RawDraftContentBlock) => { + block.entityRanges.forEach((entityRange: RawDraftEntityRange) => { + const { key, offset, length } = entityRange; + const entity: RawDraftEntity = rawContentState.entityMap[key]; + const entityType: DraftEntityType = entity.type; + const entityMutability: DraftEntityMutability = entity.mutability; + console.log(entityType, entityMutability, offset, length); + }); + + block.inlineStyleRanges.forEach((inlineStyleRange: RawDraftInlineStyleRange) => { + const { offset, length } = inlineStyleRange + const inlineStyle: DraftInlineStyleType = inlineStyleRange.style; + console.log(inlineStyle, offset, length); + }); +}); diff --git a/types/draft-js/index.d.ts b/types/draft-js/index.d.ts index bf7c2bac71..3eaa05aa30 100644 --- a/types/draft-js/index.d.ts +++ b/types/draft-js/index.d.ts @@ -262,9 +262,10 @@ declare namespace Draft { * or block types. */ "bold" | - "italic" | - "underline" | "code" | + "italic" | + "strikethrough" | + "underline" | /** * Split a block in two. @@ -328,6 +329,60 @@ declare namespace Draft { * another fragment or if the selected fragment shall be replaced */ type DraftInsertionType = "replace" | "before" | "after"; + + /** + * Valid inline styles. + */ + type DraftInlineStyleType = ( + "BOLD" | + "CODE" | + "ITALIC" | + "STRIKETHROUGH" | + "UNDERLINE" + ) + + /** + * Default entity types. + */ + type ComposedEntityType = ( + "LINK" | + "TOKEN" | + "PHOTO" | + "IMAGE" + ) + + /** + * Possible entity types. + */ + type DraftEntityType = string | ComposedEntityType; + + /** + * Possible "mutability" options for an entity. This refers to the behavior + * that should occur when inserting or removing characters in a text range + * with an entity applied to it. + * + * `MUTABLE`: + * The text range can be modified freely. Generally used in cases where + * the text content and the entity do not necessarily have a direct + * relationship. For instance, the text and URI for a link may be completely + * different. The user is allowed to edit the text as needed, and the entity + * is preserved and applied to any characters added within the range. + * + * `IMMUTABLE`: + * Not to be confused with immutable data structures used to represent the + * state of the editor. Immutable entity ranges cannot be modified in any + * way. Adding characters within the range will remove the entity from the + * entire range. Deleting characters will delete the entire range. Example: + * Facebook Page mentions. + * + * `SEGMENTED`: + * Segmented entities allow the removal of partial ranges of text, as + * separated by a delimiter. Adding characters wihin the range will remove + * the entity from the entire range. Deleting characters within a segmented + * entity will delete only the segments affected by the deletion. Example: + * Facebook User mentions. + */ + type DraftEntityMutability = "MUTABLE" | "IMMUTABLE" | "SEGMENTED"; } namespace Decorators { @@ -408,14 +463,24 @@ declare namespace Draft { } namespace Encoding { + import DraftInlineStyleType = Draft.Model.Constants.DraftInlineStyleType; + import DraftBlockType = Draft.Model.Constants.DraftBlockType; + import DraftEntityMutability = Draft.Model.Constants.DraftEntityMutability; + import DraftEntityType = Draft.Model.Constants.DraftEntityType; + import ContentBlock = Draft.Model.ImmutableData.ContentBlock; import ContentState = Draft.Model.ImmutableData.ContentState; import DraftBlockRenderMap = Draft.Component.Base.DraftBlockRenderMap; - import DraftBlockType = Draft.Model.Constants.DraftBlockType; - import DraftEntityType = Draft.Model.Entity.DraftEntityType; - import DraftEntityMutability = Draft.Model.Entity.DraftEntityMutability; + /** + * A plain object representation of an inline style range. + */ + interface RawDraftInlineStyleRange { + style: DraftInlineStyleType; + offset: number; + length: number; + } /** * A plain object representation of an entity attribution. @@ -423,21 +488,12 @@ declare namespace Draft { * The `key` value corresponds to the key of the entity in the `entityMap` of * a `ComposedText` object, not for use with `DraftEntity.get()`. */ - interface EntityRange { + interface RawDraftEntityRange { key: number, offset: number, length: number, } - /** - * A plain object representation of an inline style range. - */ - interface InlineStyleRange { - style: string; - offset: number; - length: number; - } - /** * A plain object representation of an EntityInstance. */ @@ -456,8 +512,8 @@ declare namespace Draft { type: DraftBlockType; text: string; depth: number; - inlineStyleRanges: Array; - entityRanges: Array; + inlineStyleRanges: Array; + entityRanges: Array; data?: Object; } @@ -481,36 +537,8 @@ declare namespace Draft { } namespace Entity { - type ComposedEntityType = "LINK" | "TOKEN" | "PHOTO"; - type DraftEntityType = string | ComposedEntityType; - - /** - * An enum representing the possible "mutability" options for an entity. - * This refers to the behavior that should occur when inserting or removing - * characters in a text range with an entity applied to it. - * - * `MUTABLE`: - * The text range can be modified freely. Generally used in cases where - * the text content and the entity do not necessarily have a direct - * relationship. For instance, the text and URI for a link may be completely - * different. The user is allowed to edit the text as needed, and the entity - * is preserved and applied to any characters added within the range. - * - * `IMMUTABLE`: - * Not to be confused with immutable data structures used to represent the - * state of the editor. Immutable entity ranges cannot be modified in any - * way. Adding characters within the range will remove the entity from the - * entire range. Deleting characters will delete the entire range. Example: - * Facebook Page mentions. - * - * `SEGMENTED`: - * Segmented entities allow the removal of partial ranges of text, as - * separated by a delimiter. Adding characters wihin the range will remove - * the entity from the entire range. Deleting characters within a segmented - * entity will delete only the segments affected by the deletion. Example: - * Facebook User mentions. - */ - type DraftEntityMutability = "MUTABLE" | "IMMUTABLE" | "SEGMENTED"; + import DraftEntityMutability = Draft.Model.Constants.DraftEntityMutability; + import DraftEntityType = Draft.Model.Constants.DraftEntityType; /** * A "document entity" is an object containing metadata associated with a @@ -579,10 +607,10 @@ declare namespace Draft { namespace ImmutableData { import DraftBlockType = Draft.Model.Constants.DraftBlockType; - import DraftDecoratorType = Draft.Model.Decorators.DraftDecoratorType; + import DraftEntityMutability = Draft.Model.Constants.DraftEntityMutability; + import DraftEntityType = Draft.Model.Constants.DraftEntityType; - import DraftEntityType = Draft.Model.Entity.DraftEntityType; - import DraftEntityMutability = Draft.Model.Entity.DraftEntityMutability; + import DraftDecoratorType = Draft.Model.Decorators.DraftDecoratorType; type DraftInlineStyle = Immutable.OrderedSet; type BlockMap = Immutable.OrderedMap; @@ -938,6 +966,10 @@ import RichUtils = Draft.Model.Modifier.RichTextEditorUtil; import DefaultDraftBlockRenderMap = Draft.Model.ImmutableData.DefaultDraftBlockRenderMap; import DefaultDraftInlineStyle = Draft.Model.ImmutableData.DefaultDraftInlineStyle; +import RawDraftInlineStyleRange = Draft.Model.Encoding.RawDraftInlineStyleRange; +import RawDraftEntityRange = Draft.Model.Encoding.RawDraftEntityRange; +import RawDraftEntity = Draft.Model.Encoding.RawDraftEntity; +import RawDraftContentBlock = Draft.Model.Encoding.RawDraftContentBlock; import RawDraftContentState = Draft.Model.Encoding.RawDraftContentState; import convertFromRaw = Draft.Model.Encoding.convertFromRawToDraftState; import convertToRaw = Draft.Model.Encoding.convertFromDraftStateToRaw; @@ -950,6 +982,9 @@ import getVisibleSelectionRect = Draft.Component.Selection.getVisibleSelectionRe import DraftEditorCommand = Draft.Model.Constants.DraftEditorCommand; import DraftDragType = Draft.Model.Constants.DraftDragType; import DraftBlockType = Draft.Model.Constants.DraftBlockType; +import DraftInlineStyleType = Draft.Model.Constants.DraftInlineStyleType; +import DraftEntityMutability = Draft.Model.Constants.DraftEntityMutability; +import DraftEntityType = Draft.Model.Constants.DraftEntityType; import DraftRemovalDirection = Draft.Model.Constants.DraftRemovalDirection; import DraftHandleValue = Draft.Model.Constants.DraftHandleValue; import DraftInsertionType = Draft.Model.Constants.DraftInsertionType; @@ -979,6 +1014,10 @@ export { DefaultDraftBlockRenderMap, DefaultDraftInlineStyle, + RawDraftInlineStyleRange, + RawDraftEntityRange, + RawDraftEntity, + RawDraftContentBlock, RawDraftContentState, convertFromRaw, convertToRaw, @@ -991,6 +1030,9 @@ export { DraftEditorCommand, DraftDragType, DraftBlockType, + DraftInlineStyleType, + DraftEntityType, + DraftEntityMutability, DraftRemovalDirection, DraftHandleValue, DraftInsertionType, diff --git a/types/dygraphs/index.d.ts b/types/dygraphs/index.d.ts index c8617b18fc..6e45d5ccd7 100644 --- a/types/dygraphs/index.d.ts +++ b/types/dygraphs/index.d.ts @@ -526,6 +526,12 @@ declare namespace dygraphs { */ highlightSeriesBackgroundAlpha?: number; + /** + * Sets the background color used to fade out the series in conjunction with 'highlightSeriesBackgroundAlpha'. + * Default: rgb(255, 255, 255) + */ + highlightSeriesBackgroundColor?: string; + /** * When set, the options from this object are applied to the timeseries closest to the mouse * pointer for interactive highlighting. See also 'highlightCallback'. Example: diff --git a/types/elasticsearch/elasticsearch-tests.ts b/types/elasticsearch/elasticsearch-tests.ts index 1be3f740bc..3043a1f473 100644 --- a/types/elasticsearch/elasticsearch-tests.ts +++ b/types/elasticsearch/elasticsearch-tests.ts @@ -1,6 +1,6 @@ -import elasticsearch = require("elasticsearch"); +import * as elasticsearch from "elasticsearch"; -var client = new elasticsearch.Client({ +let client = new elasticsearch.Client({ host: 'localhost:9200', log: 'trace' }); @@ -10,26 +10,26 @@ client = new elasticsearch.Client({ 'box1.server.org', 'box2.server.org' ], - selector: function (hosts: any) { } + selector: (hosts: any) => { } }); client.ping({ requestTimeout: 30000 -}, function (error) { +}, (error) => { }); client.search({ q: 'pants' -}).then(function (body) { - var hits = body.hits.hits; -}, function (error) { +}).then((body) => { + const hits = body.hits.hits; +}, (error) => { }); client.indices.delete({ index: 'test_index', ignore: [404] -}).then(function (body) { -}, function (error) { +}).then((body) => { +}, (error) => { }); client.deleteByQuery({ @@ -39,8 +39,8 @@ client.deleteByQuery({ query: { } } -}).then(function (response) { -}, function (error) { +}).then((response) => { +}, (error) => { }); client.create({ @@ -103,7 +103,7 @@ client.cluster.stats({ client.count({ index: 'index_name' -}, function (error, response) { +}, (error, response) => { // ... }); @@ -120,7 +120,7 @@ client.count({ } } } -}, function (err, response) { +}, (err, response) => { // ... }); @@ -132,7 +132,7 @@ client.explain({ // the query to score it against q: 'field:value' -}, function (error, response) { +}, (error, response) => { // ... }); @@ -145,7 +145,7 @@ client.explain({ match: { title: 'test' } } } -}, function (error, response) { +}, (error, response) => { // ... }); @@ -158,8 +158,7 @@ client.index({ tags: ['y', 'z'], published: true, } -}, function (error, response) { - +}, (error, response) => { }); client.mget({ @@ -170,7 +169,7 @@ client.mget({ { _index: 'indexC', _type: 'typeC', _id: '1' } ] } -}, function (error, response) { +}, (error, response) => { // ... }); @@ -180,14 +179,14 @@ client.mget({ body: { ids: [1, 2, 3] } -}, function (error, response) { +}, (error, response) => { // ... }); client.search({ index: 'myindex', q: 'title:test' -}, function (error, response) { +}, (error, response) => { // ... }); @@ -207,7 +206,7 @@ client.search({ } } } -}, function (error, response) { +}, (error, response) => { // ... }); @@ -221,12 +220,11 @@ client.suggest({ } } } -}, function (error, response) { +}, (error, response) => { }); - // first we do a search, and specify a scroll timeout -var allTitles: string[] = []; +const allTitles: string[] = []; client.search({ index: 'myindex', // Set to 30 seconds because we are calling right back @@ -236,14 +234,14 @@ client.search({ q: 'title:test' }, function getMoreUntilDone(error, response) { // collect the title from each response - response.hits.hits.forEach(function (hit) { + response.hits.hits.forEach((hit) => { allTitles.push(hit.fields.title); }); if (response.hits.total !== allTitles.length) { // now we can call scroll over and over client.scroll({ - scrollId: response._scroll_id, + scrollId: response._scroll_id!, scroll: '30s' }, getMoreUntilDone); } else { @@ -258,8 +256,13 @@ client.indices.updateAliases({ { add: { index: 'logstash-2014.05', alias: 'logstash-current' } } ] } -}).then(function (response) { +}).then((response) => { // ... -}, function (error) { +}, (error) => { // ... }); + +// Errors +function testErrors() { + throw new elasticsearch.errors.AuthenticationException(); +} diff --git a/types/elasticsearch/index.d.ts b/types/elasticsearch/index.d.ts index 8acc7e4097..1b45a237e5 100644 --- a/types/elasticsearch/index.d.ts +++ b/types/elasticsearch/index.d.ts @@ -1,1608 +1,1659 @@ // Type definitions for elasticsearch 5.0 // Project: https://www.elastic.co/guide/en/elasticsearch/client/javascript-api/current/index.html -// Definitions by: Casper Skydt , Blake Smith , Dave Dunkin , Jeffery Grajkowski , Margus Lamp , Ahmad Ferdous Bin Alam +// Definitions by: Casper Skydt +// Blake Smith +// Dave Dunkin +// Jeffery Grajkowski +// Margus Lamp +// Ahmad Ferdous Bin Alam +// Simon Schick // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.2 -declare module Elasticsearch { - export class Client { - constructor(params: ConfigOptions); - cat: Cat; - cluster: Cluster; - indices: Indices; - ingest: Ingest; - nodes: Nodes; - snapshot: Snapshot; - tasks: Tasks; - bulk(params: BulkIndexDocumentsParams): Promise; - bulk(params: BulkIndexDocumentsParams, callback: (error: any, response: any) => void): void; - clearScroll(params: ClearScrollParams, callback: (error: any, response: any) => void): void; - clearScroll(params: ClearScrollParams): Promise; - count(params: CountParams, callback: (error: any, response: CountResponse) => void): void; - count(params: CountParams): Promise; - create(params: CreateDocumentParams): Promise; - create(params: CreateDocumentParams, callback: (err: any, response: CreateDocumentResponse, status: any) => void): void; - delete(params: DeleteDocumentParams): Promise; - delete(params: DeleteDocumentParams, callback: (error: any, response: DeleteDocumentResponse) => void): void; - deleteByQuery(params: DeleteDocumentByQueryParams): Promise; - deleteByQuery(params: DeleteDocumentByQueryParams, callback: (error: any, response: DeleteDocumentByQueryResponse) => void): void; - deleteScript(params: DeleteScriptParams): Promise; - deleteScript(params: DeleteScriptParams, callback: (error: any, response: any) => void): void; - deleteTemplate(params: DeleteTemplateParams): Promise; - deleteTemplate(params: DeleteTemplateParams, callback: (error: any, response: any) => void): void; - exists(params: ExistsParams): Promise; - exists(params: ExistsParams, callback: (error: any, response: any, status?: any) => void): void; - explain(params: ExplainParams): Promise; - explain(params: ExplainParams, callback: (error: any, response: ExplainResponse) => void): void; - fieldStats(params: FieldStatsParams): Promise; - fieldStats(params: FieldStatsParams, callback: (error: any, response: FieldStatsResponse) => void): void; - get(params: GetParams, callback: (error: any, response: GetResponse) => void): void; - get(params: GetParams): Promise>; - getScript(params: GetScriptParams): Promise; - getScript(params: GetScriptParams, callback: (error: any, response: any) => void): void; - getSource(params: GetSourceParams): Promise; - getSource(params: GetSourceParams, callback: (error: any, response: any) => void): void; - getTemplate(params: GetTemplateParams): Promise; - getTemplate(params: GetTemplateParams, callback: (error: any, response: any) => void): void; - index(params: IndexDocumentParams): Promise; - index(params: IndexDocumentParams, callback: (error: any, response: any) => void): void; - info(params: InfoParams): Promise; - info(params: InfoParams, callback: (error: any, response: any) => void): void; - mget(params: MGetParams, callback: (error: any, response: MGetResponse) => void): void; - mget(params: MGetParams): Promise>; - msearch(params: MSearchParams, callback: (error: any, response: MSearchResponse) => void): void; - msearch(params: MSearchParams): Promise>; - msearchTemplate(params: MSearchTemplateParams, callback: (error: any, response: MSearchResponse) => void): void; - msearchTemplate(params: MSearchTemplateParams): Promise>; - mtermvectors(params: MTermVectorsParams): Promise; - mtermvectors(params: MTermVectorsParams, callback: (error: any, response: any) => void): void; - ping(params: PingParams): Promise; - ping(params: PingParams, callback: (err: any, response: any, status: any) => void): void; - putScript(params: PutScriptParams): Promise; - putScript(params: PutScriptParams, callback: (err: any, response: any, status: any) => void): void; - putTemplate(params: PutTemplateParams): Promise; - putTemplate(params: PutTemplateParams, callback: (err: any, response: any, status: any) => void): void; - reindex(params: ReindexParams): Promise; - reindex(params: ReindexParams, callback: (error: any, response: ReindexResponse) => void): void; - reindexRethrottle(params: ReindexRethrottleParams): Promise; - reindexRethrottle(params: ReindexRethrottleParams, callback: (error: any, response: any) => void): void; - renderSearchTemplate(params: RenderSearchTemplateParams): Promise; - renderSearchTemplate(params: RenderSearchTemplateParams, callback: (error: any, response: any) => void): void; - scroll(params: ScrollParams): Promise>; - scroll(params: ScrollParams, callback: (error: any, response: SearchResponse) => void): void; - search(params: SearchParams): Promise>; - search(params: SearchParams, callback: (error: any, response: SearchResponse) => void): void; - searchShards(params: SearchShardsParams): Promise; - searchShards(params: SearchShardsParams, callback: (error: any, response: SearchShardsResponse) => void): void; - searchTemplate(params: SearchTemplateParams): Promise; - searchTemplate(params: SearchTemplateParams, callback: (error: any, response: any) => void): void; - suggest(params: SuggestParams): Promise; - suggest(params: SuggestParams, callback: (error: any, response: any) => void): void; - termvectors(params: TermvectorsParams): Promise; - termvectors(params: TermvectorsParams, callback: (error: any, response: any) => void): void; - update(params: UpdateDocumentParams): Promise; - update(params: UpdateDocumentParams, callback: (error: any, response: any) => void): void; - updateByQuery(params: UpdateDocumentByQueryParams): Promise; - updateByQuery(params: UpdateDocumentByQueryParams, callback: (error: any, response: any) => void): void; - close(): void; - } +export class Client { + constructor(params: ConfigOptions); + cat: Cat; + cluster: Cluster; + indices: Indices; + ingest: Ingest; + nodes: Nodes; + snapshot: Snapshot; + tasks: Tasks; + bulk(params: BulkIndexDocumentsParams): Promise; + bulk(params: BulkIndexDocumentsParams, callback: (error: any, response: any) => void): void; + clearScroll(params: ClearScrollParams, callback: (error: any, response: any) => void): void; + clearScroll(params: ClearScrollParams): Promise; + count(params: CountParams, callback: (error: any, response: CountResponse) => void): void; + count(params: CountParams): Promise; + create(params: CreateDocumentParams): Promise; + create(params: CreateDocumentParams, callback: (err: any, response: CreateDocumentResponse, status: any) => void): void; + delete(params: DeleteDocumentParams): Promise; + delete(params: DeleteDocumentParams, callback: (error: any, response: DeleteDocumentResponse) => void): void; + deleteByQuery(params: DeleteDocumentByQueryParams): Promise; + deleteByQuery(params: DeleteDocumentByQueryParams, callback: (error: any, response: DeleteDocumentByQueryResponse) => void): void; + deleteScript(params: DeleteScriptParams): Promise; + deleteScript(params: DeleteScriptParams, callback: (error: any, response: any) => void): void; + deleteTemplate(params: DeleteTemplateParams): Promise; + deleteTemplate(params: DeleteTemplateParams, callback: (error: any, response: any) => void): void; + exists(params: ExistsParams): Promise; + exists(params: ExistsParams, callback: (error: any, response: any, status?: any) => void): void; + explain(params: ExplainParams): Promise; + explain(params: ExplainParams, callback: (error: any, response: ExplainResponse) => void): void; + fieldStats(params: FieldStatsParams): Promise; + fieldStats(params: FieldStatsParams, callback: (error: any, response: FieldStatsResponse) => void): void; + get(params: GetParams, callback: (error: any, response: GetResponse) => void): void; + get(params: GetParams): Promise>; + getScript(params: GetScriptParams): Promise; + getScript(params: GetScriptParams, callback: (error: any, response: any) => void): void; + getSource(params: GetSourceParams): Promise; + getSource(params: GetSourceParams, callback: (error: any, response: any) => void): void; + getTemplate(params: GetTemplateParams): Promise; + getTemplate(params: GetTemplateParams, callback: (error: any, response: any) => void): void; + index(params: IndexDocumentParams): Promise; + index(params: IndexDocumentParams, callback: (error: any, response: any) => void): void; + info(params: InfoParams): Promise; + info(params: InfoParams, callback: (error: any, response: any) => void): void; + mget(params: MGetParams, callback: (error: any, response: MGetResponse) => void): void; + mget(params: MGetParams): Promise>; + msearch(params: MSearchParams, callback: (error: any, response: MSearchResponse) => void): void; + msearch(params: MSearchParams): Promise>; + msearchTemplate(params: MSearchTemplateParams, callback: (error: any, response: MSearchResponse) => void): void; + msearchTemplate(params: MSearchTemplateParams): Promise>; + mtermvectors(params: MTermVectorsParams): Promise; + mtermvectors(params: MTermVectorsParams, callback: (error: any, response: any) => void): void; + ping(params: PingParams): Promise; + ping(params: PingParams, callback: (err: any, response: any, status: any) => void): void; + putScript(params: PutScriptParams): Promise; + putScript(params: PutScriptParams, callback: (err: any, response: any, status: any) => void): void; + putTemplate(params: PutTemplateParams): Promise; + putTemplate(params: PutTemplateParams, callback: (err: any, response: any, status: any) => void): void; + reindex(params: ReindexParams): Promise; + reindex(params: ReindexParams, callback: (error: any, response: ReindexResponse) => void): void; + reindexRethrottle(params: ReindexRethrottleParams): Promise; + reindexRethrottle(params: ReindexRethrottleParams, callback: (error: any, response: any) => void): void; + renderSearchTemplate(params: RenderSearchTemplateParams): Promise; + renderSearchTemplate(params: RenderSearchTemplateParams, callback: (error: any, response: any) => void): void; + scroll(params: ScrollParams): Promise>; + scroll(params: ScrollParams, callback: (error: any, response: SearchResponse) => void): void; + search(params: SearchParams): Promise>; + search(params: SearchParams, callback: (error: any, response: SearchResponse) => void): void; + searchShards(params: SearchShardsParams): Promise; + searchShards(params: SearchShardsParams, callback: (error: any, response: SearchShardsResponse) => void): void; + searchTemplate(params: SearchTemplateParams): Promise; + searchTemplate(params: SearchTemplateParams, callback: (error: any, response: any) => void): void; + suggest(params: SuggestParams): Promise; + suggest(params: SuggestParams, callback: (error: any, response: any) => void): void; + termvectors(params: TermvectorsParams): Promise; + termvectors(params: TermvectorsParams, callback: (error: any, response: any) => void): void; + update(params: UpdateDocumentParams): Promise; + update(params: UpdateDocumentParams, callback: (error: any, response: any) => void): void; + updateByQuery(params: UpdateDocumentByQueryParams): Promise; + updateByQuery(params: UpdateDocumentByQueryParams, callback: (error: any, response: any) => void): void; + close(): void; +} - export interface ConfigOptions { - host?: any; - hosts?: any; - httpAuth?: string; - log?: any; - apiVersion?: string; - plugins?: any; - sniffOnStart?: boolean; - sniffInterval?: number; - sniffOnConnectionFault?: boolean; - maxRetries?: number; - requestTimeout?: number; - deadTimeout?: number; - pingTimeout?: number; - keepAlive?: boolean; - maxSockets?: number; - suggestCompression?: boolean; - connectionClass?: string; - sniffedNodesProtocol?: string; - ssl?: Object; - selector?: any; - defer?: () => void; - nodesToHostCallback?: any; - createNodeAgent?: any; - } +export interface ConfigOptions { + host?: any; + hosts?: any; + httpAuth?: string; + log?: any; + apiVersion?: string; + plugins?: any; + sniffOnStart?: boolean; + sniffInterval?: number; + sniffOnConnectionFault?: boolean; + maxRetries?: number; + requestTimeout?: number; + deadTimeout?: number; + pingTimeout?: number; + keepAlive?: boolean; + maxSockets?: number; + suggestCompression?: boolean; + connectionClass?: string; + sniffedNodesProtocol?: string; + ssl?: object; + selector?: any; + defer?: () => void; + nodesToHostCallback?: any; + createNodeAgent?: any; +} - export interface Explanation { - value: number; - description: string; - details: Explanation[]; - } +export interface Explanation { + value: number; + description: string; + details: Explanation[]; +} - export interface GenericParams { - requestTimeout?: number; - maxRetries?: number; - method?: string; - body?: any; - ignore?: number | number[]; - filterPath?: string | string[]; - } +export interface GenericParams { + requestTimeout?: number; + maxRetries?: number; + method?: string; + body?: any; + ignore?: number | number[]; + filterPath?: string | string[]; +} - export interface ShardsResponse { - total: number; - successful: number; - failed: number; - } +export interface ShardsResponse { + total: number; + successful: number; + failed: number; +} - /** - * A string of a number and a time unit. A time unit is one of - * [d, h, m, s, ms, micros, nanos]. eg: "30s" for 30 seconds. - * These are incorrectly identified as `Date | number` in the docs as of 2016-11-15. - */ - export type TimeSpan = string; +/** + * A string of a number and a time unit. A time unit is one of + * [d, h, m, s, ms, micros, nanos]. eg: "30s" for 30 seconds. + * These are incorrectly identified as `Date | number` in the docs as of 2016-11-15. + */ +export type TimeSpan = string; - export type NameList = string | string[] | boolean; - export type Refresh = boolean | "true" | "false" | "wait_for" | ""; - export type VersionType = "internal" | "external" | "external_gte" | "force"; - export type ExpandWildcards = "open" | "closed" | "none" | "all"; - export type DefaultOperator = "AND" | "OR"; - export type Conflicts = "abort" | "proceed"; +export type NameList = string | string[] | boolean; +export type Refresh = boolean | "true" | "false" | "wait_for" | ""; +export type VersionType = "internal" | "external" | "external_gte" | "force"; +export type ExpandWildcards = "open" | "closed" | "none" | "all"; +export type DefaultOperator = "AND" | "OR"; +export type Conflicts = "abort" | "proceed"; - export interface BulkIndexDocumentsParams extends GenericParams { - waitForActiveShards?: string; - refresh?: Refresh; - routing?: string; - timeout?: TimeSpan; - type?: string; - fields?: NameList; - _source?: NameList; - _sourceExclude?: NameList; - _sourceInclude?: NameList; - pipeline?: string; - index?: string; - } +export interface BulkIndexDocumentsParams extends GenericParams { + waitForActiveShards?: string; + refresh?: Refresh; + routing?: string; + timeout?: TimeSpan; + type?: string; + fields?: NameList; + _source?: NameList; + _sourceExclude?: NameList; + _sourceInclude?: NameList; + pipeline?: string; + index?: string; +} - export interface ClearScrollParams extends GenericParams { - scrollId: NameList; - } +export interface ClearScrollParams extends GenericParams { + scrollId: NameList; +} - export interface CountParams extends GenericParams { - ignoreUnavailable?: boolean; - allowNoIndices?: boolean; - expandWildcards?: ExpandWildcards; - minScore?: number; - preference?: string; - routing?: string; - q?: string; - analyzer?: string; - analyzeWildcard?: boolean; - defaultOperator?: DefaultOperator; - df?: string; - lenient?: boolean; - lowercaseExpandedTerms?: boolean; - index?: NameList; - type?: NameList; - } +export interface CountParams extends GenericParams { + ignoreUnavailable?: boolean; + allowNoIndices?: boolean; + expandWildcards?: ExpandWildcards; + minScore?: number; + preference?: string; + routing?: string; + q?: string; + analyzer?: string; + analyzeWildcard?: boolean; + defaultOperator?: DefaultOperator; + df?: string; + lenient?: boolean; + lowercaseExpandedTerms?: boolean; + index?: NameList; + type?: NameList; +} - export interface CountResponse { - count: number; - _shards: ShardsResponse; - } +export interface CountResponse { + count: number; + _shards: ShardsResponse; +} - export interface CreateDocumentParams extends GenericParams { - waitForActiveShards?: string; - parent?: string; - refresh?: Refresh; - timeout?: TimeSpan; - timestamp?: Date | number; - ttl?: TimeSpan; - version?: number; - versionType?: VersionType; - pipeline?: string; - id?: string; - index: string; - type: string; - } +export interface CreateDocumentParams extends GenericParams { + waitForActiveShards?: string; + parent?: string; + refresh?: Refresh; + timeout?: TimeSpan; + timestamp?: Date | number; + ttl?: TimeSpan; + version?: number; + versionType?: VersionType; + pipeline?: string; + id?: string; + index: string; + type: string; +} - export interface CreateDocumentResponse { - _shards: ShardsResponse; - _index: string; - _type: string; - _id: string; - _version: number; - created: boolean; - result: string; - } +export interface CreateDocumentResponse { + _shards: ShardsResponse; + _index: string; + _type: string; + _id: string; + _version: number; + created: boolean; + result: string; +} - export interface DeleteDocumentParams extends GenericParams { - waitForActiveShards?: string; - parent?: string; - refresh?: Refresh; - routing?: string; - timeout?: TimeSpan; - version?: number; - versionType?: VersionType; - index: string; - type: string; - id: string; - } +export interface DeleteDocumentParams extends GenericParams { + waitForActiveShards?: string; + parent?: string; + refresh?: Refresh; + routing?: string; + timeout?: TimeSpan; + version?: number; + versionType?: VersionType; + index: string; + type: string; + id: string; +} - export interface DeleteDocumentResponse { - _shards: ShardsResponse; - found: boolean; - _index: string; - _type: string; - _id: string; - _version: number; - result: string; - } +export interface DeleteDocumentResponse { + _shards: ShardsResponse; + found: boolean; + _index: string; + _type: string; + _id: string; + _version: number; + result: string; +} - export interface DeleteDocumentByQueryParams extends GenericParams { - analyzer?: string; - analyzeWildcard?: boolean; - defaultOperator?: DefaultOperator; - df?: string; - from?: number; - ignoreUnavailable?: boolean; - allowNoIndices?: boolean; - conflicts?: Conflicts; - expandWildcards?: ExpandWildcards; - lenient?: boolean; - lowercaseExpandedTerms?: boolean; - preference?: string; - q?: string; - routing?: string | string[] | boolean; - scroll?: string; - searchType?: "query_then_fetch" | "dfs_query_then_fetch"; - searchTimeout?: TimeSpan; - size?: number; - sort?: NameList; - _source?: NameList; - _sourceExclude?: NameList; - _sourceInclude?: NameList; - terminateAfter?: number; - stats?: string | string[] | boolean; - version?: number; - requestCache?: boolean; - refresh?: Refresh; - timeout?: TimeSpan; - waitForActiveShards?: string; - scrollSize?: number; - waitForCompletion?: boolean; - requestsPerSecond?: number; - index?: string; - type?: string; - } +export interface DeleteDocumentByQueryParams extends GenericParams { + analyzer?: string; + analyzeWildcard?: boolean; + defaultOperator?: DefaultOperator; + df?: string; + from?: number; + ignoreUnavailable?: boolean; + allowNoIndices?: boolean; + conflicts?: Conflicts; + expandWildcards?: ExpandWildcards; + lenient?: boolean; + lowercaseExpandedTerms?: boolean; + preference?: string; + q?: string; + routing?: string | string[] | boolean; + scroll?: string; + searchType?: "query_then_fetch" | "dfs_query_then_fetch"; + searchTimeout?: TimeSpan; + size?: number; + sort?: NameList; + _source?: NameList; + _sourceExclude?: NameList; + _sourceInclude?: NameList; + terminateAfter?: number; + stats?: string | string[] | boolean; + version?: number; + requestCache?: boolean; + refresh?: Refresh; + timeout?: TimeSpan; + waitForActiveShards?: string; + scrollSize?: number; + waitForCompletion?: boolean; + requestsPerSecond?: number; + index?: string; + type?: string; +} - export interface DeleteDocumentByQueryResponse { - took: number; - timed_out: boolean; - deleted: number; - batches: number; - version_conflicts: number; - noops: number; - retries: { - bulk: number; - search: number; - }; - throttled_millis: number; - requests_per_second: number; - throttled_until_millis: number; - total: number; - failures: any[]; - } +export interface DeleteDocumentByQueryResponse { + took: number; + timed_out: boolean; + deleted: number; + batches: number; + version_conflicts: number; + noops: number; + retries: { + bulk: number; + search: number; + }; + throttled_millis: number; + requests_per_second: number; + throttled_until_millis: number; + total: number; + failures: any[]; +} - export interface DeleteScriptParams extends GenericParams { - id: string; - lang: string; - } +export interface DeleteScriptParams extends GenericParams { + id: string; + lang: string; +} - export interface DeleteTemplateParams extends GenericParams { - id: string; - } +export interface DeleteTemplateParams extends GenericParams { + id: string; +} - export interface ExistsParams extends GenericParams { - parent?: string; - preference?: string; - realtime?: boolean; - refresh?: boolean; - routing?: string; - id: string; - index: string; - type: string; - } +export interface ExistsParams extends GenericParams { + parent?: string; + preference?: string; + realtime?: boolean; + refresh?: boolean; + routing?: string; + id: string; + index: string; + type: string; +} - export interface ExplainParams extends GenericParams { - analyzeWildcard?: boolean; - analyzer?: string; - defaultOperator?: DefaultOperator; - df?: string; - storedFields?: NameList; - lenient?: boolean; - lowercaseExpandedTerms?: boolean; - parent?: string; - preference?: string; - q?: string; - routing?: string; - _source?: NameList; - _sourceExclude?: NameList; - _sourceInclude?: NameList; - id?: string; - index?: string; - type?: string; - } +export interface ExplainParams extends GenericParams { + analyzeWildcard?: boolean; + analyzer?: string; + defaultOperator?: DefaultOperator; + df?: string; + storedFields?: NameList; + lenient?: boolean; + lowercaseExpandedTerms?: boolean; + parent?: string; + preference?: string; + q?: string; + routing?: string; + _source?: NameList; + _sourceExclude?: NameList; + _sourceInclude?: NameList; + id?: string; + index?: string; + type?: string; +} - export interface ExplainResponse { - _index: string; - _type: string; - _id: string; - matched: boolean; - explanation: ExplainResponseDetails; - } +export interface ExplainResponse { + _index: string; + _type: string; + _id: string; + matched: boolean; + explanation: ExplainResponseDetails; +} - export interface ExplainResponseDetails { - value: number; - description: string; - details: ExplainResponseDetails[]; - } +export interface ExplainResponseDetails { + value: number; + description: string; + details: ExplainResponseDetails[]; +} - export interface FieldStatsParams extends GenericParams { - fields?: NameList; - level?: "indices" | "cluster"; - ignoreUnavailable?: boolean; - allowNoIndices?: boolean; - expandWildcards?: ExpandWildcards; - index?: NameList; - } +export interface FieldStatsParams extends GenericParams { + fields?: NameList; + level?: "indices" | "cluster"; + ignoreUnavailable?: boolean; + allowNoIndices?: boolean; + expandWildcards?: ExpandWildcards; + index?: NameList; +} - export interface FieldStatsResponse { - _shards: ShardsResponse; - indices: { [indexName: string]: FieldStatsResponseIndex }; - conflicts?: { [fieldName: string]: string }; - } +export interface FieldStatsResponse { + _shards: ShardsResponse; + indices: { [indexName: string]: FieldStatsResponseIndex }; + conflicts?: { [fieldName: string]: string }; +} - export interface FieldStatsResponseIndex { - fields: { [fieldName: string]: FieldStatsResponseField }; - } +export interface FieldStatsResponseIndex { + fields: { [fieldName: string]: FieldStatsResponseField }; +} - export interface FieldStatsResponseField { - max_doc: number; - doc_count: number; - density: number; - sum_doc_freq: number; - sum_total_term_freq: number; - min_value: any; - max_value: any; - is_searchable: string; - is_aggregatable: string; - } +export interface FieldStatsResponseField { + max_doc: number; + doc_count: number; + density: number; + sum_doc_freq: number; + sum_total_term_freq: number; + min_value: any; + max_value: any; + is_searchable: string; + is_aggregatable: string; +} - export interface GetParams extends GenericParams { - storedFields?: NameList; - parent?: string; - preference?: string; - realtime?: boolean; - refresh?: boolean; - routing?: string; - _source?: NameList; - _sourceExclude?: NameList; - _sourceInclude?: NameList; - version?: number; - versionType?: VersionType; - id: string; - index: string; - type: string; - } +export interface GetParams extends GenericParams { + storedFields?: NameList; + parent?: string; + preference?: string; + realtime?: boolean; + refresh?: boolean; + routing?: string; + _source?: NameList; + _sourceExclude?: NameList; + _sourceInclude?: NameList; + version?: number; + versionType?: VersionType; + id: string; + index: string; + type: string; +} - export interface GetResponse { - _index: string; - _type: string; - _id: string; - _version: number; - found: boolean; - _source: T; - } +export interface GetResponse { + _index: string; + _type: string; + _id: string; + _version: number; + found: boolean; + _source: T; +} - export interface GetScriptParams extends GenericParams { - id: string; - lang: string; - } +export interface GetScriptParams extends GenericParams { + id: string; + lang: string; +} - export interface GetSourceParams extends GenericParams { - preference?: string; - realtime?: boolean; - refresh?: boolean; - routing?: string; - _source: NameList; - _sourceExclude?: NameList; - _sourceInclude?: NameList; - version?: number; - versionType?: VersionType; - id: string; - index: string; - type: string; - } +export interface GetSourceParams extends GenericParams { + preference?: string; + realtime?: boolean; + refresh?: boolean; + routing?: string; + _source: NameList; + _sourceExclude?: NameList; + _sourceInclude?: NameList; + version?: number; + versionType?: VersionType; + id: string; + index: string; + type: string; +} - export interface GetTemplateParams extends GenericParams { - id: string; - } +export interface GetTemplateParams extends GenericParams { + id: string; +} - export interface IndexDocumentParams extends GenericParams { - waitForActiveShards?: string; - opType?: "index" | "create"; - parent?: string; - refresh?: string; - routing?: string; - timeout?: TimeSpan; - timestamp?: Date | number; - ttl?: TimeSpan; - version?: number; - versionType?: VersionType; - pipeline?: string; - id?: string; - index: string; - type: string; - body: T; - } +export interface IndexDocumentParams extends GenericParams { + waitForActiveShards?: string; + opType?: "index" | "create"; + parent?: string; + refresh?: string; + routing?: string; + timeout?: TimeSpan; + timestamp?: Date | number; + ttl?: TimeSpan; + version?: number; + versionType?: VersionType; + pipeline?: string; + id?: string; + index: string; + type: string; + body: T; +} - export interface InfoParams extends GenericParams { - } +export interface InfoParams extends GenericParams { +} - export interface MGetParams extends GenericParams { - storedFields?: NameList; - preference?: string; - realtime?: Boolean; - refresh?: Boolean; - source?: NameList; - _sourceExclude?: NameList; - _sourceInclude?: NameList; - index?: string; - type?: string; - } +export interface MGetParams extends GenericParams { + storedFields?: NameList; + preference?: string; + realtime?: boolean; + refresh?: boolean; + source?: NameList; + _sourceExclude?: NameList; + _sourceInclude?: NameList; + index?: string; + type?: string; +} - export interface MGetResponse { - docs?: GetResponse[]; - } +export interface MGetResponse { + docs?: Array>; +} - export interface MSearchParams extends GenericParams { - search_type?: "query_then_fetch" | "query_and_fetch" | "dfs_query_then_fetch" | "dfs_query_and_fetch"; - maxConcurrentSearches?: number; - index?: NameList; - type?: NameList; - } +export interface MSearchParams extends GenericParams { + search_type?: "query_then_fetch" | "query_and_fetch" | "dfs_query_then_fetch" | "dfs_query_and_fetch"; + maxConcurrentSearches?: number; + index?: NameList; + type?: NameList; +} - export interface MSearchResponse { - responses?: SearchResponse[]; - } +export interface MSearchResponse { + responses?: Array>; +} - export interface MSearchTemplateParams extends GenericParams { - search_type?: "query_then_fetch" | "query_and_fetch" | "dfs_query_then_fetch" | "dfs_query_and_fetch"; - index?: NameList; - type?: NameList; - } +export interface MSearchTemplateParams extends GenericParams { + search_type?: "query_then_fetch" | "query_and_fetch" | "dfs_query_then_fetch" | "dfs_query_and_fetch"; + index?: NameList; + type?: NameList; +} - export interface MTermVectorsParams extends GenericParams { - ids?: NameList; - termStatistics?: boolean; - fieldStatistics?: boolean; - fields?: NameList; - offsets?: boolean; - positions?: boolean; - payloads?: boolean; - preference?: string; - routing?: string; - parent?: string; - realtime?: boolean; - version?: number; - versionType?: VersionType; - index: string; - type: string; - } +export interface MTermVectorsParams extends GenericParams { + ids?: NameList; + termStatistics?: boolean; + fieldStatistics?: boolean; + fields?: NameList; + offsets?: boolean; + positions?: boolean; + payloads?: boolean; + preference?: string; + routing?: string; + parent?: string; + realtime?: boolean; + version?: number; + versionType?: VersionType; + index: string; + type: string; +} - export interface PingParams extends GenericParams { - } +export interface PingParams extends GenericParams { +} - export interface PutScriptParams extends GenericParams { - id: string; - lang: string; - body: any; - } +export interface PutScriptParams extends GenericParams { + id: string; + lang: string; + body: any; +} - export interface PutTemplateParams extends GenericParams { - id: string; - body: any; - } +export interface PutTemplateParams extends GenericParams { + id: string; + body: any; +} - export interface ReindexParams extends GenericParams { - refresh?: boolean; - timeout?: TimeSpan; - waitForActiveShards?: string; - waitForCompletion?: boolean; - requestsPerSecond?: number; - body: { - conflicts?: string; - source: { - index: string | string[]; - type?: string | string[]; - query?: any; - sort?: any; - size?: number; - remote?: { - host: string; - username?: string; - password?: string; - } - }; - dest: { - index: string; - version_type?: string; - op_type?: string; - routing?: string; - pipeline?: string; - }; - script?: { - inline: string; - lang: string; +export interface ReindexParams extends GenericParams { + refresh?: boolean; + timeout?: TimeSpan; + waitForActiveShards?: string; + waitForCompletion?: boolean; + requestsPerSecond?: number; + body: { + conflicts?: string; + source: { + index: string | string[]; + type?: string | string[]; + query?: any; + sort?: any; + size?: number; + remote?: { + host: string; + username?: string; + password?: string; } }; - } - - export interface ReindexResponse { - took: number; - updated: number; - created: number; - batches: number; - version_conflicts: number; - retries: { - bulk: number; - search: number; - }; - throttled_millis: number; - failures: any[]; - } - - export interface ReindexRethrottleParams extends GenericParams { - requestsPerSecond: number; - taskId: string; - } - - export interface RenderSearchTemplateParams extends GenericParams { - id: string; - } - - export interface ScrollParams extends GenericParams { - scroll: TimeSpan; - scrollId: string; - } - - export interface SearchParams extends GenericParams { - analyzer?: string; - analyzeWildcard?: boolean; - defaultOperator?: DefaultOperator; - df?: string; - explain?: boolean; - storedFields?: NameList; - docvalueFields?: NameList; - fielddataFields?: NameList; - from?: number; - ignoreUnavailable?: boolean; - allowNoIndices?: boolean; - expandWildcards?: ExpandWildcards; - lenient?: boolean; - lowercaseExpandedTerms?: boolean; - preference?: string; - q?: string; - routing?: NameList; - scroll?: TimeSpan; - searchType?: "query_then_fetch" | "dfs_query_then_fetch"; - size?: number; - sort?: NameList; - _source?: NameList; - _sourceExclude?: NameList; - _sourceInclude?: NameList; - terminateAfter?: number; - stats?: NameList; - suggestField?: string; - suggestMode?: "missing" | "popular" | "always"; - suggestSize?: number; - suggestText?: string; - timeout?: TimeSpan; - trackScores?: boolean; - version?: boolean; - requestCache?: boolean; - index?: NameList; - type?: NameList; - } - - export interface SearchResponse { - took: number; - timed_out: boolean; - _scroll_id?: string; - _shards: ShardsResponse; - hits: { - total: number; - max_score: number; - hits: { - _index: string; - _type: string; - _id: string; - _score: number; - _source: T; - _version?: number; - _explanation?: Explanation; - fields?: any; - highlight?: any; - inner_hits?: any; - }[]; - }; - aggregations?: any; - } - - export interface SearchShardsParams extends GenericParams { - preference?: string; - routing?: string; - local?: boolean; - ignoreUnavailable?: boolean; - allowNoIndices?: boolean; - expandWildcards?: ExpandWildcards; - index: NameList; - type: NameList; - } - - export interface SearchShardsResponse { - nodes: any; - shards: SearchShardsResponseShard[][]; - } - - export interface SearchShardsResponseShard { - index: string; - node: string; - primary: boolean; - share: number; - state: string; - allocation_id: { - id: string; - }; - relocating_node: any; - } - - export interface SearchTemplateParams extends GenericParams { - ignoreUnavailable?: boolean; - allowNoIndices?: boolean; - expandWildcards?: ExpandWildcards; - preference?: string; - routing?: NameList; - scroll?: TimeSpan; - searchType?: "query_then_fetch" | "query_and_fetch" | "dfs_query_then_fetch" | "dfs_query_and_fetch"; - index: NameList; - type: NameList; - } - - export interface SuggestParams extends GenericParams { - ignoreUnavailable?: boolean; - allowNoIndices?: boolean; - expandWildcards?: ExpandWildcards; - preference?: string; - routing?: string; - index: NameList; - } - - export interface TermvectorsParams extends GenericParams { - termStatistics?: boolean; - fieldStatistics?: boolean; - fields?: NameList; - offsets?: boolean; - positions?: boolean; - payloads?: boolean; - preference?: string; - routing?: string; - parent?: string; - realtime?: boolean; - version?: number; - versionType?: VersionType; - index: string; - type: string; - id?: string; - } - - export interface UpdateDocumentParams extends GenericParams { - waitForActiveShards?: string; - fields?: NameList; - _source?: NameList; - _sourceExclude?: NameList; - _sourceInclude?: NameList; - lang?: string; - parent?: string; - refresh?: Refresh; - retryOnConflict?: number; - routing?: string; - timeout?: TimeSpan; - timestamp?: Date | number; - ttl?: TimeSpan; - version?: number; - versionType?: "internal" | "force"; - id: string; - index: string; - type: string; - } - - export interface UpdateDocumentByQueryParams extends GenericParams { - analyzer?: string; - analyzeWildcard?: boolean; - defaultOperator?: DefaultOperator; - df?: string; - explain?: boolean; - storedFields?: NameList; - docvalueFields?: NameList; - fielddataFields?: NameList; - from?: number; - ignoreUnavailable?: boolean; - allowNoIndices?: boolean; - conflicts?: Conflicts; - expandWildcards?: ExpandWildcards; - lenient?: boolean; - lowercaseExpandedTerms?: boolean; - pipeline?: string; - preference?: string; - q?: string; - routing?: NameList; - scroll?: TimeSpan; - searchType?: "query_then_fetch" | "dfs_query_then_fetch"; - searchTimeout?: TimeSpan; - size?: number; - sort?: NameList; - _source?: NameList; - _sourceExclude?: NameList; - _sourceInclude?: NameList; - terminateAfter?: number; - stats?: NameList; - suggestField?: string; - suggestMode?: "missing" | "popular" | "always"; - suggestSize?: number; - suggestText?: string; - timeout?: TimeSpan; - trackScores?: boolean; - version?: boolean; - versionType?: boolean; - requestCache?: boolean; - refresh?: boolean; - waitForActiveShards?: string; - scrollSize?: number; - waitForCompletion?: boolean; - requestsPerSecond?: number; - index: NameList; - type: NameList; - } - - export interface Cat { - aliases(params: CatAliasesParams, callback: (error: any, response: any) => void): void; - aliases(params: CatAliasesParams): Promise; - allocation(params: CatAllocationParams, callback: (error: any, response: any) => void): void; - allocation(params: CatAllocationParams): Promise; - count(params: CatCountParams, callback: (error: any, response: any) => void): void; - count(params: CatAllocationParams): Promise; - fielddata(params: CatFielddataParams, callback: (error: any, response: any) => void): void; - fielddata(params: CatFielddataParams): Promise; - health(params: CatHealthParams, callback: (error: any, response: any) => void): void; - health(params: CatHealthParams): Promise; - help(params: CatHelpParams, callback: (error: any, response: any) => void): void; - help(params: CatHelpParams): Promise; - indices(params: CatIndicesParams, callback: (error: any, response: any) => void): void; - indices(params: CatIndicesParams): Promise; - master(params: CatCommonParams, callback: (error: any, response: any) => void): void; - master(params: CatCommonParams): Promise; - nodeattrs(params: CatCommonParams, callback: (error: any, response: any) => void): void; - nodeattrs(params: CatCommonParams): Promise; - nodes(params: CatCommonParams, callback: (error: any, response: any) => void): void; - nodes(params: CatCommonParams): Promise; - pendingTasks(params: CatCommonParams, callback: (error: any, response: any) => void): void; - pendingTasks(params: CatCommonParams): Promise; - plugins(params: CatCommonParams, callback: (error: any, response: any) => void): void; - plugins(params: CatCommonParams): Promise; - recovery(params: CatRecoveryParams, callback: (error: any, response: any) => void): void; - recovery(params: CatRecoveryParams): Promise; - repositories(params: CatCommonParams, callback: (error: any, response: any) => void): void; - repositories(params: CatCommonParams): Promise; - segments(params: CatSegmentsParams, callback: (error: any, response: any) => void): void; - segments(params: CatSegmentsParams): Promise; - shards(params: CatShardsParams, callback: (error: any, response: any) => void): void; - shards(params: CatShardsParams): Promise; - snapshots(params: CatSnapshotsParams, callback: (error: any, response: any) => void): void; - snapshots(params: CatSnapshotsParams): Promise; - tasks(params: CatTasksParams, callback: (error: any, response: any) => void): void; - tasks(params: CatTasksParams): Promise; - threadPool(params: CatThreadPoolParams, callback: (error: any, response: any) => void): void; - threadPool(params: CatThreadPoolParams): Promise; - } - - export type CatBytes = "b" | "k" | "kb" | "m" | "mb" | "g" | "gb" | "t" | "tb" | "p" | "pb"; - - export interface CatCommonParams extends GenericParams { - format: string; - local?: boolean; - masterTimeout?: TimeSpan; - h?: NameList; - help?: boolean; - v?: boolean; - } - - export interface CatAliasesParams extends CatCommonParams { - name?: NameList; - } - - export interface CatAllocationParams extends CatCommonParams { - bytes?: CatBytes; - nodeId?: NameList; - } - - export interface CatCountParams extends CatCommonParams { - index?: NameList; - } - - export interface CatFielddataParams extends CatCommonParams { - bytes?: CatBytes; - fields?: NameList; - } - - export interface CatHealthParams extends CatCommonParams { - ts?: boolean; - } - - export interface CatHelpParams extends GenericParams { - help?: boolean; - } - - export interface CatIndicesParams extends CatCommonParams { - bytes?: CatBytes; - health?: "green" | "yellow" | "red"; - pri?: boolean; - index?: NameList; - } - - export interface CatRecoveryParams extends GenericParams { - format: string; - bytes?: CatBytes; - masterTimeout?: TimeSpan; - h?: NameList; - help?: boolean; - v?: boolean; - } - - export interface CatSegmentsParams extends GenericParams { - format: string; - h?: NameList; - help?: boolean; - v?: boolean; - index?: NameList; - } - - export interface CatShardsParams extends CatCommonParams { - index?: NameList; - } - - export interface CatSnapshotsParams extends GenericParams { - format: string; - ignoreUnavailable?: boolean; - masterTimeout?: TimeSpan; - h?: NameList; - help?: boolean; - v?: boolean; - repository?: NameList; - } - - export interface CatTasksParams extends GenericParams { - format: string; - nodeId?: NameList; - actions?: NameList; - detailed?: boolean; - parentNode?: string; - parentTask?: number; - h?: NameList; - help?: boolean; - v?: boolean; - } - - export interface CatThreadPoolParams extends CatCommonParams { - size?: "" | "k" | "m" | "g" | "t" | "p"; - threadPoolPatterns?: NameList; - } - - export interface Cluster { - allocationExplain(params: ClusterAllocationExplainParams, callback: (error: any, response: any) => void): void; - allocationExplain(params: ClusterAllocationExplainParams): Promise; - getSettings(params: ClusterGetSettingsParams, callback: (error: any, response: any) => void): void; - getSettings(params: ClusterGetSettingsParams): Promise; - health(params: ClusterHealthParams, callback: (error: any, response: any) => void): void; - health(params: ClusterHealthParams): Promise; - pendingTasks(params: ClusterPendingTasksParams, callback: (error: any, response: any) => void): void; - pendingTasks(params: ClusterPendingTasksParams): Promise; - putSettings(params: ClusterPutSettingsParams, callback: (error: any, response: any) => void): void; - putSettings(params: ClusterPutSettingsParams): Promise; - reroute(params: ClusterRerouteParams, callback: (error: any, response: any) => void): void; - reroute(params: ClusterRerouteParams): Promise; - state(params: ClusterStateParams, callback: (error: any, response: any) => void): void; - state(params: ClusterStateParams): Promise; - stats(params: ClusterStatsParams, callback: (error: any, response: any) => void): void; - stats(params: ClusterStatsParams): Promise; - } - - export interface ClusterAllocationExplainParams extends GenericParams { - includeYesDecisions?: boolean; - includeDiskInfo?: boolean; - } - - export interface ClusterGetSettingsParams extends GenericParams { - flatSettings?: boolean; - masterTimeout?: TimeSpan; - timeout?: TimeSpan; - includeDefaults?: boolean; - } - - export interface ClusterHealthParams extends GenericParams { - level?: "cluster" | "indices" | "shards"; - local?: boolean; - masterTimeout?: TimeSpan; - waitForActiveShards?: string; - waitForNodes?: string; - waitForEvents?: "immediate" | "urgent" | "high" | "normal" | "low" | "languid"; - waitForRelocatingShards?: boolean; - waitForStatus?: "green" | "yellow" | "red"; - index?: NameList; - } - - export interface ClusterPendingTasksParams extends GenericParams { - local?: boolean; - masterTimeout?: TimeSpan; - } - - export interface ClusterPutSettingsParams extends GenericParams { - flatSettings?: boolean; - masterTimeout?: TimeSpan; - timeout?: TimeSpan; - } - - export interface ClusterRerouteParams extends GenericParams { - dryRun?: boolean; - explain?: boolean; - retryFailed?: boolean; - metric?: NameList; - masterTimeout?: TimeSpan; - timeout?: TimeSpan; - } - - export interface ClusterStateParams extends GenericParams { - local?: boolean; - masterTimeout?: TimeSpan; - flatSettings?: boolean; - ignoreUnavailable?: boolean; - allowNoIndices?: boolean; - expandWildcards?: ExpandWildcards; - index?: NameList; - metric?: NameList; - } - - export interface ClusterStatsParams extends GenericParams { - flatSettings?: boolean; - human?: boolean; - timeout?: TimeSpan; - nodeId?: NameList; - } - - export class Indices { - analyze(params: IndicesAnalyzeParams, callback: (error: any, response: any, status: any) => void): void; - analyze(params: IndicesAnalyzeParams): Promise; - clearCache(params: IndicesClearCacheParams, callback: (error: any, response: any, status: any) => void): void; - clearCache(params: IndicesClearCacheParams): Promise; - close(params: IndicesCloseParams, callback: (error: any, response: any, status: any) => void): void; - close(params: IndicesCloseParams): Promise; - create(params: IndicesCreateParams, callback: (error: any, response: any, status: any) => void): void; - create(params: IndicesCreateParams): Promise; - delete(params: IndicesDeleteParams, callback: (error: any, response: any, status: any) => void): void; - delete(params: IndicesDeleteParams): Promise; - deleteAlias(params: IndicesDeleteAliasParams, callback: (error: any, response: any, status: any) => void): void; - deleteAlias(params: IndicesDeleteAliasParams): Promise; - deleteTemplate(params: IndicesDeleteTemplateParams, callback: (error: any, response: any, status: any) => void): void; - deleteTemplate(params: IndicesDeleteTemplateParams): Promise; - exists(params: IndicesExistsParams, callback: (error: any, response: any, status: any) => void): void; - exists(params: IndicesExistsParams): Promise; - existsAlias(params: IndicesExistsAliasParams, callback: (error: any, response: any, status: any) => void): void; - existsAlias(params: IndicesExistsAliasParams): Promise; - existsTemplate(params: IndicesExistsTemplateParams, callback: (error: any, response: any, status: any) => void): void; - existsTemplate(params: IndicesExistsTemplateParams): Promise; - existsType(params: IndicesExistsTypeParams, callback: (error: any, response: any, status: any) => void): void; - existsType(params: IndicesExistsTypeParams): Promise; - flush(params: IndicesFlushParams, callback: (error: any, response: any, status: any) => void): void; - flush(params: IndicesFlushParams): Promise; - flushSynced(params: IndicesFlushSyncedParams, callback: (error: any, response: any, status: any) => void): void; - flushSynced(params: IndicesFlushSyncedParams): Promise; - forcemerge(params: IndicesForcemergeParams, callback: (error: any, response: any, status: any) => void): void; - forcemerge(params: IndicesForcemergeParams): Promise; - get(params: IndicesGetParams, callback: (error: any, response: any, status: any) => void): void; - get(params: IndicesGetParams): Promise; - getAlias(params: IndicesGetAliasParams, callback: (error: any, response: any, status: any) => void): void; - getAlias(params: IndicesGetAliasParams): Promise; - getFieldMapping(params: IndicesGetFieldMappingParams, callback: (error: any, response: any, status: any) => void): void; - getFieldMapping(params: IndicesGetFieldMappingParams): Promise; - getMapping(params: IndicesGetMappingParams, callback: (error: any, response: any, status: any) => void): void; - getMapping(params: IndicesGetMappingParams): Promise; - getSettings(params: IndicesGetSettingsParams, callback: (error: any, response: any, status: any) => void): void; - getSettings(params: IndicesGetSettingsParams): Promise; - getTemplate(params: IndicesGetTemplateParams, callback: (error: any, response: any, status: any) => void): void; - getTemplate(params: IndicesGetTemplateParams): Promise; - getUpgrade(params: IndicesGetUpgradeParams, callback: (error: any, response: any, status: any) => void): void; - getUpgrade(params: IndicesGetUpgradeParams): Promise; - open(params: IndicesOpenParams, callback: (error: any, response: any, status: any) => void): void; - open(params: IndicesOpenParams): Promise; - putAlias(params: IndicesPutAliasParams, callback: (error: any, response: any, status: any) => void): void; - putAlias(params: IndicesPutAliasParams): Promise; - putMapping(params: IndicesPutMappingParams, callback: (error: any, response: any, status: any) => void): void; - putMapping(params: IndicesPutMappingParams): Promise; - putSettings(params: IndicesPutSettingsParams, callback: (error: any, response: any, status: any) => void): void; - putSettings(params: IndicesPutSettingsParams): Promise; - putTemplate(params: IndicesPutTemplateParams, callback: (error: any, response: any) => void): void; - putTemplate(params: IndicesPutTemplateParams): Promise; - recovery(params: IndicesRecoveryParams, callback: (error: any, response: any) => void): void; - recovery(params: IndicesRecoveryParams): Promise; - refresh(params: IndicesRefreshParams, callback: (error: any, response: any) => void): void; - refresh(params: IndicesRefreshParams): Promise; - rollover(params: IndicesRolloverParams, callback: (error: any, response: IndicesRolloverResponse) => void): void; - rollover(params: IndicesRolloverParams): Promise; - segments(params: IndicesSegmentsParams, callback: (error: any, response: any) => void): void; - segments(params: IndicesSegmentsParams): Promise; - shardStores(params: IndicesShardStoresParams, callback: (error: any, response: any) => void): void; - shardStores(params: IndicesShardStoresParams): Promise; - shrink(params: IndicesShrinkParams, callback: (error: any, response: any) => void): void; - shrink(params: IndicesShrinkParams): Promise; - stats(params: IndicesStatsParams, callback: (error: any, response: any) => void): void; - stats(params: IndicesStatsParams): Promise; - updateAliases(params: IndicesUpdateAliasesParams, callback: (error: any, response: any) => void): void; - updateAliases(params: IndicesUpdateAliasesParams): Promise; - upgrade(params: IndicesUpgradeParams, callback: (error: any, response: any) => void): void; - upgrade(params: IndicesUpgradeParams): Promise; - validateQuery(params: IndicesValidateQueryParams, callback: (error: any, response: any) => void): void; - validateQuery(params: IndicesValidateQueryParams): Promise; - } - - export interface IndicesAnalyzeParams extends GenericParams { - analyzer?: string; - charFilter?: NameList; - field?: string; - filter?: NameList; - index?: string; - perferLocal?: boolean; - text?: NameList; - tokenizer?: string; - explain?: boolean; - attributes?: NameList; - format?: ""; - } - - export interface IndicesClearCacheParams extends GenericParams { - fieldData?: boolean; - fielddata?: boolean; // yes the docs really have both - fields?: NameList; - query?: boolean; - ignoreUnavailable?: boolean; - allowNoIndices?: boolean; - expandWildcards?: ExpandWildcards; - index?: NameList; - recycler?: boolean; - request?: boolean; - } - - export interface IndicesCloseParams extends GenericParams { - timeout?: TimeSpan; - masterTimeout?: TimeSpan; - ignoreUnavailable?: boolean; - allowNoIndices?: boolean; - expandWildcards?: ExpandWildcards; - index: NameList; - } - - export interface IndicesCreateParams extends GenericParams { - waitForActiveShards?: string; - timeout?: TimeSpan; - masterTimeout?: TimeSpan; - updateAllTypes?: boolean; - index: string; - } - - export interface IndicesDeleteParams extends GenericParams { - timeout?: TimeSpan; - masterTimeout?: TimeSpan; - index: NameList; - } - - export interface IndicesDeleteAliasParams extends GenericParams { - timeout?: TimeSpan; - masterTimeout?: TimeSpan; - index: NameList; - name: NameList; - } - - export interface IndicesDeleteTemplateParams extends GenericParams { - timeout?: TimeSpan; - masterTimeout?: TimeSpan; - name: string; - } - - export interface IndicesExistsParams extends GenericParams { - ignoreUnavailable?: boolean; - allowNoIndices?: boolean; - expandWildcards?: ExpandWildcards; - local?: boolean; - index: NameList; - } - - export interface IndicesExistsAliasParams extends IndicesExistsParams { - name: NameList; - } - - export interface IndicesExistsTemplateParams extends GenericParams { - timeout?: TimeSpan; - masterTimeout?: TimeSpan; - name: NameList; - } - - export interface IndicesExistsTypeParams extends IndicesExistsParams { - type: NameList; - } - - export interface IndicesFlushParams extends GenericParams { - force?: boolean; - waitIfOngoing?: boolean; - ignoreUnavailable?: boolean; - allowNoIndices?: boolean; - expandWildcards?: ExpandWildcards; - index: NameList; - } - - export interface IndicesFlushSyncedParams extends GenericParams { - ignoreUnavailable?: boolean; - allowNoIndices?: boolean; - expandWildcards?: ExpandWildcards; - index: NameList; - } - - export interface IndicesForcemergeParams extends GenericParams { - flush?: boolean; - ignoreUnavailable?: boolean; - allowNoIndices?: boolean; - expandWildcards?: ExpandWildcards; - maxNumSegments?: number; - onlyExpungeDeletes?: boolean; - operationThreading?: any; // even the docs don't know what this does - waitForMerge?: boolean; - index: NameList; - } - - export interface IndicesGetParams extends GenericParams { - local?: boolean; - ignoreUnavailable?: boolean; - allowNoIndices?: boolean; - expandWildcards?: ExpandWildcards; - flatSettings?: boolean; - human?: boolean; - includeDefaults?: boolean; - index?: NameList; - feature?: NameList; - } - - export interface IndicesGetAliasParams extends GenericParams { - ignoreUnavailable?: boolean; - allowNoIndices?: boolean; - expandWildcards?: ExpandWildcards; - local?: boolean; - index?: NameList; - name?: NameList; - } - - export interface IndicesGetFieldMappingParams extends GenericParams { - includeDefaults?: boolean; - ignoreUnavailable?: boolean; - allowNoIndices?: boolean; - expandWildcards?: ExpandWildcards; - local?: boolean; - index?: NameList; - type?: NameList; - fields?: NameList; - } - - export interface IndicesGetMappingParams extends GenericParams { - ignoreUnavailable?: boolean; - allowNoIndices?: boolean; - expandWildcards?: ExpandWildcards; - local?: boolean; - index?: NameList; - type?: NameList; - } - - export interface IndicesGetSettingsParams extends GenericParams { - ignoreUnavailable?: boolean; - allowNoIndices?: boolean; - expandWildcards?: ExpandWildcards; - flatSettings?: boolean; - local?: boolean; - human?: boolean; - includeDefaults?: boolean; - index?: NameList; - name?: NameList; - } - - export interface IndicesGetTemplateParams extends GenericParams { - flatSettings?: boolean; - masterTimeout?: TimeSpan; - local?: boolean; - name?: NameList; - } - - export interface IndicesGetUpgradeParams extends GenericParams { - ignoreUnavailable?: boolean; - allowNoIndices?: boolean; - expandWildcards?: ExpandWildcards; - human?: boolean; - index?: NameList; - } - - export interface IndicesOpenParams extends GenericParams { - timeout?: TimeSpan; - masterTimeout?: TimeSpan; - ignoreUnavailable?: boolean; - allowNoIndices?: boolean; - expandWildcards?: ExpandWildcards; - index?: NameList; - } - - export interface IndicesPutAliasParams extends GenericParams { - timeout?: TimeSpan; - masterTimeout?: TimeSpan; - index?: NameList; - name: NameList; - } - - export interface IndicesPutMappingParams extends GenericParams { - timeout?: TimeSpan; - masterTimeout?: TimeSpan; - ignoreUnavailable?: boolean; - allowNoIndices?: boolean; - expandWildcards?: ExpandWildcards; - updateAllTypes?: boolean; - index: NameList; - type: string; - body: any; - } - - export interface IndicesPutSettingsParams extends GenericParams { - masterTimeout?: TimeSpan; - preserveExisting?: boolean; - ignoreUnavailable?: boolean; - allowNoIndices?: boolean; - expandWildcards?: ExpandWildcards; - flatSettings?: boolean; - index: NameList; - body: any; - } - - export interface IndicesPutTemplateParams extends GenericParams { - order?: number; - create?: boolean; - timeout?: TimeSpan; - masterTimeout?: TimeSpan; - flatSettings?: boolean; - name: string; - body: any; - } - - export interface IndicesRecoveryParams extends GenericParams { - detailed?: boolean; - activeOnly?: boolean; - human?: boolean; - index: NameList; - } - - export interface IndicesRefreshParams extends GenericParams { - ignoreUnavailable?: boolean; - allowNoIndices?: boolean; - expandWildcards?: ExpandWildcards; - force?: boolean; - operationThreading?: any; // even the docs don't know what this does - index: NameList; - } - - export interface IndicesRolloverParams extends GenericParams { - timeout?: TimeSpan; - masterTimeout?: TimeSpan; - waitForActiveShards?: number | string; - alias?: string; - newIndex?: string; - } - - export interface IndicesRolloverResponse { - acknowledged: boolean; - shards_acknowledged: boolean; - old_index: string; - new_index: string; - rolled_over: boolean; - dry_run: boolean; - conditions: { [condition: string]: boolean }; - } - - export interface IndicesSegmentsParams extends GenericParams { - ignoreUnavailable?: boolean; - allowNoIndices?: boolean; - expandWildcards?: ExpandWildcards; - human?: boolean; - operationThreading?: any; // even the docs don't know what this does - verbose?: boolean; - index: NameList; - } - - export interface IndicesShardStoresParams extends GenericParams { - status?: NameList; - ignoreUnavailable?: boolean; - allowNoIndices?: boolean; - expandWildcards?: ExpandWildcards; - operationThreading?: any; // even the docs don't know what this does - index: NameList; - } - - export interface IndicesShrinkParams extends GenericParams { - timeout?: TimeSpan; - masterTimeout?: TimeSpan; - waitForActiveShards?: string | number; - index: string; - target: string; - } - - export interface IndicesStatsParams extends GenericParams { - completionFields?: NameList; - fielddataFields?: NameList; - fields?: NameList; - groups?: NameList; - human?: boolean; - level?: "cluster" | "indices" | "shards"; - types?: NameList; - index: NameList; - metric?: NameList; - } - - export interface IndicesUpdateAliasesParams extends GenericParams { - timeout?: TimeSpan; - masterTimeout?: TimeSpan; - body: { - actions: IndicesUpdateAliasesParamsAction[]; - }; - } - - export interface IndicesUpdateAliasesParamsAction { - add?: { - index?: string; - indices?: string[]; - alias: string; - }; - remove?: { - index?: string; - indices?: string[]; - alias: string; - }; - remove_index?: { + dest: { index: string; + version_type?: string; + op_type?: string; + routing?: string; + pipeline?: string; }; - } - - export interface IndicesUpgradeParams extends GenericParams { - expandWildcards?: ExpandWildcards; - ignoreUnavailable?: boolean; - waitForCompletion?: boolean; - onlyAncientSegments?: boolean; - index: NameList; - } - - export interface IndicesValidateQueryParams extends GenericParams { - explain?: boolean; - ignoreUnavailable?: boolean; - allowNoIndices?: boolean; - expandWildcards?: ExpandWildcards; - operationThreading?: any; // even the docs don't know what this does - q?: string; - analyzer?: string; - analyzeWildcard?: boolean; - defaultOperator?: DefaultOperator; - df?: string; - lenient?: boolean; - lowercaseExpandedTerms?: boolean; - rewrite?: boolean; - index: NameList; - type?: NameList; - } - - export class Ingest { - deletePipeline(params: IngestDeletePipelineParams, callback: (error: any, response: any, status: any) => void): void; - deletePipeline(params: IngestDeletePipelineParams): Promise; - getPipeline(params: IngestGetPipelineParams, callback: (error: any, response: any, status: any) => void): void; - getPipeline(params: IngestGetPipelineParams): Promise; - putPipeline(params: IngestPutPipelineParams, callback: (error: any, response: any, status: any) => void): void; - putPipeline(params: IngestPutPipelineParams): Promise; - simulate(params: IngestSimulateParams, callback: (error: any, response: any, status: any) => void): void; - simulate(params: IngestSimulateParams): Promise; - } - - export interface IngestDeletePipelineParams extends GenericParams { - masterTimeout?: number; - timeout?: number; - id: string; - } - - export interface IngestGetPipelineParams extends GenericParams { - masterTimeout?: number; - id: string; - } - - export interface IngestPutPipelineParams extends GenericParams { - masterTimeout?: number; - timeout?: number; - id: string; - body: any; - } - - export interface IngestSimulateParams extends GenericParams { - verbose?: boolean; - id: string; - } - - export class Nodes { - hotThreads(params: NodesHotThreadsParams, callback: (error: any, response: any, status: any) => void): void; - hotThreads(params: NodesHotThreadsParams): Promise; - info(params: NodesInfoParams, callback: (error: any, response: any, status: any) => void): void; - info(params: NodesInfoParams): Promise; - stats(params: NodesStatsParams, callback: (error: any, response: any, status: any) => void): void; - stats(params: NodesStatsParams): Promise; - } - - export interface NodesHotThreadsParams extends GenericParams { - interval?: TimeSpan; - snapshots?: number; - threads?: number; - ignoreIdleThreads?: boolean; - type?: "cpu" | "wait" | "blocked"; - timeout?: TimeSpan; - nodeId: NameList; - } - - export interface NodesInfoParams extends GenericParams { - flatSettings?: boolean; - human?: boolean; - timeout?: TimeSpan; - nodeId: NameList; - metric?: NameList; - } - - export interface NodesStatsParams extends GenericParams { - completionFields?: NameList; - fielddataFields?: NameList; - fields?: NameList; - groups?: boolean; - human?: boolean; - level?: "indices" | "node" | "shards"; - types?: NameList; - timeout?: TimeSpan; - metric?: NameList; - indexMetric?: NameList; - nodeId?: NameList; - } - - export class Snapshot { - create(params: SnapshotCreateParams, callback: (error: any, response: any, status: any) => void): void; - create(params: SnapshotCreateParams): Promise; - createRepository(params: SnapshotCreateRepositoryParams, callback: (error: any, response: any, status: any) => void): void; - createRepository(params: SnapshotCreateRepositoryParams): Promise; - delete(params: SnapshotDeleteParams, callback: (error: any, response: any, status: any) => void): void; - delete(params: SnapshotDeleteParams): Promise; - deleteRepository(params: SnapshotDeleteRepositoryParams, callback: (error: any, response: any, status: any) => void): void; - deleteRepository(params: SnapshotDeleteRepositoryParams): Promise; - get(params: SnapshotGetParams, callback: (error: any, response: any, status: any) => void): void; - get(params: SnapshotGetParams): Promise; - getRepository(params: SnapshotGetRepositoryParams, callback: (error: any, response: any, status: any) => void): void; - getRepository(params: SnapshotGetRepositoryParams): Promise; - restore(params: SnapshotRestoreParams, callback: (error: any, response: any, status: any) => void): void; - restore(params: SnapshotRestoreParams): Promise; - status(params: SnapshotStatusParams, callback: (error: any, response: any, status: any) => void): void; - status(params: SnapshotStatusParams): Promise; - verifyRepository(params: SnapshotVerifyRepositoryParams, callback: (error: any, response: any, status: any) => void): void; - verifyRepository(params: SnapshotVerifyRepositoryParams): Promise; - } - - export interface SnapshotCreateParams extends GenericParams { - masterTimeout?: TimeSpan; - waitForCompletion?: boolean; - repository: string; - snapshot: string; - } - - export interface SnapshotCreateRepositoryParams extends GenericParams { - masterTimeout?: TimeSpan; - timeout?: TimeSpan; - verify?: boolean; - repository: string; - } - - export interface SnapshotDeleteParams extends GenericParams { - masterTimeout?: TimeSpan; - repository: string; - snapshot: string; - } - - export interface SnapshotDeleteRepositoryParams extends GenericParams { - masterTimeout?: TimeSpan; - timeout?: TimeSpan; - repository: string; - } - - export interface SnapshotGetParams extends GenericParams { - masterTimeout?: TimeSpan; - ignoreUnavailable?: boolean; - repository: string; - snapshot: NameList; - } - - export interface SnapshotGetRepositoryParams extends GenericParams { - masterTimeout?: TimeSpan; - local?: boolean; - repository: NameList; - } - - export interface SnapshotRestoreParams extends GenericParams { - masterTimeout?: TimeSpan; - waitForCompletion?: boolean; - repository: string; - snapshot: string; - } - - export interface SnapshotStatusParams extends GenericParams { - masterTimeout?: TimeSpan; - ignoreUnavailable?: boolean; - repository: string; - snapshot: NameList; - } - - export interface SnapshotVerifyRepositoryParams extends GenericParams { - masterTimeout?: TimeSpan; - timeout?: TimeSpan; - repository: string; - } - - export class Tasks { - cancel(params: TasksCancelParams, callback: (error: any, response: any, status: any) => void): void; - cancel(params: TasksCancelParams): Promise; - get(params: TasksGetParams, callback: (error: any, response: any, status: any) => void): void; - get(params: TasksGetParams): Promise; - list(params: TasksListParams, callback: (error: any, response: any, status: any) => void): void; - list(params: TasksListParams): Promise; - } - - export interface TasksCancelParams extends GenericParams { - nodeId?: NameList; - actions?: NameList; - parentNode?: string; - parentTask?: string; - taskId?: string; - } - - export interface TasksGetParams extends GenericParams { - waitForCompletion?: boolean; - taskId?: string; - } - - export interface TasksListParams extends GenericParams { - nodeId?: NameList; - actions?: NameList; - detailed?: boolean; - parentNode?: string; - parentTask?: string; - waitForCompletion?: boolean; - groupBy?: "nodes" | "parents"; - } + script?: { + inline: string; + lang: string; + } + }; } -declare module "elasticsearch" { - export = Elasticsearch; +export interface ReindexResponse { + took: number; + updated: number; + created: number; + batches: number; + version_conflicts: number; + retries: { + bulk: number; + search: number; + }; + throttled_millis: number; + failures: any[]; +} + +export interface ReindexRethrottleParams extends GenericParams { + requestsPerSecond: number; + taskId: string; +} + +export interface RenderSearchTemplateParams extends GenericParams { + id: string; +} + +export interface ScrollParams extends GenericParams { + scroll: TimeSpan; + scrollId: string; +} + +export interface SearchParams extends GenericParams { + analyzer?: string; + analyzeWildcard?: boolean; + defaultOperator?: DefaultOperator; + df?: string; + explain?: boolean; + storedFields?: NameList; + docvalueFields?: NameList; + fielddataFields?: NameList; + from?: number; + ignoreUnavailable?: boolean; + allowNoIndices?: boolean; + expandWildcards?: ExpandWildcards; + lenient?: boolean; + lowercaseExpandedTerms?: boolean; + preference?: string; + q?: string; + routing?: NameList; + scroll?: TimeSpan; + searchType?: "query_then_fetch" | "dfs_query_then_fetch"; + size?: number; + sort?: NameList; + _source?: NameList; + _sourceExclude?: NameList; + _sourceInclude?: NameList; + terminateAfter?: number; + stats?: NameList; + suggestField?: string; + suggestMode?: "missing" | "popular" | "always"; + suggestSize?: number; + suggestText?: string; + timeout?: TimeSpan; + trackScores?: boolean; + version?: boolean; + requestCache?: boolean; + index?: NameList; + type?: NameList; +} + +export interface SearchResponse { + took: number; + timed_out: boolean; + _scroll_id?: string; + _shards: ShardsResponse; + hits: { + total: number; + max_score: number; + hits: Array<{ + _index: string; + _type: string; + _id: string; + _score: number; + _source: T; + _version?: number; + _explanation?: Explanation; + fields?: any; + highlight?: any; + inner_hits?: any; + }>; + }; + aggregations?: any; +} + +export interface SearchShardsParams extends GenericParams { + preference?: string; + routing?: string; + local?: boolean; + ignoreUnavailable?: boolean; + allowNoIndices?: boolean; + expandWildcards?: ExpandWildcards; + index: NameList; + type: NameList; +} + +export interface SearchShardsResponse { + nodes: any; + shards: SearchShardsResponseShard[][]; +} + +export interface SearchShardsResponseShard { + index: string; + node: string; + primary: boolean; + share: number; + state: string; + allocation_id: { + id: string; + }; + relocating_node: any; +} + +export interface SearchTemplateParams extends GenericParams { + ignoreUnavailable?: boolean; + allowNoIndices?: boolean; + expandWildcards?: ExpandWildcards; + preference?: string; + routing?: NameList; + scroll?: TimeSpan; + searchType?: "query_then_fetch" | "query_and_fetch" | "dfs_query_then_fetch" | "dfs_query_and_fetch"; + index: NameList; + type: NameList; +} + +export interface SuggestParams extends GenericParams { + ignoreUnavailable?: boolean; + allowNoIndices?: boolean; + expandWildcards?: ExpandWildcards; + preference?: string; + routing?: string; + index: NameList; +} + +export interface TermvectorsParams extends GenericParams { + termStatistics?: boolean; + fieldStatistics?: boolean; + fields?: NameList; + offsets?: boolean; + positions?: boolean; + payloads?: boolean; + preference?: string; + routing?: string; + parent?: string; + realtime?: boolean; + version?: number; + versionType?: VersionType; + index: string; + type: string; + id?: string; +} + +export interface UpdateDocumentParams extends GenericParams { + waitForActiveShards?: string; + fields?: NameList; + _source?: NameList; + _sourceExclude?: NameList; + _sourceInclude?: NameList; + lang?: string; + parent?: string; + refresh?: Refresh; + retryOnConflict?: number; + routing?: string; + timeout?: TimeSpan; + timestamp?: Date | number; + ttl?: TimeSpan; + version?: number; + versionType?: "internal" | "force"; + id: string; + index: string; + type: string; +} + +export interface UpdateDocumentByQueryParams extends GenericParams { + analyzer?: string; + analyzeWildcard?: boolean; + defaultOperator?: DefaultOperator; + df?: string; + explain?: boolean; + storedFields?: NameList; + docvalueFields?: NameList; + fielddataFields?: NameList; + from?: number; + ignoreUnavailable?: boolean; + allowNoIndices?: boolean; + conflicts?: Conflicts; + expandWildcards?: ExpandWildcards; + lenient?: boolean; + lowercaseExpandedTerms?: boolean; + pipeline?: string; + preference?: string; + q?: string; + routing?: NameList; + scroll?: TimeSpan; + searchType?: "query_then_fetch" | "dfs_query_then_fetch"; + searchTimeout?: TimeSpan; + size?: number; + sort?: NameList; + _source?: NameList; + _sourceExclude?: NameList; + _sourceInclude?: NameList; + terminateAfter?: number; + stats?: NameList; + suggestField?: string; + suggestMode?: "missing" | "popular" | "always"; + suggestSize?: number; + suggestText?: string; + timeout?: TimeSpan; + trackScores?: boolean; + version?: boolean; + versionType?: boolean; + requestCache?: boolean; + refresh?: boolean; + waitForActiveShards?: string; + scrollSize?: number; + waitForCompletion?: boolean; + requestsPerSecond?: number; + index: NameList; + type: NameList; +} + +export interface Cat { + aliases(params: CatAliasesParams, callback: (error: any, response: any) => void): void; + aliases(params: CatAliasesParams): Promise; + allocation(params: CatAllocationParams, callback: (error: any, response: any) => void): void; + allocation(params: CatAllocationParams): Promise; + count(params: CatCountParams, callback: (error: any, response: any) => void): void; + count(params: CatAllocationParams): Promise; + fielddata(params: CatFielddataParams, callback: (error: any, response: any) => void): void; + fielddata(params: CatFielddataParams): Promise; + health(params: CatHealthParams, callback: (error: any, response: any) => void): void; + health(params: CatHealthParams): Promise; + help(params: CatHelpParams, callback: (error: any, response: any) => void): void; + help(params: CatHelpParams): Promise; + indices(params: CatIndicesParams, callback: (error: any, response: any) => void): void; + indices(params: CatIndicesParams): Promise; + master(params: CatCommonParams, callback: (error: any, response: any) => void): void; + master(params: CatCommonParams): Promise; + nodeattrs(params: CatCommonParams, callback: (error: any, response: any) => void): void; + nodeattrs(params: CatCommonParams): Promise; + nodes(params: CatCommonParams, callback: (error: any, response: any) => void): void; + nodes(params: CatCommonParams): Promise; + pendingTasks(params: CatCommonParams, callback: (error: any, response: any) => void): void; + pendingTasks(params: CatCommonParams): Promise; + plugins(params: CatCommonParams, callback: (error: any, response: any) => void): void; + plugins(params: CatCommonParams): Promise; + recovery(params: CatRecoveryParams, callback: (error: any, response: any) => void): void; + recovery(params: CatRecoveryParams): Promise; + repositories(params: CatCommonParams, callback: (error: any, response: any) => void): void; + repositories(params: CatCommonParams): Promise; + segments(params: CatSegmentsParams, callback: (error: any, response: any) => void): void; + segments(params: CatSegmentsParams): Promise; + shards(params: CatShardsParams, callback: (error: any, response: any) => void): void; + shards(params: CatShardsParams): Promise; + snapshots(params: CatSnapshotsParams, callback: (error: any, response: any) => void): void; + snapshots(params: CatSnapshotsParams): Promise; + tasks(params: CatTasksParams, callback: (error: any, response: any) => void): void; + tasks(params: CatTasksParams): Promise; + threadPool(params: CatThreadPoolParams, callback: (error: any, response: any) => void): void; + threadPool(params: CatThreadPoolParams): Promise; +} + +export type CatBytes = "b" | "k" | "kb" | "m" | "mb" | "g" | "gb" | "t" | "tb" | "p" | "pb"; + +export interface CatCommonParams extends GenericParams { + format: string; + local?: boolean; + masterTimeout?: TimeSpan; + h?: NameList; + help?: boolean; + v?: boolean; +} + +export interface CatAliasesParams extends CatCommonParams { + name?: NameList; +} + +export interface CatAllocationParams extends CatCommonParams { + bytes?: CatBytes; + nodeId?: NameList; +} + +export interface CatCountParams extends CatCommonParams { + index?: NameList; +} + +export interface CatFielddataParams extends CatCommonParams { + bytes?: CatBytes; + fields?: NameList; +} + +export interface CatHealthParams extends CatCommonParams { + ts?: boolean; +} + +export interface CatHelpParams extends GenericParams { + help?: boolean; +} + +export interface CatIndicesParams extends CatCommonParams { + bytes?: CatBytes; + health?: "green" | "yellow" | "red"; + pri?: boolean; + index?: NameList; +} + +export interface CatRecoveryParams extends GenericParams { + format: string; + bytes?: CatBytes; + masterTimeout?: TimeSpan; + h?: NameList; + help?: boolean; + v?: boolean; +} + +export interface CatSegmentsParams extends GenericParams { + format: string; + h?: NameList; + help?: boolean; + v?: boolean; + index?: NameList; +} + +export interface CatShardsParams extends CatCommonParams { + index?: NameList; +} + +export interface CatSnapshotsParams extends GenericParams { + format: string; + ignoreUnavailable?: boolean; + masterTimeout?: TimeSpan; + h?: NameList; + help?: boolean; + v?: boolean; + repository?: NameList; +} + +export interface CatTasksParams extends GenericParams { + format: string; + nodeId?: NameList; + actions?: NameList; + detailed?: boolean; + parentNode?: string; + parentTask?: number; + h?: NameList; + help?: boolean; + v?: boolean; +} + +export interface CatThreadPoolParams extends CatCommonParams { + size?: "" | "k" | "m" | "g" | "t" | "p"; + threadPoolPatterns?: NameList; +} + +export interface Cluster { + allocationExplain(params: ClusterAllocationExplainParams, callback: (error: any, response: any) => void): void; + allocationExplain(params: ClusterAllocationExplainParams): Promise; + getSettings(params: ClusterGetSettingsParams, callback: (error: any, response: any) => void): void; + getSettings(params: ClusterGetSettingsParams): Promise; + health(params: ClusterHealthParams, callback: (error: any, response: any) => void): void; + health(params: ClusterHealthParams): Promise; + pendingTasks(params: ClusterPendingTasksParams, callback: (error: any, response: any) => void): void; + pendingTasks(params: ClusterPendingTasksParams): Promise; + putSettings(params: ClusterPutSettingsParams, callback: (error: any, response: any) => void): void; + putSettings(params: ClusterPutSettingsParams): Promise; + reroute(params: ClusterRerouteParams, callback: (error: any, response: any) => void): void; + reroute(params: ClusterRerouteParams): Promise; + state(params: ClusterStateParams, callback: (error: any, response: any) => void): void; + state(params: ClusterStateParams): Promise; + stats(params: ClusterStatsParams, callback: (error: any, response: any) => void): void; + stats(params: ClusterStatsParams): Promise; +} + +export interface ClusterAllocationExplainParams extends GenericParams { + includeYesDecisions?: boolean; + includeDiskInfo?: boolean; +} + +export interface ClusterGetSettingsParams extends GenericParams { + flatSettings?: boolean; + masterTimeout?: TimeSpan; + timeout?: TimeSpan; + includeDefaults?: boolean; +} + +export interface ClusterHealthParams extends GenericParams { + level?: "cluster" | "indices" | "shards"; + local?: boolean; + masterTimeout?: TimeSpan; + waitForActiveShards?: string; + waitForNodes?: string; + waitForEvents?: "immediate" | "urgent" | "high" | "normal" | "low" | "languid"; + waitForRelocatingShards?: boolean; + waitForStatus?: "green" | "yellow" | "red"; + index?: NameList; +} + +export interface ClusterPendingTasksParams extends GenericParams { + local?: boolean; + masterTimeout?: TimeSpan; +} + +export interface ClusterPutSettingsParams extends GenericParams { + flatSettings?: boolean; + masterTimeout?: TimeSpan; + timeout?: TimeSpan; +} + +export interface ClusterRerouteParams extends GenericParams { + dryRun?: boolean; + explain?: boolean; + retryFailed?: boolean; + metric?: NameList; + masterTimeout?: TimeSpan; + timeout?: TimeSpan; +} + +export interface ClusterStateParams extends GenericParams { + local?: boolean; + masterTimeout?: TimeSpan; + flatSettings?: boolean; + ignoreUnavailable?: boolean; + allowNoIndices?: boolean; + expandWildcards?: ExpandWildcards; + index?: NameList; + metric?: NameList; +} + +export interface ClusterStatsParams extends GenericParams { + flatSettings?: boolean; + human?: boolean; + timeout?: TimeSpan; + nodeId?: NameList; +} + +export class Indices { + analyze(params: IndicesAnalyzeParams, callback: (error: any, response: any, status: any) => void): void; + analyze(params: IndicesAnalyzeParams): Promise; + clearCache(params: IndicesClearCacheParams, callback: (error: any, response: any, status: any) => void): void; + clearCache(params: IndicesClearCacheParams): Promise; + close(params: IndicesCloseParams, callback: (error: any, response: any, status: any) => void): void; + close(params: IndicesCloseParams): Promise; + create(params: IndicesCreateParams, callback: (error: any, response: any, status: any) => void): void; + create(params: IndicesCreateParams): Promise; + delete(params: IndicesDeleteParams, callback: (error: any, response: any, status: any) => void): void; + delete(params: IndicesDeleteParams): Promise; + deleteAlias(params: IndicesDeleteAliasParams, callback: (error: any, response: any, status: any) => void): void; + deleteAlias(params: IndicesDeleteAliasParams): Promise; + deleteTemplate(params: IndicesDeleteTemplateParams, callback: (error: any, response: any, status: any) => void): void; + deleteTemplate(params: IndicesDeleteTemplateParams): Promise; + exists(params: IndicesExistsParams, callback: (error: any, response: any, status: any) => void): void; + exists(params: IndicesExistsParams): Promise; + existsAlias(params: IndicesExistsAliasParams, callback: (error: any, response: any, status: any) => void): void; + existsAlias(params: IndicesExistsAliasParams): Promise; + existsTemplate(params: IndicesExistsTemplateParams, callback: (error: any, response: any, status: any) => void): void; + existsTemplate(params: IndicesExistsTemplateParams): Promise; + existsType(params: IndicesExistsTypeParams, callback: (error: any, response: any, status: any) => void): void; + existsType(params: IndicesExistsTypeParams): Promise; + flush(params: IndicesFlushParams, callback: (error: any, response: any, status: any) => void): void; + flush(params: IndicesFlushParams): Promise; + flushSynced(params: IndicesFlushSyncedParams, callback: (error: any, response: any, status: any) => void): void; + flushSynced(params: IndicesFlushSyncedParams): Promise; + forcemerge(params: IndicesForcemergeParams, callback: (error: any, response: any, status: any) => void): void; + forcemerge(params: IndicesForcemergeParams): Promise; + get(params: IndicesGetParams, callback: (error: any, response: any, status: any) => void): void; + get(params: IndicesGetParams): Promise; + getAlias(params: IndicesGetAliasParams, callback: (error: any, response: any, status: any) => void): void; + getAlias(params: IndicesGetAliasParams): Promise; + getFieldMapping(params: IndicesGetFieldMappingParams, callback: (error: any, response: any, status: any) => void): void; + getFieldMapping(params: IndicesGetFieldMappingParams): Promise; + getMapping(params: IndicesGetMappingParams, callback: (error: any, response: any, status: any) => void): void; + getMapping(params: IndicesGetMappingParams): Promise; + getSettings(params: IndicesGetSettingsParams, callback: (error: any, response: any, status: any) => void): void; + getSettings(params: IndicesGetSettingsParams): Promise; + getTemplate(params: IndicesGetTemplateParams, callback: (error: any, response: any, status: any) => void): void; + getTemplate(params: IndicesGetTemplateParams): Promise; + getUpgrade(params: IndicesGetUpgradeParams, callback: (error: any, response: any, status: any) => void): void; + getUpgrade(params: IndicesGetUpgradeParams): Promise; + open(params: IndicesOpenParams, callback: (error: any, response: any, status: any) => void): void; + open(params: IndicesOpenParams): Promise; + putAlias(params: IndicesPutAliasParams, callback: (error: any, response: any, status: any) => void): void; + putAlias(params: IndicesPutAliasParams): Promise; + putMapping(params: IndicesPutMappingParams, callback: (error: any, response: any, status: any) => void): void; + putMapping(params: IndicesPutMappingParams): Promise; + putSettings(params: IndicesPutSettingsParams, callback: (error: any, response: any, status: any) => void): void; + putSettings(params: IndicesPutSettingsParams): Promise; + putTemplate(params: IndicesPutTemplateParams, callback: (error: any, response: any) => void): void; + putTemplate(params: IndicesPutTemplateParams): Promise; + recovery(params: IndicesRecoveryParams, callback: (error: any, response: any) => void): void; + recovery(params: IndicesRecoveryParams): Promise; + refresh(params: IndicesRefreshParams, callback: (error: any, response: any) => void): void; + refresh(params: IndicesRefreshParams): Promise; + rollover(params: IndicesRolloverParams, callback: (error: any, response: IndicesRolloverResponse) => void): void; + rollover(params: IndicesRolloverParams): Promise; + segments(params: IndicesSegmentsParams, callback: (error: any, response: any) => void): void; + segments(params: IndicesSegmentsParams): Promise; + shardStores(params: IndicesShardStoresParams, callback: (error: any, response: any) => void): void; + shardStores(params: IndicesShardStoresParams): Promise; + shrink(params: IndicesShrinkParams, callback: (error: any, response: any) => void): void; + shrink(params: IndicesShrinkParams): Promise; + stats(params: IndicesStatsParams, callback: (error: any, response: any) => void): void; + stats(params: IndicesStatsParams): Promise; + updateAliases(params: IndicesUpdateAliasesParams, callback: (error: any, response: any) => void): void; + updateAliases(params: IndicesUpdateAliasesParams): Promise; + upgrade(params: IndicesUpgradeParams, callback: (error: any, response: any) => void): void; + upgrade(params: IndicesUpgradeParams): Promise; + validateQuery(params: IndicesValidateQueryParams, callback: (error: any, response: any) => void): void; + validateQuery(params: IndicesValidateQueryParams): Promise; +} + +export interface IndicesAnalyzeParams extends GenericParams { + analyzer?: string; + charFilter?: NameList; + field?: string; + filter?: NameList; + index?: string; + perferLocal?: boolean; + text?: NameList; + tokenizer?: string; + explain?: boolean; + attributes?: NameList; + format?: ""; +} + +export interface IndicesClearCacheParams extends GenericParams { + fieldData?: boolean; + fielddata?: boolean; // yes the docs really have both + fields?: NameList; + query?: boolean; + ignoreUnavailable?: boolean; + allowNoIndices?: boolean; + expandWildcards?: ExpandWildcards; + index?: NameList; + recycler?: boolean; + request?: boolean; +} + +export interface IndicesCloseParams extends GenericParams { + timeout?: TimeSpan; + masterTimeout?: TimeSpan; + ignoreUnavailable?: boolean; + allowNoIndices?: boolean; + expandWildcards?: ExpandWildcards; + index: NameList; +} + +export interface IndicesCreateParams extends GenericParams { + waitForActiveShards?: string; + timeout?: TimeSpan; + masterTimeout?: TimeSpan; + updateAllTypes?: boolean; + index: string; +} + +export interface IndicesDeleteParams extends GenericParams { + timeout?: TimeSpan; + masterTimeout?: TimeSpan; + index: NameList; +} + +export interface IndicesDeleteAliasParams extends GenericParams { + timeout?: TimeSpan; + masterTimeout?: TimeSpan; + index: NameList; + name: NameList; +} + +export interface IndicesDeleteTemplateParams extends GenericParams { + timeout?: TimeSpan; + masterTimeout?: TimeSpan; + name: string; +} + +export interface IndicesExistsParams extends GenericParams { + ignoreUnavailable?: boolean; + allowNoIndices?: boolean; + expandWildcards?: ExpandWildcards; + local?: boolean; + index: NameList; +} + +export interface IndicesExistsAliasParams extends IndicesExistsParams { + name: NameList; +} + +export interface IndicesExistsTemplateParams extends GenericParams { + timeout?: TimeSpan; + masterTimeout?: TimeSpan; + name: NameList; +} + +export interface IndicesExistsTypeParams extends IndicesExistsParams { + type: NameList; +} + +export interface IndicesFlushParams extends GenericParams { + force?: boolean; + waitIfOngoing?: boolean; + ignoreUnavailable?: boolean; + allowNoIndices?: boolean; + expandWildcards?: ExpandWildcards; + index: NameList; +} + +export interface IndicesFlushSyncedParams extends GenericParams { + ignoreUnavailable?: boolean; + allowNoIndices?: boolean; + expandWildcards?: ExpandWildcards; + index: NameList; +} + +export interface IndicesForcemergeParams extends GenericParams { + flush?: boolean; + ignoreUnavailable?: boolean; + allowNoIndices?: boolean; + expandWildcards?: ExpandWildcards; + maxNumSegments?: number; + onlyExpungeDeletes?: boolean; + operationThreading?: any; // even the docs don't know what this does + waitForMerge?: boolean; + index: NameList; +} + +export interface IndicesGetParams extends GenericParams { + local?: boolean; + ignoreUnavailable?: boolean; + allowNoIndices?: boolean; + expandWildcards?: ExpandWildcards; + flatSettings?: boolean; + human?: boolean; + includeDefaults?: boolean; + index?: NameList; + feature?: NameList; +} + +export interface IndicesGetAliasParams extends GenericParams { + ignoreUnavailable?: boolean; + allowNoIndices?: boolean; + expandWildcards?: ExpandWildcards; + local?: boolean; + index?: NameList; + name?: NameList; +} + +export interface IndicesGetFieldMappingParams extends GenericParams { + includeDefaults?: boolean; + ignoreUnavailable?: boolean; + allowNoIndices?: boolean; + expandWildcards?: ExpandWildcards; + local?: boolean; + index?: NameList; + type?: NameList; + fields?: NameList; +} + +export interface IndicesGetMappingParams extends GenericParams { + ignoreUnavailable?: boolean; + allowNoIndices?: boolean; + expandWildcards?: ExpandWildcards; + local?: boolean; + index?: NameList; + type?: NameList; +} + +export interface IndicesGetSettingsParams extends GenericParams { + ignoreUnavailable?: boolean; + allowNoIndices?: boolean; + expandWildcards?: ExpandWildcards; + flatSettings?: boolean; + local?: boolean; + human?: boolean; + includeDefaults?: boolean; + index?: NameList; + name?: NameList; +} + +export interface IndicesGetTemplateParams extends GenericParams { + flatSettings?: boolean; + masterTimeout?: TimeSpan; + local?: boolean; + name?: NameList; +} + +export interface IndicesGetUpgradeParams extends GenericParams { + ignoreUnavailable?: boolean; + allowNoIndices?: boolean; + expandWildcards?: ExpandWildcards; + human?: boolean; + index?: NameList; +} + +export interface IndicesOpenParams extends GenericParams { + timeout?: TimeSpan; + masterTimeout?: TimeSpan; + ignoreUnavailable?: boolean; + allowNoIndices?: boolean; + expandWildcards?: ExpandWildcards; + index?: NameList; +} + +export interface IndicesPutAliasParams extends GenericParams { + timeout?: TimeSpan; + masterTimeout?: TimeSpan; + index?: NameList; + name: NameList; +} + +export interface IndicesPutMappingParams extends GenericParams { + timeout?: TimeSpan; + masterTimeout?: TimeSpan; + ignoreUnavailable?: boolean; + allowNoIndices?: boolean; + expandWildcards?: ExpandWildcards; + updateAllTypes?: boolean; + index: NameList; + type: string; + body: any; +} + +export interface IndicesPutSettingsParams extends GenericParams { + masterTimeout?: TimeSpan; + preserveExisting?: boolean; + ignoreUnavailable?: boolean; + allowNoIndices?: boolean; + expandWildcards?: ExpandWildcards; + flatSettings?: boolean; + index: NameList; + body: any; +} + +export interface IndicesPutTemplateParams extends GenericParams { + order?: number; + create?: boolean; + timeout?: TimeSpan; + masterTimeout?: TimeSpan; + flatSettings?: boolean; + name: string; + body: any; +} + +export interface IndicesRecoveryParams extends GenericParams { + detailed?: boolean; + activeOnly?: boolean; + human?: boolean; + index: NameList; +} + +export interface IndicesRefreshParams extends GenericParams { + ignoreUnavailable?: boolean; + allowNoIndices?: boolean; + expandWildcards?: ExpandWildcards; + force?: boolean; + operationThreading?: any; // even the docs don't know what this does + index: NameList; +} + +export interface IndicesRolloverParams extends GenericParams { + timeout?: TimeSpan; + masterTimeout?: TimeSpan; + waitForActiveShards?: number | string; + alias?: string; + newIndex?: string; +} + +export interface IndicesRolloverResponse { + acknowledged: boolean; + shards_acknowledged: boolean; + old_index: string; + new_index: string; + rolled_over: boolean; + dry_run: boolean; + conditions: { [condition: string]: boolean }; +} + +export interface IndicesSegmentsParams extends GenericParams { + ignoreUnavailable?: boolean; + allowNoIndices?: boolean; + expandWildcards?: ExpandWildcards; + human?: boolean; + operationThreading?: any; // even the docs don't know what this does + verbose?: boolean; + index: NameList; +} + +export interface IndicesShardStoresParams extends GenericParams { + status?: NameList; + ignoreUnavailable?: boolean; + allowNoIndices?: boolean; + expandWildcards?: ExpandWildcards; + operationThreading?: any; // even the docs don't know what this does + index: NameList; +} + +export interface IndicesShrinkParams extends GenericParams { + timeout?: TimeSpan; + masterTimeout?: TimeSpan; + waitForActiveShards?: string | number; + index: string; + target: string; +} + +export interface IndicesStatsParams extends GenericParams { + completionFields?: NameList; + fielddataFields?: NameList; + fields?: NameList; + groups?: NameList; + human?: boolean; + level?: "cluster" | "indices" | "shards"; + types?: NameList; + index: NameList; + metric?: NameList; +} + +export interface IndicesUpdateAliasesParams extends GenericParams { + timeout?: TimeSpan; + masterTimeout?: TimeSpan; + body: { + actions: IndicesUpdateAliasesParamsAction[]; + }; +} + +export interface IndicesUpdateAliasesParamsAction { + add?: { + index?: string; + indices?: string[]; + alias: string; + }; + remove?: { + index?: string; + indices?: string[]; + alias: string; + }; + remove_index?: { + index: string; + }; +} + +export interface IndicesUpgradeParams extends GenericParams { + expandWildcards?: ExpandWildcards; + ignoreUnavailable?: boolean; + waitForCompletion?: boolean; + onlyAncientSegments?: boolean; + index: NameList; +} + +export interface IndicesValidateQueryParams extends GenericParams { + explain?: boolean; + ignoreUnavailable?: boolean; + allowNoIndices?: boolean; + expandWildcards?: ExpandWildcards; + operationThreading?: any; // even the docs don't know what this does + q?: string; + analyzer?: string; + analyzeWildcard?: boolean; + defaultOperator?: DefaultOperator; + df?: string; + lenient?: boolean; + lowercaseExpandedTerms?: boolean; + rewrite?: boolean; + index: NameList; + type?: NameList; +} + +export class Ingest { + deletePipeline(params: IngestDeletePipelineParams, callback: (error: any, response: any, status: any) => void): void; + deletePipeline(params: IngestDeletePipelineParams): Promise; + getPipeline(params: IngestGetPipelineParams, callback: (error: any, response: any, status: any) => void): void; + getPipeline(params: IngestGetPipelineParams): Promise; + putPipeline(params: IngestPutPipelineParams, callback: (error: any, response: any, status: any) => void): void; + putPipeline(params: IngestPutPipelineParams): Promise; + simulate(params: IngestSimulateParams, callback: (error: any, response: any, status: any) => void): void; + simulate(params: IngestSimulateParams): Promise; +} + +export interface IngestDeletePipelineParams extends GenericParams { + masterTimeout?: number; + timeout?: number; + id: string; +} + +export interface IngestGetPipelineParams extends GenericParams { + masterTimeout?: number; + id: string; +} + +export interface IngestPutPipelineParams extends GenericParams { + masterTimeout?: number; + timeout?: number; + id: string; + body: any; +} + +export interface IngestSimulateParams extends GenericParams { + verbose?: boolean; + id: string; +} + +export class Nodes { + hotThreads(params: NodesHotThreadsParams, callback: (error: any, response: any, status: any) => void): void; + hotThreads(params: NodesHotThreadsParams): Promise; + info(params: NodesInfoParams, callback: (error: any, response: any, status: any) => void): void; + info(params: NodesInfoParams): Promise; + stats(params: NodesStatsParams, callback: (error: any, response: any, status: any) => void): void; + stats(params: NodesStatsParams): Promise; +} + +export interface NodesHotThreadsParams extends GenericParams { + interval?: TimeSpan; + snapshots?: number; + threads?: number; + ignoreIdleThreads?: boolean; + type?: "cpu" | "wait" | "blocked"; + timeout?: TimeSpan; + nodeId: NameList; +} + +export interface NodesInfoParams extends GenericParams { + flatSettings?: boolean; + human?: boolean; + timeout?: TimeSpan; + nodeId: NameList; + metric?: NameList; +} + +export interface NodesStatsParams extends GenericParams { + completionFields?: NameList; + fielddataFields?: NameList; + fields?: NameList; + groups?: boolean; + human?: boolean; + level?: "indices" | "node" | "shards"; + types?: NameList; + timeout?: TimeSpan; + metric?: NameList; + indexMetric?: NameList; + nodeId?: NameList; +} + +export class Snapshot { + create(params: SnapshotCreateParams, callback: (error: any, response: any, status: any) => void): void; + create(params: SnapshotCreateParams): Promise; + createRepository(params: SnapshotCreateRepositoryParams, callback: (error: any, response: any, status: any) => void): void; + createRepository(params: SnapshotCreateRepositoryParams): Promise; + delete(params: SnapshotDeleteParams, callback: (error: any, response: any, status: any) => void): void; + delete(params: SnapshotDeleteParams): Promise; + deleteRepository(params: SnapshotDeleteRepositoryParams, callback: (error: any, response: any, status: any) => void): void; + deleteRepository(params: SnapshotDeleteRepositoryParams): Promise; + get(params: SnapshotGetParams, callback: (error: any, response: any, status: any) => void): void; + get(params: SnapshotGetParams): Promise; + getRepository(params: SnapshotGetRepositoryParams, callback: (error: any, response: any, status: any) => void): void; + getRepository(params: SnapshotGetRepositoryParams): Promise; + restore(params: SnapshotRestoreParams, callback: (error: any, response: any, status: any) => void): void; + restore(params: SnapshotRestoreParams): Promise; + status(params: SnapshotStatusParams, callback: (error: any, response: any, status: any) => void): void; + status(params: SnapshotStatusParams): Promise; + verifyRepository(params: SnapshotVerifyRepositoryParams, callback: (error: any, response: any, status: any) => void): void; + verifyRepository(params: SnapshotVerifyRepositoryParams): Promise; +} + +export interface SnapshotCreateParams extends GenericParams { + masterTimeout?: TimeSpan; + waitForCompletion?: boolean; + repository: string; + snapshot: string; +} + +export interface SnapshotCreateRepositoryParams extends GenericParams { + masterTimeout?: TimeSpan; + timeout?: TimeSpan; + verify?: boolean; + repository: string; +} + +export interface SnapshotDeleteParams extends GenericParams { + masterTimeout?: TimeSpan; + repository: string; + snapshot: string; +} + +export interface SnapshotDeleteRepositoryParams extends GenericParams { + masterTimeout?: TimeSpan; + timeout?: TimeSpan; + repository: string; +} + +export interface SnapshotGetParams extends GenericParams { + masterTimeout?: TimeSpan; + ignoreUnavailable?: boolean; + repository: string; + snapshot: NameList; +} + +export interface SnapshotGetRepositoryParams extends GenericParams { + masterTimeout?: TimeSpan; + local?: boolean; + repository: NameList; +} + +export interface SnapshotRestoreParams extends GenericParams { + masterTimeout?: TimeSpan; + waitForCompletion?: boolean; + repository: string; + snapshot: string; +} + +export interface SnapshotStatusParams extends GenericParams { + masterTimeout?: TimeSpan; + ignoreUnavailable?: boolean; + repository: string; + snapshot: NameList; +} + +export interface SnapshotVerifyRepositoryParams extends GenericParams { + masterTimeout?: TimeSpan; + timeout?: TimeSpan; + repository: string; +} + +export class Tasks { + cancel(params: TasksCancelParams, callback: (error: any, response: any, status: any) => void): void; + cancel(params: TasksCancelParams): Promise; + get(params: TasksGetParams, callback: (error: any, response: any, status: any) => void): void; + get(params: TasksGetParams): Promise; + list(params: TasksListParams, callback: (error: any, response: any, status: any) => void): void; + list(params: TasksListParams): Promise; +} + +export interface TasksCancelParams extends GenericParams { + nodeId?: NameList; + actions?: NameList; + parentNode?: string; + parentTask?: string; + taskId?: string; +} + +export interface TasksGetParams extends GenericParams { + waitForCompletion?: boolean; + taskId?: string; +} + +export interface TasksListParams extends GenericParams { + nodeId?: NameList; + actions?: NameList; + detailed?: boolean; + parentNode?: string; + parentTask?: string; + waitForCompletion?: boolean; + groupBy?: "nodes" | "parents"; +} + +export namespace errors { + class _Abstract extends Error {} + class Generic extends _Abstract {} + class ConnectionFault extends _Abstract {} + class NoConnections extends _Abstract {} + class Serialization extends _Abstract {} + class RequestTypeError extends _Abstract {} + + class AuthenticationException extends _Abstract {} + class AuthorizationException extends _Abstract {} + class BadGateway extends _Abstract {} + class BadRequest extends _Abstract {} + class BlockedByWindowsParentalControls extends _Abstract {} + class ClientClosedRequest extends _Abstract {} + class Conflict extends _Abstract {} + class ExpectationFailed extends _Abstract {} + class GatewayTimeout extends _Abstract {} + class HTTPToHTTPS extends _Abstract {} + class HTTPVersionNotSupported extends _Abstract {} + class ImATeapot extends _Abstract {} + class InternalServerError extends _Abstract {} + class LengthRequired extends _Abstract {} + class MethodNotAllowed extends _Abstract {} + class MovedPermanently extends _Abstract {} + class MultipleChoices extends _Abstract {} + class NotAcceptable extends _Abstract {} + class NotExtended extends _Abstract {} + class NotFound extends _Abstract {} + class NotImplemented extends _Abstract {} + class NotModified extends _Abstract {} + class PaymentRequired extends _Abstract {} + class PermanentRedirect extends _Abstract {} + class PreconditionFailed extends _Abstract {} + class ProxyAuthenticationRequired extends _Abstract {} + class RequestedRangeNotSatisfiable extends _Abstract {} + class RequestEntityTooLarge extends _Abstract {} + class RequestHeaderTooLarge extends _Abstract {} + class RequestTimeout extends _Abstract {} + class RequestURITooLong extends _Abstract {} + class SeeOther extends _Abstract {} + class ServiceUnavailable extends _Abstract {} + class TemporaryRedirect extends _Abstract {} + class TooManyConnectionsFromThisIP extends _Abstract {} + class TooManyRequests extends _Abstract {} + class UnsupportedMediaType extends _Abstract {} + class UpgradeRequired extends _Abstract {} + class UseProxy extends _Abstract {} + class VariantAlsoNegotiates extends _Abstract {} } diff --git a/types/elasticsearch/tsconfig.json b/types/elasticsearch/tsconfig.json index 2d62eac43d..21ac20d7e9 100644 --- a/types/elasticsearch/tsconfig.json +++ b/types/elasticsearch/tsconfig.json @@ -7,7 +7,7 @@ ], "noImplicitAny": true, "noImplicitThis": true, - "strictNullChecks": false, + "strictNullChecks": true, "strictFunctionTypes": true, "baseUrl": "../", "typeRoots": [ @@ -21,4 +21,4 @@ "index.d.ts", "elasticsearch-tests.ts" ] -} \ No newline at end of file +} diff --git a/types/elasticsearch/tslint.json b/types/elasticsearch/tslint.json index a41bf5d19a..e9003e412b 100644 --- a/types/elasticsearch/tslint.json +++ b/types/elasticsearch/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-empty-interface": false } } diff --git a/types/ember-data/index.d.ts b/types/ember-data/index.d.ts new file mode 100644 index 0000000000..0e0678e7d7 --- /dev/null +++ b/types/ember-data/index.d.ts @@ -0,0 +1,1693 @@ +// Type definitions for ember-data 2.14 +// Project: https://github.com/emberjs/data +// Definitions by: Derek Wickern +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.4 + +import Ember from 'ember'; + +declare namespace DS { + /** + * Convert an hash of errors into an array with errors in JSON-API format. + */ + function errorsHashToArray(errors: {}): any[]; + /** + * Convert an array of errors in JSON-API format into an object. + */ + function errorsArrayToHash(errors: any[]): {}; + /** + * `DS.belongsTo` is used to define One-To-One and One-To-Many + * relationships on a [DS.Model](/api/data/classes/DS.Model.html). + */ + function belongsTo(modelName: string, options: { + async: false, + inverse?: string | null, + polymorphic?: boolean + }): Ember.ComputedProperty; + function belongsTo(modelName: string, options?: { + async?: true, + inverse?: string | null, + polymorphic?: boolean + }): Ember.ComputedProperty>; + /** + * `DS.hasMany` is used to define One-To-Many and Many-To-Many + * relationships on a [DS.Model](/api/data/classes/DS.Model.html). + */ + function hasMany(type: string, options: { + async: false, + inverse?: string | null, + polymorphic?: boolean + }): Ember.ComputedProperty>; + function hasMany(type: string, options?: { + async?: true, + inverse?: string | null, + polymorphic?: boolean + }): Ember.ComputedProperty>; + /** + * This method normalizes a modelName into the format Ember Data uses + * internally. + */ + function normalizeModelName(modelName: string): string; + const VERSION: string; + + interface AttrOptions { + defaultValue?: T | (() => T); + } + + /** + * `DS.attr` defines an attribute on a [DS.Model](/api/data/classes/DS.Model.html). + * By default, attributes are passed through as-is, however you can specify an + * optional type to have the value automatically transformed. + * Ember Data ships with four basic transform types: `string`, `number`, + * `boolean` and `date`. You can define your own transforms by subclassing + * [DS.Transform](/api/data/classes/DS.Transform.html). + */ + function attr(type: 'string', options?: AttrOptions): Ember.ComputedProperty; + function attr(type: 'boolean', options?: AttrOptions): Ember.ComputedProperty; + function attr(type: 'number', options?: AttrOptions): Ember.ComputedProperty; + function attr(type: 'date', options?: AttrOptions): Ember.ComputedProperty; + function attr(type: string, options?: AttrOptions): Ember.ComputedProperty; + function attr(options?: AttrOptions): Ember.ComputedProperty; + /** + * WARNING: This interface is likely to change in order to accomodate https://github.com/emberjs/rfcs/pull/4 + * ## Using BuildURLMixin + * To use url building, include the mixin when extending an adapter, and call `buildURL` where needed. + * The default behaviour is designed for RESTAdapter. + * ### Example + * ```javascript + * export default DS.Adapter.extend(BuildURLMixin, { + * findRecord: function(store, type, id, snapshot) { + * var url = this.buildURL(type.modelName, id, snapshot, 'findRecord'); + * return this.ajax(url, 'GET'); + * } + * }); + * ``` + * ### Attributes + * The `host` and `namespace` attributes will be used if defined, and are optional. + */ + class BuildURLMixin { + /** + * Builds a URL for a given type and optional ID. + */ + buildURL(modelName: string, id: string|any[]|{}, snapshot: Snapshot|any[], requestType: string, query: {}): string; + /** + * Builds a URL for a `store.findRecord(type, id)` call. + */ + urlForFindRecord(id: string, modelName: string, snapshot: Snapshot): string; + /** + * Builds a URL for a `store.findAll(type)` call. + */ + urlForFindAll(modelName: string, snapshot: SnapshotRecordArray): string; + /** + * Builds a URL for a `store.query(type, query)` call. + */ + urlForQuery(query: {}, modelName: string): string; + /** + * Builds a URL for a `store.queryRecord(type, query)` call. + */ + urlForQueryRecord(query: {}, modelName: string): string; + /** + * Builds a URL for coalesceing multiple `store.findRecord(type, id)` + * records into 1 request when the adapter's `coalesceFindRequests` + * property is true. + */ + urlForFindMany(ids: any[], modelName: string, snapshots: any[]): string; + /** + * Builds a URL for fetching a async hasMany relationship when a url + * is not provided by the server. + */ + urlForFindHasMany(id: string, modelName: string, snapshot: Snapshot): string; + /** + * Builds a URL for fetching a async belongsTo relationship when a url + * is not provided by the server. + */ + urlForFindBelongsTo(id: string, modelName: string, snapshot: Snapshot): string; + /** + * Builds a URL for a `record.save()` call when the record was created + * locally using `store.createRecord()`. + */ + urlForCreateRecord(modelName: string, snapshot: Snapshot): string; + /** + * Builds a URL for a `record.save()` call when the record has been update locally. + */ + urlForUpdateRecord(id: string, modelName: string, snapshot: Snapshot): string; + /** + * Builds a URL for a `record.save()` call when the record has been deleted locally. + */ + urlForDeleteRecord(id: string, modelName: string, snapshot: Snapshot): string; + /** + * Determines the pathname for a given type. + */ + pathForType(modelName: string): string; + } + /** + * A `DS.AdapterError` is used by an adapter to signal that an error occurred + * during a request to an external API. It indicates a generic error, and + * subclasses are used to indicate specific error states. The following + * subclasses are provided: + */ + class AdapterError { + } + /** + * A `DS.InvalidError` is used by an adapter to signal the external API + * was unable to process a request because the content was not + * semantically correct or meaningful per the API. Usually this means a + * record failed some form of server side validation. When a promise + * from an adapter is rejected with a `DS.InvalidError` the record will + * transition to the `invalid` state and the errors will be set to the + * `errors` property on the record. + */ + class InvalidError { + } + /** + * A `DS.TimeoutError` is used by an adapter to signal that a request + * to the external API has timed out. I.e. no response was received from + * the external API within an allowed time period. + */ + class TimeoutError { + } + /** + * A `DS.AbortError` is used by an adapter to signal that a request to + * the external API was aborted. For example, this can occur if the user + * navigates away from the current page after a request to the external API + * has been initiated but before a response has been received. + */ + class AbortError { + } + /** + * A `DS.UnauthorizedError` equates to a HTTP `401 Unauthorized` response + * status. It is used by an adapter to signal that a request to the external + * API was rejected because authorization is required and has failed or has not + * yet been provided. + */ + class UnauthorizedError { + } + /** + * A `DS.ForbiddenError` equates to a HTTP `403 Forbidden` response status. + * It is used by an adapter to signal that a request to the external API was + * valid but the server is refusing to respond to it. If authorization was + * provided and is valid, then the authenticated user does not have the + * necessary permissions for the request. + */ + class ForbiddenError { + } + /** + * A `DS.NotFoundError` equates to a HTTP `404 Not Found` response status. + * It is used by an adapter to signal that a request to the external API + * was rejected because the resource could not be found on the API. + */ + class NotFoundError { + } + /** + * A `DS.ConflictError` equates to a HTTP `409 Conflict` response status. + * It is used by an adapter to indicate that the request could not be processed + * because of a conflict in the request. An example scenario would be when + * creating a record with a client generated id but that id is already known + * to the external API. + */ + class ConflictError { + } + /** + * A `DS.ServerError` equates to a HTTP `500 Internal Server Error` response + * status. It is used by the adapter to indicate that a request has failed + * because of an error in the external API. + */ + class ServerError { + } + /** + * Holds validation errors for a given record, organized by attribute names. + */ + interface Errors extends Ember.Enumerable, Ember.Evented {} + class Errors extends Ember.Object { + /** + * DEPRECATED: + * Register with target handler + */ + registerHandlers(target: {}, becameInvalid: Function, becameValid: Function): any; + /** + * Returns errors for a given attribute + */ + errorsFor(attribute: string): any[]; + /** + * An array containing all of the error messages for this + * record. This is useful for displaying all errors to the user. + */ + messages: Ember.ComputedProperty; + /** + * Total number of errors. + */ + length: Ember.ComputedProperty; + isEmpty: Ember.ComputedProperty; + /** + * DEPRECATED: + * Adds error messages to a given attribute and sends + * `becameInvalid` event to the record. + */ + add(attribute: string, messages: any[]|string): any; + /** + * DEPRECATED: + * Removes all error messages from the given attribute and sends + * `becameValid` event to the record if there no more errors left. + */ + remove(attribute: string): any; + /** + * DEPRECATED: + * Removes all error messages and sends `becameValid` event + * to the record. + */ + clear(): any; + /** + * Checks if there is error messages for the given attribute. + */ + has(attribute: string): boolean; + } + /** + * The model class that all Ember Data records descend from. + * This is the public API of Ember Data models. If you are using Ember Data + * in your application, this is the class you should use. + * If you are working on Ember Data internals, you most likely want to be dealing + * with `InternalModel` + */ + class Model extends Ember.Object { + /** + * If this property is `true` the record is in the `empty` + * state. Empty is the first state all records enter after they have + * been created. Most records created by the store will quickly + * transition to the `loading` state if data needs to be fetched from + * the server or the `created` state if the record is created on the + * client. A record can also enter the empty state if the adapter is + * unable to locate the record. + */ + isEmpty: Ember.ComputedProperty; + /** + * If this property is `true` the record is in the `loading` state. A + * record enters this state when the store asks the adapter for its + * data. It remains in this state until the adapter provides the + * requested data. + */ + isLoading: Ember.ComputedProperty; + /** + * If this property is `true` the record is in the `loaded` state. A + * record enters this state when its data is populated. Most of a + * record's lifecycle is spent inside substates of the `loaded` + * state. + */ + isLoaded: Ember.ComputedProperty; + /** + * If this property is `true` the record is in the `dirty` state. The + * record has local changes that have not yet been saved by the + * adapter. This includes records that have been created (but not yet + * saved) or deleted. + */ + hasDirtyAttributes: Ember.ComputedProperty; + /** + * If this property is `true` the record is in the `saving` state. A + * record enters the saving state when `save` is called, but the + * adapter has not yet acknowledged that the changes have been + * persisted to the backend. + */ + isSaving: Ember.ComputedProperty; + /** + * If this property is `true` the record is in the `deleted` state + * and has been marked for deletion. When `isDeleted` is true and + * `hasDirtyAttributes` is true, the record is deleted locally but the deletion + * was not yet persisted. When `isSaving` is true, the change is + * in-flight. When both `hasDirtyAttributes` and `isSaving` are false, the + * change has persisted. + */ + isDeleted: Ember.ComputedProperty; + /** + * If this property is `true` the record is in the `new` state. A + * record will be in the `new` state when it has been created on the + * client and the adapter has not yet report that it was successfully + * saved. + */ + isNew: Ember.ComputedProperty; + /** + * If this property is `true` the record is in the `valid` state. + */ + isValid: Ember.ComputedProperty; + /** + * If the record is in the dirty state this property will report what + * kind of change has caused it to move into the dirty + * state. Possible values are: + */ + dirtyType: Ember.ComputedProperty; + /** + * If `true` the adapter reported that it was unable to save local + * changes to the backend for any reason other than a server-side + * validation error. + */ + isError: boolean; + /** + * If `true` the store is attempting to reload the record from the adapter. + */ + isReloading: boolean; + /** + * All ember models have an id property. This is an identifier + * managed by an external source. These are always coerced to be + * strings before being used internally. Note when declaring the + * attributes for a model it is an error to declare an id + * attribute. + */ + id: string; + /** + * When the record is in the `invalid` state this object will contain + * any errors returned by the adapter. When present the errors hash + * contains keys corresponding to the invalid property names + * and values which are arrays of Javascript objects with two keys: + */ + errors: Ember.ComputedProperty; + /** + * This property holds the `DS.AdapterError` object with which + * last adapter operation was rejected. + */ + adapterError: AdapterError; + /** + * Create a JSON representation of the record, using the serialization + * strategy of the store's adapter. + */ + serialize(options: {}): {}; + /** + * Use [DS.JSONSerializer](DS.JSONSerializer.html) to + * get the JSON representation of a record. + */ + toJSON(options: {}): {}; + /** + * Fired when the record is ready to be interacted with, + * that is either loaded from the server or created locally. + */ + ready(): void; + /** + * Fired when the record is loaded from the server. + */ + didLoad(): void; + /** + * Fired when the record is updated. + */ + didUpdate(): void; + /** + * Fired when a new record is commited to the server. + */ + didCreate(): void; + /** + * Fired when the record is deleted. + */ + didDelete(): void; + /** + * Fired when the record becomes invalid. + */ + becameInvalid(): void; + /** + * Fired when the record enters the error state. + */ + becameError(): void; + /** + * Fired when the record is rolled back. + */ + rolledBack(): void; + /** + * Marks the record as deleted but does not save it. You must call + * `save` afterwards if you want to persist it. You might use this + * method if you want to allow the user to still `rollbackAttributes()` + * after a delete was made. + */ + deleteRecord(): any; + /** + * Same as `deleteRecord`, but saves the record immediately. + */ + destroyRecord(options: {}): Promise; + /** + * Unloads the record from the store. This will cause the record to be destroyed and freed up for garbage collection. + */ + unloadRecord(): any; + /** + * Returns an object, whose keys are changed properties, and value is + * an [oldProp, newProp] array. + */ + changedAttributes(): {}; + /** + * If the model `hasDirtyAttributes` this function will discard any unsaved + * changes. If the model `isNew` it will be removed from the store. + */ + rollbackAttributes(): any; + /** + * Save the record and persist any changes to the record to an + * external source via the adapter. + */ + save(options?: {}): Promise; + /** + * Reload the record from the adapter. + */ + reload(): Promise; + /** + * Get the reference for the specified belongsTo relationship. + */ + belongsTo(name: string): BelongsToReference; + /** + * Get the reference for the specified hasMany relationship. + */ + hasMany(name: string): HasManyReference; + /** + * Given a callback, iterates over each of the relationships in the model, + * invoking the callback with the name of each relationship and its relationship + * descriptor. + */ + eachRelationship(callback: Function, binding: any): any; + /** + * Represents the model's class name as a string. This can be used to look up the model's class name through + * `DS.Store`'s modelFor method. + */ + static modelName: string; + /** + * For a given relationship name, returns the model type of the relationship. + */ + static typeForRelationship(name: string, store: Store): Model; + /** + * Find the relationship which is the inverse of the one asked for. + */ + static inverseFor(name: string, store: Store): {}; + /** + * The model's relationships as a map, keyed on the type of the + * relationship. The value of each entry is an array containing a descriptor + * for each relationship with that type, describing the name of the relationship + * as well as the type. + */ + static relationships: Ember.ComputedProperty; + /** + * A hash containing lists of the model's relationships, grouped + * by the relationship kind. For example, given a model with this + * definition: + */ + static relationshipNames: Ember.ComputedProperty<{}>; + /** + * An array of types directly related to a model. Each type will be + * included once, regardless of the number of relationships it has with + * the model. + */ + static relatedTypes: Ember.ComputedProperty>; + /** + * A map whose keys are the relationships of a model and whose values are + * relationship descriptors. + */ + static relationshipsByName: Ember.ComputedProperty; + /** + * A map whose keys are the fields of the model and whose values are strings + * describing the kind of the field. A model's fields are the union of all of its + * attributes and relationships. + */ + static fields: Ember.ComputedProperty; + /** + * Given a callback, iterates over each of the relationships in the model, + * invoking the callback with the name of each relationship and its relationship + * descriptor. + */ + static eachRelationship(callback: Function, binding: any): any; + /** + * Given a callback, iterates over each of the types related to a model, + * invoking the callback with the related type's class. Each type will be + * returned just once, regardless of how many different relationships it has + * with a model. + */ + static eachRelatedType(callback: Function, binding: any): any; + /** + * A map whose keys are the attributes of the model (properties + * described by DS.attr) and whose values are the meta object for the + * property. + */ + static attributes: Ember.ComputedProperty; + /** + * A map whose keys are the attributes of the model (properties + * described by DS.attr) and whose values are type of transformation + * applied to each attribute. This map does not include any + * attributes that do not have an transformation type. + */ + static transformedAttributes: Ember.ComputedProperty; + /** + * Iterates through the attributes of the model, calling the passed function on each + * attribute. + */ + static eachAttribute(callback: Function, binding: {}): any; + /** + * Iterates through the transformedAttributes of the model, calling + * the passed function on each attribute. Note the callback will not be + * called for any attributes that do not have an transformation type. + */ + static eachTransformedAttribute(callback: Function, binding: {}): any; + /** + * Discards any unsaved changes to the given attribute. This feature is not enabled by default. You must enable `ds-rollback-attribute` and be running a canary build. + */ + rollbackAttribute(): any; + /** + * This Ember.js hook allows an object to be notified when a property + * is defined. + */ + didDefineProperty(proto: {}, key: string, value: Ember.ComputedProperty): any; + } + /** + * ### State + */ + class RootState { + } + /** + * Represents an ordered list of records whose order and membership is + * determined by the adapter. For example, a query sent to the adapter + * may trigger a search on the server, whose results would be loaded + * into an instance of the `AdapterPopulatedRecordArray`. + */ + class AdapterPopulatedRecordArray extends RecordArray { + } + /** + * Represents a list of records whose membership is determined by the + * store. As records are created, loaded, or modified, the store + * evaluates them to determine if they should be part of the record + * array. + */ + class FilteredRecordArray extends RecordArray { + /** + * The filterFunction is a function used to test records from the store to + * determine if they should be part of the record array. + */ + filterFunction(record: Model): boolean; + } + /** + * A record array is an array that contains records of a certain modelName. The record + * array materializes records as needed when they are retrieved for the first + * time. You should not create record arrays yourself. Instead, an instance of + * `DS.RecordArray` or its subclasses will be returned by your application's store + * in response to queries. + */ + interface RecordArray extends Ember.ArrayProxy, Ember.Evented {} + class RecordArray { + /** + * The flag to signal a `RecordArray` is finished loading data. + */ + isLoaded: boolean; + /** + * The flag to signal a `RecordArray` is currently loading data. + */ + isUpdating: boolean; + /** + * The modelClass represented by this record array. + */ + type: Ember.ComputedProperty; + /** + * Used to get the latest version of all of the records in this array + * from the adapter. + */ + update(): any; + /** + * Saves all of the records in the `RecordArray`. + */ + save(): PromiseArray; + } + /** + * A BelongsToReference is a low level API that allows users and + * addon author to perform meta-operations on a belongs-to + * relationship. + */ + class BelongsToReference { + /** + * This returns a string that represents how the reference will be + * looked up when it is loaded. If the relationship has a link it will + * use the "link" otherwise it defaults to "id". + */ + remoteType(): string; + /** + * The `id` of the record that this reference refers to. Together, the + * `type()` and `id()` methods form a composite key for the identity + * map. This can be used to access the id of an async relationship + * without triggering a fetch that would normally happen if you + * attempted to use `record.get('relationship.id')`. + */ + id(): string; + /** + * The link Ember Data will use to fetch or reload this belongs-to + * relationship. + */ + link(): string; + /** + * The meta data for the belongs-to relationship. + */ + meta(): {}; + /** + * `push` can be used to update the data in the relationship and Ember + * Data will treat the new data as the conanical value of this + * relationship on the backend. + */ + push(objectOrPromise: {}|Promise): Promise; + /** + * `value()` synchronously returns the current value of the belongs-to + * relationship. Unlike `record.get('relationshipName')`, calling + * `value()` on a reference does not trigger a fetch if the async + * relationship is not yet loaded. If the relationship is not loaded + * it will always return `null`. + */ + value(objectOrPromise: {}|Promise): Model; + /** + * Loads a record in a belongs to relationship if it is not already + * loaded. If the relationship is already loaded this method does not + * trigger a new load. + */ + load(): Promise; + /** + * Triggers a reload of the value in this relationship. If the + * remoteType is `"link"` Ember Data will use the relationship link to + * reload the relationship. Otherwise it will reload the record by its + * id. + */ + reload(): Promise; + } + /** + * A HasManyReference is a low level API that allows users and addon + * author to perform meta-operations on a has-many relationship. + */ + class HasManyReference { + /** + * This returns a string that represents how the reference will be + * looked up when it is loaded. If the relationship has a link it will + * use the "link" otherwise it defaults to "id". + */ + remoteType(): string; + /** + * The link Ember Data will use to fetch or reload this has-many + * relationship. + */ + link(): string; + /** + * `ids()` returns an array of the record ids in this relationship. + */ + ids(): any[]; + /** + * The meta data for the has-many relationship. + */ + meta(): {}; + /** + * `push` can be used to update the data in the relationship and Ember + * Data will treat the new data as the canonical value of this + * relationship on the backend. + */ + push(objectOrPromise: T[] | Promise): ManyArray; + /** + * `value()` synchronously returns the current value of the has-many + * relationship. Unlike `record.get('relationshipName')`, calling + * `value()` on a reference does not trigger a fetch if the async + * relationship is not yet loaded. If the relationship is not loaded + * it will always return `null`. + */ + value(): ManyArray; + /** + * Loads the relationship if it is not already loaded. If the + * relationship is already loaded this method does not trigger a new + * load. + */ + load(): Promise; + /** + * Reloads this has-many relationship. + */ + reload(): Promise; + } + /** + * An RecordReference is a low level API that allows users and + * addon author to perform meta-operations on a record. + */ + class RecordReference { + /** + * The `id` of the record that this reference refers to. + */ + id(): string; + /** + * How the reference will be looked up when it is loaded: Currently + * this always return `identity` to signifying that a record will be + * loaded by the `type` and `id`. + */ + remoteType(): string; + /** + * This API allows you to provide a reference with new data. The + * simplest usage of this API is similar to `store.push`: you provide a + * normalized hash of data and the object represented by the reference + * will update. + */ + push(payload: Promise|{}): PromiseObject & T; + /** + * If the entity referred to by the reference is already loaded, it is + * present as `reference.value`. Otherwise the value returned by this function + * is `null`. + */ + value(): T | null; + /** + * Triggers a fetch for the backing entity based on its `remoteType` + * (see `remoteType` definitions per reference type). + */ + load(): PromiseObject & T; + /** + * Reloads the record if it is already loaded. If the record is not + * loaded it will load the record via `store.findRecord` + */ + reload(): PromiseObject & T; + } + /** + * A `ManyArray` is a `MutableArray` that represents the contents of a has-many + * relationship. + */ + interface ManyArray extends Ember.MutableArray {} + class ManyArray extends Ember.Object.extend(Ember.MutableArray as {}, Ember.Evented) { + /** + * The loading state of this array + */ + isLoaded: boolean; + /** + * Metadata associated with the request for async hasMany relationships. + */ + meta: {}; + /** + * Reloads all of the records in the manyArray. If the manyArray + * holds a relationship that was originally fetched using a links url + * Ember Data will revisit the original links url to repopulate the + * relationship. + */ + reload(): PromiseArray; + /** + * Saves all of the records in the `ManyArray`. + */ + save(): PromiseArray; + /** + * Create a child record within the owner + */ + createRecord(inputProperties?: {}): T; + } + /** + * A `PromiseArray` is an object that acts like both an `Ember.Array` + * and a promise. When the promise is resolved the resulting value + * will be set to the `PromiseArray`'s `content` property. This makes + * it easy to create data bindings with the `PromiseArray` that will be + * updated when the promise resolves. + */ + interface PromiseArray extends Ember.ArrayProxy, Ember.PromiseProxyMixin> {} + class PromiseArray { + } + /** + * A `PromiseObject` is an object that acts like both an `Ember.Object` + * and a promise. When the promise is resolved, then the resulting value + * will be set to the `PromiseObject`'s `content` property. This makes + * it easy to create data bindings with the `PromiseObject` that will + * be updated when the promise resolves. + */ + interface PromiseObject extends Ember.ObjectProxy, Ember.PromiseProxyMixin> {} + class PromiseObject { + } + /** + * A PromiseManyArray is a PromiseArray that also proxies certain method calls + * to the underlying manyArray. + * Right now we proxy: + */ + class PromiseManyArray extends PromiseArray { + /** + * Reloads all of the records in the manyArray. If the manyArray + * holds a relationship that was originally fetched using a links url + * Ember Data will revisit the original links url to repopulate the + * relationship. + */ + reload(): PromiseManyArray; + /** + * Create a child record within the owner + */ + createRecord(inputProperties?: {}): T; + } + class SnapshotRecordArray { + /** + * Number of records in the array + */ + length: number; + /** + * Meta objects for the record array. + */ + meta: {}; + /** + * A hash of adapter options passed into the store method for this request. + */ + adapterOptions: {}; + /** + * The relationships to include for this request. + */ + include: string|any[]; + /** + * The type of the underlying records for the snapshots in the array, as a DS.Model + */ + type: Model; + /** + * Get snapshots of the underlying record array + */ + snapshots(): any[]; + } + class Snapshot { + /** + * The underlying record for this snapshot. Can be used to access methods and + * properties defined on the record. + */ + record: Model; + /** + * The id of the snapshot's underlying record + */ + id: string; + /** + * A hash of adapter options + */ + adapterOptions: {}; + /** + * The name of the type of the underlying record for this snapshot, as a string. + */ + modelName: string; + /** + * The type of the underlying record for this snapshot, as a DS.Model. + */ + type: Model; + /** + * Returns the value of an attribute. + */ + attr(keyName: string): {}; + /** + * Returns all attributes and their corresponding values. + */ + attributes(): {}; + /** + * Returns all changed attributes and their old and new values. + */ + changedAttributes(): {}; + /** + * Returns the current value of a belongsTo relationship. + */ + belongsTo(keyName: string, options: {}): Snapshot|string|null|undefined; + /** + * Returns the current value of a hasMany relationship. + */ + hasMany(keyName: string, options: {}): any[]|undefined; + /** + * Iterates through all the attributes of the model, calling the passed + * function on each attribute. + */ + eachAttribute(callback: Function, binding: {}): any; + /** + * Iterates through all the relationships of the model, calling the passed + * function on each relationship. + */ + eachRelationship(callback: Function, binding: {}): any; + /** + * Serializes the snapshot using the serializer for the model. + */ + serialize(options: {}): {}; + } + /** + * The store contains all of the data for records loaded from the server. + * It is also responsible for creating instances of `DS.Model` that wrap + * the individual data for a record, so that they can be bound to in your + * Handlebars templates. + */ + class Store { + /** + * The default adapter to use to communicate to a backend server or + * other persistence layer. This will be overridden by an application + * adapter if present. + */ + adapter: string; + /** + * Create a new record in the current store. The properties passed + * to this method are set on the newly created record. + */ + createRecord(modelName: string, inputProperties?: {}): T; + /** + * For symmetry, a record can be deleted via the store. + */ + deleteRecord(record: Model): void; + /** + * For symmetry, a record can be unloaded via the store. + * This will cause the record to be destroyed and freed up for garbage collection. + */ + unloadRecord(record: Model): void; + /** + * This method returns a record for a given type and id combination. + */ + findRecord(modelName: string, id: string|number, options?: {}): PromiseObject & T; + /** + * Get the reference for the specified record. + */ + getReference(modelName: string, id: string|number): RecordReference; + /** + * Get a record by a given type and ID without triggering a fetch. + */ + peekRecord(modelName: string, id: string|number): T|null; + /** + * This method returns true if a record for a given modelName and id is already + * loaded in the store. Use this function to know beforehand if a findRecord() + * will result in a request or that it will be a cache hit. + */ + hasRecordForId(modelName: string, id: string|number): boolean; + /** + * This method delegates a query to the adapter. This is the one place where + * adapter-level semantics are exposed to the application. + */ + query(modelName: string, query: any): AdapterPopulatedRecordArray & PromiseArray; + /** + * This method makes a request for one record, where the `id` is not known + * beforehand (if the `id` is known, use [`findRecord`](#method_findRecord) + * instead). + */ + queryRecord(modelName: string, query: any): Promise; + /** + * `findAll` asks the adapter's `findAll` method to find the records for the + * given type, and returns a promise which will resolve with all records of + * this type present in the store, even if the adapter only returns a subset + * of them. + */ + findAll(modelName: string, options?: { + reload?: boolean, + backgroundReload?: boolean, + include?: string, + adapterOptions?: any + }): PromiseArray; + /** + * This method returns a filtered array that contains all of the + * known records for a given type in the store. + */ + peekAll(modelName: string): RecordArray; + /** + * This method unloads all records in the store. + * It schedules unloading to happen during the next run loop. + */ + unloadAll(modelName: string): void; + /** + * DEPRECATED: + * This method has been deprecated and is an alias for store.hasRecordForId, which should + * be used instead. + */ + recordIsLoaded(modelName: string, id: string): boolean; + /** + * Returns the model class for the particular `modelName`. + */ + modelFor(modelName: string): Model; + /** + * Push some data for a given type into the store. + */ + push(data: {}): Model|any[]; + /** + * Push some raw data into the store. + */ + pushPayload(modelName: string, inputPayload: {}): any; + pushPayload(inputPayload: {}): any; + /** + * `normalize` converts a json payload into the normalized form that + * [push](#method_push) expects. + */ + normalize(modelName: string, payload: {}): {}; + /** + * Returns an instance of the adapter for a given type. For + * example, `adapterFor('person')` will return an instance of + * `App.PersonAdapter`. + */ + adapterFor(modelName: string): Adapter; + /** + * Returns an instance of the serializer for a given type. For + * example, `serializerFor('person')` will return an instance of + * `App.PersonSerializer`. + */ + serializerFor(modelName: string): Serializer; + } + /** + * The `JSONAPIAdapter` is the default adapter used by Ember Data. It + * is responsible for transforming the store's requests into HTTP + * requests that follow the [JSON API](http://jsonapi.org/format/) + * format. + */ + class JSONAPIAdapter extends RESTAdapter { + /** + * By default the JSONAPIAdapter will send each find request coming from a `store.find` + * or from accessing a relationship separately to the server. If your server supports passing + * ids as a query string, you can set coalesceFindRequests to true to coalesce all find requests + * within a single runloop. + */ + coalesceFindRequests: boolean; + } + /** + * The REST adapter allows your store to communicate with an HTTP server by + * transmitting JSON via XHR. Most Ember.js apps that consume a JSON API + * should use the REST adapter. + */ + class RESTAdapter extends Adapter implements BuildURLMixin { + /** + * Takes a URL, an HTTP method and a hash of data, and makes an HTTP request. + */ + ajax(url: string, type: string, options?: object): Promise; + /** + * Generate ajax options + */ + ajaxOptions(url: string, type: string, options?: object): object; + /** + * By default, the RESTAdapter will send the query params sorted alphabetically to the + * server. + */ + sortQueryParams(obj: {}): {}; + /** + * By default the RESTAdapter will send each find request coming from a `store.find` + * or from accessing a relationship separately to the server. If your server supports passing + * ids as a query string, you can set coalesceFindRequests to true to coalesce all find requests + * within a single runloop. + */ + coalesceFindRequests: boolean; + /** + * Endpoint paths can be prefixed with a `namespace` by setting the namespace + * property on the adapter: + */ + namespace: string; + /** + * An adapter can target other hosts by setting the `host` property. + */ + host: string; + /** + * Some APIs require HTTP headers, e.g. to provide an API + * key. Arbitrary headers can be set as key/value pairs on the + * `RESTAdapter`'s `headers` object and Ember Data will send them + * along with each ajax request. For dynamic headers see [headers + * customization](/api/data/classes/DS.RESTAdapter.html#toc_headers-customization). + */ + headers: {}; + /** + * Called by the store in order to fetch the JSON for a given + * type and ID. + */ + findRecord(store: Store, type: Model, id: string, snapshot: Snapshot): Promise; + /** + * Called by the store in order to fetch a JSON array for all + * of the records for a given type. + */ + findAll(store: Store, type: Model, sinceToken: string, snapshotRecordArray: SnapshotRecordArray): Promise; + /** + * Called by the store in order to fetch a JSON array for + * the records that match a particular query. + */ + query(store: Store, type: Model, query: {}): Promise; + /** + * Called by the store in order to fetch a JSON object for + * the record that matches a particular query. + */ + queryRecord(store: Store, type: Model, query: {}): Promise; + /** + * Called by the store in order to fetch several records together if `coalesceFindRequests` is true + */ + findMany(store: Store, type: Model, ids: any[], snapshots: any[]): Promise; + /** + * Called by the store in order to fetch a JSON array for + * the unloaded records in a has-many relationship that were originally + * specified as a URL (inside of `links`). + */ + findHasMany(store: Store, snapshot: Snapshot, url: string, relationship: {}): Promise; + /** + * Called by the store in order to fetch the JSON for the unloaded record in a + * belongs-to relationship that was originally specified as a URL (inside of + * `links`). + */ + findBelongsTo(store: Store, snapshot: Snapshot, url: string): Promise; + /** + * Called by the store when a newly created record is + * saved via the `save` method on a model record instance. + */ + createRecord(store: Store, type: Model, snapshot: Snapshot): Promise; + /** + * Called by the store when an existing record is saved + * via the `save` method on a model record instance. + */ + updateRecord(store: Store, type: Model, snapshot: Snapshot): Promise; + /** + * Called by the store when a record is deleted. + */ + deleteRecord(store: Store, type: Model, snapshot: Snapshot): Promise; + /** + * Organize records into groups, each of which is to be passed to separate + * calls to `findMany`. + */ + groupRecordsForFindMany(store: Store, snapshots: any[]): any[]; + /** + * Takes an ajax response, and returns the json payload or an error. + */ + handleResponse(status: number, headers: {}, payload: {}, requestData: {}): {}; + /** + * Default `handleResponse` implementation uses this hook to decide if the + * response is a success. + */ + isSuccess(status: number, headers: {}, payload: {}): boolean; + /** + * Default `handleResponse` implementation uses this hook to decide if the + * response is an invalid error. + */ + isInvalid(status: number, headers: {}, payload: {}): boolean; + /** + * Get the data (body or query params) for a request. + */ + dataForRequest(params: {}): {}; + /** + * Get the HTTP method for a request. + */ + methodForRequest(params: {}): string; + /** + * Get the URL for a request. + */ + urlForRequest(params: {}): string; + /** + * Get the headers for a request. + */ + headersForRequest(params: {}): {}; + /** + * Builds a URL for a given type and optional ID. + */ + buildURL(modelName: string, id: string|any[]|{}, snapshot: Snapshot|any[], requestType: string, query: {}): string; + /** + * Builds a URL for a `store.findRecord(type, id)` call. + */ + urlForFindRecord(id: string, modelName: string, snapshot: Snapshot): string; + /** + * Builds a URL for a `store.findAll(type)` call. + */ + urlForFindAll(modelName: string, snapshot: SnapshotRecordArray): string; + /** + * Builds a URL for a `store.query(type, query)` call. + */ + urlForQuery(query: {}, modelName: string): string; + /** + * Builds a URL for a `store.queryRecord(type, query)` call. + */ + urlForQueryRecord(query: {}, modelName: string): string; + /** + * Builds a URL for coalesceing multiple `store.findRecord(type, id)` + * records into 1 request when the adapter's `coalesceFindRequests` + * property is true. + */ + urlForFindMany(ids: any[], modelName: string, snapshots: any[]): string; + /** + * Builds a URL for fetching a async hasMany relationship when a url + * is not provided by the server. + */ + urlForFindHasMany(id: string, modelName: string, snapshot: Snapshot): string; + /** + * Builds a URL for fetching a async belongsTo relationship when a url + * is not provided by the server. + */ + urlForFindBelongsTo(id: string, modelName: string, snapshot: Snapshot): string; + /** + * Builds a URL for a `record.save()` call when the record was created + * locally using `store.createRecord()`. + */ + urlForCreateRecord(modelName: string, snapshot: Snapshot): string; + /** + * Builds a URL for a `record.save()` call when the record has been update locally. + */ + urlForUpdateRecord(id: string, modelName: string, snapshot: Snapshot): string; + /** + * Builds a URL for a `record.save()` call when the record has been deleted locally. + */ + urlForDeleteRecord(id: string, modelName: string, snapshot: Snapshot): string; + /** + * Determines the pathname for a given type. + */ + pathForType(modelName: string): string; + } + /** + * ## Using Embedded Records + */ + class EmbeddedRecordsMixin { + /** + * Normalize the record and recursively normalize/extract all the embedded records + * while pushing them into the store as they are encountered + */ + normalize(typeClass: Model, hash: {}, prop: string): {}; + /** + * Serialize `belongsTo` relationship when it is configured as an embedded object. + */ + serializeBelongsTo(snapshot: Snapshot, json: {}, relationship: {}): any; + /** + * Serializes `hasMany` relationships when it is configured as embedded objects. + */ + serializeHasMany(snapshot: Snapshot, json: {}, relationship: {}): any; + /** + * When serializing an embedded record, modify the property (in the json payload) + * that refers to the parent record (foreign key for relationship). + */ + removeEmbeddedForeignKey(snapshot: Snapshot, embeddedSnapshot: Snapshot, relationship: {}, json: {}): any; + } + /** + * Ember Data 2.0 Serializer: + */ + class JSONAPISerializer extends JSONSerializer { + pushPayload(store: Store, payload: {}): any; + /** + * Dasherizes and singularizes the model name in the payload to match + * the format Ember Data uses internally for the model name. + */ + modelNameFromPayloadKey(key: string): string; + /** + * Converts the model name to a pluralized version of the model name. + */ + payloadKeyFromModelName(modelName: string): string; + /** + * `keyForAttribute` can be used to define rules for how to convert an + * attribute name in your model to a key in your JSON. + * By default `JSONAPISerializer` follows the format used on the examples of + * http://jsonapi.org/format and uses dashes as the word separator in the JSON + * attribute keys. + */ + keyForAttribute(key: string, method: string): string; + /** + * `keyForRelationship` can be used to define a custom key when + * serializing and deserializing relationship properties. + * By default `JSONAPISerializer` follows the format used on the examples of + * http://jsonapi.org/format and uses dashes as word separators in + * relationship properties. + */ + keyForRelationship(key: string, typeClass: string, method: string): string; + /** + * `modelNameFromPayloadType` can be used to change the mapping for a DS model + * name, taken from the value in the payload. + */ + modelNameFromPayloadType(payloadType: string): string; + /** + * `payloadTypeFromModelName` can be used to change the mapping for the type in + * the payload, taken from the model name. + */ + payloadTypeFromModelName(modelname: string): string; + } + /** + * Ember Data 2.0 Serializer: + */ + class JSONSerializer extends Serializer { + /** + * The `primaryKey` is used when serializing and deserializing + * data. Ember Data always uses the `id` property to store the id of + * the record. The external source may not always follow this + * convention. In these cases it is useful to override the + * `primaryKey` property to match the `primaryKey` of your external + * store. + */ + primaryKey: string; + /** + * The `attrs` object can be used to declare a simple mapping between + * property names on `DS.Model` records and payload keys in the + * serialized JSON object representing the record. An object with the + * property `key` can also be used to designate the attribute's key on + * the response payload. + */ + attrs: {}; + /** + * The `normalizeResponse` method is used to normalize a payload from the + * server to a JSON-API Document. + */ + normalizeResponse(store: Store, primaryModelClass: Model, payload: {}, id: string|number, requestType: string): {}; + normalizeFindRecordResponse(store: Store, primaryModelClass: Model, payload: {}, id: string|number, requestType: string): {}; + normalizeQueryRecordResponse(store: Store, primaryModelClass: Model, payload: {}, id: string|number, requestType: string): {}; + normalizeFindAllResponse(store: Store, primaryModelClass: Model, payload: {}, id: string|number, requestType: string): {}; + normalizeFindBelongsToResponse(store: Store, primaryModelClass: Model, payload: {}, id: string|number, requestType: string): {}; + normalizeFindHasManyResponse(store: Store, primaryModelClass: Model, payload: {}, id: string|number, requestType: string): {}; + normalizeFindManyResponse(store: Store, primaryModelClass: Model, payload: {}, id: string|number, requestType: string): {}; + normalizeQueryResponse(store: Store, primaryModelClass: Model, payload: {}, id: string|number, requestType: string): {}; + normalizeCreateRecordResponse(store: Store, primaryModelClass: Model, payload: {}, id: string|number, requestType: string): {}; + normalizeDeleteRecordResponse(store: Store, primaryModelClass: Model, payload: {}, id: string|number, requestType: string): {}; + normalizeUpdateRecordResponse(store: Store, primaryModelClass: Model, payload: {}, id: string|number, requestType: string): {}; + normalizeSaveResponse(store: Store, primaryModelClass: Model, payload: {}, id: string|number, requestType: string): {}; + normalizeSingleResponse(store: Store, primaryModelClass: Model, payload: {}, id: string|number, requestType: string): {}; + normalizeArrayResponse(store: Store, primaryModelClass: Model, payload: {}, id: string|number, requestType: string): {}; + /** + * Normalizes a part of the JSON payload returned by + * the server. You should override this method, munge the hash + * and call super if you have generic normalization to do. + */ + normalize(typeClass: Model, hash: {}): {}; + /** + * Returns the resource's ID. + */ + extractId(modelClass: {}, resourceHash: {}): string; + /** + * Returns the resource's attributes formatted as a JSON-API "attributes object". + */ + extractAttributes(modelClass: {}, resourceHash: {}): {}; + /** + * Returns a relationship formatted as a JSON-API "relationship object". + */ + extractRelationship(relationshipModelName: {}, relationshipHash: {}): {}; + /** + * Returns a polymorphic relationship formatted as a JSON-API "relationship object". + */ + extractPolymorphicRelationship(relationshipModelName: {}, relationshipHash: {}, relationshipOptions: {}): {}; + /** + * Returns the resource's relationships formatted as a JSON-API "relationships object". + */ + extractRelationships(modelClass: {}, resourceHash: {}): {}; + modelNameFromPayloadKey(key: string): string; + /** + * Check if the given hasMany relationship should be serialized + */ + shouldSerializeHasMany(snapshot: Snapshot, key: string, relationshipType: string): boolean; + /** + * Called when a record is saved in order to convert the + * record into JSON. + */ + serialize(snapshot: Snapshot, options: {}): {}; + /** + * You can use this method to customize how a serialized record is added to the complete + * JSON hash to be sent to the server. By default the JSON Serializer does not namespace + * the payload and just sends the raw serialized JSON object. + * If your server expects namespaced keys, you should consider using the RESTSerializer. + * Otherwise you can override this method to customize how the record is added to the hash. + * The hash property should be modified by reference. + */ + serializeIntoHash(hash: {}, typeClass: Model, snapshot: Snapshot, options: {}): any; + /** + * `serializeAttribute` can be used to customize how `DS.attr` + * properties are serialized + */ + serializeAttribute(snapshot: Snapshot, json: {}, key: string, attribute: {}): any; + /** + * `serializeBelongsTo` can be used to customize how `DS.belongsTo` + * properties are serialized. + */ + serializeBelongsTo(snapshot: Snapshot, json: {}, relationship: {}): any; + /** + * `serializeHasMany` can be used to customize how `DS.hasMany` + * properties are serialized. + */ + serializeHasMany(snapshot: Snapshot, json: {}, relationship: {}): any; + /** + * You can use this method to customize how polymorphic objects are + * serialized. Objects are considered to be polymorphic if + * `{ polymorphic: true }` is pass as the second argument to the + * `DS.belongsTo` function. + */ + serializePolymorphicType(snapshot: Snapshot, json: {}, relationship: {}): any; + /** + * `extractMeta` is used to deserialize any meta information in the + * adapter payload. By default Ember Data expects meta information to + * be located on the `meta` property of the payload object. + */ + extractMeta(store: Store, modelClass: Model, payload: {}): any; + /** + * `extractErrors` is used to extract model errors when a call + * to `DS.Model#save` fails with an `InvalidError`. By default + * Ember Data expects error information to be located on the `errors` + * property of the payload object. + */ + extractErrors(store: Store, typeClass: Model, payload: {}, id: string|number): {}; + /** + * `keyForAttribute` can be used to define rules for how to convert an + * attribute name in your model to a key in your JSON. + */ + keyForAttribute(key: string, method: string): string; + /** + * `keyForRelationship` can be used to define a custom key when + * serializing and deserializing relationship properties. By default + * `JSONSerializer` does not provide an implementation of this method. + */ + keyForRelationship(key: string, typeClass: string, method: string): string; + /** + * `keyForLink` can be used to define a custom key when deserializing link + * properties. + */ + keyForLink(key: string, kind: string): string; + modelNameFromPayloadType(type: string): string; + /** + * serializeId can be used to customize how id is serialized + * For example, your server may expect integer datatype of id + */ + serializeId(snapshot: Snapshot, json: {}, primaryKey: string): any; + } + /** + * Normally, applications will use the `RESTSerializer` by implementing + * the `normalize` method. + */ + class RESTSerializer extends JSONSerializer { + /** + * `keyForPolymorphicType` can be used to define a custom key when + * serializing and deserializing a polymorphic type. By default, the + * returned key is `${key}Type`. + */ + keyForPolymorphicType(key: string, typeClass: string, method: string): string; + /** + * Normalizes a part of the JSON payload returned by + * the server. You should override this method, munge the hash + * and call super if you have generic normalization to do. + */ + normalize(modelClass: Model, resourceHash: {}, prop?: string): {}; + /** + * This method allows you to push a payload containing top-level + * collections of records organized per type. + */ + pushPayload(store: Store, payload: {}): any; + /** + * This method is used to convert each JSON root key in the payload + * into a modelName that it can use to look up the appropriate model for + * that part of the payload. + */ + modelNameFromPayloadKey(key: string): string; + /** + * Called when a record is saved in order to convert the + * record into JSON. + */ + serialize(snapshot: Snapshot, options: {}): {}; + /** + * You can use this method to customize the root keys serialized into the JSON. + * The hash property should be modified by reference (possibly using something like _.extend) + * By default the REST Serializer sends the modelName of a model, which is a camelized + * version of the name. + */ + serializeIntoHash(hash: {}, typeClass: Model, snapshot: Snapshot, options: {}): any; + /** + * You can use `payloadKeyFromModelName` to override the root key for an outgoing + * request. By default, the RESTSerializer returns a camelized version of the + * model's name. + */ + payloadKeyFromModelName(modelName: string): string; + /** + * You can use this method to customize how polymorphic objects are serialized. + * By default the REST Serializer creates the key by appending `Type` to + * the attribute and value from the model's camelcased model name. + */ + serializePolymorphicType(snapshot: Snapshot, json: {}, relationship: {}): any; + /** + * You can use this method to customize how a polymorphic relationship should + * be extracted. + */ + extractPolymorphicRelationship(relationshipType: {}, relationshipHash: {}, relationshipOptions: {}): {}; + /** + * `modelNameFromPayloadType` can be used to change the mapping for a DS model + * name, taken from the value in the payload. + */ + modelNameFromPayloadType(payloadType: string): string; + /** + * `payloadTypeFromModelName` can be used to change the mapping for the type in + * the payload, taken from the model name. + */ + payloadTypeFromModelName(modelName: string): string; + } + /** + * The `DS.BooleanTransform` class is used to serialize and deserialize + * boolean attributes on Ember Data record objects. This transform is + * used when `boolean` is passed as the type parameter to the + * [DS.attr](../../data#method_attr) function. + */ + class BooleanTransform extends Transform { + } + /** + * The `DS.DateTransform` class is used to serialize and deserialize + * date attributes on Ember Data record objects. This transform is used + * when `date` is passed as the type parameter to the + * [DS.attr](../../data#method_attr) function. It uses the [`ISO 8601`](https://en.wikipedia.org/wiki/ISO_8601) + * standard. + */ + class DateTransform extends Transform { + } + /** + * The `DS.NumberTransform` class is used to serialize and deserialize + * numeric attributes on Ember Data record objects. This transform is + * used when `number` is passed as the type parameter to the + * [DS.attr](../../data#method_attr) function. + */ + class NumberTransform extends Transform { + } + /** + * The `DS.StringTransform` class is used to serialize and deserialize + * string attributes on Ember Data record objects. This transform is + * used when `string` is passed as the type parameter to the + * [DS.attr](../../data#method_attr) function. + */ + class StringTransform extends Transform { + } + /** + * The `DS.Transform` class is used to serialize and deserialize model + * attributes when they are saved or loaded from an + * adapter. Subclassing `DS.Transform` is useful for creating custom + * attributes. All subclasses of `DS.Transform` must implement a + * `serialize` and a `deserialize` method. + */ + class Transform extends Ember.Object { + /** + * When given a deserialized value from a record attribute this + * method must return the serialized value. + */ + serialize(deserialized: any, options: AttrOptions): any; + /** + * When given a serialize value from a JSON object this method must + * return the deserialized value for the record attribute. + */ + deserialize(serialized: any, options: AttrOptions): any; + } + /** + * An adapter is an object that receives requests from a store and + * translates them into the appropriate action to take against your + * persistence layer. The persistence layer is usually an HTTP API, but + * may be anything, such as the browser's local storage. Typically the + * adapter is not invoked directly instead its functionality is accessed + * through the `store`. + */ + class Adapter extends Ember.Object { + /** + * If you would like your adapter to use a custom serializer you can + * set the `defaultSerializer` property to be the name of the custom + * serializer. + */ + defaultSerializer: string; + /** + * The `findRecord()` method is invoked when the store is asked for a record that + * has not previously been loaded. In response to `findRecord()` being called, you + * should query your persistence layer for a record with the given ID. The `findRecord` + * method should return a promise that will resolve to a JavaScript object that will be + * normalized by the serializer. + */ + findRecord(store: Store, type: Model, id: string, snapshot: Snapshot): Promise; + /** + * The `findAll()` method is used to retrieve all records for a given type. + */ + findAll(store: Store, type: Model, sinceToken: string, snapshotRecordArray: SnapshotRecordArray): Promise; + /** + * This method is called when you call `query` on the store. + */ + query(store: Store, type: Model, query: {}, recordArray: AdapterPopulatedRecordArray): Promise; + /** + * The `queryRecord()` method is invoked when the store is asked for a single + * record through a query object. + */ + queryRecord(store: Store, type: Model, query: {}): Promise; + /** + * If the globally unique IDs for your records should be generated on the client, + * implement the `generateIdForRecord()` method. This method will be invoked + * each time you create a new record, and the value returned from it will be + * assigned to the record's `primaryKey`. + */ + generateIdForRecord(store: Store, type: Model, inputProperties: {}): string|number; + /** + * Proxies to the serializer's `serialize` method. + */ + serialize(snapshot: Snapshot, options: {}): {}; + /** + * Implement this method in a subclass to handle the creation of + * new records. + */ + createRecord(store: Store, type: Model, snapshot: Snapshot): Promise; + /** + * Implement this method in a subclass to handle the updating of + * a record. + */ + updateRecord(store: Store, type: Model, snapshot: Snapshot): Promise; + /** + * Implement this method in a subclass to handle the deletion of + * a record. + */ + deleteRecord(store: Store, type: Model, snapshot: Snapshot): Promise; + /** + * By default the store will try to coalesce all `fetchRecord` calls within the same runloop + * into as few requests as possible by calling groupRecordsForFindMany and passing it into a findMany call. + * You can opt out of this behaviour by either not implementing the findMany hook or by setting + * coalesceFindRequests to false. + */ + coalesceFindRequests: boolean; + /** + * The store will call `findMany` instead of multiple `findRecord` + * requests to find multiple records at once if coalesceFindRequests + * is true. + */ + findMany(store: Store, type: Model, ids: any[], snapshots: any[]): Promise; + /** + * Organize records into groups, each of which is to be passed to separate + * calls to `findMany`. + */ + groupRecordsForFindMany(store: Store, snapshots: any[]): any[]; + /** + * This method is used by the store to determine if the store should + * reload a record from the adapter when a record is requested by + * `store.findRecord`. + */ + shouldReloadRecord(store: Store, snapshot: Snapshot): boolean; + /** + * This method is used by the store to determine if the store should + * reload all records from the adapter when records are requested by + * `store.findAll`. + */ + shouldReloadAll(store: Store, snapshotRecordArray: SnapshotRecordArray): boolean; + /** + * This method is used by the store to determine if the store should + * reload a record after the `store.findRecord` method resolves a + * cached record. + */ + shouldBackgroundReloadRecord(store: Store, snapshot: Snapshot): boolean; + /** + * This method is used by the store to determine if the store should + * reload a record array after the `store.findAll` method resolves + * with a cached record array. + */ + shouldBackgroundReloadAll(store: Store, snapshotRecordArray: SnapshotRecordArray): boolean; + } + /** + * `DS.Serializer` is an abstract base class that you should override in your + * application to customize it for your backend. The minimum set of methods + * that you should implement is: + */ + class Serializer extends Ember.Object { + /** + * The `store` property is the application's `store` that contains + * all records. It can be used to look up serializers for other model + * types that may be nested inside the payload response. + */ + store: Store; + /** + * The `normalizeResponse` method is used to normalize a payload from the + * server to a JSON-API Document. + */ + normalizeResponse(store: Store, primaryModelClass: Model, payload: {}, id: string|number, requestType: string): {}; + /** + * The `serialize` method is used when a record is saved in order to convert + * the record into the form that your external data source expects. + */ + serialize(snapshot: Snapshot, options: {}): {}; + /** + * The `normalize` method is used to convert a payload received from your + * external data source into the normalized form `store.push()` expects. You + * should override this method, munge the hash and return the normalized + * payload. + */ + normalize(typeClass: Model, hash: {}): {}; + } +} +export default DS; + +declare module 'ember' { + namespace Ember { + /* + * The store is automatically injected into these objects + * + * https://github.com/emberjs/data/blob/05e95280e11c411177f2fbcb65fd83488d6a9d89/addon/setup-container.js#L71-L78 + */ + interface Route { + store: DS.Store; + } + interface Controller { + store: DS.Store; + } + interface DataAdapter { + store: DS.Store; + } + } +} diff --git a/types/ember-data/test/adapter.ts b/types/ember-data/test/adapter.ts new file mode 100644 index 0000000000..5d9d45fd4b --- /dev/null +++ b/types/ember-data/test/adapter.ts @@ -0,0 +1,56 @@ +import Ember from 'ember'; +import DS from 'ember-data'; + +const JsonApi = DS.JSONAPIAdapter.extend({ + // Application specific overrides go here +}); + +const Customized = DS.JSONAPIAdapter.extend({ + host: 'https://api.example.com', + namespace: 'api/v1', + headers: { + 'API_KEY': 'secret key', + 'ANOTHER_HEADER': 'Some header value' + } +}); + +const AuthTokenHeader = DS.JSONAPIAdapter.extend({ + session: Ember.inject.service('session'), + headers: Ember.computed('session.authToken', function() { + return { + 'API_KEY': this.get('session.authToken'), + 'ANOTHER_HEADER': 'Some header value' + }; + }) +}); + +const UseAjax = DS.JSONAPIAdapter.extend({ + query(store: DS.Store, type: string, query: object) { + const url = 'https://api.example.com/my-api'; + return this.ajax(url, 'POST', { + param: 'foo' + }); + } +}); + +const UseAjaxOptions = DS.JSONAPIAdapter.extend({ + query(store: DS.Store, type: string, query: object) { + const url = 'https://api.example.com/my-api'; + const options = this.ajaxOptions(url, 'DELETE', { + foo: 'bar' + }); + return Ember.$.ajax(url, { + ...options + }); + } +}); + +const UseAjaxOptionsWithOptionalThirdParams = DS.JSONAPIAdapter.extend({ + query(store: DS.Store, type: string, query: object) { + const url = 'https://api.example.com/my-api'; + const options = this.ajaxOptions(url, 'DELETE'); + return Ember.$.ajax(url, { + ...options + }); + } +}); diff --git a/types/ember-data/test/belongs-to.ts b/types/ember-data/test/belongs-to.ts new file mode 100644 index 0000000000..9e59aa6128 --- /dev/null +++ b/types/ember-data/test/belongs-to.ts @@ -0,0 +1,16 @@ +import DS from 'ember-data'; +import { assertType } from './lib/assert'; + +class Folder extends DS.Model { + name = DS.attr('string'); + children = DS.hasMany('folder', { inverse: 'parent' }); + parent = DS.belongsTo('folder', { inverse: 'children' }); +} + +const folder = Folder.create(); +assertType(folder.get('parent')); +assertType(folder.get('parent').get('name')); +folder.get('parent').then(parent => { + assertType(parent); + assertType(parent.get('name')); +}); diff --git a/types/ember-data/test/has-many.ts b/types/ember-data/test/has-many.ts new file mode 100644 index 0000000000..7fb586ff4a --- /dev/null +++ b/types/ember-data/test/has-many.ts @@ -0,0 +1,43 @@ +import DS from 'ember-data'; +import { assertType } from './lib/assert'; + +class Comment extends DS.Model { + text = DS.attr('string'); +} + +class BlogPost extends DS.Model { + title = DS.attr('string'); + commentsAsync = DS.hasMany('comment'); + commentsSync = DS.hasMany('comment', { async: false }); +} + +const post = BlogPost.create(); + +assertType>(post.get('commentsSync').reload()); +assertType(post.get('commentsSync').createRecord()); + +const comment = post.get('commentsSync').get('firstObject'); +assertType(comment); +if (comment) { + assertType(comment.get('text')); +} + +assertType>(post.get('commentsAsync').reload()); +assertType(post.get('commentsAsync').createRecord()); +assertType(post.get('commentsAsync').get('firstObject')); + +const commentAsync = post.get('commentsAsync').get('firstObject'); +assertType(commentAsync); +if (commentAsync) { + assertType(commentAsync.get('text')); +} +assertType(post.get('commentsAsync').get('isFulfilled')); + +post.get('commentsAsync').then(comments => { + assertType(comments.get('firstObject')); + assertType(comments.get('firstObject')!.get('text')); +}); + +class Polymorphic extends DS.Model { + paymentMethods = DS.hasMany('payment-method', { polymorphic: true }); +} diff --git a/types/ember-data/test/injections.ts b/types/ember-data/test/injections.ts new file mode 100644 index 0000000000..4c0a6e4e6b --- /dev/null +++ b/types/ember-data/test/injections.ts @@ -0,0 +1,22 @@ +import Ember from 'ember'; +import DS from 'ember-data'; + +Ember.Route.extend({ + model(): any { + return this.store.findAll('my-model'); + } +}); + +Ember.Controller.extend({ + actions: { + create(): any { + return this.store.createRecord('my-model'); + } + } +}); + +Ember.DataAdapter.extend({ + test() { + this.store.findRecord('my-model', 123); + } +}); diff --git a/types/ember-data/test/lib/assert.ts b/types/ember-data/test/lib/assert.ts new file mode 100644 index 0000000000..10094b9616 --- /dev/null +++ b/types/ember-data/test/lib/assert.ts @@ -0,0 +1,2 @@ +/** Static assertion that `value` has type `T` */ +export declare function assertType(value: T): void; diff --git a/types/ember-data/test/model.ts b/types/ember-data/test/model.ts new file mode 100644 index 0000000000..b3fa04e086 --- /dev/null +++ b/types/ember-data/test/model.ts @@ -0,0 +1,29 @@ +import Ember from 'ember'; +import DS from 'ember-data'; +import { assertType } from "./lib/assert"; + +const Person = DS.Model.extend({ + firstName: DS.attr(), + lastName: DS.attr(), + title: DS.attr({ defaultValue: "The default" }), + title2: DS.attr({ defaultValue: () => "The default" }), + + fullName: Ember.computed('firstName', 'lastName', function() { + return `${this.get('firstName')} ${this.get('lastName')}`; + }) +}); + +const User = DS.Model.extend({ + username: DS.attr('string'), + email: DS.attr('string'), + verified: DS.attr('boolean', { defaultValue: false }), + createdAt: DS.attr('date', { + defaultValue() { return new Date(); } + }) +}); + +const user = User.create({ username: 'dwickern' }); +assertType(user.get('id')); +assertType(user.get('username')); +assertType(user.get('verified')); +assertType(user.get('createdAt')); diff --git a/types/ember-data/test/record-reference.ts b/types/ember-data/test/record-reference.ts new file mode 100644 index 0000000000..bb4fda42d4 --- /dev/null +++ b/types/ember-data/test/record-reference.ts @@ -0,0 +1,38 @@ +import DS from 'ember-data'; +import { assertType } from "./lib/assert"; + +declare const store: DS.Store; + +class User extends DS.Model { + username = DS.attr('string'); +} + +let userRef = store.getReference('user', 1); + +// get the record of the reference (null if not yet available) +let user = userRef.value(); +if (user !== null) { + assertType(user); +} + +// get the identifier of the reference +if (userRef.remoteType() === 'id') { + let id = userRef.id(); + assertType(id); +} + +// load user (via store.find) +userRef.load().then(user => { + assertType(user); +}); + +// or trigger a reload +userRef.reload().then(user => { + assertType(user); +}); + +// provide data for reference +userRef.push({ id: 1, username: '@user' }).then(function(user) { + assertType(user); + userRef.value() === user; +}); diff --git a/types/ember-data/test/relationships.ts b/types/ember-data/test/relationships.ts new file mode 100644 index 0000000000..a878428bc4 --- /dev/null +++ b/types/ember-data/test/relationships.ts @@ -0,0 +1,30 @@ +import Ember from 'ember'; +import DS from 'ember-data'; + +declare const store: DS.Store; + +const Person = DS.Model.extend({ + children: DS.hasMany('folder', { inverse: 'parent' }), + parent: DS.belongsTo('folder', { inverse: 'children' }) +}); + +const Polymorphic = DS.Model.extend({ + paymentMethods: DS.hasMany('payment-method', { polymorphic: true }) +}); + +class Comment extends DS.Model { + author = DS.attr('string'); +} + +class BlogPost extends DS.Model { + title = DS.attr('string'); + tag = DS.attr('string'); + comments = DS.hasMany('comment', { async: true }); + relatedPosts = DS.hasMany('post'); +} + +let blogPost = store.peekRecord('blog-post', 1); +blogPost!.get('comments').then((comments) => { + // now we can work with the comments + let author: string = comments.get('firstObject')!.get('author'); +}); diff --git a/types/ember-data/test/serializer.ts b/types/ember-data/test/serializer.ts new file mode 100644 index 0000000000..986020144f --- /dev/null +++ b/types/ember-data/test/serializer.ts @@ -0,0 +1,38 @@ +import Ember from 'ember'; +import DS from 'ember-data'; + +const JsonApi = DS.JSONAPISerializer.extend({}); + +const Customized = DS.JSONAPISerializer.extend({ + serialize(snapshot: DS.Snapshot, options: {}) { + let json: any = this._super(...Array.from(arguments)); + + json.data.attributes.cost = { + amount: json.data.attributes.amount, + currency: json.data.attributes.currency + }; + + return json; + }, + normalizeResponse(store: DS.Store, primaryModelClass: DS.Model, payload: any, id: string|number, requestType: string) { + payload.data.attributes.amount = payload.data.attributes.cost.amount; + payload.data.attributes.currency = payload.data.attributes.cost.currency; + + delete payload.data.attributes.cost; + + return this._super(...Array.from(arguments)); + } +}); + +const EmbeddedRecordMixin = DS.JSONSerializer.extend(DS.EmbeddedRecordsMixin, { + attrs: { + author: { + serialize: false, + deserialize: 'records' + }, + comments: { + deserialize: 'records', + serialize: 'ids' + } + } +}); diff --git a/types/ember-data/test/store.ts b/types/ember-data/test/store.ts new file mode 100644 index 0000000000..f7560a231f --- /dev/null +++ b/types/ember-data/test/store.ts @@ -0,0 +1,119 @@ +import Ember from 'ember'; +import DS from 'ember-data'; +import { assertType } from "./lib/assert"; + +declare const store: DS.Store; + +class Post extends DS.Model { + title = DS.attr('string'); +} + +let post = store.createRecord('post', { + title: 'Rails is Omakase', + body: 'Lorem ipsum' +}); + +post.save(); // => POST to '/posts' +post.save().then((saved) => { + assertType(saved); +}); + +store.findRecord('post', 1).then(function(post) { + post.get('title'); // => "Rails is Omakase" + post.set('title', 'A new post'); + post.save(); // => PATCH to '/posts/1' +}); + +class User extends DS.Model { + username = DS.attr('string'); +} + +store.queryRecord('user', {}).then(function(user) { + let username = user.get('username'); + console.log(`Currently logged in as ${username}`); +}); + +store.findAll('blog-post'); // => GET /blog-posts +store.findAll('author', { reload: true }).then(function(authors) { + authors.getEach('id'); // ['first', 'second'] +}); +store.findAll('post', { + adapterOptions: { subscribe: false } +}); +store.findAll('post', { include: 'comments,comments.author' }); + +store.peekAll('blog-post'); // => no network request + +if (store.hasRecordForId('post', 1)) { + let maybePost = store.peekRecord('post', 1); + if (maybePost) { + maybePost.get('id'); // 1 + } +} + +class Message extends DS.Model { + hasBeenSeen = DS.attr('boolean'); +} + +const messages = store.peekAll('message'); +messages.forEach(function(message) { + message.set('hasBeenSeen', true); +}); +messages.save(); + +const people = store.peekAll('person'); +people.get('isUpdating'); // false +people.update().then(function() { + people.get('isUpdating'); // false +}); +people.get('isUpdating'); // true + +const MyRoute = Ember.Route.extend({ + model(params: any): any { + return this.store.findRecord('post', params.post_id, {include: 'comments,comments.author'}); + } +}); + +// GET to /users?filter[email]=tomster@example.com +const tom = store.query('user', { + filter: { + email: 'tomster@example.com' + } +}).then(function(users) { + return users.get("firstObject"); +}); + +// GET /users?isAdmin=true +const admins = store.query('user', { isAdmin: true }); +admins.then(function() { + console.log(admins.get("length")); // 42 +}); +admins.update().then(function() { + admins.get('isUpdating'); // false + console.log(admins.get("length")); // 123 +}); + +store.push({ + data: [{ + id: 1, + type: 'album', + attributes: { + title: 'Fewer Moving Parts', + artist: 'David Bazan', + songCount: 10 + }, + relationships: {} + }, { + id: 2, + type: 'album', + attributes: { + title: 'Calgary b/w I Can\'t Make You Love Me/Nick Of Time', + artist: 'Bon Iver', + songCount: 2 + }, + relationships: {} + }] +}); + +assertType(store.adapterFor('person')); +assertType(store.serializerFor('person')); diff --git a/types/ember-data/test/transform.ts b/types/ember-data/test/transform.ts new file mode 100644 index 0000000000..b76d40a73f --- /dev/null +++ b/types/ember-data/test/transform.ts @@ -0,0 +1,16 @@ +import Ember from 'ember'; +import DS from 'ember-data'; + +class Point extends Ember.Object { + x: number; + y: number; +} + +const PointTransform = DS.Transform.extend({ + serialize(value: Point): number[] { + return [value.get('x'), value.get('y')]; + }, + deserialize(value: [ number, number ]): Point { + return Point.create({ x: value[0], y: value[1] }); + } +}); diff --git a/types/ember-data/tsconfig.json b/types/ember-data/tsconfig.json new file mode 100644 index 0000000000..155515ac6b --- /dev/null +++ b/types/ember-data/tsconfig.json @@ -0,0 +1,32 @@ +{ + "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", + "test/lib/assert.ts", + "test/model.ts", + "test/adapter.ts", + "test/serializer.ts", + "test/transform.ts", + "test/relationships.ts", + "test/store.ts", + "test/has-many.ts", + "test/belongs-to.ts", + "test/record-reference.ts", + "test/injections.ts" + ] +} diff --git a/types/ember-data/tslint.json b/types/ember-data/tslint.json new file mode 100644 index 0000000000..dd3a7f529c --- /dev/null +++ b/types/ember-data/tslint.json @@ -0,0 +1,16 @@ +{ + "extends": "dtslint/dt.json", + "rules": { + // Heavy use of Function type in this older package. + "ban-types": false, + "jsdoc-format": false, + "no-misused-new": false, + // not sure what this means + "no-single-declare-module": false, + "object-literal-key-quotes": false, + "only-arrow-functions": false, + "no-empty-interface": false, + "prefer-const": false, + "no-unnecessary-generics": false + } +} diff --git a/types/ember/index.d.ts b/types/ember/index.d.ts index bb6cce8b36..adef4e70c2 100755 --- a/types/ember/index.d.ts +++ b/types/ember/index.d.ts @@ -558,6 +558,8 @@ declare module 'ember' { **/ interface ArrayProxy extends MutableArray {} class ArrayProxy extends Object.extend(MutableArray as {}) { + content: NativeArray; + /** * Should actually retrieve the object at the specified index from the * content. You can override this method in subclasses to transform the @@ -1837,7 +1839,7 @@ declare module 'ember' { * A hook you can implement to convert the URL into the model for * this route. */ - model(params: {}, transition: Transition): T | Rsvp.Promise; + model(params: {}, transition: Transition): any; /** * Returns the model of a parent (or any ancestor) route diff --git a/types/ember/test/array-proxy.ts b/types/ember/test/array-proxy.ts old mode 100755 new mode 100644 index 763034bbd0..dceea7b847 --- a/types/ember/test/array-proxy.ts +++ b/types/ember/test/array-proxy.ts @@ -21,7 +21,6 @@ class MyNewProxy extends Ember.ArrayProxy { isNew = true; } -let x = MyNewProxy.create({ content: Ember.A([1, 2, 3]) }); -// TODO: type inference can't infer 'number', just '{}' -// x.get('firstObject'); // $ExpectType number | undefined -x.isNew; // $ExpectType boolean +let x = MyNewProxy.create({ content: Ember.A([1, 2, 3]) }) as MyNewProxy; +assertType(x.get('firstObject')); +assertType(x.isNew); diff --git a/types/enzyme/enzyme-tests.tsx b/types/enzyme/enzyme-tests.tsx index 63e716c50b..c48c050357 100644 --- a/types/enzyme/enzyme-tests.tsx +++ b/types/enzyme/enzyme-tests.tsx @@ -1,5 +1,14 @@ import * as React from "react"; -import { shallow, mount, render, ShallowWrapper, ReactWrapper } from "enzyme"; +import { + shallow, + mount, + render, + ShallowWrapper, + ReactWrapper, + configure, + EnzymeAdapter, + ShallowRendererProps, +} from "enzyme"; import { Component, ReactElement, HTMLAttributes, ComponentClass, StatelessComponent } from "react"; // Help classes/interfaces @@ -24,6 +33,18 @@ class MyComponent extends Component { const MyStatelessComponent = (props: StatelessProps) => ; +// Enzyme.configure +function configureTest() { + const configureAdapter: { adapter: EnzymeAdapter } = { adapter: {} }; + configure(configureAdapter); + + const configureAdapterAndDisableLifecycle: typeof configureAdapter & Pick = { + adapter: {}, + disableLifecycleMethods: true, + }; + configure(configureAdapterAndDisableLifecycle); +} + // ShallowWrapper function ShallowWrapperTest() { let shallowWrapper: ShallowWrapper = @@ -50,7 +71,8 @@ function ShallowWrapperTest() { context: { test: "a", }, - lifecycleExperimental: true + lifecycleExperimental: true, + disableLifecycleMethods: true }); } diff --git a/types/enzyme/index.d.ts b/types/enzyme/index.d.ts index bfd714fd22..3a8ea149f9 100644 --- a/types/enzyme/index.d.ts +++ b/types/enzyme/index.d.ts @@ -551,6 +551,12 @@ export class ReactWrapper

{ } export interface ShallowRendererProps { + // See https://github.com/airbnb/enzyme/blob/enzyme@3.1.1/docs/api/shallow.md#arguments + /** + * If set to true, componentDidMount is not called on the component, and componentDidUpdate is not called after + * setProps and setContext. Default to false. + */ + disableLifecycleMethods?: boolean; /** * Enable experimental support for full react lifecycle methods */ @@ -602,4 +608,14 @@ export class EnzymeAdapter { * Configure enzyme to use the correct adapter for the react verstion * This is enabling the Enzyme configuration with adapters in TS */ -export function configure(options: { adapter: EnzymeAdapter }): void; +export function configure(options: { + adapter: EnzymeAdapter, + // See https://github.com/airbnb/enzyme/blob/enzyme@3.1.1/docs/guides/migration-from-2-to-3.md#lifecycle-methods + // Actually, `{adapter:} & Pick` is more precise. However, + // in that case jsdoc won't be shown + /** + * If set to true, componentDidMount is not called on the component, and componentDidUpdate is not called after + * setProps and setContext. Default to false. + */ + disableLifecycleMethods?: boolean; +}): void; diff --git a/types/expo/expo-tests.tsx b/types/expo/expo-tests.tsx new file mode 100644 index 0000000000..333b9d3e3c --- /dev/null +++ b/types/expo/expo-tests.tsx @@ -0,0 +1,203 @@ +import * as React from 'react'; + +import { + Accelerometer, + Amplitude, + Asset, + AuthSession, + Audio, + AppLoading, + BarCodeScanner, + BlurViewProps, + BlurView, + Brightness, + Camera, + DocumentPicker, + Facebook, + FacebookAds, + FileSystem +} from 'expo'; + +Accelerometer.addListener((obj) => { + obj.x; + obj.y; + obj.z; +}); +Accelerometer.removeAllListeners(); +Accelerometer.setUpdateInterval(1000); + +Amplitude.initialize('key'); +Amplitude.setUserId('userId'); +Amplitude.setUserProperties({key: 1}); +Amplitude.clearUserProperties(); +Amplitude.logEvent('name'); +Amplitude.logEventWithProperties('event', {key: 'value'}); +Amplitude.setGroup('type', {key: 'value'}); + +const asset = Asset.fromModule(1); +asset.downloadAsync(); +Asset.loadAsync(1); +Asset.loadAsync([1, 2, 3]); +const asset1 = new Asset({ + uri: 'uri', + type: 'type', + name: 'name', + hash: 'hash', + width: 122, + height: 122 +}); + +const url = AuthSession.getRedirectUrl(); +AuthSession.dismiss(); +AuthSession.startAsync({ + authUrl: 'url1', + returnUrl: 'url2' +}).then(result => { + switch (result.type) { + case 'success': + result.event; + result.params; + break; + case 'error': + result.errorCode; + result.params; + result.event; + break; + case 'dismissed': + case 'cancel': + result.type; + break; + } +}); + +Audio.setAudioModeAsync({ + shouldDuckAndroid: false, + playsInSilentModeIOS: true, + interruptionModeIOS: 2, + interruptionModeAndroid: 1, + allowsRecordingIOS: true +}); +Audio.setIsEnabledAsync(true); +async () => { + const result = await Audio.Sound.create('uri', { + volume: 0.5, + rate: 0.6 + }, null, true); + + const sound = result.sound; + const status = result.status; + + if (!status.isLoaded) { + status.error; + } else { + status.didJustFinish; + // etc. + } + + const _status = await sound.getStatusAsync(); + await sound.loadAsync('uri'); +}; + +() => ( + Promise.resolve()} + onFinish={() => {}} + onError={(error) => console.log(error)} /> +); +() => ( + +); + +const barcodeReadCallback = () => {}; +() => ( + +); + +() => ( + +); + +async () => { + await Brightness.setBrightnessAsync(.6); + await Brightness.setSystemBrightnessAsync(.7); + const br1 = await Brightness.getBrightnessAsync(); + const br2 = await Brightness.getSystemBrightnessAsync(); +}; + +Camera.Constants.AutoFocus; +Camera.Constants.Type; +Camera.Constants.FlashMode; +Camera.Constants.WhiteBalance; +Camera.Constants.VideoQuality; +Camera.Constants.BarCodeType; +() => { + return( { + if (component) { + component.recordAsync(); + } + }} />); +}; + +async () => { + const result = await DocumentPicker.getDocumentAsync(); + + if (result.type === 'success') { + result.name; + result.uri; + result.size; + } +}; + +async () => { + const result = await Facebook.logInWithReadPermissionsAsync('appId'); + + if (result.type === 'success') { + result.expires; + result.token; + } +}; + +() => ( + {}} + onError={() => {}} /> +); + +async () => { + const info = await FileSystem.getInfoAsync('file'); + + info.exists; + info.isDirectory; + + if (info.exists) { + info.md5; + info.uri; + info.size; + info.modificationTime; + } + + const string: string = await FileSystem.readAsStringAsync('file'); + await FileSystem.writeAsStringAsync('file', 'content'); + await FileSystem.deleteAsync('file'); + await FileSystem.moveAsync({ from: 'from', to: 'to'}); + await FileSystem.copyAsync({ from: 'from', to: 'to' }); + await FileSystem.makeDirectoryAsync('dir'); + const dirs: string[] = await FileSystem.readDirectoryAsync('dir'); + const result = await FileSystem.downloadAsync('from', 'to'); + + result.headers; + result.status; + result.uri; + result.md5; +}; diff --git a/types/expo/index.d.ts b/types/expo/index.d.ts new file mode 100644 index 0000000000..04d500ab6b --- /dev/null +++ b/types/expo/index.d.ts @@ -0,0 +1,1481 @@ +// Type definitions for expo 23.0 +// Project: https://github.com/expo/expo-sdk +// Definitions by: Konstantin Kai +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.4 + +import { EventSubscription } from 'fbemitter'; +import { Component, Ref } from 'react'; +import { + ViewStyle, + ViewProperties, + ColorPropType, + ImageURISource, + NativeEventEmitter, + ImageRequireSource +} from 'react-native'; + +export type URISource = ImageURISource; +export type RequireSource = ImageRequireSource; +export type ResizeModeContain = 'contain'; +export type ResizeModeCover = 'cover'; +export type ResizeModeStretch = 'stretch'; +export type Orientation = 'portrait' | 'landscape'; +export type Axis = number; +export interface HashMap { [key: string]: any; } +export type FloatFromZeroToOne = 0 | 0.1 | 0.2 | 0.3 | 0.4 | 0.5 | 0.6 | 0.7 | 0.8 | 0.9 | 1; +export type BarCodeReadCallback = (params: { type: string; data: string; }) => void; +export type Md5 = string; + +/** + * Accelerometer + */ +export namespace Accelerometer { + interface AccelerometerObject { + x: Axis; + y: Axis; + z: Axis; + } + + function addListener(listener: (obj: AccelerometerObject) => any): EventSubscription; + function removeAllListeners(): void; + function setUpdateInterval(intervalMs: number): void; +} + +/** + * Amplitude + */ +export namespace Amplitude { + function initialize(apiKey: string): void; + function setUserId(userId: string): void; + function setUserProperties(userProperties: HashMap): void; + function clearUserProperties(): void; + function logEvent(eventName: string): void; + function logEventWithProperties(eventName: string, properties: HashMap): void; + function setGroup(groupType: string, groupNames: HashMap): void; +} + +/** + * Asset + */ +export class Asset { + constructor({ name, type, hash, uri, width, height }: { + name: string; + type: string; + hash: string; + uri: string; + width?: number; + height?: number; + }); + name: string; + type: string; + hash: string; + uri: string; + localUri: string; + width?: number; + height?: number; + + downloading: boolean; + downloaded: boolean; + downloadCallbacks: Array<{ resolve: () => any, reject: (e?: any) => any }>; + + downloadAsync(): Promise; + + static fromModule(module: RequireSource): Asset; + static loadAsync(module: RequireSource[] | RequireSource): Promise; +} + +/** + * AuthSession + */ +export namespace AuthSession { + function startAsync(options: { authUrl: string; returnUrl: string; }): Promise<{ + type: 'cancel'; + } | { + type: 'dismissed'; + } | { + type: 'success'; + params: HashMap; + event: HashMap; + } | { + type: 'error'; + params: HashMap; + errorCode: string; + event: HashMap; + }>; + function dismiss(): void; + function getRedirectUrl(): string; +} + +/** + * AV + */ +export type PlaybackStatus = { + isLoaded: false; + androidImplementation?: string; + error?: string; +} | { + isLoaded: true; + androidImplementation?: string; + uri: string; + progressUpdateIntervalMillis: number; + durationMillis?: number; + positionMillis: number; + playableDurationMillis?: number; + shouldPlay: boolean; + isPlaying: boolean; + isBuffering: boolean; + rate: number; + shouldCorrectPitch: boolean; + volume: number; + isMuted: boolean; + isLooping: boolean; + didJustFinish: boolean; +}; + +export interface PlaybackStatusToSet { + androidImplementation?: string; + progressUpdateIntervalMillis?: number; + positionMillis?: number; + shouldPlay?: boolean; + rate?: FloatFromZeroToOne; + shouldCorrectPitch?: boolean; + volume?: FloatFromZeroToOne; + isMuted?: boolean; + isLooping?: boolean; +} + +export type Source = string | RequireSource | Asset; + +export class PlaybackObject { + loadAsync(source: Source, initialStatus?: PlaybackStatusToSet, downloadFirst?: boolean): Promise; + unloadAsync(): Promise; + getStatusAsync(): Promise; + setOnPlaybackStatusUpdate(onPlaybackStatusUpdate: (status: PlaybackStatus) => void): void; + setStatusAsync(status: PlaybackStatusToSet): Promise; + playAsync(): Promise; + playFromPositionAsync(positionMillis: number): Promise; + pauseAsync(): Promise; + stopAsync(): Promise; + setPositionAsync(positionMillis: number): Promise; + setRateAsync(rate: number, shouldCorrectPitch: boolean): Promise; + setVolumeAsync(volume: number): Promise; + setIsMutedAsync(isMuted: boolean): Promise; + setIsLoopingAsync(isLooping: boolean): Promise; + setProgressUpdateIntervalAsync(progressUpdateIntervalMillis: number): Promise; +} + +export namespace Audio { + enum InterruptionModeIOS { + INTERRUPTION_MODE_IOS_MIX_WITH_OTHERS = 0, + INTERRUPTION_MODE_IOS_DO_NOT_MIX = 1, + INTERRUPTION_MODE_IOS_DUCK_OTHERS = 2 + } + + enum InterruptionModeAndroid { + INTERRUPTION_MODE_ANDROID_DO_NOT_MIX = 1, + INTERRUPTION_MODE_ANDROID_DUCK_OTHERS = 2 + } + + type RecordingStatus = { + canRecord: false, + isDoneRecording: false + } | { + canRecord: true, + isRecording: boolean, + durationMillis: number + } | { + canRecord: false, + isDoneRecording: true, + durationMillis: number + }; + + interface AudioMode { + playsInSilentModeIOS: boolean; + allowsRecordingIOS: boolean; + interruptionModeIOS: InterruptionModeIOS; + shouldDuckAndroid: boolean; + interruptionModeAndroid: InterruptionModeAndroid; + } + + function setIsEnabledAsync(value: boolean): Promise; + function setAudioModeAsync(mode: AudioMode): Promise; + + class Sound extends PlaybackObject { + constructor(); + + static create( + source: Source, + initialStatus?: PlaybackStatusToSet, + onPlaybackStatusUpdate?: ((status: PlaybackStatus) => void) | null, + downloadFirst?: boolean + ): Promise<{ sound: Sound, status: PlaybackStatus }>; + } + + interface RecordingOptions { + android: { + extension: string; + outputFormat: number; + audioEncoder: number; + sampleRate?: number; + numberOfChannels?: number; + bitRate?: number; + maxFileSize?: number; + }; + ios: { + extension: string; + outputFormat?: string | number; + audioQuality: number; + sampleRate: number; + numberOfChannels: number; + bitRate: number; + bitRateStrategy?: number; + bitDepthHint?: number; + linearPCMBitDepth?: number; + linearPCMIsBigEndian?: boolean; + linearPCMIsFloat?: boolean; + }; + } + + class Recording { + constructor(); + + getStatusAsync(): Promise; + setOnRecordingStatusUpdate(onRecordingStatusUpdate: (status: RecordingStatus) => void): void; + setProgressUpdateInterval(miliss: number): void; + prepareToRecordAsync(options: Recording): Promise; + isPreparedToRecord(): boolean; + startAsync(): Promise; + pauseAsync(): Promise; + stopAndUnloadAsync(): Promise; + getURI(): string | undefined; + createNewLoadedSound(initialStatus: PlaybackStatusToSet, onPlaybackStatusUpdate: (status: PlaybackStatus) => void): Promise<{ sound: Sound, status: PlaybackStatus }>; + } +} + +/** + * Expo Video + */ +export interface NaturalSize { + width: number; + height: number; + orientation: Orientation; +} + +export interface ReadyForDisplayEvent { + naturalSize: NaturalSize; + status: PlaybackStatus; +} + +export enum FullscreenUpdateVariants { + IOS_FULLSCREEN_UPDATE_PLAYER_WILL_PRESENT = 0, + IOS_FULLSCREEN_UPDATE_PLAYER_DID_PRESENT = 1, + IOS_FULLSCREEN_UPDATE_PLAYER_WILL_DISMISS = 2, + IOS_FULLSCREEN_UPDATE_PLAYER_DID_DISMISS = 3 +} + +export interface FullscreenUpdateEvent { + fullscreenUpdate: FullscreenUpdateVariants; + status: PlaybackStatus; +} + +export interface VideoProps { + source?: Source | null; + posterSource?: URISource | RequireSource; + + resizeMode?: ResizeModeContain | ResizeModeCover | ResizeModeStretch; + useNativeControls?: boolean; + usePoster?: boolean; + + onPlaybackStatusUpdate?: (status: PlaybackStatus) => void; + onReadyForDisplay?: (event: ReadyForDisplayEvent) => void; + onIOSFullscreenUpdate?: (event: FullscreenUpdateEvent) => void; + + onLoadStart?: () => void; + onLoad?: (status: PlaybackStatus) => void; + onError?: (error: string) => void; + + status?: PlaybackStatusToSet; + progressUpdateIntervalMillis?: number; + positionMillis?: number; + shouldPlay?: boolean; + rate?: number; + shouldCorrectPitch?: boolean; + volume?: number; + isMuted?: boolean; + isLooping?: boolean; + + scaleX?: number; + scaleY?: number; + translateX?: number; + translateY?: number; + rotation?: number; + ref?: Ref; +} + +export interface VideoState { + showPoster: boolean; +} + +export class Video extends Component { + static RESIZE_MODE_CONTAIN: ResizeModeContain; + static RESIZE_MODE_COVER: ResizeModeCover; + static RESIZE_MODE_STRETCH: ResizeModeStretch; + static IOS_FULLSCREEN_UPDATE_PLAYER_WILL_PRESENT: FullscreenUpdateVariants.IOS_FULLSCREEN_UPDATE_PLAYER_WILL_PRESENT; + static IOS_FULLSCREEN_UPDATE_PLAYER_DID_PRESENT: FullscreenUpdateVariants.IOS_FULLSCREEN_UPDATE_PLAYER_DID_PRESENT; + static IOS_FULLSCREEN_UPDATE_PLAYER_WILL_DISMISS: FullscreenUpdateVariants.IOS_FULLSCREEN_UPDATE_PLAYER_WILL_DISMISS; + static IOS_FULLSCREEN_UPDATE_PLAYER_DID_DISMISS: FullscreenUpdateVariants.IOS_FULLSCREEN_UPDATE_PLAYER_DID_DISMISS; +} + +/** + * AppLoading + */ +export type AppLoadingProperties = { + startAsync: () => Promise; + onFinish: () => void; + onError?: (error: Error) => void; +} | { + startAsync: null; + onFinish: null; + onError?: null; +}; +export class AppLoading extends Component { } + +/** + * BarCodeScanner + */ +export interface BarCodeScannerProps extends ViewProperties { + type?: 'front' | 'back'; + torchMode?: 'on' | 'off'; + barCodeTypes?: string[]; + onBarCodeRead?: BarCodeReadCallback; +} + +export class BarCodeScanner extends Component { } + +/** + * BlurView + */ +export interface BlurViewProps extends ViewProperties { + tint: 'light' | 'default' | 'dark'; + intensity: number; +} +export class BlurView extends Component { } + +/** + * Brightness + */ +export namespace Brightness { + function setBrightnessAsync(brightnessValue: FloatFromZeroToOne): Promise; + function getBrightnessAsync(): Promise; + function getSystemBrightnessAsync(): Promise; + function setSystemBrightnessAsync(brightnessValue: FloatFromZeroToOne): Promise; +} + +/** + * Camera + */ +export interface TakePictureOptions { + quality?: number; + base64?: boolean; + exif?: boolean; +} +export interface PictureResponse { + uri: string; + width: number; + height: number; + exif: string; + base64: string; +} +export interface RecordOptions { + quality?: string; + maxDuration?: number; + maxFileSize?: number; + mute?: boolean; +} +export class CameraObject { + takePictureAsync(options: TakePictureOptions): Promise; + recordAsync(options: RecordOptions): Promise<{ uri: string; }>; + stopRecording(): void; + getSupportedRatiosAsync(): Promise; // Android only +} +export interface CameraProperties extends ViewProperties { + flashMode?: string | number; + type?: string | number; + ratio?: string; + autoFocus?: string | number | boolean; + focusDepth?: FloatFromZeroToOne; + zoom?: FloatFromZeroToOne; + whiteBalance?: string | number; + barCodeTypes?: string[]; + onCameraReady?: () => void; + onMountError?: () => void; + onBarCodeRead?: BarCodeReadCallback; + ref?: Ref; +} +export interface CameraConstants { + readonly Type: string; + readonly FlashMode: string; + readonly AutoFocus: string; + readonly WhiteBalance: string; + readonly VideoQuality: string; + readonly BarCodeType: string; +} +export class Camera extends Component { + static readonly Constants: CameraConstants; +} + +/** + * Constants + */ +export namespace Constants { + const appOwnership: 'expo' | 'standalone' | 'guest'; + const expoVersion: string; + const deviceId: string; + const deviceName: string; + const deviceYearClass: number; + const isDevice: boolean; + + interface Platform { + ios: { + platform: string; + model: string; + userInterfaceIdiom: string; + }; + } + const platform: Platform; + const sessionId: string; + const statusBarHeight: number; + const systemFonts: string[]; + + interface Manifest { + name: string; + description?: string; + slug?: string; + sdkVersion?: string; + version?: string; + orientation?: Orientation; + primaryColor?: string; + icon?: string; + notification?: { + icon?: string, + color?: string, + androidMode?: 'default' | 'collapse', + androidCollapsedTitle?: string + }; + loading?: { + icon?: string, + exponentIconColor?: 'white' | 'blue', + exponentIconGrayscale?: 1 | 0, + backgroundImage?: string, + backgroundColor?: string, + hideExponentText?: boolean + }; + appKey?: string; + androidStatusBarColor?: string; + androidStatusBar?: { + barStyle?: 'lignt-content' | 'dark-content', + backgroundColor?: string + }; + androidHideExponentNotificationInShellApp?: boolean; + scheme?: string; + extra?: { + [propName: string]: any + }; + rnCliPath?: any; + entryPoint?: string; + packagerOpts?: { + hostType?: string, + dev?: boolean, + strict?: boolean, + minify?: boolean, + urlType?: string, + urlRandomness?: string, + lanType?: string, + [propName: string]: any + }; + ignoreNodeModulesValidation?: any; + nodeModulesPath?: string; + ios?: { + bundleIdentifier?: string, + buildNumber?: string, + config?: { + usesNonExemptEncryption?: boolean, + googleSignIn?: { + reservedClientId: string + } + }, + supportsTablet?: boolean, + infoPlist?: any + }; + android?: { + package?: string, + versionCode?: string, + config?: { + fabric?: { + apiKey: string, + buildSecret: string + }, + googleMaps?: { + apiKey: string + }, + googleSignIn?: { + apiKey: string, + certificateHash: string + } + } + }; + facebookScheme: any; + xde: boolean; + developper?: { + tool?: string, + [propName: string]: any + }; + bundleUrl?: string; + debuggerHost?: string; + mainModuleName?: string; + logUrl?: string; + [propName: string]: any; + } + const manifest: Manifest; + const linkingUri: string; +} + +/** + * Contacts + */ +export namespace Contacts { + type PhoneNumbers = 'phoneNumbers'; + type Emails = 'emails'; + type Addresses = 'addresses'; + type Image = 'image'; + type Thumbnail = 'thumbnail'; + type Note = 'note'; + type Birthday = 'birthday'; + type NonGregorianBirthday = 'nonGregorianBirthday'; + type NamePrefix = 'namePrefix'; + type NameSuffix = 'nameSuffix'; + type PhoneticFirstName = 'phoneticFirstName'; + type PhoneticMiddleName = 'phoneticMiddleName'; + type PhoneticLastName = 'phoneticLastName'; + type SocialProfiles = 'socialProfiles'; + type InstantMessageAddresses = 'instantMessageAddresses'; + type UrlAddresses = 'urlAddresses'; + type Dates = 'dates'; + type Relationships = 'relationships'; + + const PHONE_NUMBERS: PhoneNumbers; + const EMAILS: Emails; + const ADDRESSES: Addresses; + const IMAGE: Image; + const THUMBNAIL: Thumbnail; + const NOTE: Note; + const BIRTHDAY: Birthday; + const NON_GREGORIAN_BIRTHDAY: NonGregorianBirthday; + const NAME_PREFIX: NamePrefix; + const NAME_SUFFIX: NameSuffix; + const PHONETIC_FIRST_NAME: PhoneticFirstName; + const PHONETIC_MIDDLE_NAME: PhoneticMiddleName; + const PHONETIC_LAST_NAME: PhoneticLastName; + const SOCIAL_PROFILES: SocialProfiles; + const IM_ADDRESSES: InstantMessageAddresses; + const URLS: UrlAddresses; + const DATES: Dates; + const RELATIONSHIPS: Relationships; + + type FieldType = PhoneNumbers | Emails | Addresses | Image | Thumbnail | + Note | Birthday | NonGregorianBirthday | NamePrefix | NameSuffix | + PhoneticFirstName | PhoneticMiddleName | PhoneticLastName | SocialProfiles | + InstantMessageAddresses | UrlAddresses | Dates | Relationships; + + interface Options { + pageSize?: number; + pageOffset?: number; + fields?: FieldType[]; + } + + interface Contact { + id: string; + contactType: string; + name: string; + firstName?: string; + middleName?: string; + lastName?: string; + previousLastName?: string; + namePrefix?: string; + nameSuffix?: string; + nickname?: string; + phoneticFirstName?: string; + phoneticMiddleName?: string; + phoneticLastName?: string; + emails?: Array<{ + email?: string; + primary?: boolean; + label: string; + id: string; + }>; + phoneNumbers?: Array<{ + number?: string; + primary?: boolean; + digits?: string; + countryCode?: string; + label: string; + id: string; + }>; + addresses?: Array<{ + street?: string; + city?: string; + country?: string; + region?: string; + neighborhood?: string; + postalCode?: string; + poBox?: string; + isoCountryCode?: string; + label: string; + id: string; + }>; + socialProfiles?: Array<{ + service?: string; + localizedProfile?: string; + url?: string; + username?: string; + userId?: string; + label: string; + id: string; + }>; + instantMessageAddresses?: Array<{ + service?: string; + username?: string; + localizedService?: string; + label: string; + id: string; + }>; + urls?: { + label: string; + url?: string; + id: string; + }; + company?: string; + jobTitle?: string; + department?: string; + imageAvailable?: boolean; + image?: { + uri?: string; + }; + thumbnail?: { + uri?: string; + }; + note?: string; + dates?: Array<{ + day?: number; + month?: number; + year?: number; + id: string; + label: string; + }>; + relationships?: Array<{ + label: string; + name?: string; + id: string; + }>; + } + + interface Response { + data: Contact[]; + total: number; + hasNextPage: boolean; + hasPreviousPage: boolean; + } + + function getContactsAsync(options: Options): Promise; + function getContactByIdAsync(options: { id?: string; fields?: FieldType[] }): Promise; +} + +/** + * DocumentPicker + */ +export namespace DocumentPicker { + interface Options { + type?: string; + } + type Response = { + type: 'success'; + uri: string; + name: string; + size: number; + } | { + type: 'cancel'; + }; + + function getDocumentAsync(options?: Options): Promise; +} + +/** + * ErrorRecovery + */ +export namespace ErrorRecovery { + function setRecoveryProps(props: HashMap): void; +} + +/** + * Facebook + */ +export namespace Facebook { + interface Options { + permissions?: string[]; + behavior?: 'web' | 'native' | 'browser' | 'system'; + } + type Response = { + type: 'success'; + token: string; + expires: number; + } | { + type: 'cancel'; + }; + function logInWithReadPermissionsAsync(appId: string, options?: Options): Promise; +} + +/** + * Facebook Ads + */ +export namespace FacebookAds { + /** + * Interstitial Ads + */ + namespace InterstitialAdManager { + function showAd(placementId: string): Promise; + } + + /** + * Native Ads + */ + type MediaCachePolicy = 'none' | 'icon' | 'image' | 'all'; + class NativeAdsManager { + constructor(placementId: string, numberOfAdsToRequest?: number); + disableAutoRefresh(): void; + setMediaCachePolicy(cachePolicy: MediaCachePolicy): void; + } + + function withNativeAd(component: Component<{ + icon?: string; + coverImage?: string; + title?: string; + subtitle?: string; + description?: string; + callToActionText?: string; + socialContext?: string; + }>): Component<{ adsManager: NativeAdsManager }, { ad: any, canRequestAds: boolean }>; + + /** + * Banner View + */ + type AdType = 'large' | 'rectangle' | 'standard'; + + interface BannerViewProps { + type: AdType; + placementId: string; + onPress: () => void; + onError: () => void; + } + + class BannerView extends Component { } + + /** + * Ad Settings + */ + namespace AdSettings { + const currentDeviceHash: string; + function addTestDevice(device: string): void; + function clearTestDevices(): void; + type SDKLogLevel = 'none' | 'debug' | 'verbose' | 'warning' | 'error' | 'notification'; + function setLogLevel(logLevel: SDKLogLevel): void; + function setIsChildDirected(isDirected: boolean): void; + function setMediationService(mediationService: string): void; + function setUrlPrefix(urlPrefix: string): void; + } +} + +/** + * FileSystem + */ +export namespace FileSystem { + type FileInfo = { + exists: true; + isDirectory: boolean; + uri: string; + size: number; + modificationTime: number; + md5?: Md5; + } | { + exists: false; + isDirectory: false; + }; + + interface DownloadResult { + uri: string; + status: number; + headers: { [name: string]: string }; + md5?: Md5; + } + + const documentDirectory: string; + const cacheDirectory: string; + + function getInfoAsync(fileUri: string, options?: { md5?: string, size?: boolean; }): Promise; + function readAsStringAsync(fileUri: string): Promise; + function writeAsStringAsync(fileUri: string, contents: string): Promise; + function deleteAsync(fileUri: string, options?: { idempotent: boolean; }): Promise; + function moveAsync(options: { from: string, to: string; }): Promise; + function copyAsync(options: { from: string, to: string; }): Promise; + function makeDirectoryAsync(dirUri: string, options?: { intermediates: boolean }): Promise; + function readDirectoryAsync(dirUri: string): Promise; + function downloadAsync(uri: string, fileUri: string, options?: { md5?: boolean; }): Promise; + function createDownloadResumable( + uri: string, + fileUri: string, + options?: DownloadOptions, + callback?: (totalBytesWritten: number, totalBytesExpectedToWrite: number) => void, + resumeData?: string | null + ): DownloadResumable; + + interface PauseResult { + url: string; + fileUri: string; + options: { md5: boolean; }; + resumeData: string; + } + + interface DownloadOptions { + md5?: boolean; + headers?: { [name: string]: string }; + } + + interface DownloadProgressData { + totalBytesWritten: number; + totalBytesExpectedToWrite: number; + } + + type DownloadProgressCallback = (data: DownloadProgressData) => void; + + class DownloadResumable { + constructor( + url: string, + fileUri: string, + options: DownloadOptions, + callback?: DownloadProgressCallback, + resumeData?: string + ); + + downloadAsync(): Promise; + pauseAsync(): Promise; + resumeAsync(): Promise; + savable(): PauseResult; + } +} + +/** + * Fingerprint + */ +export namespace Fingerprint { + type FingerprintAuthenticationResult = { success: true } | { success: false, error: string }; + + function hasHardwareAsync(): Promise; + function isEnrolledAsync(): Promise; + function authenticateAsync(promptMessageIOS?: string): Promise; + function cancelAuthenticate(): void; +} + +/** + * Font + */ +export namespace Font { + interface FontMap { + [name: string]: RequireSource; + } + + function loadAsync(name: string, url: string): Promise; + function loadAsync(map: FontMap): Promise; +} + +/** + * GLView + */ +export interface GLViewProps extends ViewProperties { + onContextCreate(): void; + msaaSamples: number; +} +export class GLView extends Component { } + +/** + * Google + */ +export namespace Google { + interface LogInConfig { + androidClientId?: string; + androidStandaloneAppClientId?: string; + iosClientId?: string; + iosStandaloneAppClientId?: string; + webClientId?: string; + behavior?: 'system' | 'web'; + scopes?: string[]; + } + + type LogInResult = { + type: 'cancel'; + } | { + type: 'success'; + accessToken: string; + idToken?: string; + refreshToken?: string; + serverAuthCode?: string; + user: { + id: string; + name: string; + givenName: string; + familyName: string; + photoUrl?: string; + email?: string; + } + }; + + function logInAsync(config: LogInConfig): Promise; +} + +/** + * Gyroscope + */ +export namespace Gyroscope { + interface GyroscopeObject { + x: Axis; + y: Axis; + z: Axis; + } + + function addListener(listener: (obj: GyroscopeObject) => any): EventSubscription; + function removeAllListeners(): void; + function setUpdateInterval(intervalMs: number): void; +} + +/** + * Image Picker + */ +export namespace ImagePicker { + interface ImageInfo { + uri: string; + width: number; + height: number; + } + + type ImageResult = { cancelled: true } | ({ cancelled: false } & ImageInfo); + + interface ImageLibraryOptions { + allowsEditing?: boolean; + aspect?: [number, number]; + quality?: number; + } + + function launchImageLibraryAsync(options?: ImageLibraryOptions): Promise; + + interface CameraOptions { + allowsEditing?: boolean; + aspect?: [number, number]; + quality?: number; + } + function launchCameraAsync(options?: CameraOptions): Promise; +} + +/** + * IntentLauncherAndroid + */ +export namespace IntentLauncherAndroid { + const ACTION_ACCESSIBILITY_SETTINGS: string; + const ACTION_APP_NOTIFICATION_REDACTION: string; + const ACTION_CONDITION_PROVIDER_SETTINGS: string; + const ACTION_NOTIFICATION_LISTENER_SETTINGS: string; + const ACTION_PRINT_SETTINGS: string; + const ACTION_ADD_ACCOUNT_SETTINGS: string; + const ACTION_AIRPLANE_MODE_SETTINGS: string; + const ACTION_APN_SETTINGS: string; + const ACTION_APPLICATION_DETAILS_SETTINGS: string; + const ACTION_APPLICATION_DEVELOPMENT_SETTINGS: string; + const ACTION_APPLICATION_SETTINGS: string; + const ACTION_APP_NOTIFICATION_SETTINGS: string; + const ACTION_APP_OPS_SETTINGS: string; + const ACTION_BATTERY_SAVER_SETTINGS: string; + const ACTION_BLUETOOTH_SETTINGS: string; + const ACTION_CAPTIONING_SETTINGS: string; + const ACTION_CAST_SETTINGS: string; + const ACTION_DATA_ROAMING_SETTINGS: string; + const ACTION_DATE_SETTINGS: string; + const ACTION_DEVICE_INFO_SETTINGS: string; + const ACTION_DEVICE_NAME: string; + const ACTION_DISPLAY_SETTINGS: string; + const ACTION_DREAM_SETTINGS: string; + const ACTION_HARD_KEYBOARD_SETTINGS: string; + const ACTION_HOME_SETTINGS: string; + const ACTION_IGNORE_BACKGROUND_DATA_RESTRICTIONS_SETTINGS: string; + const ACTION_IGNORE_BATTERY_OPTIMIZATION_SETTINGS: string; + const ACTION_INPUT_METHOD_SETTINGS: string; + const ACTION_INPUT_METHOD_SUBTYPE_SETTINGS: string; + const ACTION_INTERNAL_STORAGE_SETTINGS: string; + const ACTION_LOCALE_SETTINGS: string; + const ACTION_LOCATION_SOURCE_SETTINGS: string; + const ACTION_MANAGE_ALL_APPLICATIONS_SETTINGS: string; + const ACTION_MANAGE_APPLICATIONS_SETTINGS: string; + const ACTION_MANAGE_DEFAULT_APPS_SETTINGS: string; + const ACTION_MEMORY_CARD_SETTINGS: string; + const ACTION_MONITORING_CERT_INFO: string; + const ACTION_NETWORK_OPERATOR_SETTINGS: string; + const ACTION_NFCSHARING_SETTINGS: string; + const ACTION_NFC_PAYMENT_SETTINGS: string; + const ACTION_NFC_SETTINGS: string; + const ACTION_NIGHT_DISPLAY_SETTINGS: string; + const ACTION_NOTIFICATION_POLICY_ACCESS_SETTINGS: string; + const ACTION_NOTIFICATION_SETTINGS: string; + const ACTION_PAIRING_SETTINGS: string; + const ACTION_PRIVACY_SETTINGS: string; + const ACTION_QUICK_LAUNCH_SETTINGS: string; + const ACTION_REQUEST_IGNORE_BATTERY_OPTIMIZATIONS: string; + const ACTION_SECURITY_SETTINGS: string; + const ACTION_SETTINGS: string; + const ACTION_SHOW_ADMIN_SUPPORT_DETAILS: string; + const ACTION_SHOW_INPUT_METHOD_PICKER: string; + const ACTION_SHOW_REGULATORY_INFO: string; + const ACTION_SHOW_REMOTE_BUGREPORT_DIALOG: string; + const ACTION_SOUND_SETTINGS: string; + const ACTION_STORAGE_MANAGER_SETTINGS: string; + const ACTION_SYNC_SETTINGS: string; + const ACTION_SYSTEM_UPDATE_SETTINGS: string; + const ACTION_TETHER_PROVISIONING_UI: string; + const ACTION_TRUSTED_CREDENTIALS_USER: string; + const ACTION_USAGE_ACCESS_SETTINGS: string; + const ACTION_USER_DICTIONARY_INSERT: string; + const ACTION_USER_DICTIONARY_SETTINGS: string; + const ACTION_USER_SETTINGS: string; + const ACTION_VOICE_CONTROL_AIRPLANE_MODE: string; + const ACTION_VOICE_CONTROL_BATTERY_SAVER_MODE: string; + const ACTION_VOICE_CONTROL_DO_NOT_DISTURB_MODE: string; + const ACTION_VOICE_INPUT_SETTINGS: string; + const ACTION_VPN_SETTINGS: string; + const ACTION_VR_LISTENER_SETTINGS: string; + const ACTION_WEBVIEW_SETTINGS: string; + const ACTION_WIFI_IP_SETTINGS: string; + const ACTION_WIFI_SETTINGS: string; + const ACTION_WIRELESS_SETTINGS: string; + const ACTION_ZEN_MODE_AUTOMATION_SETTINGS: string; + const ACTION_ZEN_MODE_EVENT_RULE_SETTINGS: string; + const ACTION_ZEN_MODE_EXTERNAL_RULE_SETTINGS: string; + const ACTION_ZEN_MODE_PRIORITY_SETTINGS: string; + const ACTION_ZEN_MODE_SCHEDULE_RULE_SETTINGS: string; + const ACTION_ZEN_MODE_SETTINGS: string; + + function startActivityAsync(activity: string, data?: HashMap): Promise; +} + +/** + * KeepAwake + */ +export class KeepAwake extends Component { + static activate(): void; + static deactivate(): void; +} + +/** + * LinearGradient + */ +export interface LinearGradientProps { + colors: string[]; + start: [number, number]; + end: [number, number]; + locations: number[]; +} + +export class LinearGradient extends Component { } + +/** + * Location + */ +export namespace Location { + interface LocationOptions { + enableHighAccuracy?: boolean; + timeInterval?: number; + distanceInterval?: number; + } + + interface LocationProps { + latitude: number; + longitude: number; + } + + interface Coords extends LocationProps { + altitude: number; + accuracy: number; + } + + interface LocationData { + coords: { + heading: number; + speed: number + } & Coords; + timestamp: number; + } + + interface ProviderStatus { + locationServicesEnabled: boolean; + gpsAvailable?: boolean; + networkAvailable?: boolean; + passiveAvailable?: boolean; + } + + interface HeadingStatus { + magHeading: number; + trueHeading: number; + accuracy: number; + } + + interface GeocodeData { + city: string; + street: string; + region: string; + postalCode: string; + country: string; + name: string; + } + + type LocationCallback = (data: LocationData) => void; + + function getCurrentPositionAsync(options: LocationOptions): Promise; + function watchPositionAsync(options: LocationOptions, callback: LocationCallback): EventSubscription; + function getProviderStatusAsync(): Promise; + function getHeadingAsync(): Promise; + function watchHeadingAsync(callback: (status: HeadingStatus) => void): EventSubscription; + function geocodeAsync(address: string): Promise; + function reverseGeocodeAsync(location: LocationProps): Promise; + function setApiKey(key: string): void; +} + +/** + * Magnetometer + */ +export namespace Magnetometer { + interface MagnetometerObject { + x: Axis; + y: Axis; + z: Axis; + } + + function addListener(listener: (obj: MagnetometerObject) => any): EventSubscription; + function removeAllListeners(): void; + function setUpdateInterval(intervalMs: number): void; +} + +/** + * Notifications + */ +export namespace Notifications { + interface Notification { + origin: 'selected' | 'received'; + data: any; + remote: boolean; + isMultiple: boolean; + } + + interface LocalNotification { + title: string; + body?: string; + data?: any; + ios?: { + sound?: boolean + }; + android?: { + sound?: boolean; + icon?: string; + color?: string; + priority?: 'min' | 'low' | 'high' | 'max'; + sticky?: boolean; + vibrate?: boolean | number[]; + link?: string; + }; + } + + type LocalNotificationId = string | number; + + function addListener(listener: (notification: Notification) => any): EventSubscription; + function getExponentPushTokenAsync(): Promise; + function presentLocalNotificationAsync(localNotification: LocalNotification): Promise; + function scheduleLocalNotificationAsync( + localNotification: LocalNotification, + schedulingOptions: { time: Date | number, repeat?: 'minute' | 'hour' | 'day' | 'week' | 'month' | 'year' } + ): Promise; + function dismissNotificationAsync(localNotificationId: LocalNotificationId): Promise; + function dismissAllNotificationsAsync(): Promise; + function cancelScheduledNotificationAsync(localNotificationId: LocalNotificationId): Promise; + function cancelAllScheduledNotificationsAsync(): Promise; + function getBadgeNumberAsync(): Promise; + function setBadgeNumberAsync(number: number): Promise; +} + +/** + * Pedometer + */ +export namespace Pedometer { + function isAvailableAsync(): Promise; + function getStepCountAsync(start: Date, end: Date): Promise<{ steps: number; }>; + function watchStepCount(callback: (params: { steps: number; }) => void): EventSubscription; +} + +/** + * Permissions + */ +export namespace Permissions { + type PermissionType = 'remoteNotifications' | 'location' | + 'camera' | 'contacts' | 'audioRecording'; + type PermissionStatus = 'undetermined' | 'granted' | 'denied'; + type PermissionExpires = 'never'; + interface PermissionDetailsLocationIOS { + scope: 'whenInUse' | 'always'; + } + interface PermissionDetailsLocationAndroid { + scope: 'fine' | 'coarse' | 'none'; + } + interface PermissionResponse { + status: PermissionStatus; + expires: PermissionExpires; + ios?: PermissionDetailsLocationIOS; + android?: PermissionDetailsLocationAndroid; + } + + function getAsync(type: PermissionType): Promise; + function askAsync(type: PermissionType): Promise; + + const CAMERA: string; + const CAMERA_ROLL: string; + const AUDIO_RECORDING: string; + const LOCATION: string; + const REMOTE_NOTIFICATIONS: string; + const NOTIFICATIONS: string; + const CONTACTS: string; +} + +/** + * Register Root Component + */ +export function registerRootComponent(component: Component): Component; + +/** + * ScreenOrientation + */ +export namespace ScreenOrientation { + interface Orientation { + ALL: 'ALL'; + ALL_BUT_UPSIDE_DOWN: 'ALL_BUT_UPSIDE_DOWN'; + PORTRAIT: 'PORTRAIT'; + PORTRAIT_UP: 'PORTRAIT_UP'; + PORTRAIT_DOWN: 'PORTRAIT_DOWN'; + LANDSCAPE: 'LANDSCAPE'; + LANDSCAPE_LEFT: 'LANDSCAPE_LEFT'; + LANDSCAPE_RIGHT: 'LANDSCAPE_RIGHT'; + } + const Orientation: Orientation; + function allow(orientation: string): void; +} + +/** + * SecureStore + */ +export namespace SecureStore { + interface SecureStoreOptions { + keychainService?: string; + keychainAccessible?: number; + } + function setItemAsync(key: string, value: string, options?: SecureStoreOptions): Promise; + function getItemAsync(key: string, options?: SecureStoreOptions): Promise; + function deleteItemAsync(key: string, options?: SecureStoreOptions): Promise; +} + +/** + * Segment + */ +export namespace Segment { + function initialize(keys: { + androidWriteKey: string; + iosWriteKey: string; + }): void; + function identify(userId: string): void; + function identifyWithTraits(userId: string, traits: object): void; + function track(event: string): void; + function reset(): void; + function trackWithProperties(event: string, properties: object): void; + function screen(screenName: string): void; + function screenWithProperties(screenName: string, properties: object): void; + function flush(): void; +} + +/** + * Speech + */ +export namespace Speech { + interface SpeechOptions { + language?: string; + pitch?: number; + rate?: number; + onStart?: () => void; + onStopped?: () => void; + onDone?: () => void; + onError?: (error: string) => void; + } + + function speak(text: string, options?: SpeechOptions): void; + function stop(): void; + function isSpeakingAsync(): Promise; +} + +/** + * SQLite + */ +export namespace SQLite { + type Error = any; + + interface Database { + transaction( + callback: (transaction: Transaction) => any, + error?: (error: Error) => any, // TODO def of error + success?: () => any + ): void; + } + + interface Transaction { + executeSql( + sqlStatement: string, + arguments?: string[] | number[], + success?: (transaction: Transaction, resultSet: ResultSet) => any, + error?: (transaction: Transaction, error: Error) => any + ): void; + } + + interface ResultSet { + insertId: number; + rowAffected: number; + rows: { + length: number; + item: (index: number) => any; + _array: HashMap[]; + }; + } + + function openDatabase( + name: string | { + name: string, + version?: string, + description?: string, + size?: number, + callback?: () => any + }, + version?: string, + description?: string, + size?: number, + callback?: () => any + ): any; +} + +/** + * Svg + */ +export interface SvgCommonProps { + fill?: string; + fillOpacity?: number; + stroke?: string; + strokeWidth?: number; + strokeOpacity?: number; + strokeLinecap?: string; + strokeLineJoin?: string; + strokeDasharray?: any[]; + strokeDashoffset?: any; + x?: Axis; + y?: Axis; + rotate?: number; + scale?: number; + origin?: number | string; + originX?: number; + originY?: number; +} + +export class Svg extends Component<{ width: number, heigth: number }> { } +export class Rect extends Component { } + +export interface CircleProps extends SvgCommonProps { + cx: Axis; + cy: Axis; +} +export class Circle extends Component { } + +export interface EllipseProps extends CircleProps { + rx: Axis; + ry: Axis; +} +export class Ellipse extends Component { } + +export interface LineProps extends SvgCommonProps { + x1: Axis; + y1: Axis; + x2: Axis; + y2: Axis; +} +export class Line extends Component { } + +export interface PolyProps extends SvgCommonProps { + points: string; +} +export class Polygon extends Component { } +export class Polyline extends Component { } + +export interface PathLine extends SvgCommonProps { + d: string; +} +export class Path extends Component { } + +export interface TextProps extends SvgCommonProps { + textAnchor: string; +} +export class Text extends Component { } +export class G extends Component { } +export class Use extends Component<{ href: string, x: number, y: number }> { } +export class Symbol extends Component<{ viewbox: string, widt: number, height: number }> { } +export class Defs extends Component { } +export class RadialGradient extends Component { } + +/** + * Take Snapshot + */ +export function takeSnapshotAsync( + view?: (number | React.ReactElement), + options?: { + width?: number, + height?: number, + format?: 'png' | 'jpg' | 'jpeg' | 'webm', + quality?: number, + result?: 'file' | 'base64' | 'data-uri', + } +): Promise; + +/** + * Util + */ +export namespace Util { + function getCurrentDeviceCountryAsync(): Promise; + function getCurrentLocaleAsync(): Promise; + function getCurrentTimeZoneAsync(): Promise; + function reload(): void; + function addNewVersionListenerExperimental(listener: (event: { + manifest: object; + }) => void): { remove(): void; }; // Android only +} + +/** + * Web Browser + */ +export namespace WebBrowser { + function openBrowserAsync(url: string): Promise<{ type: 'cancelled' | 'dismissed' }>; + function openAuthSessionAsync(url: string, redirectUrl?: string): Promise<{ type: 'cancelled' | 'dismissed' }>; + function dismissBrowser(): Promise<{ type: 'dismissed' }>; +} diff --git a/types/expo/tsconfig.json b/types/expo/tsconfig.json new file mode 100644 index 0000000000..5d0f560837 --- /dev/null +++ b/types/expo/tsconfig.json @@ -0,0 +1,24 @@ +{ + "compilerOptions": { + "module": "commonjs", + "lib": [ + "es6" + ], + "jsx": "react", + "noImplicitAny": true, + "noImplicitThis": true, + "strictNullChecks": true, + "strictFunctionTypes": true, + "baseUrl": "../", + "typeRoots": [ + "../" + ], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true + }, + "files": [ + "index.d.ts", + "expo-tests.tsx" + ] +} diff --git a/types/expo/tslint.json b/types/expo/tslint.json new file mode 100644 index 0000000000..3db14f85ea --- /dev/null +++ b/types/expo/tslint.json @@ -0,0 +1 @@ +{ "extends": "dtslint/dt.json" } diff --git a/types/express-serve-static-core/index.d.ts b/types/express-serve-static-core/index.d.ts index 9119c8497f..2f8d862b14 100644 --- a/types/express-serve-static-core/index.d.ts +++ b/types/express-serve-static-core/index.d.ts @@ -820,7 +820,7 @@ export interface Application extends IRouter, Express.Application { * Express instance itself is a request handler, which could be invoked without * third argument. */ - (req: Request, res: Response): any; + (req: Request | http.IncomingMessage, res: Response | http.ServerResponse): any; /** * Initialize the server. diff --git a/types/gapi.auth2/index.d.ts b/types/gapi.auth2/index.d.ts index c5cfff0d9e..0acae5e2a7 100644 --- a/types/gapi.auth2/index.d.ts +++ b/types/gapi.auth2/index.d.ts @@ -27,7 +27,7 @@ declare namespace gapi.auth2 { * Signs in the user using the specified options. * If no option specified here, fallback to the options specified to gapi.auth2.init(). */ - signIn(options?: SigninOptions | SigninOptionsBuilder): any; + signIn(options?: SigninOptions | SigninOptionsBuilder): Promise; /** * Signs out all accounts from the application. diff --git a/types/geojson/geojson-tests.ts b/types/geojson/geojson-tests.ts index 4adb7f88f2..ce8c62418e 100644 --- a/types/geojson/geojson-tests.ts +++ b/types/geojson/geojson-tests.ts @@ -1,4 +1,10 @@ -let featureCollection: GeoJSON.FeatureCollection = { +import { + BBox, + Feature, FeatureCollection, GeometryCollection, LineString, + MultiLineString, MultiPoint, MultiPolygon, Point, Polygon, GeometryObject +} from "geojson"; + +let featureCollection: FeatureCollection = { type: "FeatureCollection", features: [ { @@ -34,7 +40,7 @@ let featureCollection: GeoJSON.FeatureCollection = { geometry: { type: "Polygon", coordinates: [ - [ [100.0, 0.0], [101.0, 0.0], [101.0, 1.0], [100.0, 1.0], [100.0, 0.0] ] + [[100.0, 0.0], [101.0, 0.0], [101.0, 1.0], [100.0, 1.0], [100.0, 0.0]] ] }, properties: { @@ -44,17 +50,10 @@ let featureCollection: GeoJSON.FeatureCollection = { } } } - ], - crs: { - type: "link", - properties: { - href: "http://example.com/crs/42", - type: "proj4" - } - } + ] }; -let featureWithPolygon: GeoJSON.Feature = { +const featureWithPolygon: Feature = { type: "Feature", bbox: [-180.0, -90.0, 180.0, 90.0], geometry: { @@ -66,57 +65,57 @@ let featureWithPolygon: GeoJSON.Feature = { properties: null }; -let point: GeoJSON.Point = { +const point: Point = { type: "Point", coordinates: [100.0, 0.0] }; // This type is commonly used in the turf package -let pointCoordinates: number[] = point.coordinates; +const pointCoordinates: number[] = point.coordinates; -let lineString: GeoJSON.LineString = { +const lineString: LineString = { type: "LineString", - coordinates: [ [100.0, 0.0], [101.0, 1.0] ] + coordinates: [[100.0, 0.0], [101.0, 1.0]] }; -let polygon: GeoJSON.Polygon = { +const polygon: Polygon = { type: "Polygon", coordinates: [ - [ [100.0, 0.0], [101.0, 0.0], [101.0, 1.0], [100.0, 1.0], [100.0, 0.0] ] + [[100.0, 0.0], [101.0, 0.0], [101.0, 1.0], [100.0, 1.0], [100.0, 0.0]] ] }; -let polygonWithHole: GeoJSON.Polygon = { +const polygonWithHole: Polygon = { type: "Polygon", coordinates: [ - [ [100.0, 0.0], [101.0, 0.0], [101.0, 1.0], [100.0, 1.0], [100.0, 0.0] ], - [ [100.2, 0.2], [100.8, 0.2], [100.8, 0.8], [100.2, 0.8], [100.2, 0.2] ] + [[100.0, 0.0], [101.0, 0.0], [101.0, 1.0], [100.0, 1.0], [100.0, 0.0]], + [[100.2, 0.2], [100.8, 0.2], [100.8, 0.8], [100.2, 0.8], [100.2, 0.2]] ] }; -let multiPoint: GeoJSON.MultiPoint = { +const multiPoint: MultiPoint = { type: "MultiPoint", - coordinates: [ [100.0, 0.0], [101.0, 1.0] ] + coordinates: [[100.0, 0.0], [101.0, 1.0]] }; -let multiLineString: GeoJSON.MultiLineString = { +const multiLineString: MultiLineString = { type: "MultiLineString", coordinates: [ - [ [100.0, 0.0], [101.0, 1.0] ], - [ [102.0, 2.0], [103.0, 3.0] ] + [[100.0, 0.0], [101.0, 1.0]], + [[102.0, 2.0], [103.0, 3.0]] ] }; -let multiPolygon: GeoJSON.MultiPolygon = { +const multiPolygon: MultiPolygon = { type: "MultiPolygon", coordinates: [ [[[102.0, 2.0], [103.0, 2.0], [103.0, 3.0], [102.0, 3.0], [102.0, 2.0]]], [[[100.0, 0.0], [101.0, 0.0], [101.0, 1.0], [100.0, 1.0], [100.0, 0.0]], - [[100.2, 0.2], [100.8, 0.2], [100.8, 0.8], [100.2, 0.8], [100.2, 0.2]]] + [[100.2, 0.2], [100.8, 0.2], [100.8, 0.8], [100.2, 0.8], [100.2, 0.2]]] ] }; -let geometryCollection: GeoJSON.GeometryCollection = { +const geometryCollection: GeometryCollection = { type: "GeometryCollection", geometries: [ { @@ -125,16 +124,17 @@ let geometryCollection: GeoJSON.GeometryCollection = { }, { type: "LineString", - coordinates: [ [101.0, 0.0], [102.0, 1.0] ] + coordinates: [[101.0, 0.0], [102.0, 1.0]] } ] }; -let feature: GeoJSON.Feature = { +let feature: Feature = { type: "Feature", geometry: lineString, properties: null }; + feature = { type: "Feature", geometry: polygon, @@ -172,44 +172,37 @@ featureCollection = { { type: "Feature", geometry: lineString, - properties: {test: "OK"} + properties: { test: "OK" } }, { type: "Feature", geometry: polygon, - properties: {test: "OK"} + properties: { test: "OK" } }, { type: "Feature", geometry: polygonWithHole, - properties: {test: "OK"} + properties: { test: "OK" } }, { type: "Feature", geometry: multiPoint, - properties: {test: "OK"} + properties: { test: "OK" } }, { type: "Feature", geometry: multiLineString, - properties: {test: "OK"} + properties: { test: "OK" } }, { type: "Feature", geometry: multiPolygon, - properties: {test: "OK"} + properties: { test: "OK" } }, { type: "Feature", geometry: geometryCollection, - properties: {test: "OK"} + properties: { test: "OK" } } - ], - crs: { - type: "link", - properties: { - href: "http://example.com/crs/42", - type: "proj4" - } - } + ] }; // Allow access to custom properties -const pt: GeoJSON.Feature = { +const pt: Feature = { type: "Feature", properties: { foo: "bar", @@ -221,9 +214,14 @@ const pt: GeoJSON.Feature = { coordinates: [0, 0] } }; -pt.properties.foo; -pt.properties.hello; -pt.properties[1]; + +if (pt.properties) { + if (pt.properties.foo == null || pt.properties.hello == null || pt.properties[1] == null) { + throw TypeError("Properties should not be null or undefined."); + } +} else { + throw TypeError("Feature should have a 'properties' property."); +} // Optional generic for properties @@ -232,19 +230,21 @@ interface TestProperty { hello: string; } -const typedPropertiesFeature: GeoJSON.Feature = { +const testProps: TestProperty = { + foo: "bar", + hello: "world" +}; + +const typedPropertiesFeature: Feature = { type: "Feature", - properties: { - foo: "bar", - hello: "world", - }, + properties: testProps, geometry: { type: "Point", coordinates: [0, 0] } }; -const typedPropertiesFeatureCollection: GeoJSON.FeatureCollection = { +const typedPropertiesFeatureCollection: FeatureCollection = { type: "FeatureCollection", features: [typedPropertiesFeature] }; diff --git a/types/geojson/index.d.ts b/types/geojson/index.d.ts index b916179fac..e6783255eb 100644 --- a/types/geojson/index.d.ts +++ b/types/geojson/index.d.ts @@ -1,123 +1,165 @@ -// Type definitions for GeoJSON Format Specification Revision 1.0 -// Project: http://geojson.org/ +// Type definitions for geojson 7946.0 +// Project: https://geojson.org/ // Definitions by: Jacob Bruun // Arne Schubert +// Jeff Jacobson // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped // TypeScript Version: 2.3 +// Note: as of the RFC 7946 version of GeoJSON, Coordinate Reference Systems +// are no longer supported. (See https://tools.ietf.org/html/rfc7946#appendix-B)} + export as namespace GeoJSON; -/*** - * http://geojson.org/geojson-spec.html#geojson-objects +/** + * The valid values for the "type" property of GeoJSON geometry objects. + * https://tools.ietf.org/html/rfc7946#section-1.4 + */ +export type GeoJsonGeometryTypes = "Point" | "LineString" | "MultiPoint" | "Polygon" | "MultiLineString" | + "MultiPolygon" | "GeometryCollection"; + +/** + * The value values for the "type" property of GeoJSON Objects. + * https://tools.ietf.org/html/rfc7946#section-1.4 + */ +export type GeoJsonTypes = "FeatureCollection" | "Feature" | GeoJsonGeometryTypes; + +/** + * Bounding box + * https://tools.ietf.org/html/rfc7946#section-5 + */ +export type BBox = [number, number, number, number] | [number, number, number, number, number, number]; + +/** + * A Position is an array of coordinates. + * https://tools.ietf.org/html/rfc7946#section-3.1.1 + * Array should contain between two and three elements. + * The previous GeoJSON specification allowed more elements (e.g., which could be used to represent M values), + * but the current specification only allows X, Y, and (optionally) Z to be defined. + */ +export type Position = number[]; // [number, number] | [number, number, number]; + +/** + * The base GeoJSON object. + * https://tools.ietf.org/html/rfc7946#section-3 + * The GeoJSON specification also allows foreign members + * (https://tools.ietf.org/html/rfc7946#section-6.1) + * Developers should use "&" type in TypeScript or extend the interface + * to add these foreign members. */ export interface GeoJsonObject { - type: string; - bbox?: number[]; - crs?: CoordinateReferenceSystem; + // Don't include foreign members directly into this type def. + // in order to preserve type safety. + // [key: string]: any; + /** + * Specifies the type of GeoJSON object. + */ + type: GeoJsonTypes; + /** + * Bounding box of the coordinate range of the object's Geometries, Features, or Feature Collections. + * https://tools.ietf.org/html/rfc7946#section-5 + */ + bbox?: BBox; } -/*** - * http://geojson.org/geojson-spec.html#positions - */ -export type Position = number[]; - -/*** - * http://geojson.org/geojson-spec.html#geometry-objects - */ -export interface DirectGeometryObject extends GeoJsonObject { - coordinates: Position[][][] | Position[][] | Position[] | Position; -} /** - * GeometryObject supports geometry collection as well + * A geometry object. + * https://tools.ietf.org/html/rfc7946#section-3 */ -export type GeometryObject = DirectGeometryObject | GeometryCollection; +export interface GeometryObject extends GeoJsonObject { + type: GeoJsonGeometryTypes; +} -/*** - * http://geojson.org/geojson-spec.html#point +/** + * Point geometry object. + * https://tools.ietf.org/html/rfc7946#section-3.1.2 */ -export interface Point extends DirectGeometryObject { +export interface Point extends GeometryObject { type: "Point"; coordinates: Position; } -/*** - * http://geojson.org/geojson-spec.html#multipoint +/** + * MultiPoint geometry object. + * https://tools.ietf.org/html/rfc7946#section-3.1.3 */ -export interface MultiPoint extends DirectGeometryObject { +export interface MultiPoint extends GeometryObject { type: "MultiPoint"; coordinates: Position[]; } -/*** - * http://geojson.org/geojson-spec.html#linestring +/** + * LineString geometry object. + * https://tools.ietf.org/html/rfc7946#section-3.1.4 */ -export interface LineString extends DirectGeometryObject { +export interface LineString extends GeometryObject { type: "LineString"; coordinates: Position[]; } -/*** - * http://geojson.org/geojson-spec.html#multilinestring +/** + * MultiLineString geometry object. + * https://tools.ietf.org/html/rfc7946#section-3.1.5 */ -export interface MultiLineString extends DirectGeometryObject { +export interface MultiLineString extends GeometryObject { type: "MultiLineString"; coordinates: Position[][]; } -/*** - * http://geojson.org/geojson-spec.html#polygon +/** + * Polygon geometry object. + * https://tools.ietf.org/html/rfc7946#section-3.1.6 */ -export interface Polygon extends DirectGeometryObject { +export interface Polygon extends GeometryObject { type: "Polygon"; coordinates: Position[][]; } -/*** - * http://geojson.org/geojson-spec.html#multipolygon +/** + * MultiPolygon geometry object. + * https://tools.ietf.org/html/rfc7946#section-3.1.7 */ -export interface MultiPolygon extends DirectGeometryObject { +export interface MultiPolygon extends GeometryObject { type: "MultiPolygon"; coordinates: Position[][][]; } -/*** - * http://geojson.org/geojson-spec.html#geometry-collection +/** + * Geometry Collection + * https://tools.ietf.org/html/rfc7946#section-3.1.8 */ -export interface GeometryCollection extends GeoJsonObject { +export interface GeometryCollection extends GeometryObject { type: "GeometryCollection"; - geometries: GeometryObject[]; + geometries: Array; } -/*** +export type GeoJsonProperties = { [name: string]: any; } | null; + +/** + * A feature object which contains a geometry and associated properties. * https://tools.ietf.org/html/rfc7946#section-3.2 */ -export interface Feature extends GeoJsonObject { +export interface Feature extends GeoJsonObject { type: "Feature"; - geometry: G; - properties: P; + /** + * The feature's geometry + */ + geometry: G | null; + /** + * A value that uniquely identifies this feature in a + * https://tools.ietf.org/html/rfc7946#section-3.2. + */ id?: string | number; + /** + * Properties associated with this feature. + */ + properties: P | null; } -/*** - * http://geojson.org/geojson-spec.html#feature-collection-objects +/** + * A collection of feature objects. + * https://tools.ietf.org/html/rfc7946#section-3.3 */ -export interface FeatureCollection extends GeoJsonObject { - type: "FeatureCollection"; +export interface FeatureCollection extends GeoJsonObject { features: Array>; } - -/*** - * http://geojson.org/geojson-spec.html#coordinate-reference-system-objects - */ -export interface CoordinateReferenceSystem { - type: string; - properties: any; -} - -export interface NamedCoordinateReferenceSystem extends CoordinateReferenceSystem { - properties: { name: string }; -} - -export interface LinkedCoordinateReferenceSystem extends CoordinateReferenceSystem { - properties: { href: string; type: string }; -} diff --git a/types/gzip-size/gzip-size-tests.ts b/types/gzip-size/gzip-size-tests.ts index f07d99bd50..70ea15b5e6 100644 --- a/types/gzip-size/gzip-size-tests.ts +++ b/types/gzip-size/gzip-size-tests.ts @@ -1,7 +1,16 @@ +import fs = require('fs'); import gzipSize = require('gzip-size'); const string = 'Lorem ipsum dolor sit amet.'; console.log(string.length); +gzipSize(string).then(size => console.log(size)); + console.log(gzipSize.sync(string)); + +const stream = fs.createReadStream("index.d.ts"); +const gstream = stream.pipe(gzipSize.stream()).on("gzip-size", size => console.log(size)); +console.log(gstream.gzipSize); // Could be a number or undefined. Recommended to use "gzip-size" event instead + +gzipSize.file("index.d.ts").then(size => console.log(size)); diff --git a/types/gzip-size/index.d.ts b/types/gzip-size/index.d.ts index cab8ec225b..66251e0da8 100644 --- a/types/gzip-size/index.d.ts +++ b/types/gzip-size/index.d.ts @@ -1,7 +1,8 @@ -// Type definitions for gzip-size 4.0 +// Type definitions for gzip-size 4.1 // Project: https://github.com/sindresorhus/gzip-size // Definitions by: York Yao // Jimi van der Woning +// Andre Wiggins // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped /// @@ -9,11 +10,45 @@ import * as stream from 'stream'; import * as zlib from 'zlib'; +interface GzipSizeStream extends stream.PassThrough { + on(event: string, listener: (...args: any[]) => void): this; + on(event: "gzip-size", listener: (size: number) => void): this; + + /** + * Contains the gzip size of the stream after it is finished. + * Since this happens asynchronously, it is recommended you use + * the `.on("gzip-size", size => console.log(size))` method instead + */ + gzipSize?: number; +} + +/** + * Returns a Promise for the size. + * @param input A string or Buffer to determine the gzip size of + * @param options Any zlib option + */ declare function gzipSize(input: string | Buffer, options?: zlib.ZlibOptions): Promise; declare namespace gzipSize { + /** + * Returns the size synchronously + * @param input A string or Buffer to determine the gzip size of + * @param options Any zlib option + */ function sync(input: string | Buffer, options?: zlib.ZlibOptions): number; - function stream(options?: zlib.ZlibOptions): stream.PassThrough; + + /** + * Returns a stream.PassThrough. The stream emits a gzip-size event and has a gzipSize property. + * @param options Any zlib option + */ + function stream(options?: zlib.ZlibOptions): GzipSizeStream; + + /** + * Returns a Promise for the size of the file. + * @param path The path to the file + * @param options Any zlib option + */ + function file(path: string, options?: zlib.ZlibOptions): Promise; } export = gzipSize; diff --git a/types/highlight.js/index.d.ts b/types/highlight.js/index.d.ts index d691811b47..f96be1c06f 100644 --- a/types/highlight.js/index.d.ts +++ b/types/highlight.js/index.d.ts @@ -1,10 +1,14 @@ // Type definitions for highlight.js v9.12 // Project: https://github.com/isagalaev/highlight.js -// Definitions by: Niklas Mollenhauer , Jeremy Hull +// Definitions by: Niklas Mollenhauer +// Jeremy Hull +// Josh Goldberg // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped declare namespace hljs { + interface Node { } + export function highlight( name: string, value: string, diff --git a/types/highlight.js/tsconfig.json b/types/highlight.js/tsconfig.json index 5f5d2ae011..e3627e99ca 100644 --- a/types/highlight.js/tsconfig.json +++ b/types/highlight.js/tsconfig.json @@ -2,8 +2,7 @@ "compilerOptions": { "module": "commonjs", "lib": [ - "es6", - "dom" + "es6" ], "noImplicitAny": true, "noImplicitThis": true, diff --git a/types/http-aws-es/index.d.ts b/types/http-aws-es/index.d.ts index c14547a58f..91e12604f8 100644 --- a/types/http-aws-es/index.d.ts +++ b/types/http-aws-es/index.d.ts @@ -2,6 +2,7 @@ // Project: https://github.com/TheDeveloper/http-aws-es#readme // Definitions by: Marco Gonzalez // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.2 /// diff --git a/types/http-proxy-agent/http-proxy-agent-tests.ts b/types/http-proxy-agent/http-proxy-agent-tests.ts new file mode 100644 index 0000000000..f730cd1bde --- /dev/null +++ b/types/http-proxy-agent/http-proxy-agent-tests.ts @@ -0,0 +1,12 @@ +import Agent = require('http-proxy-agent'); + +// $ExpectType HttpProxyAgent +new Agent('url'); +new Agent({}); +new Agent({ host: 'url' }); + +// $ExpectError +new Agent(); + +// $ExpectError +new Agent({ a: 1 }); diff --git a/types/http-proxy-agent/index.d.ts b/types/http-proxy-agent/index.d.ts new file mode 100644 index 0000000000..015508b5d1 --- /dev/null +++ b/types/http-proxy-agent/index.d.ts @@ -0,0 +1,15 @@ +// Type definitions for http-proxy-agent 2.0 +// Project: https://github.com/TooTallNate/node-http-proxy-agent +// Definitions by: mrmlnc +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +/// + +import { Agent } from 'http'; +import { Url } from 'url'; + +declare class HttpProxyAgent extends Agent { + constructor(options: string | Url); +} + +export = HttpProxyAgent; diff --git a/types/http-proxy-agent/tsconfig.json b/types/http-proxy-agent/tsconfig.json new file mode 100644 index 0000000000..626d4eaa4c --- /dev/null +++ b/types/http-proxy-agent/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", + "http-proxy-agent-tests.ts" + ] +} diff --git a/types/http-proxy-agent/tslint.json b/types/http-proxy-agent/tslint.json new file mode 100644 index 0000000000..3db14f85ea --- /dev/null +++ b/types/http-proxy-agent/tslint.json @@ -0,0 +1 @@ +{ "extends": "dtslint/dt.json" } diff --git a/types/i18n-js/i18n-js-tests.ts b/types/i18n-js/i18n-js-tests.ts new file mode 100644 index 0000000000..4f19dc4c02 --- /dev/null +++ b/types/i18n-js/i18n-js-tests.ts @@ -0,0 +1,81 @@ +/** + * Test suite created by Yuya Tanaka + * Created by using code examples from https://github.com/fnando/i18n-js + */ + +import I18n = require("i18n-js"); + +I18n.defaultLocale = "pt-BR"; +I18n.locale = "pt-BR"; +I18n.currentLocale() === "pt-BR"; + +I18n.t("some.scoped.translation"); +I18n.t("some.scoped.translation", { locale: "fr" }); +I18n.t("hello", { name: "John Doe" }); +I18n.t("some.missing.scope", { defaultValue: "A default message" }); +I18n.t("noun", { defaultValue: "I'm a {{noun}}", noun: "Mac" }); +I18n.t("some.missing.scope", { defaults: [{ scope: "some.existing.scope" }] }); +I18n.t("some.missing.scope", { defaults: [{ message: "Some message" }] }); + +I18n.fallbacks = true; +I18n.locales.no = ["nb", "en"]; +I18n.locales.no = "nb"; +I18n.locales.no = locale => ["nb"]; + +I18n.missingBehaviour = "guess"; +I18n.missingTranslationPrefix = "EE: "; +I18n.missingTranslation = (scope, options) => "foobar"; +I18n.missingTranslation = (scope, options) => null; +I18n.missingTranslation = (scope, options) => undefined; + +I18n.t("inbox.counting", { count: 10 }); +I18n.pluralization["ru"] = count => { + const key = count % 10 === 1 && count % 100 !== 11 ? "one" + : [2, 3, 4].indexOf(count % 10) >= 0 && [12, 13, 14].indexOf(count % 100) < 0 ? "few" + : count % 10 === 0 || [5, 6, 7, 8, 9].indexOf(count % 10) >= 0 || [11, 12, 13, 14].indexOf(count % 100) >= 0 ? "many" + : "other"; + return [key]; +}; + +const options = { scope: "activerecord.attributes.user" }; +I18n.t("name", options); +I18n.t(["greetings", "hello"]); + +I18n.l("currency", 1990.99); +I18n.l("number", 1990.99); +I18n.l("percentage", 123.45); + +I18n.toNumber(1000); +I18n.toCurrency(1000); +I18n.toPercentage(100); + +I18n.toNumber(1000, { precision: 0 }); +I18n.toNumber(1000, { delimiter: ".", separator: "," }); +I18n.toNumber(1000, { delimiter: ".", precision: 0 }); + +I18n.toCurrency(1000, { precision: 0 }); + +I18n.toHumanSize(1234); + +I18n.l("date.formats.short", "2009-09-18"); +I18n.l("time.formats.short", "2009-09-18 23:12:43"); +I18n.l("time.formats.short", "2009-11-09T18:10:34"); +I18n.l("time.formats.short", "2009-11-09T18:10:34Z"); +I18n.l("date.formats.short", 1251862029000); +I18n.l("date.formats.short", "09/18/2009"); +I18n.l("date.formats.short", (new Date())); + +I18n.l("date.formats.ordinal_day", "2009-09-18", { day: "18th" }); + +I18n.strftime(new Date(), "%d/%m/%Y"); + +const point_in_number = 1000; +I18n.t("point", { count: point_in_number, formatted_number: I18n.toNumber(point_in_number) }); + +I18n.translations = {}; +I18n.translations["en"] = { + message: "Some special message for you" +}; +I18n.translations["pt-BR"] = { + message: "Uma mensagem especial para você" +}; diff --git a/types/i18n-js/index.d.ts b/types/i18n-js/index.d.ts new file mode 100644 index 0000000000..4800125087 --- /dev/null +++ b/types/i18n-js/index.d.ts @@ -0,0 +1,79 @@ +// Type definitions for i18n-js 3.0 +// Project: https://github.com/fnando/i18n-js +// Definitions by: Yuya Tanaka +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.2 + +// tslint:disable-next-line:export-just-namespace +export = I18n; +export as namespace I18n; + +declare namespace I18n { + type Scope = string | string[]; + + let defaultLocale: string; + let locale: string; + let defaultSeparator: string; + let placeholder: RegExp; + let fallbacks: boolean; + let missingBehaviour: "message" | "guess"; + let missingTranslationPrefix: string; + + // tslint:disable-next-line prefer-declare-function + let missingTranslation: (scope: string, options?: TranslateOptions) => string | null | undefined; + // tslint:disable-next-line prefer-declare-function + let missingPlaceholder: (placeholder: string, message: string, options?: InterpolateOptions) => string | null | undefined; + // tslint:disable-next-line prefer-declare-function + let nullPlaceholder: (placeholder: string, message: string, options?: InterpolateOptions) => string | null | undefined; + + let translations: { [locale: string]: object }; + let locales: { [key: string]: string | string[] | ((locale: string) => string | string[]) }; + let pluralization: { [locale: string]: (count: number) => string[] }; + + function reset(): void; + + function currentLocale(): string; + + interface InterpolateOptions { + [key: string]: any; // interpolation + } + + interface TranslateOptions extends InterpolateOptions { + scope?: Scope; + message?: string; + defaults?: Array<{ message: string } | { scope: Scope }>; + defaultValue?: string; + } + function translate(scope: Scope, options?: TranslateOptions): string; + function t(scope: Scope, options?: TranslateOptions): string; + + function localize(scope: "currency" | "number" | "percentage", value: number, options?: InterpolateOptions): string; + function localize(scope: Scope, value: string | number | Date, options?: InterpolateOptions): string; + function l(scope: "currency" | "number" | "percentage", value: number, options?: InterpolateOptions): string; + function l(scope: Scope, value: string | number | Date, options?: InterpolateOptions): string; + + interface ToNumberOptions { + precision?: number; + separator?: string; + delimiter?: string; + strip_insignificant_zeros?: boolean; + } + function toNumber(num: number, options?: ToNumberOptions): string; + + type ToPercentageOptions = ToNumberOptions; + function toPercentage(num: number, options?: ToPercentageOptions): string; + + interface ToCurrencyOptions extends ToNumberOptions { + format?: string; + unit?: string; + sign_first?: boolean; + } + function toCurrency(num: number, options?: ToCurrencyOptions): string; + + interface ToHumanSizeOptions extends ToNumberOptions { + format?: string; + } + function toHumanSize(num: number, options?: ToHumanSizeOptions): string; + + function strftime(date: Date, format: string): string; +} diff --git a/types/i18n-js/tsconfig.json b/types/i18n-js/tsconfig.json new file mode 100644 index 0000000000..4a9e4d110b --- /dev/null +++ b/types/i18n-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", + "i18n-js-tests.ts" + ] +} diff --git a/types/i18n-js/tslint.json b/types/i18n-js/tslint.json new file mode 100644 index 0000000000..299e93b32f --- /dev/null +++ b/types/i18n-js/tslint.json @@ -0,0 +1,7 @@ +{ + "extends": "dtslint/dt.json", + "rules": { + "indent": [true, "spaces", 4], + "quotemark": [true, "double", "avoid-escape"] + } +} diff --git a/types/iltorb/iltorb-tests.ts b/types/iltorb/iltorb-tests.ts new file mode 100644 index 0000000000..5c30fcd3b5 --- /dev/null +++ b/types/iltorb/iltorb-tests.ts @@ -0,0 +1,36 @@ +import { createReadStream, createWriteStream } from 'fs'; +import * as br from 'iltorb'; + +const opts: br.BrotliEncodeParams = { + disable_literal_context_modeling: false, + lgblock: 0, + lgwin: 22, + mode: 0, + quality: 11, + size_hint: 0 +}; + +const onCompress = (err1: Error | null | undefined, compressed: Buffer) => { + br.decompress(compressed, (err2: Error | null | undefined, decompressed: Buffer) => { + console.log(decompressed.toString()); + }); +}; + +br.compress(Buffer.from('foo', 'utf8'), onCompress); + +br.compress(Buffer.from('foo', 'utf8'), opts, onCompress); + +createReadStream(__filename) + .pipe(br.compressStream()) + .pipe(createWriteStream('foo.ts')); + +createReadStream(__dirname) + .pipe(br.compressStream(opts)) + .pipe(createWriteStream('bar.ts')); + +createReadStream('bar.ts') + .pipe(br.decompressStream()) + .pipe(createWriteStream('qux.ts')); + +br.decompressSync(br.compressSync(Buffer.from('foo', 'utf8'))); +br.decompressSync(br.compressSync(Buffer.from('foo', 'utf8'), opts)); diff --git a/types/iltorb/index.d.ts b/types/iltorb/index.d.ts new file mode 100644 index 0000000000..bd6cd88fb7 --- /dev/null +++ b/types/iltorb/index.d.ts @@ -0,0 +1,30 @@ +// Type definitions for iltorb 2.0 +// Project: https://github.com/MayhemYDG/iltorb +// Definitions by: Arturas Molcanovas +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +/// + +import { Transform } from 'stream'; + +export interface BrotliEncodeParams { + disable_literal_context_modeling?: boolean; + lgblock?: number; + lgwin?: number; + mode?: number; + quality?: number; + size_hint?: number; +} + +export type IltorbCallback = (err: Error | null | undefined, output: Buffer) => void; + +export function compress(buffer: Buffer, options: BrotliEncodeParams, callback: IltorbCallback): void; +export function compress(buffer: Buffer, callback: IltorbCallback): void; + +export function decompress(buffer: Buffer, callback: IltorbCallback): void; + +export function compressSync(buffer: Buffer, options?: BrotliEncodeParams): Buffer; +export function decompressSync(buffer: Buffer): Buffer; + +export function compressStream(options?: BrotliEncodeParams): Transform; +export function decompressStream(): Transform; diff --git a/types/iltorb/tsconfig.json b/types/iltorb/tsconfig.json new file mode 100644 index 0000000000..c12ff988ba --- /dev/null +++ b/types/iltorb/tsconfig.json @@ -0,0 +1,23 @@ +{ + "compilerOptions": { + "module": "commonjs", + "lib": [ + "es5" + ], + "noImplicitAny": true, + "noImplicitThis": true, + "strictNullChecks": true, + "strictFunctionTypes": true, + "baseUrl": "../", + "typeRoots": [ + "../" + ], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true + }, + "files": [ + "index.d.ts", + "iltorb-tests.ts" + ] +} diff --git a/types/iltorb/tslint.json b/types/iltorb/tslint.json new file mode 100644 index 0000000000..f93cf8562a --- /dev/null +++ b/types/iltorb/tslint.json @@ -0,0 +1,3 @@ +{ + "extends": "dtslint/dt.json" +} diff --git a/types/jest/index.d.ts b/types/jest/index.d.ts index 1b8d137094..5c2152694f 100644 --- a/types/jest/index.d.ts +++ b/types/jest/index.d.ts @@ -145,10 +145,16 @@ declare namespace jest { */ function runOnlyPendingTimers(): typeof jest; /** - * Executes only the macro task queue (i.e. all tasks queued by setTimeout() - * or setInterval() and setImmediate()). + * (renamed to `advanceTimersByTime` in Jest 21.3.0+) Executes only the macro + * task queue (i.e. all tasks queued by setTimeout() or setInterval() and setImmediate()). */ function runTimersToTime(msToRun: number): typeof jest; + /** + * Advances all timers by msToRun milliseconds. All pending "macro-tasks" that have been + * queued via setTimeout() or setInterval(), and would be executed within this timeframe + * will be executed. + */ + function advanceTimersByTime(msToRun: number): typeof jest; /** * Explicitly supplies the mock object that the module system should return * for the specified module. @@ -555,7 +561,7 @@ declare namespace jasmine { function anything(): Any; function arrayContaining(sample: any[]): ArrayContaining; function objectContaining(sample: any): ObjectContaining; - function createSpy(name: string, originalFn?: (...args: any[]) => any): Spy; + function createSpy(name?: string, originalFn?: (...args: any[]) => any): Spy; function createSpyObj(baseName: string, methodNames: any[]): any; function createSpyObj(baseName: string, methodNames: any[]): T; function pp(value: any): string; @@ -867,6 +873,7 @@ declare namespace jest { runAllTicks(): void; runAllTimers(): void; runTimersToTime(msToRun: number): void; + advanceTimersByTime(msToRun: number): void; runOnlyPendingTimers(): void; runWithRealTimers(callback: any): void; useFakeTimers(): void; diff --git a/types/js-yaml/index.d.ts b/types/js-yaml/index.d.ts index 543391b23b..2fa264cbd9 100644 --- a/types/js-yaml/index.d.ts +++ b/types/js-yaml/index.d.ts @@ -1,96 +1,103 @@ -// Type definitions for js-yaml 3.10.0 +// Type definitions for js-yaml 3.10 // Project: https://github.com/nodeca/js-yaml // Definitions by: Bart van der Schoor , Sebastian Clausen // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.2 -declare namespace jsyaml { - export function safeLoad(str: string, opts?: LoadOptions): any; - export function load(str: string, opts?: LoadOptions): any; +export function safeLoad(str: string, opts?: LoadOptions): any; +export function load(str: string, opts?: LoadOptions): any; - export interface Type extends TypeConstructorOptions { } - export class Type { - constructor(tag: string, opts?: TypeConstructorOptions); - tag: string; - } - export class Schema { - constructor(definition: SchemaDefinition); - public static create(types: Type[] | Type): Schema; - public static create(schemas: Schema[] | Schema, types: Type[] | Type): Schema; - } - - export function safeLoadAll(str: string, iterator?: (doc: any) => void, opts?: LoadOptions): any; - export function loadAll(str: string, iterator?: (doc: any) => void, opts?: LoadOptions): any; - - export function safeDump(obj: any, opts?: DumpOptions): string; - export function dump(obj: any, opts?: DumpOptions): string; - - export interface LoadOptions { - // string to be used as a file path in error/warning messages. - filename?: string; - // makes the loader to throw errors instead of warnings. - strict?: boolean; - // specifies a schema to use. - schema?: any; - } - - export interface DumpOptions { - // indentation width to use (in spaces). - indent?: number; - // do not throw on invalid types (like function in the safe schema) and skip pairs and single values with such types. - skipInvalid?: boolean; - // specifies level of nesting, when to switch from block to flow style for collections. -1 means block style everwhere - flowLevel?: number; - // Each tag may have own set of styles. - "tag" => "style" map. - styles?: Object; - // specifies a schema to use. - schema?: any; - // if true, sort keys when dumping YAML. If a function, use the function to sort the keys. (default: false) - sortKeys?: boolean | ((a: any, b: any) => number); - // set max line width. (default: 80) - lineWidth?: number; - // if true, don't convert duplicate objects into references (default: false) - noRefs?: boolean; - // if true don't try to be compatible with older yaml versions. Currently: don't quote "yes", "no" and so on, as required for YAML 1.1 (default: false) - noCompatMode?: boolean; - // if true flow sequences will be condensed, omitting the space between `key: value` or `a, b`. Eg. `'[a,b]'` or `{a:{b:c}}`. Can be useful when using yaml for pretty URL query params as spaces are %-encoded. (default: false) - condenseFlow?: boolean; - } - - export interface TypeConstructorOptions { - kind?: string; - resolve?: Function; - construct?: Function; - instanceOf?: Object; - predicate?: string; - represent?: Function; - defaultStyle?: string; - styleAliases?: Object; - } - - export interface SchemaDefinition { - implicit?: any[]; - explicit?: any[]; - include?: any[]; - } - - // only strings, arrays and plain objects: http://www.yaml.org/spec/1.2/spec.html#id2802346 - export var FAILSAFE_SCHEMA: any; - // only strings, arrays and plain objects: http://www.yaml.org/spec/1.2/spec.html#id2802346 - export var JSON_SCHEMA: any; - // same as JSON_SCHEMA: http://www.yaml.org/spec/1.2/spec.html#id2804923 - export var CORE_SCHEMA: any; - // all supported YAML types, without unsafe ones (!!js/undefined, !!js/regexp and !!js/function): http://yaml.org/type/ - export var DEFAULT_SAFE_SCHEMA: any; - // all supported YAML types. - export var DEFAULT_FULL_SCHEMA: any; - export var MINIMAL_SCHEMA: any; - export var SAFE_SCHEMA: any; - - export class YAMLException extends Error { - constructor(reason?: any, mark?: any); - toString(compact?: boolean): string; - } +export class Type { + constructor(tag: string, opts?: TypeConstructorOptions); + kind: 'sequence' | 'scalar' | 'mapping' | null; + resolve(data: any): boolean; + construct(data: any): any; + instanceOf: object | null; + predicate: string | null; + represent: ((data: object) => any) | { [x: string]: (data: object) => any; } | null; + defaultStyle: string | null; + styleAliases: { [x: string]: any; }; } -export = jsyaml; -export as namespace jsyaml; +/* tslint:disable-next-line:no-unnecessary-class */ +export class Schema implements SchemaDefinition { + constructor(definition: SchemaDefinition); + static create(types: Type[] | Type): Schema; + static create(schemas: Schema[] | Schema, types: Type[] | Type): Schema; +} + +export function safeLoadAll(str: string, iterator?: (doc: any) => void, opts?: LoadOptions): any; +export function loadAll(str: string, iterator?: (doc: any) => void, opts?: LoadOptions): any; + +export function safeDump(obj: any, opts?: DumpOptions): string; +export function dump(obj: any, opts?: DumpOptions): string; + +export interface LoadOptions { + // string to be used as a file path in error/warning messages. + filename?: string; + // makes the loader to throw errors instead of warnings. + strict?: boolean; + // specifies a schema to use. + schema?: any; + // compatibility with JSON.parse behaviour. + json?: boolean; +} + +export interface DumpOptions { + // indentation width to use (in spaces). + indent?: number; + // do not throw on invalid types (like function in the safe schema) and skip pairs and single values with such types. + skipInvalid?: boolean; + // specifies level of nesting, when to switch from block to flow style for collections. -1 means block style everwhere + flowLevel?: number; + // Each tag may have own set of styles. - "tag" => "style" map. + styles?: { [x: string]: any; }; + // specifies a schema to use. + schema?: any; + // if true, sort keys when dumping YAML. If a function, use the function to sort the keys. (default: false) + sortKeys?: boolean | ((a: any, b: any) => number); + // set max line width. (default: 80) + lineWidth?: number; + // if true, don't convert duplicate objects into references (default: false) + noRefs?: boolean; + // if true don't try to be compatible with older yaml versions. Currently: don't quote "yes", "no" and so on, as required for YAML 1.1 (default: false) + noCompatMode?: boolean; + // if true flow sequences will be condensed, omitting the space between `key: value` or `a, b`. Eg. `'[a,b]'` or `{a:{b:c}}`. + // Can be useful when using yaml for pretty URL query params as spaces are %-encoded. (default: false) + condenseFlow?: boolean; +} + +export interface TypeConstructorOptions { + kind?: 'sequence' | 'scalar' | 'mapping'; + resolve?: (data: any) => boolean; + construct?: (data: any) => any; + instanceOf?: object; + predicate?: string; + represent?: ((data: object) => any) | { [x: string]: (data: object) => any }; + defaultStyle?: string; + styleAliases?: { [x: string]: any; }; +} + +export interface SchemaDefinition { + implicit?: any[]; + explicit?: Type[]; + include?: Schema[]; +} + +// only strings, arrays and plain objects: http://www.yaml.org/spec/1.2/spec.html#id2802346 +export let FAILSAFE_SCHEMA: Schema; +// only strings, arrays and plain objects: http://www.yaml.org/spec/1.2/spec.html#id2802346 +export let JSON_SCHEMA: Schema; +// same as JSON_SCHEMA: http://www.yaml.org/spec/1.2/spec.html#id2804923 +export let CORE_SCHEMA: Schema; +// all supported YAML types, without unsafe ones (!!js/undefined, !!js/regexp and !!js/function): http://yaml.org/type/ +export let DEFAULT_SAFE_SCHEMA: Schema; +// all supported YAML types. +export let DEFAULT_FULL_SCHEMA: Schema; +export let MINIMAL_SCHEMA: Schema; +export let SAFE_SCHEMA: Schema; + +export class YAMLException extends Error { + constructor(reason?: any, mark?: any); + toString(compact?: boolean): string; +} diff --git a/types/js-yaml/js-yaml-tests.ts b/types/js-yaml/js-yaml-tests.ts index af932cb934..3d5ecc17bf 100644 --- a/types/js-yaml/js-yaml-tests.ts +++ b/types/js-yaml/js-yaml-tests.ts @@ -1,45 +1,55 @@ - - import yaml = require('js-yaml'); import LoadOptions = yaml.LoadOptions; import DumpOptions = yaml.DumpOptions; import TypeConstructorOptions = yaml.TypeConstructorOptions; import SchemaDefinition = yaml.SchemaDefinition; -var bool: boolean; -var num: number; -var str: string; -var obj: Object; -var value: any; -var array: any[]; -var fn: Function; -var schemaDefinition: SchemaDefinition = { +const bool = true; +const num = 0; +const str = ""; +const obj: object = {}; +const map: { [x: string]: any; } = {}; +const array: any[] = []; +const fn: (...args: any[]) => any = () => {}; +const type = new yaml.Type(str); + +const schemaDefinition: SchemaDefinition = { implicit: array, explicit: array, include: array }; -var typeConstructorOptions: TypeConstructorOptions = { - kind: str, +const typeConstructorOptions: TypeConstructorOptions = { + kind: "scalar", resolve: fn, construct: fn, instanceOf: obj, predicate: str, represent: fn, defaultStyle: str, - styleAliases: obj + styleAliases: map }; -var loadOpts: LoadOptions; -var dumpOpts: DumpOptions; +const schema: yaml.Schema = new yaml.Schema(schemaDefinition); + +let value: any; +let loadOpts: LoadOptions; +let dumpOpts: DumpOptions; // -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- +// $ExpectType Schema yaml.FAILSAFE_SCHEMA; +// $ExpectType Schema yaml.JSON_SCHEMA; +// $ExpectType Schema yaml.CORE_SCHEMA; +// $ExpectType Schema yaml.DEFAULT_SAFE_SCHEMA; +// $ExpectType Schema yaml.DEFAULT_FULL_SCHEMA; +// $ExpectType Schema yaml.MINIMAL_SCHEMA; +// $ExpectType Schema yaml.SAFE_SCHEMA; // -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- @@ -53,6 +63,9 @@ loadOpts = { loadOpts = { schema: bool }; +loadOpts = { + json: bool +}; // -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- @@ -74,46 +87,87 @@ dumpOpts = { // -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -value = yaml.safeLoad(str); -value = yaml.safeLoad(str, loadOpts); +// $ExpectType Type +new yaml.Type(str, typeConstructorOptions); -value = yaml.load(str); -value = yaml.load(str, loadOpts); +// $ExpectType "sequence" | "scalar" | "mapping" | null +type.kind; +// $ExpectType (data: any) => boolean +type.resolve; +// $ExpectType (data: any) => any +type.construct; +// $ExpectType object | null +type.instanceOf; +// $ExpectType string | null +type.predicate; +// $ExpectType ((data: object) => any) | { [x: string]: (data: object) => any; } | null +type.represent; +// $ExpectType string | null +type.defaultStyle; +// $ExpectType { [x: string]: any; } +type.styleAliases; // -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -value = yaml.safeLoadAll(str); -value = yaml.safeLoadAll(str, (doc) => { +// $ExpectType any +yaml.safeLoad(str); +// $ExpectType any +yaml.safeLoad(str, loadOpts); + +// $ExpectType any +yaml.load(str); +// $ExpectType any +yaml.load(str, loadOpts); + +// -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- + +// $ExpectType any +yaml.safeLoadAll(str); +// $ExpectType any +yaml.safeLoadAll(str, (doc) => { value = doc; }); -value = yaml.safeLoadAll(str, (doc) => { +// $ExpectType any +yaml.safeLoadAll(str, (doc) => { value = doc; }, loadOpts); value = yaml.safeLoadAll(str, undefined, loadOpts); +// $ExpectType any value = yaml.loadAll(str); -value = yaml.loadAll(str, (doc) => { +// $ExpectType any +yaml.loadAll(str, (doc) => { value = doc; }); -value = yaml.loadAll(str, (doc) => { +// $ExpectType any +yaml.loadAll(str, (doc) => { value = doc; }, loadOpts); value = yaml.loadAll(str, undefined, loadOpts); // -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -value = yaml.safeDump(str); -value = yaml.safeDump(str, dumpOpts); +// $ExpectType string +yaml.safeDump(str); +// $ExpectType string +yaml.safeDump(str, dumpOpts); -value = yaml.dump(str); -value = yaml.dump(str, dumpOpts); +// $ExpectType string +yaml.dump(str); +// $ExpectType string +yaml.dump(str, dumpOpts); -value = new yaml.YAMLException(); -value = new yaml.Type(str, typeConstructorOptions); -value = new yaml.Schema(schemaDefinition); -value = yaml.Schema.create([new yaml.Type(str)]); -value = yaml.Schema.create(new yaml.Type(str)); -value = yaml.Schema.create(new yaml.Schema(schemaDefinition), [new yaml.Type(str)]); -value = yaml.Schema.create([new yaml.Schema(schemaDefinition)], [new yaml.Type(str)]); -value = yaml.Schema.create(new yaml.Schema(schemaDefinition), new yaml.Type(str)); -value = yaml.Schema.create([new yaml.Schema(schemaDefinition)], new yaml.Type(str)); +new yaml.YAMLException(); + +// $ExpectType Schema +yaml.Schema.create([type]); +// $ExpectType Schema +yaml.Schema.create(type); +// $ExpectType Schema +yaml.Schema.create(schema, [type]); +// $ExpectType Schema +yaml.Schema.create([schema], [type]); +// $ExpectType Schema +yaml.Schema.create(schema, type); +// $ExpectType Schema +yaml.Schema.create([schema], type); diff --git a/types/js-yaml/tsconfig.json b/types/js-yaml/tsconfig.json index b1e787d1b3..c36931fa61 100644 --- a/types/js-yaml/tsconfig.json +++ b/types/js-yaml/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", "js-yaml-tests.ts" ] -} \ No newline at end of file +} diff --git a/types/js-yaml/tslint.json b/types/js-yaml/tslint.json index a41bf5d19a..3db14f85ea 100644 --- a/types/js-yaml/tslint.json +++ b/types/js-yaml/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/js.spec/index.d.ts b/types/js.spec/index.d.ts index 735de40976..764bfa845e 100644 --- a/types/js.spec/index.d.ts +++ b/types/js.spec/index.d.ts @@ -71,7 +71,7 @@ export interface Problem { * @param value the value to test * @returns true if valid */ -export function valid(spec: Spec, value: any): boolean; +export function valid(spec: spec.SpecInput, value: any): boolean; /** * Returns the conformed value to this spec. @@ -79,7 +79,7 @@ export function valid(spec: Spec, value: any): boolean; * @param value the value to test * @returns if the value does not conform to the spec, or the conformed value if it does. */ -export function conform(spec: Spec, value: any): any; +export function conform(spec: spec.SpecInput, value: any): any; /** * Like explain(), but returns Problems array. @@ -87,28 +87,28 @@ export function conform(spec: Spec, value: any): any; * @param value the value to test * @returns list of problems or null if none */ -export function explainData(spec: Spec, value: any): Problem[]; +export function explainData(spec: spec.SpecInput, value: any): Problem[]; /** * Prints, to the console, reasons why the value did not conform to this spec. * @param spec the spec to test with * @param value the value to test */ -export function explain(spec: Spec, value: any): void; +export function explain(spec: spec.SpecInput, value: any): void; /** * Returns a multiline string with reasons why the value did not conform to this spec. * @param spec the spec to test with * @param value the value to test */ -export function explainStr(spec: Spec, value: any): string; +export function explainStr(spec: spec.SpecInput, value: any): string; /** * Tests if a value conforms to a spec, and if not, throws an Error. * @param spec the spec to test with * @param value the value to test */ -export function assert(spec: Spec, value: any): void; +export function assert(spec: spec.SpecInput, value: any): void; export namespace symbol { /** diff --git a/types/js.spec/js.spec-tests.ts b/types/js.spec/js.spec-tests.ts index 8bb9611e87..e1d7703f76 100644 --- a/types/js.spec/js.spec-tests.ts +++ b/types/js.spec/js.spec-tests.ts @@ -7,20 +7,28 @@ const name: string = spec.name; const options: object = spec.options; const isValid: boolean = S.valid(S.spec.boolean, true); +S.valid((value) => true, "a value"); const result = S.conform(S.spec.map("dancing", {field: S.spec.string}), "not a map"); +S.conform((value) => true, "a value"); const problems: S.Problem[] = S.explainData(S.spec.int, "not a number"); +S.explainData((value) => true, "a value"); const {path, via, value, predicate}: {path: string[], via: string[], value: any, predicate: S.Predicate} = problems[0]; const problemStr: string = S.explainStr(S.spec.even, 3); +S.explainStr((value) => true, "a value"); // $ExpectType void S.explain(S.spec.positive, true); +// $ExpectType void +S.explain((value) => true, "a value"); // $ExpectType void S.assert(S.spec.string, "things"); +// $ExpectType void +S.assert((value) => true, "a value"); const symbols: symbol[] = [S.symbol.count, S.symbol.invalid, S.symbol.maxCount, S.symbol.minCount, S.symbol.optional]; diff --git a/types/keypress.js/index.d.ts b/types/keypress.js/index.d.ts index 63da327acd..202990da93 100644 --- a/types/keypress.js/index.d.ts +++ b/types/keypress.js/index.d.ts @@ -1,4 +1,4 @@ -// Type definitions for Keypress 2.0 +// Type definitions for Keypress 2.1 // Project: https://github.com/dmauro/Keypress/ // Definitions by: Roger Chen // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped @@ -39,9 +39,9 @@ export class Listener { simple_combo(keys: string, on_keydown_callback: (event?: KeyboardEvent, count?: number) => any): void; counting_combo(keys: string, on_count_callback: (event?: KeyboardEvent, count?: number) => any): void; sequence_combo(keys: string, callback: (event?: KeyboardEvent, count?: number) => any): void; - register_combo(combo: Combo): void; + register_combo(combo: Combo): Combo; unregister_combo(combo: Combo | string): void; - register_many(combos: Combo[]): void; + register_many(combos: Combo[]): Combo[]; unregister_many(combos: Combo[] | string[]): void; get_registered_combos(): Combo[]; destroy(): void; diff --git a/types/koa-router/index.d.ts b/types/koa-router/index.d.ts index b543a764b0..4ad96140eb 100644 --- a/types/koa-router/index.d.ts +++ b/types/koa-router/index.d.ts @@ -150,7 +150,7 @@ declare class Router { * "down" the middleware stack. */ use(...middleware: Array): Router; - use(path: string | RegExp, ...middleware: Array): Router; + use(path: string | string[] | RegExp, ...middleware: Array): Router; /** * HTTP get method diff --git a/types/koa/index.d.ts b/types/koa/index.d.ts index d46920bf07..d4f339aa32 100644 --- a/types/koa/index.d.ts +++ b/types/koa/index.d.ts @@ -136,6 +136,11 @@ declare interface ContextDelegatedRequest { */ secure: boolean; + /** + * Request remote address. Supports X-Forwarded-For when app.proxy is true. + */ + ip: string; + /** * When `app.proxy` is `true`, parse * the "X-Forwarded-For" ip address list. diff --git a/types/lodash/index.d.ts b/types/lodash/index.d.ts index f038846d22..a0eaef941c 100644 --- a/types/lodash/index.d.ts +++ b/types/lodash/index.d.ts @@ -1234,7 +1234,7 @@ declare namespace _ { */ findIndex( array: List | null | undefined, - predicate?: ListIterateeBoolean, + predicate?: ListIterateeCustom, fromIndex?: number ): number; } @@ -1245,7 +1245,7 @@ declare namespace _ { */ findIndex( this: LoDashImplicitWrapper | null | undefined>, - predicate?: ListIterateeBoolean, + predicate?: ListIterateeCustom, fromIndex?: number ): number; } @@ -1256,7 +1256,7 @@ declare namespace _ { */ findIndex( this: LoDashExplicitWrapper | null | undefined>, - predicate?: ListIterateeBoolean, + predicate?: ListIterateeCustom, fromIndex?: number ): LoDashExplicitWrapper; } @@ -1282,7 +1282,7 @@ declare namespace _ { */ findLastIndex( array: List | null | undefined, - predicate?: ListIterateeBoolean, + predicate?: ListIterateeCustom, fromIndex?: number ): number; } @@ -1293,7 +1293,7 @@ declare namespace _ { */ findLastIndex( this: LoDashImplicitWrapper | null | undefined>, - predicate?: ListIterateeBoolean, + predicate?: ListIterateeCustom, fromIndex?: number ): number; } @@ -1304,7 +1304,7 @@ declare namespace _ { */ findLastIndex( this: LoDashExplicitWrapper | null | undefined>, - predicate?: ListIterateeBoolean, + predicate?: ListIterateeCustom, fromIndex?: number ): LoDashExplicitWrapper; } @@ -4315,6 +4315,14 @@ declare namespace _ { * @param thisArg The this binding of iteratee. * @return Returns the composed aggregate object. */ + countBy( + collection: string | null | undefined, + iteratee?: StringIterator + ): Dictionary; + + /** + * @see _.countBy + */ countBy( collection: List | null | undefined, iteratee?: ListIteratee @@ -4338,6 +4346,14 @@ declare namespace _ { } interface LoDashImplicitWrapper { + /** + * @see _.countBy + */ + countBy( + this: LoDashImplicitWrapper, + iteratee?: StringIterator + ): LoDashImplicitWrapper>; + /** * @see _.countBy */ @@ -4364,6 +4380,14 @@ declare namespace _ { } interface LoDashExplicitWrapper { + /** + * @see _.countBy + */ + countBy( + this: LoDashExplicitWrapper, + iteratee?: StringIterator + ): LoDashExplicitWrapper>; + /** * @see _.countBy */ @@ -4479,7 +4503,7 @@ declare namespace _ { */ every( collection: List | null | undefined, - predicate?: ListIterateeBoolean + predicate?: ListIterateeCustom ): boolean; /** @@ -4487,7 +4511,7 @@ declare namespace _ { */ every( collection: NumericDictionary | null | undefined, - predicate?: NumericDictionaryIterateeBoolean + predicate?: NumericDictionaryIterateeCustom ): boolean; /** @@ -4495,7 +4519,7 @@ declare namespace _ { */ every( collection: T | null | undefined, - predicate?: ObjectIterateeBoolean + predicate?: ObjectIterateeCustom ): boolean; } @@ -4505,7 +4529,7 @@ declare namespace _ { */ every( this: LoDashImplicitWrapper | null | undefined>, - predicate?: ListIterateeBoolean + predicate?: ListIterateeCustom ): boolean; /** @@ -4513,7 +4537,7 @@ declare namespace _ { */ every( this: LoDashImplicitWrapper, - predicate?: ObjectIterateeBoolean + predicate?: ObjectIterateeCustom ): boolean; /** @@ -4521,7 +4545,7 @@ declare namespace _ { */ every( this: LoDashImplicitWrapper | null | undefined>, - predicate?: NumericDictionaryIterateeBoolean + predicate?: NumericDictionaryIterateeCustom ): boolean; } @@ -4531,7 +4555,7 @@ declare namespace _ { */ every( this: LoDashExplicitWrapper | null | undefined>, - predicate?: ListIterateeBoolean + predicate?: ListIterateeCustom ): LoDashExplicitWrapper; /** @@ -4539,7 +4563,7 @@ declare namespace _ { */ every( this: LoDashExplicitWrapper, - predicate?: ObjectIterateeBoolean + predicate?: ObjectIterateeCustom ): LoDashExplicitWrapper; /** @@ -4547,7 +4571,7 @@ declare namespace _ { */ every( this: LoDashExplicitWrapper | null | undefined>, - predicate?: NumericDictionaryIterateeBoolean + predicate?: NumericDictionaryIterateeCustom ): LoDashExplicitWrapper; } @@ -4589,7 +4613,7 @@ declare namespace _ { */ filter( collection: List | null | undefined, - predicate?: ListIterateeBoolean + predicate?: ListIterateeCustom ): T[]; /** @@ -4605,7 +4629,7 @@ declare namespace _ { */ filter( collection: T | null | undefined, - predicate?: ObjectIterateeBoolean + predicate?: ObjectIterateeCustom ): Array; } @@ -4631,7 +4655,7 @@ declare namespace _ { */ filter( this: LoDashImplicitWrapper | null | undefined>, - predicate?: ListIterateeBoolean + predicate?: ListIterateeCustom ): LoDashImplicitWrapper; /** @@ -4647,7 +4671,7 @@ declare namespace _ { */ filter( this: LoDashImplicitWrapper, - predicate?: ObjectIterateeBoolean + predicate?: ObjectIterateeCustom ): LoDashImplicitWrapper>; } @@ -4673,7 +4697,7 @@ declare namespace _ { */ filter( this: LoDashExplicitWrapper | null | undefined>, - predicate?: ListIterateeBoolean + predicate?: ListIterateeCustom ): LoDashExplicitWrapper; /** @@ -4689,7 +4713,7 @@ declare namespace _ { */ filter( this: LoDashExplicitWrapper, - predicate?: ObjectIterateeBoolean + predicate?: ObjectIterateeCustom ): LoDashExplicitWrapper>; } @@ -4724,7 +4748,7 @@ declare namespace _ { */ find( collection: List | null | undefined, - predicate?: ListIterateeBoolean, + predicate?: ListIterateeCustom, fromIndex?: number ): T|undefined; @@ -4742,7 +4766,7 @@ declare namespace _ { */ find( collection: T | null | undefined, - predicate?: ObjectIterateeBoolean, + predicate?: ObjectIterateeCustom, fromIndex?: number ): T[keyof T]|undefined; } @@ -4762,7 +4786,7 @@ declare namespace _ { */ find( this: LoDashImplicitWrapper | null | undefined>, - predicate?: ListIterateeBoolean, + predicate?: ListIterateeCustom, fromIndex?: number ): T|undefined; @@ -4780,7 +4804,7 @@ declare namespace _ { */ find( this: LoDashImplicitWrapper, - predicate?: ObjectIterateeBoolean, + predicate?: ObjectIterateeCustom, fromIndex?: number ): T[keyof T]|undefined; } @@ -4800,7 +4824,7 @@ declare namespace _ { */ find( this: LoDashExplicitWrapper | null | undefined>, - predicate?: ListIterateeBoolean, + predicate?: ListIterateeCustom, fromIndex?: number ): LoDashExplicitWrapper; @@ -4818,7 +4842,7 @@ declare namespace _ { */ find( this: LoDashExplicitWrapper, - predicate?: ObjectIterateeBoolean, + predicate?: ObjectIterateeCustom, fromIndex?: number ): LoDashExplicitWrapper; } @@ -4844,7 +4868,7 @@ declare namespace _ { */ findLast( collection: List | null | undefined, - predicate?: ListIterateeBoolean, + predicate?: ListIterateeCustom, fromIndex?: number ): T|undefined; @@ -4862,7 +4886,7 @@ declare namespace _ { */ findLast( collection: T | null | undefined, - predicate?: ObjectIterateeBoolean, + predicate?: ObjectIterateeCustom, fromIndex?: number ): T[keyof T]|undefined; } @@ -4882,7 +4906,7 @@ declare namespace _ { */ findLast( this: LoDashImplicitWrapper | null | undefined>, - predicate?: ListIterateeBoolean, + predicate?: ListIterateeCustom, fromIndex?: number ): T | undefined; @@ -4900,7 +4924,7 @@ declare namespace _ { */ findLast( this: LoDashImplicitWrapper, - predicate?: ObjectIterateeBoolean, + predicate?: ObjectIterateeCustom, fromIndex?: number ): T[keyof T]|undefined; } @@ -4920,7 +4944,7 @@ declare namespace _ { */ findLast( this: LoDashExplicitWrapper | null | undefined>, - predicate?: ListIterateeBoolean, + predicate?: ListIterateeCustom, fromIndex?: number ): LoDashExplicitWrapper; @@ -4938,7 +4962,7 @@ declare namespace _ { */ findLast( this: LoDashExplicitWrapper, - predicate?: ObjectIterateeBoolean, + predicate?: ObjectIterateeCustom, fromIndex?: number ): LoDashExplicitWrapper; } @@ -5849,9 +5873,17 @@ declare namespace _ { * @param thisArg The this binding of iteratee. * @return Returns the composed aggregate object. */ + keyBy( + collection: string | null | undefined, + iteratee?: StringIterator + ): Dictionary; + + /** + * @see _.keyBy + */ keyBy( collection: List | null | undefined, - iteratee?: ListIteratee + iteratee?: ListIterateeCustom ): Dictionary; /** @@ -5859,7 +5891,7 @@ declare namespace _ { */ keyBy( collection: T | null | undefined, - iteratee?: ObjectIteratee + iteratee?: ObjectIterateeCustom ): Dictionary; /** @@ -5867,17 +5899,25 @@ declare namespace _ { */ keyBy( collection: NumericDictionary | null | undefined, - iteratee?: NumericDictionaryIteratee + iteratee?: NumericDictionaryIterateeCustom ): Dictionary; } interface LoDashImplicitWrapper { + /** + * @see _.keyBy + */ + keyBy( + this: LoDashImplicitWrapper, + iteratee?: StringIterator + ): LoDashImplicitWrapper>; + /** * @see _.keyBy */ keyBy( this: LoDashImplicitWrapper | null | undefined>, - iteratee?: ListIteratee + iteratee?: ListIterateeCustom ): LoDashImplicitWrapper>; /** @@ -5885,7 +5925,7 @@ declare namespace _ { */ keyBy( this: LoDashImplicitWrapper, - iteratee?: ObjectIteratee + iteratee?: ObjectIterateeCustom ): LoDashImplicitWrapper>; /** @@ -5893,17 +5933,25 @@ declare namespace _ { */ keyBy( this: LoDashImplicitWrapper | null | undefined>, - iteratee?: NumericDictionaryIteratee + iteratee?: NumericDictionaryIterateeCustom ): LoDashImplicitWrapper>; } interface LoDashExplicitWrapper { + /** + * @see _.keyBy + */ + keyBy( + this: LoDashExplicitWrapper, + iteratee?: StringIterator + ): LoDashExplicitWrapper>; + /** * @see _.keyBy */ keyBy( this: LoDashExplicitWrapper | null | undefined>, - iteratee?: ListIteratee + iteratee?: ListIterateeCustom ): LoDashExplicitWrapper>; /** @@ -5911,7 +5959,7 @@ declare namespace _ { */ keyBy( this: LoDashExplicitWrapper, - iteratee?: ObjectIteratee + iteratee?: ObjectIterateeCustom ): LoDashExplicitWrapper>; /** @@ -5919,7 +5967,7 @@ declare namespace _ { */ keyBy( this: LoDashExplicitWrapper | null | undefined>, - iteratee?: NumericDictionaryIteratee + iteratee?: NumericDictionaryIterateeCustom ): LoDashExplicitWrapper>; } @@ -6718,7 +6766,7 @@ declare namespace _ { */ reject( collection: List | null | undefined, - predicate?: ListIterateeBoolean + predicate?: ListIterateeCustom ): T[]; /** @@ -6726,7 +6774,7 @@ declare namespace _ { */ reject( collection: T | null | undefined, - predicate?: ObjectIterateeBoolean + predicate?: ObjectIterateeCustom ): Array; } @@ -6744,7 +6792,7 @@ declare namespace _ { */ reject( this: LoDashImplicitWrapper | null | undefined>, - predicate?: ListIterateeBoolean + predicate?: ListIterateeCustom ): LoDashImplicitWrapper; /** @@ -6752,7 +6800,7 @@ declare namespace _ { */ reject( this: LoDashImplicitWrapper, - predicate?: ObjectIterateeBoolean + predicate?: ObjectIterateeCustom ): LoDashImplicitWrapper>; } @@ -6770,7 +6818,7 @@ declare namespace _ { */ reject( this: LoDashExplicitWrapper | null | undefined>, - predicate?: ListIterateeBoolean + predicate?: ListIterateeCustom ): LoDashExplicitWrapper; /** @@ -6778,7 +6826,7 @@ declare namespace _ { */ reject( this: LoDashExplicitWrapper, - predicate?: ObjectIterateeBoolean + predicate?: ObjectIterateeCustom ): LoDashExplicitWrapper>; } @@ -6992,7 +7040,7 @@ declare namespace _ { */ some( collection: List | null | undefined, - predicate?: ListIterateeBoolean + predicate?: ListIterateeCustom ): boolean; /** @@ -7000,7 +7048,7 @@ declare namespace _ { */ some( collection: T | null | undefined, - predicate?: ObjectIterateeBoolean + predicate?: ObjectIterateeCustom ): boolean; /** @@ -7008,7 +7056,7 @@ declare namespace _ { */ some( collection: NumericDictionary | null | undefined, - predicate?: NumericDictionaryIterateeBoolean + predicate?: NumericDictionaryIterateeCustom ): boolean; } @@ -7018,7 +7066,7 @@ declare namespace _ { */ some( this: LoDashImplicitWrapper | null | undefined>, - predicate?: ListIterateeBoolean + predicate?: ListIterateeCustom ): boolean; /** @@ -7026,7 +7074,7 @@ declare namespace _ { */ some( this: LoDashImplicitWrapper, - predicate?: ObjectIterateeBoolean + predicate?: ObjectIterateeCustom ): boolean; /** @@ -7034,7 +7082,7 @@ declare namespace _ { */ some( this: LoDashImplicitWrapper | null | undefined>, - predicate?: NumericDictionaryIterateeBoolean + predicate?: NumericDictionaryIterateeCustom ): boolean; } @@ -7044,7 +7092,7 @@ declare namespace _ { */ some( this: LoDashExplicitWrapper | null | undefined>, - predicate?: ListIterateeBoolean + predicate?: ListIterateeCustom ): LoDashExplicitWrapper; /** @@ -7052,7 +7100,7 @@ declare namespace _ { */ some( this: LoDashExplicitWrapper, - predicate?: ObjectIterateeBoolean + predicate?: ObjectIterateeCustom ): LoDashExplicitWrapper; /** @@ -7060,7 +7108,7 @@ declare namespace _ { */ some( this: LoDashExplicitWrapper | null | undefined>, - predicate?: NumericDictionaryIterateeBoolean + predicate?: NumericDictionaryIterateeCustom ): LoDashExplicitWrapper; } @@ -9315,14 +9363,16 @@ declare namespace _ { /** * @see _.conformsTo */ - conformsTo(source: ConformsPredicateObject): boolean; + conformsTo(this: LoDashImplicitWrapper, source: ConformsPredicateObject): boolean; + // Note: we can't use TValue here, because it generates a typescript error when strictFunctionTypes is enabled. } interface LoDashExplicitWrapper { /** * @see _.conformsTo */ - conformsTo(source: ConformsPredicateObject): LoDashExplicitWrapper; + conformsTo(this: LoDashImplicitWrapper, source: ConformsPredicateObject): LoDashExplicitWrapper; + // Note: we can't use TValue here, because it generates a typescript error when strictFunctionTypes is enabled. } type CondPair = [(val: T) => boolean, (val: T) => R] @@ -10723,7 +10773,7 @@ declare namespace _ { /** * @see _.toArray */ - toArray(): LoDashImplicitWrapper>; + toArray(this: LoDashImplicitWrapper): LoDashImplicitWrapper>; } interface LoDashExplicitWrapper { @@ -10735,7 +10785,7 @@ declare namespace _ { /** * @see _.toArray */ - toArray(): LoDashExplicitWrapper>; + toArray(this: LoDashImplicitWrapper): LoDashExplicitWrapper>; } //_.toPlainObject @@ -14348,6 +14398,9 @@ declare namespace _ { ...props: Array> ): Pick; + /** + * @see _.pick + */ pick( object: T | null | undefined, ...props: PropertyPath[] @@ -14355,6 +14408,14 @@ declare namespace _ { } interface LoDashImplicitWrapper { + /** + * @see _.pick + */ + pick( + this: LoDashImplicitWrapper, + ...props: Array> + ): LoDashImplicitWrapper>; + /** * @see _.pick */ @@ -14365,6 +14426,14 @@ declare namespace _ { } interface LoDashExplicitWrapper { + /** + * @see _.pick + */ + pick( + this: LoDashExplicitWrapper, + ...props: Array> + ): LoDashExplicitWrapper>; + /** * @see _.pick */ @@ -17015,13 +17084,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 ListIterateeBoolean = ListIterator | string | [string, any] | PartialDeep; + type ListIterateeCustom = ListIterator | string | [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 ObjectIterateeBoolean = ObjectIterator | string | [string, any] | PartialDeep; + type ObjectIterateeCustom = ObjectIterator | string | [string, any] | PartialDeep; type ObjectIteratorTypeGuard = (value: TObject[keyof TObject], key: string, collection: TObject) => value is S; type DictionaryIterator = ObjectIterator, TResult>; @@ -17030,7 +17099,7 @@ declare namespace _ { type NumericDictionaryIterator = (value: T, key: number, collection: NumericDictionary) => TResult; type NumericDictionaryIteratee = NumericDictionaryIterator | string | [string, any] | PartialDeep; - type NumericDictionaryIterateeBoolean = NumericDictionaryIterator | string | [string, any] | PartialDeep; + type NumericDictionaryIterateeCustom = NumericDictionaryIterator | string | [string, any] | PartialDeep; type StringIterator = (char: string, index: number, string: string) => TResult; diff --git a/types/lodash/lodash-tests.ts b/types/lodash/lodash-tests.ts index e40569204d..dbefb1abaa 100644 --- a/types/lodash/lodash-tests.ts +++ b/types/lodash/lodash-tests.ts @@ -4,86 +4,19 @@ interface IFoodOrganic { name: string; organic: boolean; } - -interface IFoodType { - name: string; - type: string; -} - -interface IFoodCombined { - name: string; - organic: boolean; - type: string; -} - -interface IStoogesQuote { - name: string; - quotes: string[]; -} - interface IStoogesAge { name: string; age: number; } -interface IStoogesCombined { - name: string; - age: number; - quotes: string[]; -} - -interface IKey { - dir: string; - code: number; -} - -interface IDictionary { - [index: string]: T; -} - const foodsOrganic: IFoodOrganic[] = [ { name: 'banana', organic: true }, { name: 'beet', organic: false }, ]; -const foodsType: IFoodType[] = [ - { name: 'apple', type: 'fruit' }, - { name: 'banana', type: 'fruit' }, - { name: 'beet', type: 'vegetable' } -]; -const foodsCombined: IFoodCombined[] = [ - { 'name': 'apple', 'organic': false, 'type': 'fruit' }, - { 'name': 'carrot', 'organic': true, 'type': 'vegetable' } -]; - -const stoogesQuotes: IStoogesQuote[] = [ - { 'name': 'curly', 'quotes': ['Oh, a wise guy, eh?', 'Poifect!'] }, - { 'name': 'moe', 'quotes': ['Spread out!', 'You knucklehead!'] } -]; const stoogesAges: IStoogesAge[] = [ { 'name': 'moe', 'age': 40 }, { 'name': 'larry', 'age': 50 } ]; -const stoogesAgesDict: IDictionary = { - first: { 'name': 'moe', 'age': 40 }, - second: { 'name': 'larry', 'age': 50 } -}; -const stoogesCombined: IStoogesCombined[] = [ - { 'name': 'curly', 'age': 30, 'quotes': ['Oh, a wise guy, eh?', 'Poifect!'] }, - { 'name': 'moe', 'age': 40, 'quotes': ['Spread out!', 'You knucklehead!'] } -]; - -const keys: IKey[] = [ - { 'dir': 'left', 'code': 97 }, - { 'dir': 'right', 'code': 100 } -]; - -class Dog { - constructor(public name: string) { } - - bark() { - // Woof - } -} let result: any; @@ -4591,9 +4524,9 @@ namespace TestFilter { let obj: any = {}; let dictionary: _.Dictionary | null | undefined = obj; - let stringIterator: (char: string, index: number, string: string) => any = (char: string, index: number, string: string) => 1; - let listIterator: (value: TResult, index: number, collection: _.List) => any = (value: TResult, index: number, collection: _.List) => 1; - let dictionaryIterator: (value: TResult, key: string, collection: _.Dictionary) => any = (value: TResult, key: string, collection: _.Dictionary) => 1; + let stringIterator = (char: string, index: number, string: string) => true; + let listIterator = (value: TResult, index: number, collection: _.List) => true; + let dictionaryIterator = (value: TResult, key: string, collection: _.Dictionary) => true; { let result: string[]; @@ -5207,7 +5140,7 @@ namespace TestFlatMapDepth { let listIterator: (value: number|number[], index: number, collection: _.List) => _.ListOfRecursiveArraysOrValues = (a, b, c) =>[ 1]; - let dictionaryIterator: (value: number|number[], key: number, collection: _.Dictionary) => _.ListOfRecursiveArraysOrValues = (a, b, c) => [1]; + let dictionaryIterator: (value: number|number[], key: string, collection: _.Dictionary) => _.ListOfRecursiveArraysOrValues = (a, b, c) => [1]; let numericDictionaryIterator: (value: number|number[], key: number, collection: _.NumericDictionary) => _.ListOfRecursiveArraysOrValues = (a, b, c) => [1]; @@ -5776,8 +5709,8 @@ namespace TestGroupBy { { let result: _.Dictionary; - result = _.groupBy(''); - result = _.groupBy('', stringIterator); + result = _.groupBy(''); + result = _.groupBy('', stringIterator); } { @@ -5909,16 +5842,16 @@ namespace TestKeyBy { let dictionary: _.Dictionary | null | undefined = obj; let numericDictionary: _.NumericDictionary | null | undefined = obj; - let stringIterator: (value: string, index: number, collection: string) => any = (value: string, index: number, collection: string) => 1; - let listIterator: (value: SampleObject, index: number, collection: _.List) => any = (value: SampleObject, index: number, collection: _.List) => 1; - let dictionaryIterator: (value: SampleObject, key: string, collection: _.Dictionary) => any = (value: SampleObject, key: string, collection: _.Dictionary) => 1; - let numericDictionaryIterator: (value: SampleObject, key: number, collection: _.NumericDictionary) => any = (value: SampleObject, key: number, collection: _.NumericDictionary) => 1; + let stringIterator = (value: string, index: number, collection: string) => "a"; + let listIterator = (value: SampleObject, index: number, collection: _.List) => 1; + let dictionaryIterator = (value: SampleObject, key: string, collection: _.Dictionary) => Symbol.name; + let numericDictionaryIterator = (value: SampleObject, key: number, collection: _.NumericDictionary) => "a"; { let result: _.Dictionary; - result = _.keyBy('abcd'); - result = _.keyBy('abcd', stringIterator); + result = _.keyBy('abcd'); + result = _.keyBy('abcd', stringIterator); } { @@ -6464,9 +6397,9 @@ namespace TestReject { let obj: any = {}; let dictionary: _.Dictionary | null | undefined = obj; - let stringIterator: (char: string, index: number, string: string) => any = (char: string, index: number, string: string) => 1; - let listIterator: (value: TResult, index: number, collection: _.List) => any = (value: TResult, index: number, collection: _.List) => 1; - let dictionaryIterator: (value: TResult, key: string, collection: _.Dictionary) => any = (value: TResult, key: string, collection: _.Dictionary) => 1; + let stringIterator = (char: string, index: number, string: string) => true; + let listIterator = (value: TResult, index: number, collection: _.List) => true; + let dictionaryIterator = (value: TResult, key: string, collection: _.Dictionary) => true; { let result: string[]; @@ -8667,9 +8600,7 @@ namespace TestIsEqual { // _.isEqualWith namespace TestIsEqualWith { - let customizer = (value: any, other: any, indexOrKey: number|string|undefined, parent: any, otherParent: any, stack: any) => { - return value ? undefined : true; - }; + let customizer = (value: any, other: any, indexOrKey: number|string|symbol|undefined, parent: any, otherParent: any, stack: any) => true; { let result: boolean; @@ -8873,7 +8804,7 @@ namespace TestIsMatch { // _.isMatchWith namespace TestIsMatchWith { - let testIsMatchCustiomizerFn = (value: any, other: any, indexOrKey: number|string) => true; + let testIsMatchCustiomizerFn = (value: any, other: any, indexOrKey: number|string|symbol) => true; let result: boolean; @@ -11890,7 +11821,7 @@ namespace TestPick { { let result: Pick; result = _.pick(obj, 'a', 'b'); - result = _.pick(obj, ['a', 'b']); + result = _.pick(obj, ['a' as 'a', 'b' as 'b']); } { @@ -11901,6 +11832,13 @@ namespace TestPick { result = _(obj).pick(['b', 1], 0, 'a'); } + { + let result: _.LoDashImplicitWrapper>; + + result = _(obj).pick('a', 'b'); + result = _(obj).pick(['a' as 'a', 'b' as 'b']); + } + { let result: _.LoDashExplicitWrapper>; @@ -11908,6 +11846,13 @@ namespace TestPick { result = _(obj).chain().pick(0, 'a'); result = _(obj).chain().pick(['b', 1], 0, 'a'); } + + { + let result: _.LoDashExplicitWrapper>; + + result = _(obj).chain().pick('a', 'b'); + result = _(obj).chain().pick(['a' as 'a', 'b' as 'b']); + } } // _.pickBy diff --git a/types/lodash/tsconfig.json b/types/lodash/tsconfig.json index 2c4aa57c54..8bd56c0b87 100644 --- a/types/lodash/tsconfig.json +++ b/types/lodash/tsconfig.json @@ -7,7 +7,7 @@ "noImplicitAny": true, "noImplicitThis": true, "strictNullChecks": true, - "strictFunctionTypes": false, + "strictFunctionTypes": true, "baseUrl": "../", "typeRoots": [ "../" diff --git a/types/lolex/index.d.ts b/types/lolex/index.d.ts index c0dec4cd56..510cb911ec 100644 --- a/types/lolex/index.d.ts +++ b/types/lolex/index.d.ts @@ -1,6 +1,8 @@ -// Type definitions for lolex 1.5 +// Type definitions for lolex 2.1 // Project: https://github.com/sinonjs/lolex -// Definitions by: Wim Looman , Josh Goldberg +// Definitions by: Wim Looman +// Josh Goldberg +// Rogier Schouten // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped /** @@ -34,7 +36,7 @@ type BrowserClock = LolexClock; type NodeClock = LolexClock & { /** * Mimicks process.hrtime(). - * + * * @param prevTime Previous system time to calculate time elapsed. * @returns High resolution real time as [seconds, nanoseconds]. */ @@ -49,7 +51,7 @@ type Clock = BrowserClock | NodeClock; /** * Names of clock methods that may be faked by install. */ -type FakeMethod = "setTimeout" | "clearTimeout" | "setImmediate" | "clearImmediate" | "setInterval" | "clearInterval" | "Date"; +type FakeMethod = "setTimeout" | "clearTimeout" | "setImmediate" | "clearImmediate" | "setInterval" | "clearInterval" | "Date" | "nextTick" | "hrtime"; /** * Controls the flow of time. @@ -67,7 +69,7 @@ export interface LolexClock { /** * Schedules a callback to be fired once timeout milliseconds have ticked by. - * + * * @param callback Callback to be fired. * @param timeout How many ticks to wait to run the callback. * @param args Any extra arguments to pass to the callback. @@ -77,14 +79,14 @@ export interface LolexClock { /** * Clears a timer, as long as it was created using setTimeout. - * + * * @param id Timer ID or object. */ clearTimeout(id: TTimerId): void; /** * Schedules a callback to be fired every time timeout milliseconds have ticked by. - * + * * @param callback Callback to be fired. * @param timeout How many ticks to wait between callbacks. * @param args Any extra arguments to pass to the callback. @@ -94,14 +96,14 @@ export interface LolexClock { /** * Clears a timer, as long as it was created using setInterval. - * + * * @param id Timer ID or object. */ clearInterval(id: TTimerId): void; /** * Schedules the callback to be fired once 0 milliseconds have ticked by. - * + * * @param callback Callback to be fired. * @remarks You'll still have to call clock.tick() for the callback to fire. * @remarks If called during a tick the callback won't fire until 1 millisecond has ticked by. @@ -110,11 +112,16 @@ export interface LolexClock { /** * Clears a timer, as long as it was created using setImmediate. - * + * * @param id Timer ID or object. */ clearImmediate(id: TTimerId): void; + /** + * Simulates process.nextTick(); + */ + nextTick(callback: () => void): void; + /** * Advances the clock to the the moment of the first scheduled timer, firing it. */ @@ -122,14 +129,14 @@ export interface LolexClock { /** * Advance the clock, firing callbacks if necessary. - * + * * @param time How many ticks to advance by. */ tick(time: number | string): void; /** * Runs all pending timers until there are none remaining. - * + * * @remarks If new timers are added while it is executing they will be run as well. */ runAll(): void; @@ -142,7 +149,7 @@ export interface LolexClock { /** * Simulates a user changing the system clock. - * + * * @param now New system time. * @remarks This affects the current time but it does not in itself cause timers to fire. */ @@ -157,7 +164,7 @@ export interface LolexClock { /** * Creates a clock. - * + * * @param now Current time for the clock. * @param loopLimit Maximum number of timers that will be run when calling runAll() * before assuming that we have an infinite loop and throwing an error @@ -167,23 +174,47 @@ export interface LolexClock { */ export declare function createClock(now?: number | Date, loopLimit?: number): TClock; -/** - * Creates a clock and installs it globally. - * - * @param now Current time for the clock, as with lolex.createClock(). - * @param toFake Names of methods that should be faked. - * @type TClock Type of clock to create. - * @usage lolex.install(["setTimeout", "clearTimeout"]); - */ -export declare function install(now?: number | Date, toFake?: FakeMethod[]): TClock; + +export interface LolexInstallOpts { + /** + * Installs lolex onto the specified target context (default: global) + */ + target?: any; + + /** + * Installs lolex with the specified unix epoch (default: 0) + */ + now?: number; + + /** + * An array with explicit function names to hijack. When not set, lolex will automatically fake all methods except nextTick + * e.g., lolex.install({ toFake: ["setTimeout", "nextTick"]}) will fake only setTimeout and nextTick + */ + toFake?: FakeMethod[]; + + /** + * The maximum number of timers that will be run when calling runAll() (default: 1000) + */ + loopLimit?: number; + + /** + * Tells lolex to increment mocked time automatically based on the real system time shift (e.g. the mocked time will be incremented by + * 20ms for every 20ms change in the real system time) (default: false) + */ + shouldAdvanceTime?: boolean; + + /** + * Relevant only when using with shouldAdvanceTime: true. increment mocked time by advanceTimeDelta ms every advanceTimeDelta ms change + * in the real system time (default: 20) + */ + advanceTimeDelta?: number; +} /** - * Creates a clock and installs it onto the context object. - * - * @param context Context to install the clock onto. + * Creates a clock and installs it globally. + * * @param now Current time for the clock, as with lolex.createClock(). * @param toFake Names of methods that should be faked. * @type TClock Type of clock to create. - * @usage lolex.install(context, ["setTimeout", "clearTimeout"]); */ -export declare function install(context?: any, now?: number | Date, toFake?: FakeMethod[]): TClock; +export declare function install(opts: LolexInstallOpts): TClock; diff --git a/types/lolex/lolex-tests.ts b/types/lolex/lolex-tests.ts index 876e4280c5..95b6a2be78 100644 --- a/types/lolex/lolex-tests.ts +++ b/types/lolex/lolex-tests.ts @@ -16,25 +16,14 @@ lolex.createClock(new Date()); lolex.createClock(7, 9001); lolex.createClock(new Date(), 9001); -lolex.install(7); -lolex.install(new Date()); -lolex.install(7, ["setTimeout"]); -lolex.install(new Date(), ["setTimeout"]); - -lolex.install(7); -lolex.install(new Date()); -lolex.install(7, ["setTimeout"]); -lolex.install(new Date(), ["setTimeout"]); - -lolex.install({}, 7); -lolex.install({}, new Date()); -lolex.install({}, 7, ["setTimeout"]); -lolex.install({}, new Date(), ["setTimeout"]); - -lolex.install({}, 7); -lolex.install({}, new Date()); -lolex.install({}, 7, ["setTimeout"]); -lolex.install({}, new Date(), ["setTimeout"]); +lolex.install({ + advanceTimeDelta: 20, + loopLimit: 10, + now: 0, + shouldAdvanceTime: true, + target: {}, + toFake: ["setTimeout", "nextTick", "hrtime"] +}); const browserNow: number = browserClock.now; const browserDate: Date = new browserClock.Date(); @@ -80,5 +69,7 @@ nodeClock.setSystemTime(); nodeClock.setSystemTime(7); nodeClock.setSystemTime(new Date()); +nodeClock.nextTick(() => undefined); + browserClock.uninstall(); nodeClock.uninstall(); diff --git a/types/lusca/index.d.ts b/types/lusca/index.d.ts new file mode 100644 index 0000000000..8527ef3411 --- /dev/null +++ b/types/lusca/index.d.ts @@ -0,0 +1,78 @@ +// Type definitions for lusca 1.5 +// Project: https://github.com/krakenjs/lusca#readme +// Definitions by: Corbin Crutchley +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.2 + +import express = require('express'); + +declare function lusca(options?: lusca.LuscaOptions): express.RequestHandler; + +declare namespace lusca { + /*~ Documentation declares that: + *~ Setting any value to false will disable it. + */ + interface LuscaOptions { + csrf?: csrfOptions | boolean; + csp?: cspOptions | false; + xframe?: string | false; + p3p?: string | false; + hsts?: hstsOptions | false; + xssProtection?: xssProtectionOptions | boolean; + nosniff?: boolean; + referrerPolicy?: string | false; + } + + interface cspOptions { + policy?: string | object | Array; + reportOnly?: boolean; + reportUri?: string; + styleNonce?: boolean; + scriptNonce?: boolean; + } + + interface hstsOptions { + maxAge?: number; + includeSubDomains?: boolean; + preload?: boolean; + } + + type csrfOptions = csrfOptionsAngular | csrfOptionsNonAngular; + + interface csrfOptionsAngular { + key?: string; + secret?: string; + impl?: () => any; + cookie?: string | { + options?: object; + }; + angular: true; + } + + interface csrfOptionsNonAngular { + key?: string; + secret?: string; + impl?: () => any; + cookie?: string | { + name: string; + options?: object; + }; + angular?: false; + } + + interface xssProtectionOptions { + enabled?: boolean; + mode?: string; + } + + function csrf(options?: csrfOptions): express.RequestHandler; + function csp(options?: cspOptions): express.RequestHandler; + function xframe(value: string): express.RequestHandler; + function p3p(value: string): express.RequestHandler; + function hsts(options?: hstsOptions): express.RequestHandler; + function xssProtection(options?: xssProtectionOptions | true): express.RequestHandler; + function nosniff(): express.RequestHandler; + function referrerPolicy(value: string): express.RequestHandler; +} + +export = lusca; diff --git a/types/lusca/lusca-tests.ts b/types/lusca/lusca-tests.ts new file mode 100644 index 0000000000..8a74ec5e8a --- /dev/null +++ b/types/lusca/lusca-tests.ts @@ -0,0 +1,24 @@ +import express = require('express'); +import lusca = require('lusca'); + +const app = express(); + +app.use(lusca({ + csrf: true, + csp: { policy: "referrer no-referrer"}, + xframe: 'SAMEORIGIN', + p3p: 'ABCDEF', + hsts: {maxAge: 31536000, includeSubDomains: true, preload: true}, + xssProtection: true, + nosniff: true, + referrerPolicy: 'same-origin' +})); + +app.use(lusca.csrf()); +app.use(lusca.csp({policy: [{ "img-src": "'self' http:" }, "block-all-mixed-content"], reportOnly: false})); +app.use(lusca.xframe('SAMEORIGIN')); +app.use(lusca.p3p('ABCDEF')); +app.use(lusca.hsts({ maxAge: 31536000 })); +app.use(lusca.xssProtection(true)); +app.use(lusca.nosniff()); +app.use(lusca.referrerPolicy('same-origin')); diff --git a/types/lusca/tsconfig.json b/types/lusca/tsconfig.json new file mode 100644 index 0000000000..ede7926c1c --- /dev/null +++ b/types/lusca/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", + "lusca-tests.ts" + ] +} diff --git a/types/lusca/tslint.json b/types/lusca/tslint.json new file mode 100644 index 0000000000..3db14f85ea --- /dev/null +++ b/types/lusca/tslint.json @@ -0,0 +1 @@ +{ "extends": "dtslint/dt.json" } diff --git a/types/mapbox-gl/index.d.ts b/types/mapbox-gl/index.d.ts index 6be9a465ef..ddaafced3d 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.40.1 +// Type definitions for Mapbox GL JS v0.41.0 // Project: https://github.com/mapbox/mapbox-gl-js // Definitions by: Dominik Bruderer , Patrick Reames // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped @@ -901,7 +901,7 @@ declare namespace mapboxgl { export interface Layer { id: string; - type?: "fill" | "line" | "symbol" | "circle" | "fill-extrusion" | "raster" | "background"; + type?: "fill" | "line" | "symbol" | "circle" | "fill-extrusion" | "raster" | "background" | "heatmap"; metadata?: any; ref?: string; diff --git a/types/mixpanel/index.d.ts b/types/mixpanel/index.d.ts index 4964a55c79..08bbe26720 100644 --- a/types/mixpanel/index.d.ts +++ b/types/mixpanel/index.d.ts @@ -1,4 +1,4 @@ -// Type definitions for Mixpanel 2.13 +// Type definitions for Mixpanel 2.14 // Project: https://mixpanel.com/ // https://github.com/mixpanel/mixpanel-js // Definitions by: Knut Eirik Leira Hjelle @@ -348,6 +348,21 @@ declare namespace Mixpanel { set_once(prop: string, value: any, callback?: () => void): void; set_once(keys: { [index: string]: any }, callback?: () => void): void; + /** + * Unset properties on a user record (permanently removes the properties and their values from a profile). + * + * ### Usage: + * + * mixpanel.people.unset('gender'); + * + * // or unset multiple properties at once + * mixpanel.people.unset(['gender', 'Company']); + * + * @param prop If a string, this is the name of the property. If an array, this is a list of property names. + * @param callback If provided, the callback will be called after the tracking event + */ + unset(prop: string | string[], callback?: () => void): void; + /** * Increment/decrement numeric people analytics properties. * diff --git a/types/mixpanel/mixpanel-tests.ts b/types/mixpanel/mixpanel-tests.ts index b1d735c22e..a48cd4065a 100644 --- a/types/mixpanel/mixpanel-tests.ts +++ b/types/mixpanel/mixpanel-tests.ts @@ -95,6 +95,11 @@ function mixpanel_people() { 'Starting Plan': 'Premium' }, () => {}); + mixpanel.people.unset('Company'); + mixpanel.people.unset('Company', () => {}); + mixpanel.people.unset(['Company', 'Plan']); + mixpanel.people.unset(['Company', 'Plan'], () => {}); + mixpanel.people.increment('page_views'); mixpanel.people.increment('page_views', 1); mixpanel.people.increment('credits_left', -1); diff --git a/types/mobx-apollo/index.d.ts b/types/mobx-apollo/index.d.ts new file mode 100644 index 0000000000..4054601717 --- /dev/null +++ b/types/mobx-apollo/index.d.ts @@ -0,0 +1,29 @@ +// Type definitions for mobx-apollo 0.0 +// Project: https://github.com/sonaye/mobx-apollo#readme +// Definitions by: Paul Selden +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.3 + +import { + ApolloClient, + ObservableQuery, + WatchQueryOptions, + ApolloError +} from 'apollo-client'; + +export interface MobxApolloQueryOptions extends WatchQueryOptions { + client: ApolloClient; + onFetch?: (result: T) => void; + onError?: (error: ApolloError) => void; +} + +export interface MobxApolloQuery { + loading: boolean; + data: T; + error?: ApolloError; + ref: ObservableQuery; +} + +export default function graphql( + options: MobxApolloQueryOptions +): MobxApolloQuery; diff --git a/types/mobx-apollo/mobx-apollo-tests.ts b/types/mobx-apollo/mobx-apollo-tests.ts new file mode 100644 index 0000000000..964e6b0c6e --- /dev/null +++ b/types/mobx-apollo/mobx-apollo-tests.ts @@ -0,0 +1,34 @@ +import { ApolloClient } from 'apollo-client'; +import query from 'mobx-apollo'; + +const PostsQuery = ` + { + posts { + id + title + } + } +` as any; + +interface Post { + id: string; + title: string; +} + +class PostStore { + private get postsQuery() { + return query<{ posts: Post[] }>({ + client: new ApolloClient({ + link: {} as any, + cache: {} as any + }), + query: PostsQuery + }); + } + + get posts() { + return this.postsQuery.data.posts; + } +} + +new PostStore(); diff --git a/types/mobx-apollo/package.json b/types/mobx-apollo/package.json new file mode 100644 index 0000000000..da0ffc3953 --- /dev/null +++ b/types/mobx-apollo/package.json @@ -0,0 +1,6 @@ +{ + "private": true, + "dependencies": { + "apollo-client": "^2.0.0" + } +} diff --git a/types/mobx-apollo/tsconfig.json b/types/mobx-apollo/tsconfig.json new file mode 100644 index 0000000000..c4c2acace4 --- /dev/null +++ b/types/mobx-apollo/tsconfig.json @@ -0,0 +1,17 @@ +{ + "compilerOptions": { + "module": "commonjs", + "lib": ["es6"], + "target": "es5", + "noImplicitAny": true, + "noImplicitThis": true, + "strictNullChecks": true, + "strictFunctionTypes": true, + "baseUrl": "../", + "typeRoots": ["../"], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true + }, + "files": ["index.d.ts", "mobx-apollo-tests.ts"] +} diff --git a/types/mobx-apollo/tslint.json b/types/mobx-apollo/tslint.json new file mode 100644 index 0000000000..3db14f85ea --- /dev/null +++ b/types/mobx-apollo/tslint.json @@ -0,0 +1 @@ +{ "extends": "dtslint/dt.json" } diff --git a/types/moment-timezone/index.d.ts b/types/moment-timezone/index.d.ts index a839b093c4..ca62b3cb82 100644 --- a/types/moment-timezone/index.d.ts +++ b/types/moment-timezone/index.d.ts @@ -18,6 +18,7 @@ declare module "moment" { abbr(timestamp: number): string; offset(timestamp: number): number; + utcOffset(timestamp: number): number; parse(timestamp: number): number; } diff --git a/types/moment-timezone/moment-timezone-tests.ts b/types/moment-timezone/moment-timezone-tests.ts index 9e3e720d24..14df62915b 100644 --- a/types/moment-timezone/moment-timezone-tests.ts +++ b/types/moment-timezone/moment-timezone-tests.ts @@ -49,7 +49,7 @@ moment.tz(mo, "America/Los_Angeles"); moment.tz(obj, "America/Los_Angeles"); moment.tz.zone('America/Los_Angeles').abbr(1403465838805); -moment.tz.zone('America/Los_Angeles').offset(1403465838805); +moment.tz.zone('America/Los_Angeles').utcOffset(1403465838805); const zone = moment.tz.zone('America/New_York'); zone.parse(Date.UTC(2012, 2, 19, 8, 30)); // 240 diff --git a/types/mongodb/index.d.ts b/types/mongodb/index.d.ts index 19cf0136e2..32bc523d38 100644 --- a/types/mongodb/index.d.ts +++ b/types/mongodb/index.d.ts @@ -5,6 +5,7 @@ // Gady Piazza // Jason Dreyzehner // Gaurav Lahoti +// Mariano Cortesi // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped // TypeScript Version: 2.3 @@ -146,6 +147,9 @@ export interface DbCreateOptions { promiseLibrary?: Object; // https://docs.mongodb.com/manual/reference/read-concern/#read-concern readConcern?: { level?: Object }; + // Sets a cap on how many operations the driver will buffer up before giving up on getting a + // working connection, default is -1 which is unlimited. + bufferMaxEntries?: number; } // http://mongodb.github.io/node-mongodb-native/2.2/api/Server.html diff --git a/types/mongodb/mongodb-tests.ts b/types/mongodb/mongodb-tests.ts index 2b8c49d186..52f2d6e4f8 100644 --- a/types/mongodb/mongodb-tests.ts +++ b/types/mongodb/mongodb-tests.ts @@ -3,7 +3,7 @@ import mongodb = require('mongodb'); var MongoClient = mongodb.MongoClient; var format = require('util').format; -let options = { +let options: mongodb.MongoClientOptions = { authSource : ' ', w : 1, wtimeout : 300, diff --git a/types/mongoose/index.d.ts b/types/mongoose/index.d.ts index b819e37ad9..f86dea4f8a 100644 --- a/types/mongoose/index.d.ts +++ b/types/mongoose/index.d.ts @@ -1622,7 +1622,7 @@ declare module "mongoose" { * getters/setters or other Mongoose magic applied. * @param bool defaults to true */ - lean(bool?: boolean): Query; + lean(bool?: boolean): Query; /** Specifies the maximum number of documents the query will return. Cannot be used with distinct() */ limit(val: number): this; diff --git a/types/mongoose/mongoose-tests.ts b/types/mongoose/mongoose-tests.ts index d6f262ebf6..9fe20cd8ad 100644 --- a/types/mongoose/mongoose-tests.ts +++ b/types/mongoose/mongoose-tests.ts @@ -385,8 +385,14 @@ Animal['findByName']('fido', function(err: any, animals: any) { animalSchema.virtual('name.full').get(function () { return this.name.first + ' ' + this.name.last; }); -new mongoose.Schema({ - child: { name: String } +var childSchema = new mongoose.Schema({ name: String }); +var parentSchema = new mongoose.Schema({ + children: [childSchema], + child: childSchema, + name: { + index: true, + required: true + } }); new mongoose.Schema({ eggs: { @@ -1349,6 +1355,17 @@ MongoModel.findOne({ type: 'iphone' }, 'name').exec(function (err, adventure) {} MongoModel.findOne({ type: 'iphone' }, 'name', { lean: true }, cb); MongoModel.findOne({ type: 'iphone' }, 'name', { lean: true }).exec(cb); MongoModel.findOne({ type: 'iphone' }).select('name').lean().exec(cb); +interface ModelUser { + _id: any; + name: string; + abctest: string; +} +MongoModel.findOne({ type: 'iphone' }).select('name').lean().exec() +.then(function(doc: ModelUser) { + doc._id; + doc.name; + doc.abctest; +}); MongoModel.findOneAndRemove({}, {}, cb); MongoModel.findOneAndRemove({}, {}); MongoModel.findOneAndRemove({}, cb); diff --git a/types/moxios/index.d.ts b/types/moxios/index.d.ts index b4ca5580fd..b0cc379fef 100644 --- a/types/moxios/index.d.ts +++ b/types/moxios/index.d.ts @@ -3,7 +3,7 @@ // Definitions by: Asuka Ito // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -import { AxiosInstance } from "axios"; +import { AxiosInstance, AxiosRequestConfig } from "axios"; interface Item { response?: any; @@ -75,7 +75,14 @@ declare class Request { * @param reject The function to call when Promise is rejected * @param config The config object to be used for the request */ - constructor(resolve: (arg: any) => void, reject: (arg: any) => void, config: any); + constructor(resolve: (arg: any) => void, reject: (arg: any) => void, config: AxiosRequestConfig); + + config: AxiosRequestConfig; + headers: any; + url: string; + timeout: number; + withCredentials: boolean; + responseType: string; /** * Respond to this request with a timeout result @@ -102,12 +109,13 @@ declare class Response { */ constructor(req: Request, res: any); - config: any; + config: AxiosRequestConfig; data?: any; status?: number; statusText?: string; headers: any; request: Request; + code?: string; } declare let moxios: { diff --git a/types/mysql/index.d.ts b/types/mysql/index.d.ts index 7260dc2e85..7d3281218f 100644 --- a/types/mysql/index.d.ts +++ b/types/mysql/index.d.ts @@ -2,6 +2,7 @@ // Project: https://github.com/mysqljs/mysql // Definitions by: William Johnston // Kacper Polak +// Krittanan Pingclasai // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped // TypeScript Version: 2.1 @@ -422,7 +423,7 @@ export interface ConnectionConfig extends ConnectionOptions { /** * object with ssl parameters or a string containing name of ssl profile */ - ssl?: tls.SecureContextOptions & { rejectUnauthorized?: boolean }; + ssl?: string | (tls.SecureContextOptions & { rejectUnauthorized?: boolean }); } export interface PoolConfig extends ConnectionConfig { diff --git a/types/mysql/mysql-tests.ts b/types/mysql/mysql-tests.ts index a708aa6163..a3ddb27248 100644 --- a/types/mysql/mysql-tests.ts +++ b/types/mysql/mysql-tests.ts @@ -39,6 +39,11 @@ connection.query('SELECT 1', (err, rows) => { // connected! (unless `err` is set) }); +connection = mysql.createConnection({ + host: 'localhost', + ssl: 'Amazon RDS' +}); + connection = mysql.createConnection({ host: 'localhost', ssl: { diff --git a/types/nightwatch/index.d.ts b/types/nightwatch/index.d.ts index 3a7e81d0fa..a32a07b3dd 100644 --- a/types/nightwatch/index.d.ts +++ b/types/nightwatch/index.d.ts @@ -4,8 +4,6 @@ // Connor Schlesiger // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -/* tslint:disable:max-line-length */ - export interface NightwatchCustomPageObjects { page: {}; } @@ -887,7 +885,7 @@ export interface NightwatchAPI { * @param callback: Optional callback function to be called when the command finishes. * @returns The value of the attribute */ - getAttribute(selector: string, attribute: string, callback?: (result: NightwatchCallbackResult) => void): this; + getAttribute(selector: string, attribute: string, callback?: (this: NightwatchAPI, result: NightwatchCallbackResult) => void): this; /** * Retrieve a single cookie visible to the current page. The cookie is returned as a cookie JSON object, as defined here. @@ -906,7 +904,7 @@ export interface NightwatchAPI { * @param callback: The callback function which will receive the response as an argument. * @returns The cookie object as a selenium cookie JSON object or null if the cookie wasn't found. */ - getCookie(name: string, callback?: (result: NightwatchCallbackResult) => void): this; + getCookie(name: string, callback?: (this: NightwatchAPI, result: NightwatchCallbackResult) => void): this; /** * Retrieve all cookies visible to the current page. The cookies are returned as an array of cookie JSON object, @@ -924,7 +922,7 @@ export interface NightwatchAPI { * @param callback: The callback function which will receive the response as an argument. * @returns A list of cookies */ - getCookies(callback?: (result: NightwatchCallbackResult) => void): this; + getCookies(callback?: (this: NightwatchAPI, result: NightwatchCallbackResult) => void): this; /** * Retrieve the value of a css property for a given DOM element. Uses elementIdCssProperty protocol command. @@ -944,7 +942,7 @@ export interface NightwatchAPI { * @param callback: Optional callback function to be called when the command finishes. * @returns The value of the css property */ - getCssProperty(selector: string, cssProperty: string, callback?: (result: NightwatchCallbackResult) => void): this; + getCssProperty(selector: string, cssProperty: string, callback?: (this: NightwatchAPI, result: NightwatchCallbackResult) => void): this; /** * Determine an element's size in pixels. Uses elementIdSize protocol command. @@ -964,7 +962,7 @@ export interface NightwatchAPI { * @param callback: Optional callback function to be called when the command finishes. * @returns The width and height of the element in pixels */ - getElementSize(selector: string, callback?: (result: NightwatchCallbackResult) => void): this; + getElementSize(selector: string, callback?: (this: NightwatchAPI, result: NightwatchCallbackResult) => void): this; /** * Determine an element's location on the page. The point (0, 0) refers to the upper-left corner of the page. @@ -985,7 +983,7 @@ export interface NightwatchAPI { * @param callback: Optional callback function to be called when the command finishes. * @returns The X and Y coordinates for the element on the page */ - getLocation(selector: string, callback?: (result: NightwatchCallbackResult) => void): this; + getLocation(selector: string, callback?: (this: NightwatchAPI, result: NightwatchCallbackResult) => void): this; /** * Determine an element's location on the screen once it has been scrolled into view. Uses elementIdLocationInView protocol command. @@ -1005,7 +1003,7 @@ export interface NightwatchAPI { * @param callback: Optional callback function to be called when the command finishes. * @returns The X and Y coordinates for the element on the page. */ - getLocationInView(selector: string, callback?: (result: NightwatchCallbackResult) => void): this; + getLocationInView(selector: string, callback?: (this: NightwatchAPI, result: NightwatchCallbackResult) => void): this; /** * Gets a log from selenium @@ -1059,7 +1057,7 @@ export interface NightwatchAPI { * @param callback: Optional callback function to be called when the command finishes. * @returns The element's tag name, as a lowercase string. */ - getTagName(selector: string, callback?: (result: NightwatchCallbackResult) => void): this; + getTagName(selector: string, callback?: (this: NightwatchAPI, result: NightwatchCallbackResult) => void): this; /** * Returns the visible text for the element. Uses elementIdText protocol command. @@ -1078,7 +1076,7 @@ export interface NightwatchAPI { * @param callback: Optional callback function to be called when the command finishes. * @returns The element's visible text. */ - getText(selector: string, callback?: (result: NightwatchCallbackResult) => void): this; + getText(selector: string, callback?: (this: NightwatchAPI, result: NightwatchCallbackResult) => void): this; /** * Returns the title of the current page. Uses title protocol command. @@ -1095,7 +1093,7 @@ export interface NightwatchAPI { * @param callback: Optional callback function to be called when the command finishes. * @returns The page title. */ - getTitle(callback?: (result: NightwatchCallbackResult) => void): this; + getTitle(callback?: (this: NightwatchAPI, result?: string) => void): this; /** * Returns a form element current value. Uses elementIdValue protocol command. @@ -1114,7 +1112,7 @@ export interface NightwatchAPI { * @param callback: Optional callback function to be called when the command finishes. * @returns The element's value. */ - getValue(selector: string, callback?: (result: NightwatchCallbackResult) => void): this; + getValue(selector: string, callback?: (this: NightwatchAPI, result: NightwatchCallbackResult) => void): this; /** * This command is an alias to url and also a convenience method when called without any arguments in the sense that it performs a call to .url() with passing the value of launch_url @@ -1180,7 +1178,7 @@ export interface NightwatchAPI { * @param selector: The CSS/Xpath selector used to locate the element. * @param callback: Optional callback function to be called when the command finishes. */ - isVisible(selector: string, callback?: (result: NightwatchCallbackResult) => void): this; + isVisible(selector: string, callback?: (this: NightwatchAPI, result: NightwatchCallbackResult) => void): this; /** * Maximizes the current window. @@ -1559,7 +1557,9 @@ export interface NightwatchAPI { * ``` * @param selector: The selector (CSS / Xpath) used to locate the element. * @param time: The number of milliseconds to wait. The runner performs repeated checks every 500 ms. - * @param abortOnFailure: By the default if the element is not found the test will fail. Set this to false if you wish for the test to continue even if the assertion fails. To set this globally you can define a property `abortOnNightwatchAssertionsFailure` in your globals. + * @param abortOnFailure: By the default if the element is not found the test will fail. + * Set this to false if you wish for the test to continue even if the assertion fails. + * To set this globally you can define a property `abortOnNightwatchAssertionsFailure` in your globals. * @param callback: Optional callback function to be called when the command finishes. * @param message: Optional message to be shown in the output; the message supports two placeholders: %s for current selector and %d for the time (e.g. Element %s was not in the page for %d ms). */ @@ -1847,7 +1847,8 @@ export interface NightwatchAPI { /** * Send a sequence of key strokes to the active element. The sequence is defined in the same format as the sendKeys command. * An object map with available keys and their respective UTF-8 characters, as defined on W3C WebDriver draft spec, is loaded onto the main Nightwatch instance as client.Keys. - * Rather than the setValue, the modifiers are not released at the end of the call. The state of the modifier keys is kept between calls, so mouse interactions can be performed while modifier keys are depressed. + * Rather than the setValue, the modifiers are not released at the end of the call. + * The state of the modifier keys is kept between calls, so mouse interactions can be performed while modifier keys are depressed. * @param keysToSend: The keys sequence to be sent. * @param callback: Optional callback function to be called when the command finishes. */ @@ -1862,8 +1863,10 @@ export interface NightwatchAPI { mouseButtonClick(button: string, callback?: () => void): this; /** - * Click and hold the left mouse button (at the coordinates set by the last moveto command). Note that the next mouse-related command that should follow is mouseButtonUp . Any other mouse command (such as click or another call to buttondown) will yield undefined behaviour. - * Can be used for implementing drag-and-drop. The button can be (0, 1, 2) or ('left', 'middle', 'right'). It defaults to left mouse button, and if you don't pass in a button but do pass in a callback, it will handle it correctly. + * Click and hold the left mouse button (at the coordinates set by the last moveto command). Note that the next mouse-related command that should follow is mouseButtonUp . + * Any other mouse command (such as click or another call to buttondown) will yield undefined behaviour. + * Can be used for implementing drag-and-drop. The button can be (0, 1, 2) or ('left', 'middle', 'right'). + * It defaults to left mouse button, and if you don't pass in a button but do pass in a callback, it will handle it correctly. * @param button: The mouse button * @param callback: Optional callback function to be called when the command finishes. */ @@ -1871,14 +1874,16 @@ export interface NightwatchAPI { /** * Releases the mouse button previously held (where the mouse is currently at). Must be called once for every mouseButtonDown command issued. - * Can be used for implementing drag-and-drop. The button can be (0, 1, 2) or ('left', 'middle', 'right'). It defaults to left mouse button, and if you don't pass in a button but do pass in a callback, it will handle it correctly. + * Can be used for implementing drag-and-drop. The button can be (0, 1, 2) or ('left', 'middle', 'right'). + * It defaults to left mouse button, and if you don't pass in a button but do pass in a callback, it will handle it correctly. * @param button: The mouse button * @param callback: Optional callback function to be called when the command finishes. */ mouseButtonUp(button: string, callback?: () => void): this; /** - * Move the mouse by an offset of the specificed element. If no element is specified, the move is relative to the current mouse cursor. If an element is provided but no offset, the mouse will be moved to the center of the element. + * Move the mouse by an offset of the specificed element. If no element is specified, the move is relative to the current mouse cursor. + * If an element is provided but no offset, the mouse will be moved to the center of the element. * If the element is not visible, it will be scrolled into view. * @param element: Opaque ID assigned to the element to move to. If not specified or is null, the offset is relative to current position of the mouse. * @param xofset: X offset to move to, relative to the top-left corner of the element. If not specified, the mouse will move to the middle of the element. @@ -1997,14 +2002,16 @@ export interface NightwatchAPI { /** * Configure the amount of time that a particular type of operation can execute for before they are aborted and a |Timeout| error is returned to the client. - * @param typeOfOperation: The type of operation to set the timeout for. Valid values are: "script" for script timeouts, "implicit" for modifying the implicit wait timeout and "page load" for setting a page load timeout. + * @param typeOfOperation: The type of operation to set the timeout for. + * Valid values are: "script" for script timeouts, "implicit" for modifying the implicit wait timeout and "page load" for setting a page load timeout. * @param ms: The amount of time, in milliseconds, that time-limited commands are permitted to run. * @param callback: Optional callback function to be called when the command finishes. */ timeouts(typeOfOperation: string, ms: number, callback?: () => void): this; /** - * Set the amount of time, in milliseconds, that asynchronous scripts executed by /session/:sessionId/execute_async are permitted to run before they are aborted and a |Timeout| error is returned to the client. + * Set the amount of time, in milliseconds, that asynchronous scripts executed by /session/:sessionId/execute_async are permitted + * to run before they are aborted and a |Timeout| error is returned to the client. * @param ms: The amount of time, in milliseconds, that time-limited commands are permitted to run. * @param callback: Optional callback function to be called when the command finishes. */ @@ -2087,7 +2094,8 @@ export interface NightwatchAPI { windowMaximize(handleOrName?: string, callback?: () => void): this; /** - * Change or get the position of the specified window. If the second argument is a function it will be used as a callback and the call will perform a get request to retrieve the existing window position. + * Change or get the position of the specified window. If the second argument is a function it will be used as a callback and the call + * will perform a get request to retrieve the existing window position. * @param windowHandle: * @param: offsetX: * @param: offsetY: @@ -2199,5 +2207,3 @@ export interface Nightwatch { api: NightwatchAPI; client: NightwatchClient; } - -/* tslint:enable:max-line-length */ diff --git a/types/nightwatch/nightwatch-tests.ts b/types/nightwatch/nightwatch-tests.ts index a40c8c466a..548dcee9bd 100644 --- a/types/nightwatch/nightwatch-tests.ts +++ b/types/nightwatch/nightwatch-tests.ts @@ -7,6 +7,9 @@ const test: NightwatchTests = { .waitForElementVisible('body', 1000) .setValue('input[type=text]', 'nightwatch') .waitForElementVisible('button[name=btnG]', 1000) + .getTitle(function(result) { + this.assert.equal(typeof result, 'string'); + }) .click('button[name=btnG]') .pause(1000) .assert.containsText('#main', 'Night Watch') diff --git a/types/nightwatch/tslint.json b/types/nightwatch/tslint.json index b1439230db..495d29983d 100644 --- a/types/nightwatch/tslint.json +++ b/types/nightwatch/tslint.json @@ -1,7 +1,5 @@ { "extends": "dtslint/dt.json", "rules": { - // TODO - "no-any-union": false } } diff --git a/types/passport-facebook-token/index.d.ts b/types/passport-facebook-token/index.d.ts index 9013910ee1..9877b84527 100644 --- a/types/passport-facebook-token/index.d.ts +++ b/types/passport-facebook-token/index.d.ts @@ -7,15 +7,17 @@ import * as passport from 'passport'; import * as express from 'express'; -declare class Strategy implements passport.Strategy { - constructor(options: Strategy.StrategyOptionsWithRequest, verify: Strategy.VerifyFunctionWithRequest) - constructor(options: Strategy.StrategyOptions, verify: Strategy.VerifyFunction); +declare namespace PassportFacebookToken { + interface StrategyStatic { + new(options: StrategyOptionsWithRequest, verify: VerifyFunctionWithRequest): StrategyInstance; + new(options: StrategyOptions, verify: VerifyFunction): StrategyInstance; + } - name: string; - authenticate: (req: express.Request, options?: any) => void; -} + interface StrategyInstance { + name: string; + authenticate: (req: express.Request, options?: any) => void; + } -declare namespace Strategy { interface ValueObject { value: string; } @@ -55,4 +57,5 @@ declare namespace Strategy { type VerifyFunctionWithRequest = (req: express.Request, accessToken: string, refreshToken: string, profile: Profile, done: (error: any, user?: any, info?: any) => void) => void; } -export = Strategy; +declare const PassportFacebookToken: PassportFacebookToken.StrategyStatic; +export = PassportFacebookToken; diff --git a/types/passport-facebook-token/passport-facebook-token-tests.ts b/types/passport-facebook-token/passport-facebook-token-tests.ts index cb2f078e88..c926748286 100644 --- a/types/passport-facebook-token/passport-facebook-token-tests.ts +++ b/types/passport-facebook-token/passport-facebook-token-tests.ts @@ -1,8 +1,6 @@ import * as express from 'express'; import * as passport from 'passport'; -import * as FacebookStrategy from 'passport-facebook-token'; -// tslint:disable-next-line:no-duplicate-imports -import { StrategyOptions, StrategyOptionsWithRequest, VerifyFunction, VerifyFunctionWithRequest, Profile } from 'passport-facebook-token'; +import * as PassportFacebookToken from 'passport-facebook-token'; const User = { findOrCreate(id: string, provider: string, callback: (err: any, user: any) => void): void { @@ -10,18 +8,19 @@ const User = { } }; -const options: StrategyOptions = { +const options: PassportFacebookToken.StrategyOptions = { clientID: 'TEST_CLIENT_ID', clientSecret: 'TEST_CLIENT_SECRET' }; -const optionsWithRequest: StrategyOptionsWithRequest = { +const optionsWithRequest: PassportFacebookToken.StrategyOptionsWithRequest = { clientID: 'TEST_CLIENT_ID', clientSecret: 'TEST_CLIENT_SECRET', passReqToCallback: true }; -const verify: VerifyFunction = (accessToken: string, refreshToken: string, profile: Profile, done: (err: any, user?: any, info?: any) => void) => { +const verify: PassportFacebookToken.VerifyFunction = + (accessToken: string, refreshToken: string, profile: PassportFacebookToken.Profile, done: (err: any, user?: any, info?: any) => void) => { User.findOrCreate(profile.id, profile.provider, (err, user) => { if (err) { done(err); @@ -30,7 +29,8 @@ const verify: VerifyFunction = (accessToken: string, refreshToken: string, profi }); }; -const verifyWithRequest: VerifyFunctionWithRequest = (req: express.Request, accessToken: string, refreshToken: string, profile: Profile, done: (err: any, user?: any, info?: any) => void) => { +const verifyWithRequest: PassportFacebookToken.VerifyFunctionWithRequest = + (req: express.Request, accessToken: string, refreshToken: string, profile: PassportFacebookToken.Profile, done: (err: any, user?: any, info?: any) => void) => { User.findOrCreate(profile.id, profile.provider, (err, user) => { if (err) { done(err); @@ -39,5 +39,5 @@ const verifyWithRequest: VerifyFunctionWithRequest = (req: express.Request, acce }); }; -passport.use(new FacebookStrategy(options, verify)); -passport.use(new FacebookStrategy(optionsWithRequest, verifyWithRequest)); +passport.use(new PassportFacebookToken(options, verify)); +passport.use(new PassportFacebookToken(optionsWithRequest, verifyWithRequest)); diff --git a/types/pdfjs-dist/index.d.ts b/types/pdfjs-dist/index.d.ts index a40c612d5a..f72d70f44e 100644 --- a/types/pdfjs-dist/index.d.ts +++ b/types/pdfjs-dist/index.d.ts @@ -407,6 +407,12 @@ declare namespace PDF { * in browsers which support the fullscreen API. */ disableFullscreen: boolean; + + /** + * Disable the text layer of PDF when used PDF.js renders a canvas instead of div elements + * + */ + disableTextLayer: boolean; /** * Enables CSS only zooming. @@ -475,5 +481,11 @@ declare namespace PDF { : PDFPromise; PDFViewer(params: PDFViewerParams): void; + /** + * yet another viewer, this will render only one page at the time, reducing rendering time + * very important for mobile development + * @params {PDFViewerParams} + */ + PDFSinglePageViewer(params: PDFViewerParams): void; } } diff --git a/types/pg/index.d.ts b/types/pg/index.d.ts index 68fba5fb40..62208830b3 100644 --- a/types/pg/index.d.ts +++ b/types/pg/index.d.ts @@ -1,4 +1,4 @@ -// Type definitions for pg 7.1 +// Type definitions for pg 7.4 // Project: https://github.com/brianc/node-postgres // Definitions by: Phips Peter // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped @@ -47,6 +47,7 @@ export interface QueryConfig { name?: string; text: string; values?: any[]; + rowMode?: string; } export interface QueryResult { diff --git a/types/pixelmatch/index.d.ts b/types/pixelmatch/index.d.ts new file mode 100644 index 0000000000..0a2e4277ac --- /dev/null +++ b/types/pixelmatch/index.d.ts @@ -0,0 +1,30 @@ +// Type definitions for pixelmatch 4.0 +// Project: https://github.com/mapbox/pixelmatch#readme +// Definitions by: Oleg Repin +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +/// + +declare function Pixelmatch( + /** Image data of the first image to compare. Note: image dimensions must be equal. */ + img1: Buffer | Uint8Array, + /** Image data of the second image to compare. Note: image dimensions must be equal. */ + img2: Buffer | Uint8Array, + /** Image data to write the diff to, or null if don't need a diff image. */ + output: Buffer | Uint8Array | null, + /** Width of the images. Note that all three images need to have the same dimensions. */ + width: number, + /** Height of the images. Note that all three images need to have the same dimensions. */ + height: number, + /** Options. */ + options?: Options, +): number; + +interface Options { + /** Matching threshold, ranges from 0 to 1. Smaller values make the comparison more sensitive. 0.1 by default. */ + readonly threshold?: number; + /** If true, disables detecting and ignoring anti-aliased pixels. false by default. */ + readonly includeAA?: boolean; +} + +export = Pixelmatch; diff --git a/types/pixelmatch/pixelmatch-tests.ts b/types/pixelmatch/pixelmatch-tests.ts new file mode 100644 index 0000000000..dc49f7f326 --- /dev/null +++ b/types/pixelmatch/pixelmatch-tests.ts @@ -0,0 +1,27 @@ +/** + * This test code taken from pixelmatch example usage. + * https://github.com/mapbox/pixelmatch#example-usage + */ + +import * as fs from 'fs'; +import pixelmatch = require('pixelmatch'); +import { PNG } from 'pngjs'; + +const img1 = fs.createReadStream('img1.png') + .pipe(new PNG()) + .on('parsed', doneReading); + +const img2 = fs.createReadStream('img2.png') + .pipe(new PNG()) + .on('parsed', doneReading); + +let filesRead = 0; + +function doneReading() { + if (++filesRead < 2) return; + const diff = new PNG({width: img1.width, height: img1.height}); + + pixelmatch(img1.data, img2.data, diff.data, img1.width, img1.height, {threshold: 0.1}); + + diff.pack().pipe(fs.createWriteStream('diff.png')); +} diff --git a/types/pixelmatch/tsconfig.json b/types/pixelmatch/tsconfig.json new file mode 100644 index 0000000000..02115e3fdc --- /dev/null +++ b/types/pixelmatch/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", + "pixelmatch-tests.ts" + ] +} diff --git a/types/pixelmatch/tslint.json b/types/pixelmatch/tslint.json new file mode 100644 index 0000000000..3db14f85ea --- /dev/null +++ b/types/pixelmatch/tslint.json @@ -0,0 +1 @@ +{ "extends": "dtslint/dt.json" } diff --git a/types/plotly.js/index.d.ts b/types/plotly.js/index.d.ts index a34dbf2ab8..81286fe0a4 100644 --- a/types/plotly.js/index.d.ts +++ b/types/plotly.js/index.d.ts @@ -94,23 +94,30 @@ export function downloadImage(root: Root, opts: DownloadImgopts): Promise; autosize: boolean; showlegend: boolean; - xaxis: Partial; - yaxis: Partial; - yaxis2: Partial; - yaxis3: Partial; - yaxis4: Partial; - yaxis5: Partial; - yaxis6: Partial; - yaxis7: Partial; - yaxis8: Partial; - yaxis9: Partial; + paper_bgcolor: Color; + plot_bgcolor: Color; + separators: string; + hidesources: boolean; + xaxis: Partial; + yaxis: Partial; + yaxis2: Partial; + yaxis3: Partial; + yaxis4: Partial; + yaxis5: Partial; + yaxis6: Partial; + yaxis7: Partial; + yaxis8: Partial; + yaxis9: Partial; margin: Partial; height: number; width: number; - hovermode: "closest" | "x" | "y" | false; - 'xaxis.range': [Datum, Datum]; + hovermode: 'closest' | 'x' | 'y' | false; + hoverlabel: Partial