diff --git a/types/ace/index.d.ts b/types/ace/index.d.ts index b1e013bea9..828aab87c2 100644 --- a/types/ace/index.d.ts +++ b/types/ace/index.d.ts @@ -3039,6 +3039,37 @@ declare namespace AceAjax { **/ new(container: HTMLElement, theme?: string): VirtualRenderer; } + + export interface Completer { + /** + * Provides possible completion results asynchronously using the given callback. + * @param editor The editor to associate with + * @param session The `EditSession` to refer to + * @param pos An object containing the row and column + * @param prefix The prefixing string before the current position + * @param callback Function to provide the results or error + */ + getCompletions: (editor: Editor, session: IEditSession, pos: Position, prefix: string, callback: CompletionCallback) => void; + + /** + * Provides tooltip information about a completion result. + * @param item The completion result + */ + getDocTooltip?: (item: Completion) => void; + } + + export interface Completion { + value: string; + meta: string; + type?: string; + caption?: string; + snippet?: any; + score?: number; + exactMatch?: number; + docHTML?: string; + } + + export type CompletionCallback = (error: Error, results: Completion[]) => void; } declare var ace: AceAjax.Ace; diff --git a/types/adone/glosses/application.d.ts b/types/adone/glosses/app.d.ts similarity index 90% rename from types/adone/glosses/application.d.ts rename to types/adone/glosses/app.d.ts index 4c9661843a..1c6dee3369 100644 --- a/types/adone/glosses/application.d.ts +++ b/types/adone/glosses/app.d.ts @@ -1,5 +1,5 @@ declare namespace adone { - namespace application { + namespace app { namespace I { type ArgumentType = ((x: string, index: number) => any) | RegExp; @@ -12,7 +12,7 @@ declare namespace adone { | "append" | "count" | "set"; - nargs?: number | "+" | "*" | "?" + nargs?: number | "+" | "*" | "?"; type?: ArgumentType | ArgumentType[]; verify?: (args: any, opts: any) => boolean; // TODO required?: boolean; @@ -49,7 +49,7 @@ declare namespace adone { name?: string; description?: string; subsystems?: SubsystemInfo[]; - commandsGroups?: Group[] + commandsGroups?: Group[]; } interface SubsystemInfo { @@ -71,24 +71,24 @@ declare namespace adone { namespace I { interface LoadSubsystemOptions { - name?: string, - description?: string, - group?: string, - transpile?: boolean + name?: string; + description?: string; + group?: string; + transpile?: boolean; } interface CommonAddSubsystemInfo { - name?: string, - useFilename?: boolean - description?: string, - group?: string, - configureArgs?: any[] - transpile?: boolean, - bind?: boolean | string + name?: string; + useFilename?: boolean; + description?: string; + group?: string; + configureArgs?: any[]; + transpile?: boolean; + bind?: boolean | string; } interface AddSubsystemInfo extends CommonAddSubsystemInfo { - subsystem: Subsystem | string, + subsystem: Subsystem | string; } interface SysInfo { @@ -109,7 +109,7 @@ declare namespace adone { } interface AddSubsystemsFromOptions extends CommonAddSubsystemInfo { - filter?: string[] | ((file: string) => boolean | Promise) + filter?: string[] | ((file: string) => boolean | Promise); } } @@ -211,25 +211,22 @@ declare namespace adone { _rejectionHandled(p: Promise): void; _signalExit(sigName: string): void; - } namespace I { interface Command { - // ? + names: string[]; + // TODO } interface Argument { - // ? + names: string[]; + // TODO } - interface PositionalArgument extends Argument { - // ? - } + type PositionalArgument = Argument; // TODO - interface OptionalArgument extends Argument { - // ? - } + type OptionalArgument = Argument; // TODO interface DefineCommandFromSubsystemOptions { name?: string; diff --git a/types/adone/glosses/is.d.ts b/types/adone/glosses/is.d.ts index 011b906234..bf8bb0a347 100644 --- a/types/adone/glosses/is.d.ts +++ b/types/adone/glosses/is.d.ts @@ -320,12 +320,12 @@ declare namespace adone { /** * Checks whether the given object is an adone subsystem */ - export function subsystem(obj: any): obj is adone.application.Subsystem; + export function subsystem(obj: any): obj is adone.app.Subsystem; /** * Checks whether the given object is an adone application */ - export function application(obj: any): obj is adone.application.Application; + export function application(obj: any): obj is adone.app.Application; /** * Checks whether the given object is an adone logger diff --git a/types/adone/index.d.ts b/types/adone/index.d.ts index a74641c4df..c6add2eeea 100644 --- a/types/adone/index.d.ts +++ b/types/adone/index.d.ts @@ -5,7 +5,7 @@ // TypeScript Version: 2.4 /// -/// +/// /// /// /// diff --git a/types/adone/test/glosses/application.ts b/types/adone/test/glosses/app.ts similarity index 99% rename from types/adone/test/glosses/application.ts rename to types/adone/test/glosses/app.ts index 38c5b0c8ff..8d74c8093b 100644 --- a/types/adone/test/glosses/application.ts +++ b/types/adone/test/glosses/app.ts @@ -8,7 +8,7 @@ namespace applicationTests { Subsystem, runCli, Application - } = adone.application; + } = adone.app; namespace DApplicationTests { { diff --git a/types/adone/tsconfig.json b/types/adone/tsconfig.json index 3f02029dcc..7194901d7a 100644 --- a/types/adone/tsconfig.json +++ b/types/adone/tsconfig.json @@ -24,6 +24,7 @@ "adone.d.ts", "async.d.ts", "benchmark.d.ts", + "glosses/app.d.ts", "glosses/archives.d.ts", "glosses/assertion.d.ts", "glosses/collections/array_set.d.ts", @@ -95,7 +96,7 @@ "glosses/utils.d.ts", "glosses/vault.d.ts", "index.d.ts", - "test/glosses/application.ts", + "test/glosses/app.ts", "test/glosses/archives.ts", "test/glosses/assertion.ts", "test/glosses/collections/array_set.ts", diff --git a/types/algoliasearch/algoliasearch-tests.ts b/types/algoliasearch/algoliasearch-tests.ts index 0814b0fc03..b8cd1db6c5 100644 --- a/types/algoliasearch/algoliasearch-tests.ts +++ b/types/algoliasearch/algoliasearch-tests.ts @@ -2,16 +2,16 @@ import * as algoliasearch from 'algoliasearch'; import { ClientOptions, SynonymOption, - AlgoliaApiKeyOptions, + ApiKeyOptions, SearchSynonymOptions, - AlgoliaResponse, - AlgoliaSecuredApiOptions, - AlgoliaIndexSettings, - AlgoliaQueryParameters, - AlgoliaIndex, + SecuredApiOptions, + Index, + Response, + IndexSettings, + QueryParameters, } from 'algoliasearch'; -let _algoliaResponse: AlgoliaResponse = { +let _algoliaResponse: Response = { hits: [{}, {}], page: 0, nbHits: 12, @@ -33,7 +33,7 @@ let _synonymOption: SynonymOption = { replaceExistingSynonyms: false, }; -let _algoliaApiKeyOptions: AlgoliaApiKeyOptions = { +let _algoliaApiKeyOptions: ApiKeyOptions = { validity: 0, maxQueriesPerIPPerHour: 0, indexes: [''], @@ -48,14 +48,14 @@ let _searchSynonymOptions: SearchSynonymOptions = { hitsPerPage: 0, }; -let _algoliaSecuredApiOptions: AlgoliaSecuredApiOptions = { +let _algoliaSecuredApiOptions: SecuredApiOptions = { filters: '', validUntil: 0, restrictIndices: '', userToken: '', }; -let _algoliaIndexSettings: AlgoliaIndexSettings = { +let _algoliaIndexSettings: IndexSettings = { attributesToIndex: [''], attributesForFaceting: [''], unretrievableAttributes: [''], @@ -63,7 +63,7 @@ let _algoliaIndexSettings: AlgoliaIndexSettings = { ranking: [''], customRanking: [''], replicas: [''], - maxValuesPerFacet: '', + maxValuesPerFacet: 100, attributesToHighlight: [''], attributesToSnippet: [''], highlightPreTag: '', @@ -96,13 +96,13 @@ let _algoliaIndexSettings: AlgoliaIndexSettings = { placeholders: '', }; -let _algoliaQueryParameters: AlgoliaQueryParameters = { +let _algoliaQueryParameters: QueryParameters = { query: '', filters: '', attributesToRetrieve: [''], restrictSearchableAttributes: [''], facets: '', - maxValuesPerFacet: '', + maxValuesPerFacet: 2, attributesToHighlight: [''], attributesToSnippet: [''], highlightPreTag: '', @@ -147,7 +147,7 @@ let _algoliaQueryParameters: AlgoliaQueryParameters = { minProximity: 0, }; -let index: AlgoliaIndex = algoliasearch('', '').initIndex(''); +let index: Index = algoliasearch('', '').initIndex(''); let search = index.search({ query: '' }); index.search({ query: '' }, (err, res) => {}); diff --git a/types/algoliasearch/index.d.ts b/types/algoliasearch/index.d.ts index 3304ad579d..fca13ac161 100644 --- a/types/algoliasearch/index.d.ts +++ b/types/algoliasearch/index.d.ts @@ -1,4 +1,4 @@ -// Type definitions for algoliasearch-client-js 3.24.8 +// Type definitions for algoliasearch-client-js 3.27.0 // Project: https://github.com/algolia/algoliasearch-client-js // Definitions by: Baptiste Coquelle // Haroen Viaene @@ -7,87 +7,44 @@ // TypeScript Version: 2.2 declare namespace algoliasearch { - interface AlgoliaResponse { - /** - * Contains all the hits matching the query - * https://github.com/algolia/algoliasearch-client-js#response-format - */ - hits: any[]; - /** - * Current page - * https://github.com/algolia/algoliasearch-client-js#response-format - */ - page: number; - /** - * Number of total hits matching the query - * https://github.com/algolia/algoliasearch-client-js#response-format - */ - nbHits: number; - /** - * Number of pages - * https://github.com/algolia/algoliasearch-client-js#response-format - */ - nbPages: number; - /** - * Number of hits per pages - * https://github.com/algolia/algoliasearch-client-js#response-format - */ - hitsPerPage: number; - /** - * Engine processing time (excluding network transfer) - * https://github.com/algolia/algoliasearch-client-js#response-format - */ - processingTimeMS: number; - /** - * Query used to perform the search - * https://github.com/algolia/algoliasearch-client-js#response-format - */ - query: string; - /** - * GET parameters used to perform the search - * https://github.com/algolia/algoliasearch-client-js#response-format - */ - params: string; - } - interface AlgoliaMultiResponse { - results: AlgoliaResponse[]; - } - /* - Interface for the algolia client object - */ - interface AlgoliaClient { + /** + * Interface for the algolia client object + */ + interface Client { /** * Initialization of the index - * @param name: index name - * return algolia index object * https://github.com/algolia/algoliasearch-client-js#init-index---initindex */ - initIndex(name: string): AlgoliaIndex; + initIndex(indexName: string): Index; /** * Query on multiple index - * @param queries index name, query and query parameters - * @param cb callback(err, res) * https://github.com/algolia/algoliasearch-client-js#multiple-queries---multiplequeries */ search( queries: { indexName: string; query: string; - params: AlgoliaQueryParameters; + params: QueryParameters; }[], - cb: (err: Error, res: AlgoliaMultiResponse) => void + cb: (err: Error, res: MultiResponse) => void ): void; /** * Query on multiple index - * @param queries index name, query and query parameters - * return {Promise} * https://github.com/algolia/algoliasearch-client-js#multiple-queries---multiplequeries */ - search(queries: { - indexName: string; - query: string; - params: AlgoliaQueryParameters; - }[]): Promise; + search( + queries: { + indexName: string; + query: string; + params: QueryParameters; + }[] + ): Promise; + /** + * Query for facet values of a specific facet + */ + searchForFacetValues( + queries: [{ indexName: string; params: SearchForFacetValues.Parameters }] + ): Promise; /** * clear browser cache * https://github.com/algolia/algoliasearch-client-js#cache @@ -107,336 +64,256 @@ declare namespace algoliasearch { */ getExtraHeader(name: string): string; /** - * remove an extra header for all upcoming requests + * Remove an extra header for all upcoming requests */ unsetExtraHeader(name: string): void; /** * List all your indices along with their associated information (number of entries, disk size, etc.) - * @param cb(err, res) * https://github.com/algolia/algoliasearch-client-js#list-indices---listindexes */ listIndexes(cb: (err: Error, res: any) => void): void; /** * List all your indices along with their associated information (number of entries, disk size, etc.) - * return {Promise} * https://github.com/algolia/algoliasearch-client-js#list-indices---listindexes */ listIndexes(): Promise; /** * Delete a specific index - * @param name - * @param cb(err, res) * https://github.com/algolia/algoliasearch-client-js#delete-index---deleteindex */ - deleteIndex(name: string, cb: (err: Error, res: any) => void): void; + deleteIndex(name: string, cb: (err: Error, res: Task) => void): void; /** * Delete a specific index - * @param name - * return {Promise} * https://github.com/algolia/algoliasearch-client-js#delete-index---deleteindex */ - deleteIndex(name: string): Promise; + deleteIndex(name: string): Promise; /** * Copy an index from a specific index to a new one - * @param from origin index - * @param to destination index - * @param cb(err, res) * https://github.com/algolia/algoliasearch-client-js#copy-index---copyindex */ copyIndex( from: string, to: string, - cb: (err: Error, res: any) => void + scope: ('settings' | 'synonyms' | 'rules')[], + cb: (err: Error, res: Task) => void ): void; /** * Copy an index from a specific index to a new one - * @param from origin index - * @param to destination index - * return {Promise} * https://github.com/algolia/algoliasearch-client-js#copy-index---copyindex */ - copyIndex(from: string, to: string): Promise; + copyIndex( + from: string, + to: string, + scope: ('settings' | 'synonyms' | 'rules')[] + ): Promise; /** * Move index to a new one (and will overwrite the original one) - * @param from origin index - * @param to destination index - * @param cb(err, res) * https://github.com/algolia/algoliasearch-client-js#move-index---moveindex */ moveIndex( from: string, to: string, - cb: (err: Error, res: any) => void + cb: (err: Error, res: Task) => void ): void; /** * Move index to a new one (and will overwrite the original one) - * @param from origin index - * @param to destination index - * return {Promise} * https://github.com/algolia/algoliasearch-client-js#move-index---moveindex */ - moveIndex(from: string, to: string): Promise; + moveIndex(from: string, to: string): Promise; /** * Generate a public API key - * @param key api key - * @param filters * https://github.com/algolia/algoliasearch-client-js#generate-key---generatesecuredapikey */ - generateSecuredApiKey( - key: string, - filters: AlgoliaSecuredApiOptions - ): string; + generateSecuredApiKey(key: string, filters: SecuredApiOptions): string; /** * Perform multiple operations with one API call to reduce latency - * @param action - * @param cb(err, res) * https://github.com/algolia/algoliasearch-client-js#custom-batch---batch */ - batch(action: AlgoliaAction[], cb: (err: Error, res: any) => void): void; + batch(action: Action[], cb: (err: Error, res: Task) => void): void; /** * Perform multiple operations with one API call to reduce latency - * @param action - * return {Promise} * https://github.com/algolia/algoliasearch-client-js#custom-batch---batch */ - batch(action: AlgoliaAction[]): Promise; + batch(action: Action[]): Promise; /** * Lists global API Keys - * @param cb(err, res) * https://github.com/algolia/algoliasearch-client-js#backup--export-an-index---browse */ listApiKeys(cb: (err: Error, res: any) => void): void; /** * Lists global API Keys - * return {Promise} * https://github.com/algolia/algoliasearch-client-js#backup--export-an-index---browse */ listApiKeys(): Promise; /** * Add global API Keys - * @param scopes - * @param cb(err, res) * https://github.com/algolia/algoliasearch-client-js#add-user-key---addapikey */ - addApiKey(scopes: string[], cb: (err: Error, res: any) => void): void; + addApiKey(scopes: string[], cb: (err: Error, res: Task) => void): void; /** * Add global API Key - * @param scopes - * @param options - * @param cb(err, res) * https://github.com/algolia/algoliasearch-client-js#add-user-key---addapikey */ addApiKey( scopes: string[], - options: AlgoliaApiKeyOptions, - cb: (err: Error, res: any) => void + options: ApiKeyOptions, + cb: (err: Error, res: Task) => void ): void; /** * Add global API Keys - * @param scopes - * @param options - * return {Promise} * https://github.com/algolia/algoliasearch-client-js#add-user-key---addapikey */ - addApiKey(scopes: string[], options?: AlgoliaApiKeyOptions): Promise; + addApiKey(scopes: string[], options?: ApiKeyOptions): Promise; /** * Update global API key - * @param key - * @param scopes - * @param cb(err, res) * https://github.com/algolia/algoliasearch-client-js#update-user-key---updateapikey */ updateApiKey( key: string, scopes: string[], - cb: (err: Error, res: any) => void + cb: (err: Error, res: Task) => void ): void; /** * Update global API key - * @param key - * @param scopes - * @param options - * @param cb(err, res) * https://github.com/algolia/algoliasearch-client-js#update-user-key---updateapikey */ updateApiKey( key: string, scopes: string[], - options: AlgoliaApiKeyOptions, - cb: (err: Error, res: any) => void + options: ApiKeyOptions, + cb: (err: Error, res: Task) => void ): void; /** * Update global API key - * @param key - * @param scopes - * @param options - * return {Promise} * https://github.com/algolia/algoliasearch-client-js#update-user-key---updateapikey */ updateApiKey( key: string, scopes: string[], - options?: AlgoliaApiKeyOptions - ): Promise; + options?: ApiKeyOptions + ): Promise; /** * Gets the rights of a global key - * @param key - * @param cb(err, res) * https://github.com/algolia/algoliasearch-client-js#update-user-key---updateapikey */ getApiKey(key: string, cb: (err: Error, res: any) => void): void; /** * Gets the rights of a global key - * @param key - * return {Promise} * https://github.com/algolia/algoliasearch-client-js#update-user-key---updateapikey */ getApiKey(key: string): Promise; /** * Deletes a global key - * @param key - * @param cb(err,res) * https://github.com/algolia/algoliasearch-client-js#delete-user-key---deleteapikey */ - deleteApiKey(key: string, cb: (err: Error, res: any) => void): void; + deleteApiKey(key: string, cb: (err: Error, res: Task) => void): void; /** * Deletes a global key - * @param key - * return {Promise} * https://github.com/algolia/algoliasearch-client-js#delete-user-key---deleteapikey */ - deleteApiKey(key: string): Promise; + deleteApiKey(key: string): Promise; /** * Get 1000 last events - * @param options - * @param cb(err, res) * https://github.com/algolia/algoliasearch-client-js#get-logs---getlogs */ - getLogs(options: LogsOptions, cb: (err: Error, res: any) => void): void; + getLogs( + options: LogsOptions, + cb: (err: Error, res: { logs: Log[] }) => void + ): void; /** * Get 1000 last events - * @param options - * return {Promise} * https://github.com/algolia/algoliasearch-client-js#get-logs---getlogs */ - getLogs(options: LogsOptions): Promise; + getLogs(options: LogsOptions): Promise<{ logs: Log[] }>; } /** * Interface for the index algolia object */ - interface AlgoliaIndex { + interface Index { /** * Gets a specific object - * @param objectID - * @param cb(err, res) * https://github.com/algolia/algoliasearch-client-js#find-by-ids---getobjects */ - getObject(objectID: string, cb: (err: Error, res: any) => void): void; + getObject(objectID: string, cb: (err: Error, res: {}) => void): void; /** * Gets specific attributes from an object - * @param objectID - * @param attributes - * @param cb(err, res) * https://github.com/algolia/algoliasearch-client-js#find-by-ids---getobjects */ getObject( objectID: string, attributes: string[], - cb: (err: Error, res: any) => void + cb: (err: Error, res: {}) => void ): void; /** * Gets a list of objects - * @param objectIDs - * @param cb(err, res) * https://github.com/algolia/algoliasearch-client-js#find-by-ids---getobjects */ - getObjects(objectIDs: string[], cb: (err: Error, res: any) => void): void; + getObjects( + objectIDs: string[], + cb: (err: Error, res: { results: {}[] }) => void + ): void; /** * Add a specific object - * @param object without objectID - * @param cb(err, res) * https://github.com/algolia/algoliasearch-client-js#add-objects---addobjects */ - addObject(object: {}, cb: (err: Error, res: any) => void): void; + addObject(object: {}, cb: (err: Error, res: Task) => void): void; /** * Add a list of objects - * @param object with objectID - * @param objectID - * @param cb(err, res) * https://github.com/algolia/algoliasearch-client-js#add-objects---addobjects */ addObject( object: {}, objectID: string, - cb: (err: Error, res: any) => void + cb: (err: Error, res: Task) => void ): void; /** * Add list of objects - * @param objects - * @param cb(err, res) * https://github.com/algolia/algoliasearch-client-js#add-objects---addobjects */ - addObjects(objects: {}[], cb: (err: Error, res: any) => void): void; + addObjects(objects: {}[], cb: (err: Error, res: Task) => void): void; /** * Add or replace a specific object - * @param object - * @param cb(err, res) * https://github.com/algolia/algoliasearch-client-js#update-objects---saveobjects */ - saveObject(object: {}, cb: (err: Error, res: any) => void): void; + saveObject(object: {}, cb: (err: Error, res: Task) => void): void; /** * Add or replace several objects - * @param objects - * @param cb(err, res) * https://github.com/algolia/algoliasearch-client-js#update-objects---saveobjects */ - saveObjects(objects: object[], cb: (err: Error, res: any) => void): void; + saveObjects(objects: object[], cb: (err: Error, res: Task) => void): void; /** * Update parameters of a specific object - * @param object - * @param cb(err, res) * https://github.com/algolia/algoliasearch-client-js#update-objects---saveobjects */ - partialUpdateObject(object: {}, cb: (err: Error, res: any) => void): void; + partialUpdateObject(object: {}, cb: (err: Error, res: Task) => void): void; /** * Update parameters of a list of objects - * @param objects - * @param cb(err, res) * https://github.com/algolia/algoliasearch-client-js#update-objects---saveobjects */ partialUpdateObjects( objects: {}[], - cb: (err: Error, res: any) => void + cb: (err: Error, res: Task) => void ): void; /** * Delete a specific object - * @param objectID - * @param cb(err, res) * https://github.com/algolia/algoliasearch-client-js#delete-objects---deleteobjects */ - deleteObject(objectID: string, cb: (err: Error, res: any) => void): void; + deleteObject(objectID: string, cb: (err: Error, res: Task) => void): void; /** * Delete a list of objects - * @param objectIDs - * @param cb(err, res) * https://github.com/algolia/algoliasearch-client-js#delete-objects---deleteobjects */ deleteObjects( objectIDs: string[], - cb: (err: Error, res: any) => void + cb: (err: Error, res: Task) => void ): void; /** * Delete objects that matches the query - * @param query - * @param cb(err, res) * https://github.com/algolia/algoliasearch-client-js#delete-by-query---deletebyquery */ deleteByQuery(query: string, cb: (err: Error, res: any) => void): void; /** * Delete objects that matches the query - * @param query - * @param params of the object - * @param cb(err, res) * https://github.com/algolia/algoliasearch-client-js#delete-by-query---deletebyquery */ deleteByQuery( @@ -446,34 +323,26 @@ declare namespace algoliasearch { ): void; /** * Delete objects that matches the query - * @param query - * @param params of the object - * @param cb(err, res) * https://github.com/algolia/algoliasearch-client-js#delete-by-query---deleteby */ - deleteBy(params: {}, cb: (err: Error, res: any) => void): void; + deleteBy(params: {}, cb: (err: Error, res: Task) => void): void; /** * Wait for an indexing task to be compete - * @param taskID - * @param cb(err, res) * https://github.com/algolia/algoliasearch-client-js#wait-for-operations---waittask */ waitTask(taskID: number, cb: (err: Error, res: any) => void): void; /** * Get an index settings - * @param cb(err, res) * https://github.com/algolia/algoliasearch-client-js#get-settings---getsettings */ - getSettings(cb: (err: Error, res: any) => void): void; + getSettings(cb: (err: Error, res: IndexSettings) => void): void; /** * Set an index settings - * @param settings - * @param cb(err, res) * https://github.com/algolia/algoliasearch-client-js#set-settings---setsettings */ setSettings( - settings: AlgoliaIndexSettings, - cb: (err: Error, res: any) => void + settings: IndexSettings, + cb: (err: Error, res: Task) => void ): void; /** * Clear cache of an index @@ -482,66 +351,53 @@ declare namespace algoliasearch { clearCache(): void; /** * Clear an index content - * @param cb(err, res) * https://github.com/algolia/algoliasearch-client-js#clear-index---clearindex */ - clearIndex(cb: (err: Error, res: any) => void): void; + clearIndex(cb: (err: Error, res: Task) => void): void; /** * Save a synonym object - * @param synonym - * @param options - * @param cb(err, res) * https://github.com/algolia/algoliasearch-client-js#save-synonym---savesynonym */ saveSynonym( - synonym: AlgoliaSynonym, + synonym: Synonym, options: SynonymOption, - cb: (err: Error, res: any) => void + cb: (err: Error, res: Task) => void ): void; /** * Save a synonym object - * @param synonyms - * @param options - * @param cb(err, res) */ batchSynonyms( - synonyms: AlgoliaSynonym[], + synonyms: Synonym[], options: SynonymOption, - cb: (err: Error, res: any) => void + cb: (err: Error, res: Task) => void ): void; /** * Delete a specific synonym - * @param identifier - * @param options - * @param cb(err, res) * https://github.com/algolia/algoliasearch-client-js#batch-synonyms---batchsynonyms */ deleteSynonym( identifier: string, options: SynonymOption, - cb: (err: Error, res: any) => void + cb: (err: Error, res: Task) => void ): void; /** * Clear all synonyms of an index - * @param options - * @param cb(err, res) * https://github.com/algolia/algoliasearch-client-js#clear-all-synonyms---clearsynonyms */ clearSynonyms( options: SynonymOption, - cb: (err: Error, res: any) => void + cb: (err: Error, res: Task) => void ): void; /** * Get a specific synonym - * @param identifier - * @param cb(err, res) * https://github.com/algolia/algoliasearch-client-js#get-synonym---getsynonym */ - getSynonym(identifier: string, cb: (err: Error, res: any) => void): void; + getSynonym( + identifier: string, + cb: (err: Error, res: Synonym) => void + ): void; /** * Search a synonyms - * @param options - * @param cb(err, res) * https://github.com/algolia/algoliasearch-client-js#search-synonyms---searchsynonyms */ searchSynonyms( @@ -550,57 +406,42 @@ declare namespace algoliasearch { ): void; /** * Save a rule object - * @param rule - * @param options - * @param cb(err, res) * https://github.com/algolia/algoliasearch-client-js#save-rule---saverule */ saveRule( - rule: AlgoliaRule, + rule: Rule, options: RuleOption, - cb: (err: Error, res: any) => void + cb: (err: Error, res: Task) => void ): void; /** * Save a rule object - * @param rules - * @param options - * @param cb(err, res) */ batchRules( - rules: AlgoliaRule[], + rules: Rule[], options: RuleOption, - cb: (err: Error, res: any) => void + cb: (err: Error, res: Task) => void ): void; /** * Delete a specific rule - * @param identifier - * @param options - * @param cb(err, res) * https://github.com/algolia/algoliasearch-client-js#batch-rules---batchrules */ deleteRule( identifier: string, options: RuleOption, - cb: (err: Error, res: any) => void + cb: (err: Error, res: Task) => void ): void; /** * Clear all rules of an index - * @param options - * @param cb(err, res) * https://github.com/algolia/algoliasearch-client-js#clear-all-rules---clearrules */ - clearRules(options: RuleOption, cb: (err: Error, res: any) => void): void; + clearRules(options: RuleOption, cb: (err: Error, res: Task) => void): void; /** * Get a specific rule - * @param identifier - * @param cb(err, res) * https://github.com/algolia/algoliasearch-client-js#get-rule---getrule */ - getRule(identifier: string, cb: (err: Error, res: any) => void): void; + getRule(identifier: string, cb: (err: Error, res: Rule) => void): void; /** * Search a rules - * @param options - * @param cb(err, res) * https://github.com/algolia/algoliasearch-client-js#search-rules---searchrules */ searchRules( @@ -609,403 +450,284 @@ declare namespace algoliasearch { ): void; /** * List index user keys - * @param cb(err, res) * https://github.com/algolia/algoliasearch-client-js#list-api-keys---listapikeys */ listApiKeys(cb: (err: Error, res: any) => void): void; /** * Add key for this index - * @param scopes - * @param cb(err, res) * https://github.com/algolia/algoliasearch-client-js#add-user-key---addapikey */ - addApiKey(scopes: string[], cb: (err: Error, res: any) => void): void; + addApiKey(scopes: string[], cb: (err: Error, res: Task) => void): void; /** * Add key for this index - * @param scopes - * @param options - * @param cb(err, res) * https://github.com/algolia/algoliasearch-client-js#add-user-key---addapikey */ addApiKey( scopes: string[], - options: AlgoliaApiKeyOptions, - cb: (err: Error, res: any) => void + options: ApiKeyOptions, + cb: (err: Error, res: Task) => void ): void; /** * Update a key for this index - * @param key - * @param scopes - * @param cb(err, res) * https://github.com/algolia/algoliasearch-client-js#update-user-key---updateapikey */ updateApiKey( key: string, scopes: string[], - cb: (err: Error, res: any) => void + cb: (err: Error, res: Task) => void ): void; /** * Update a key for this index - * @param key - * @param scopes - * @param options - * @param cb(err, res) * https://github.com/algolia/algoliasearch-client-js#update-user-key---updateapikey */ updateApiKey( key: string, scopes: string[], - options: AlgoliaApiKeyOptions, - cb: (err: Error, res: any) => void + options: ApiKeyOptions, + cb: (err: Error, res: Task) => void ): void; /** * Gets the rights of an index specific key - * @param key - * @param cb(err, res) * https://github.com/algolia/algoliasearch-client-js#get-key-permissions---getapikeyacl */ getApiKey(key: string, cb: (err: Error, res: any) => void): void; /** * Deletes an index specific key - * @param key - * @param cb(err, res) * https://github.com/algolia/algoliasearch-client-js#delete-user-key---deleteapikey */ - deleteApiKey(key: string, cb: (err: Error, res: any) => void): void; + deleteApiKey(key: string, cb: (err: Error, res: Task) => void): void; /** * Gets specific attributes from an object - * @param objectID - * @param attributes - * return {Promise} * https://github.com/algolia/algoliasearch-client-js#find-by-ids---getobjects */ - getObject(objectID: string, attributes?: string[]): Promise; + getObject(objectID: string, attributes?: string[]): Promise<{}>; /** * Gets a list of objects - * @param objectIDs - * return {Promise} * https://github.com/algolia/algoliasearch-client-js#find-by-ids---getobjects */ - getObjects(objectIDs: string[]): Promise; + getObjects(objectIDs: string[]): Promise<{ results: {}[] }>; /** * Add a list of objects - * @param object with objectID - * @param objectID - * return {Promise} * https://github.com/algolia/algoliasearch-client-js#add-objects---addobjects */ - addObject(object: {}, objectID?: string): Promise; + addObject(object: {}, objectID?: string): Promise; /** * Add list of objects - * @param objects - * return {Promise} * https://github.com/algolia/algoliasearch-client-js#add-objects---addobjects */ - addObjects(objects: {}[]): Promise; + addObjects(objects: {}[]): Promise; /** * Add or replace a specific object - * @param object - * return {Promise} * https://github.com/algolia/algoliasearch-client-js#update-objects---saveobjects */ - saveObject(object: {}): Promise; + saveObject(object: {}): Promise; /** * Add or replace several objects - * @param objects - * return {Promise} * https://github.com/algolia/algoliasearch-client-js#update-objects---saveobjects */ - saveObjects(objects: object[]): Promise; + saveObjects(objects: object[]): Promise; /** * Update parameters of a specific object - * @param object - * return {Promise} * https://github.com/algolia/algoliasearch-client-js#update-objects---saveobjects */ - partialUpdateObject(object: {}): Promise; + partialUpdateObject(object: {}): Promise; /** * Update parameters of a list of objects - * @param objects - * return {Promise} * https://github.com/algolia/algoliasearch-client-js#update-objects---saveobjects */ - partialUpdateObjects(objects: {}[]): Promise; + partialUpdateObjects(objects: {}[]): Promise; /** * Delete a specific object - * @param objectID - * return {Promise} * https://github.com/algolia/algoliasearch-client-js#delete-objects---deleteobjects */ - deleteObject(objectID: string): Promise; + deleteObject(objectID: string): Promise; /** * Delete a list of objects - * @param objectIDs - * return {Promise} * https://github.com/algolia/algoliasearch-client-js#delete-objects---deleteobjects */ - deleteObjects(objectIDs: string[]): Promise; + deleteObjects(objectIDs: string[]): Promise; /** * Delete objects that matches the query - * @param query - * @param params of the object - * return {Promise} * https://github.com/algolia/algoliasearch-client-js#delete-by-query---deletebyquery */ deleteByQuery(query: string, params?: {}): Promise; /** * Delete objects that matches the query - * @param params of the search - * return {Promise} * https://www.algolia.com/doc/api-reference/api-methods/delete-by-query/ */ - deleteBy(params: {}): Promise; + deleteBy(params: {}): Promise; /** * Wait for an indexing task to be compete - * @param taskID - * return {Promise} * https://github.com/algolia/algoliasearch-client-js#wait-for-operations---waittask */ waitTask(taskID: number): Promise; /** * Get an index settings - * return {Promise} * https://github.com/algolia/algoliasearch-client-js#get-settings---getsettings */ - getSettings(): Promise; + getSettings(): Promise; /** * Set an index settings - * @param settings - * return {Promise} * https://github.com/algolia/algoliasearch-client-js#set-settings---setsettings */ - setSettings(settings: AlgoliaIndexSettings): Promise; + setSettings(settings: IndexSettings): Promise; /** * Search in an index - * @param params query parameter - * return {Promise} - * @param err() error callback * https://github.com/algolia/algoliasearch-client-js#search-in-an-index---search */ - search(params: AlgoliaQueryParameters): Promise; + search(params: QueryParameters): Promise; /** * Search in an index - * @param params query parameter - * @param cb(err, res) - * @param err() error callback * https://github.com/algolia/algoliasearch-client-js#search-in-an-index---search */ search( - params: AlgoliaQueryParameters, - cb: (err: Error, res: AlgoliaResponse) => void + params: QueryParameters, + cb: (err: Error, res: Response) => void ): void; /** * Search in an index - * @param params query parameter - * return {Promise} - * @param err() error callback * https://www.algolia.com/doc/api-reference/api-methods/search-for-facet-values/ */ - searchForFacetValues(options: { - facetName: string; - facetQuery: string; - } & AlgoliaQueryParameters): Promise; + searchForFacetValues( + options: SearchForFacetValues.Parameters + ): Promise; /** * Search in an index - * @param params query parameter - * @param cb(err, res) - * @param err() error callback * https://www.algolia.com/doc/api-reference/api-methods/search-for-facet-values/ */ - searchForFacetValues(options: { - facetName: string; - facetQuery: string; - } & AlgoliaQueryParameters, - cb: (err: Error, res: any) => void + searchForFacetValues( + options: SearchForFacetValues.Parameters, + cb: (err: Error, res: SearchForFacetValues.Response) => void ): void; /** * Browse an index - * @param query - * @param cb(err, content) * https://github.com/algolia/algoliasearch-client-js#backup--export-an-index---browse */ - browse(query: string, cb: (err: Error, res: any) => void): void; + browse(query: string, cb: (err: Error, res: BrowseResponse) => void): void; /** * Browse an index - * @param query - * return {Promise} * https://github.com/algolia/algoliasearch-client-js#backup--export-an-index---browse */ - browse(query: string): Promise; + browse(query: string): Promise; /** * Browse an index from a cursor - * @param cursor - * @param cb(err, content) * https://github.com/algolia/algoliasearch-client-js#backup--export-an-index---browse */ - browseFrom(cursor: string, cb: (err: Error, res: any) => void): void; + browseFrom( + cursor: string, + cb: (err: Error, res: BrowseResponse) => void + ): void; /** * Browse an index from a cursor - * @param cursor - * return {Promise} * https://github.com/algolia/algoliasearch-client-js#backup--export-an-index---browse */ - browseFrom(cursor: string): Promise; + browseFrom(cursor: string): Promise; /** * Browse an entire index - * return Promise * https://github.com/algolia/algoliasearch-client-js#backup--export-an-index---browse */ - browseAll(): Promise; + browseAll(): Promise; /** * Clear an index content - * return {Promise} * https://github.com/algolia/algoliasearch-client-js#clear-index---clearindex */ - clearIndex(): Promise; + clearIndex(): Promise; /** * Save a synonym object - * @param synonym - * @param options - * return {Promise} * https://github.com/algolia/algoliasearch-client-js#save-synonym---savesynonym */ - saveSynonym(synonym: AlgoliaSynonym, options: SynonymOption): Promise; + saveSynonym(synonym: Synonym, options: SynonymOption): Promise; /** * Save a synonym object - * @param synonyms - * @param options - * return {Promise} */ - batchSynonyms( - synonyms: AlgoliaSynonym[], - options: SynonymOption - ): Promise; + batchSynonyms(synonyms: Synonym[], options: SynonymOption): Promise; /** * Delete a specific synonym - * @param identifier - * @param options - * return {Promise} * https://github.com/algolia/algoliasearch-client-js#batch-synonyms---batchsynonyms */ - deleteSynonym(identifier: string, options: SynonymOption): Promise; + deleteSynonym(objectID: string, options: SynonymOption): Promise; /** * Clear all synonyms of an index - * @param options - * return {Promise} * https://github.com/algolia/algoliasearch-client-js#clear-all-synonyms---clearsynonyms */ - clearSynonyms(options: SynonymOption): Promise; + clearSynonyms(options: SynonymOption): Promise; /** * Get a specific synonym - * @param identifier - * return {Promise} * https://github.com/algolia/algoliasearch-client-js#get-synonym---getsynonym */ - getSynonym(identifier: string): Promise; + getSynonym(objectID: string): Promise; /** * Search a synonyms - * @param options - * return {Promise} * https://github.com/algolia/algoliasearch-client-js#search-synonyms---searchsynonyms */ searchSynonyms(options: SearchSynonymOptions): Promise; /** * Save a rule object - * @param rule - * @param options - * return {Promise} * https://github.com/algolia/algoliasearch-client-js#save-rule---saverule */ - saveRule(rule: AlgoliaRule, options: RuleOption): Promise; + saveRule(rule: Rule, options: RuleOption): Promise; /** * Save a rule object - * @param rules - * @param options - * return {Promise} */ - batchRules(rules: AlgoliaRule[], options: RuleOption): Promise; + batchRules(rules: Rule[], options: RuleOption): Promise; /** * Delete a specific rule - * @param identifier - * @param options - * return {Promise} * https://github.com/algolia/algoliasearch-client-js#batch-rules---batchrules */ - deleteRule(identifier: string, options: RuleOption): Promise; + deleteRule(identifier: string, options: RuleOption): Promise; /** * Clear all query rules of an index - * @param options - * return {Promise} * https://github.com/algolia/algoliasearch-client-js#clear-all-rules---clearrules */ - clearRules(options: RuleOption): Promise; + clearRules(options: RuleOption): Promise; /** * Get a specific query rule - * @param identifier - * return {Promise} * https://github.com/algolia/algoliasearch-client-js#get-rule---getrule */ - getRule(identifier: string): Promise; + getRule(identifier: string): Promise; /** * Search for query rules - * @param options - * return {Promise} * https://github.com/algolia/algoliasearch-client-js#search-rules---searchrules */ searchRules(options: SearchRuleOptions): Promise; /** * List index user keys - * return {Promise} * https://github.com/algolia/algoliasearch-client-js#list-api-keys---listapikeys */ listApiKeys(): Promise; /** * Add key for this index - * @param scopes - * @param options - * return {Promise} * https://github.com/algolia/algoliasearch-client-js#add-user-key---addapikey */ - addApiKey(scopes: string[], options?: AlgoliaApiKeyOptions): Promise; + addApiKey(scopes: string[], options?: ApiKeyOptions): Promise; /** * Update a key for this index - * @param key - * @param scopes - * return {Promise} * https://github.com/algolia/algoliasearch-client-js#update-user-key---updateapikey */ - updateApiKey(key: string, scopes: string[]): Promise; + updateApiKey(key: string, scopes: string[]): Promise; /** * Update a key for this index - * @param key - * @param scopes - * @param options - * return {Promise} * https://github.com/algolia/algoliasearch-client-js#update-user-key---updateapikey */ updateApiKey( key: string, scopes: string[], - options: AlgoliaApiKeyOptions - ): Promise; + options: ApiKeyOptions + ): Promise; /** * Gets the rights of an index specific key - * @param key - * return {Promise} * https://github.com/algolia/algoliasearch-client-js#get-key-permissions---getapikeyacl */ getApiKey(key: string): Promise; /** * Deletes an index specific key - * @param key - * return {Promise} * https://github.com/algolia/algoliasearch-client-js#delete-user-key---deleteapikey */ - deleteApiKey(key: string): Promise; + deleteApiKey(key: string): Promise; } - /* -Interface describing available options when initializing a client -*/ + /** + * Interface describing available options when initializing a client + */ interface ClientOptions { /** * Timeout for requests to our servers, in milliseconds @@ -1020,20 +742,20 @@ Interface describing available options when initializing a client */ protocol?: string; /** - * (node only) httpAgent instance to use when communicating with Algolia servers. + * (node only) httpAgent instance to use when communicating with servers. * https://github.com/algolia/algoliasearch-client-js#client-options */ httpAgent?: any; /** - * read: array of read hosts to use to call Algolia servers, computed automatically - * write: array of read hosts to use to call Algolia servers, computed automatically + * read: array of read hosts to use to call servers, computed automatically + * write: array of read hosts to use to call servers, computed automatically * https://github.com/algolia/algoliasearch-client-js#client-options */ hosts?: { read?: string[]; write?: string[] }; } - /* -Interface describing options available for gettings the logs -*/ + /** + * Interface describing options available for gettings the logs + */ interface LogsOptions { /** * Specify the first entry to retrieve (0-based, 0 is the most recent log entry). @@ -1062,11 +784,15 @@ Interface describing options available for gettings the logs * https://github.com/algolia/algoliasearch-client-js#get-logs---getlogs */ type?: string; + /** + * The index to request logs from + */ + indexName?: string; } /** * Describe the action object used for batch operation */ - interface AlgoliaAction { + interface Action { /** * Type of the batch action * https://github.com/algolia/algoliasearch-client-js#custom-batch---batch @@ -1093,7 +819,7 @@ Interface describing options available for gettings the logs /** * Describes the option used when creating user key */ - interface AlgoliaApiKeyOptions { + interface ApiKeyOptions { /** * Add a validity period. The key will be valid for a specific period of time (in seconds). * https://github.com/algolia/algoliasearch-client-js#add-user-key---addapikey @@ -1123,7 +849,7 @@ Interface describing options available for gettings the logs * Specify the list of query parameters * https://github.com/algolia/algoliasearch-client-js#add-user-key---addapikey */ - queryParameters?: AlgoliaQueryParameters; + queryParameters?: QueryParameters; /** * Specify a description to describe where the key is used. * https://github.com/algolia/algoliasearch-client-js#add-user-key---addapikey @@ -1216,9 +942,9 @@ Interface describing options available for gettings the logs */ hitsPerPage?: number; } - interface AlgoliaBrowseResponse { + interface BrowseResponse { cursor?: string; - hits: any[]; + hits: {}[]; params: string; query: string; processingTimeMS: number; @@ -1226,7 +952,7 @@ Interface describing options available for gettings the logs /** * Describes a synonym object */ - interface AlgoliaSynonym { + interface Synonym { /** * ObjectID of the synonym * https://github.com/algolia/algoliasearch-client-js#save-synonym---savesynonym @@ -1246,7 +972,7 @@ Interface describing options available for gettings the logs /** * Describes a query rule object */ - interface AlgoliaRule { + interface Rule { /** * ObjectID of the synonym * https://github.com/algolia/algoliasearch-client-js#save-synonym---savesynonym @@ -1332,7 +1058,7 @@ Interface describing options available for gettings the logs /** * Describes the options used when generating new api keys */ - interface AlgoliaSecuredApiOptions { + interface SecuredApiOptions { /** * Filter the query with numeric, facet or/and tag filters * default: "" @@ -1355,266 +1081,7 @@ Interface describing options available for gettings the logs */ userToken?: string; } - - /** - * Describes the settings available for configure your index - */ - interface AlgoliaIndexSettings { - /** - * The list of attributes you want index - * default: * - * https://github.com/algolia/algoliasearch-client-js#attributestoindex - */ - attributesToIndex?: string[]; - /** - * The list of attributes you want to use for faceting - * default: null - * https://github.com/algolia/algoliasearch-client-js#attributesforfaceting - */ - attributesForFaceting?: string[]; - /** - * The list of attributes that cannot be retrieved at query time - * default: null - * https://github.com/algolia/algoliasearch-client-js#unretrievableattributes - */ - unretrievableAttributes?: string[]; - /** - * List of attributes you want to use for textual search - * default: [] - * https://github.com/algolia/algoliasearch-client-js#searchableattributes - */ - searchableAttributes?: string[]; - /** - * A string that contains the list of attributes you want to retrieve in order to minimize the size of the JSON answer - * default: * - * https://github.com/algolia/algoliasearch-client-js#attributestoretrieve - */ - attributesToRetrieve?: string[]; - /** - * Controls the way results are sorted - * default: ['typo', 'geo', 'words', 'filters', 'proximity', 'attribute', 'exact', 'custom'] - * https://github.com/algolia/algoliasearch-client-js#ranking - */ - ranking?: string[]; - /** - * Lets you specify part of the ranking - * default: [] - * https://github.com/algolia/algoliasearch-client-js#customranking - */ - customRanking?: string[]; - /** - * The list of indices on which you want to replicate all write operations - * default: [] - * https://github.com/algolia/algoliasearch-client-js#replicas - */ - replicas?: string[]; - /** - * Limit the number of facet values returned for each facet - * default: "" - * https://github.com/algolia/algoliasearch-client-js#maxvaluesperfacet - */ - maxValuesPerFacet?: string; - /** - * Default list of attributes to highlight. If set to null, all indexed attributes are highlighted. - * default: null - * https://github.com/algolia/algoliasearch-client-js#attributestohighlight - */ - attributesToHighlight?: string[]; - /** - * Default list of attributes to snippet alongside the number of words to return - * default: null - * https://github.com/algolia/algoliasearch-client-js#attributestosnippet - */ - attributesToSnippet?: string[]; - /** - * Specify the string that is inserted before the highlighted parts in the query result - * default: - * https://github.com/algolia/algoliasearch-client-js#highlightpretag - */ - highlightPreTag?: string; - /** - * Specify the string that is inserted after the highlighted parts in the query result - * default: - * https://github.com/algolia/algoliasearch-client-js#highlightposttag - */ - highlightPostTag?: string; - /** - * String used as an ellipsis indicator when a snippet is truncated. - * default: … - * https://github.com/algolia/algoliasearch-client-js#snippetellipsistext - */ - snippetEllipsisText?: string; - /** - * If set to true, restrict arrays in highlights and snippets to items that matched the query at least partially else return all array items in highlights and snippets - * default: false - * https://github.com/algolia/algoliasearch-client-js#restricthighlightandsnippetarrays - */ - restrictHighlightAndSnippetArrays?: boolean; - /** - * Pagination parameter used to select the number of hits per page - * default: 20 - * https://github.com/algolia/algoliasearch-client-js#hitsperpage - */ - hitsPerPage?: number; - /** - * The minimum number of characters needed to accept one typo - * default: 4 - * https://github.com/algolia/algoliasearch-client-js#minwordsizefor1typo - */ - minWordSizefor1Typo?: number; - /** - * The minimum number of characters needed to accept two typos. - * default: 8 - * https://github.com/algolia/algoliasearch-client-js#highlightposttag - */ - minWordSizefor2Typos?: number; - /** - * This option allows you to control the number of typos allowed in the result set - * default: true - * 'true' The typo tolerance is enabled and all matching hits are retrieved (default behavior). - * 'false' The typo tolerance is disabled. All results with typos will be hidden. - * 'min' Only keep results with the minimum number of typos. For example, if one result matches without typos, then all results with typos will be hidden. - * 'strict' Hits matching with 2 typos are not retrieved if there are some matching without typos. - * https://github.com/algolia/algoliasearch-client-js#typotolerance - */ - typoTolerance?: any; - /** - * If set to false, disables typo tolerance on numeric tokens (numbers). - * default: true - * https://github.com/algolia/algoliasearch-client-js#allowtyposonnumerictokens - */ - allowTyposOnNumericTokens?: boolean; - /** - * If set to true, plural won't be considered as a typo - * default: false - * https://github.com/algolia/algoliasearch-client-js#ignoreplurals - */ - ignorePlurals?: boolean; - /** - * List of attributes on which you want to disable typo tolerance - * default: "" - * https://github.com/algolia/algoliasearch-client-js#disabletypotoleranceonattributes - */ - disableTypoToleranceOnAttributes?: string; - /** - * Specify the separators (punctuation characters) to index. - * default: "" - * https://github.com/algolia/algoliasearch-client-js#separatorstoindex - */ - separatorsToIndex?: string; - /** - * Selects how the query words are interpreted - * default: 'prefixLast' - * 'prefixAll' All query words are interpreted as prefixes. This option is not recommended. - * 'prefixLast' Only the last word is interpreted as a prefix (default behavior). - * 'prefixNone' No query word is interpreted as a prefix. This option is not recommended. - * https://github.com/algolia/algoliasearch-client-js#querytype - */ - queryType?: any; - /** - * This option is used to select a strategy in order to avoid having an empty result page - * default: 'none' - * 'lastWords' When a query does not return any results, the last word will be added as optional - * 'firstWords' When a query does not return any results, the first word will be added as optional - * 'allOptional' When a query does not return any results, a second trial will be made with all words as optional - * 'none' No specific processing is done when a query does not return any results - * https://github.com/algolia/algoliasearch-client-js#removewordsifnoresults - */ - removeWordsIfNoResults?: string; - /** - * Enables the advanced query syntax - * default: false - * https://github.com/algolia/algoliasearch-client-js#advancedsyntax - */ - advancedSyntax?: boolean; - /** - * A string that contains the comma separated list of words that should be considered as optional when found in the query - * default: [] - * https://github.com/algolia/algoliasearch-client-js#optionalwords - */ - optionalWords?: string[]; - /** - * Remove stop words from the query before executing it - * default: false - * true|false: enable or disable stop words for all 41 supported languages; or - * a list of language ISO codes (as a comma-separated string) for which stop words should be enable - * https://github.com/algolia/algoliasearch-client-js#removestopwords - */ - removeStopWords?: string[]; - /** - * List of attributes on which you want to disable prefix matching - * default: [] - * https://github.com/algolia/algoliasearch-client-js#disableprefixonattributes - */ - disablePrefixOnAttributes?: string[]; - /** - * List of attributes on which you want to disable the computation of exact criteria - * default: [] - * https://github.com/algolia/algoliasearch-client-js#disableexactonattributes - */ - disableExactOnAttributes?: string[]; - /** - * This parameter control how the exact ranking criterion is computed when the query contains one word - * default: attribute - * 'none': no exact on single word query - * 'word': exact set to 1 if the query word is found in the record - * 'attribute': exact set to 1 if there is an attribute containing a string equals to the query - * https://github.com/algolia/algoliasearch-client-js#exactonsinglewordquery - */ - exactOnSingleWordQuery?: string; - /** - * Specify the list of approximation that should be considered as an exact match in the ranking formula - * default: ['ignorePlurals', 'singleWordSynonym'] - * 'ignorePlurals': alternative words added by the ignorePlurals feature - * 'singleWordSynonym': single-word synonym (For example "NY" = "NYC") - * 'multiWordsSynonym': multiple-words synonym - * https://github.com/algolia/algoliasearch-client-js#alternativesasexact - */ - alternativesAsExact?: any; - /** - * The name of the attribute used for the Distinct feature - * default: null - * https://github.com/algolia/algoliasearch-client-js#attributefordistinct - */ - attributeForDistinct?: string; - /** - * If set to 1, enables the distinct feature, disabled by default, if the attributeForDistinct index setting is set. - * https://github.com/algolia/algoliasearch-client-js#distinct - */ - distinct?: any; - /** - * All numerical attributes are automatically indexed as numerical filters - * default '' - * https://github.com/algolia/algoliasearch-client-js#numericattributestoindex - */ - numericAttributesToIndex?: string[]; - /** - * Allows compression of big integer arrays. - * default: false - * https://github.com/algolia/algoliasearch-client-js#allowcompressionofintegerarray - */ - allowCompressionOfIntegerArray?: boolean; - /** - * Specify alternative corrections that you want to consider. - * default: [] - * https://github.com/algolia/algoliasearch-client-js#altcorrections - */ - altCorrections?: {}[]; - /** - * Configure the precision of the proximity ranking criterion - * default: 1 - * https://github.com/algolia/algoliasearch-client-js#minproximity - */ - minProximity?: number; - /** - * This is an advanced use-case to define a token substitutable by a list of words without having the original token searchable - * default: '' - * https://github.com/algolia/algoliasearch-client-js#placeholders - */ - placeholders?: any; - } - - interface AlgoliaQueryParameters { + interface QueryParameters { /** * Query string used to perform the search * default: '' @@ -1650,7 +1117,7 @@ Interface describing options available for gettings the logs * default: "" * https://github.com/algolia/algoliasearch-client-js#maxvaluesperfacet */ - maxValuesPerFacet?: string; + maxValuesPerFacet?: number; /** * Default list of attributes to highlight. If set to null, all indexed attributes are highlighted. * default: null @@ -1922,6 +1389,408 @@ Interface describing options available for gettings the logs * https://github.com/algolia/algoliasearch-client-js#minproximity */ minProximity?: number; + + nbShards?: number; + userData?: string | object; + } + + interface AlgoliaResponse { + /** + * Contains all the hits matching the query + * https://github.com/algolia/algoliasearch-client-js#response-format + */ + hits: any[]; + /** + * Current page + * https://github.com/algolia/algoliasearch-client-js#response-format + */ + page: number; + /** + * Number of total hits matching the query + * https://github.com/algolia/algoliasearch-client-js#response-format + */ + nbHits: number; + /** + * Number of pages + * https://github.com/algolia/algoliasearch-client-js#response-format + */ + nbPage: number; + /** + * Number of hits per pages + * https://github.com/algolia/algoliasearch-client-js#response-format + */ + hitsPerPage: number; + /** + * Engine processing time (excluding network transfer) + * https://github.com/algolia/algoliasearch-client-js#response-format + */ + processingTimeMS: number; + /** + * Query used to perform the search + * https://github.com/algolia/algoliasearch-client-js#response-format + */ + query: string; + /** + * GET parameters used to perform the search + * https://github.com/algolia/algoliasearch-client-js#response-format + */ + params: string; + facets: { + [facetName: string]: { [facetValue: string]: number }; + }; + } + + namespace SearchForFacetValues { + interface Parameters extends QueryParameters { + /** + * The facet to search in + */ + facetName: string; + /** + * The query for the search in this facet + */ + facetQuery: string; + } + + interface Response { + facetHits: { value: string; highlighted: string; count: number }[]; + exhaustiveFacetsCount: boolean; + processingTimeMS: number; + } + } + + interface Log { + timestamp: string; + method: string; + answer_code: number; + query_body: string; + answer: string; + url: string; + ip: string; + query_headers: string; + sha1: string; + nb_api_calls: string; + index: string; + query_params: string; + query_nb_hits: string; + processing_time_ms: string; + exhaustive_faceting?: false; + exhaustive_nb_hits?: false; + } + + interface Task { + taskID: number; + } + + interface IndexSettings { + /** + * The list of attributes you want index + * default: * + * https://github.com/algolia/algoliasearch-client-js#attributestoindex + */ + attributesToIndex?: string[]; + /** + * The list of attributes you want to use for faceting + * default: null + * https://github.com/algolia/algoliasearch-client-js#attributesforfaceting + */ + attributesForFaceting?: string[]; + /** + * The list of attributes that cannot be retrieved at query time + * default: null + * https://github.com/algolia/algoliasearch-client-js#unretrievableattributes + */ + unretrievableAttributes?: string[]; + /** + * List of attributes you want to use for textual search + * default: [] + * https://github.com/algolia/algoliasearch-client-js#searchableattributes + */ + searchableAttributes?: string[]; + /** + * A string that contains the list of attributes you want to retrieve in order to minimize the size of the JSON answer + * default: * + * https://github.com/algolia/algoliasearch-client-js#attributestoretrieve + */ + attributesToRetrieve?: string[]; + /** + * Controls the way results are sorted + * default: ['typo', 'geo', 'words', 'filters', 'proximity', 'attribute', 'exact', 'custom'] + * https://github.com/algolia/algoliasearch-client-js#ranking + */ + ranking?: string[]; + /** + * Lets you specify part of the ranking + * default: [] + * https://github.com/algolia/algoliasearch-client-js#customranking + */ + customRanking?: string[]; + /** + * The list of indices on which you want to replicate all write operations + * default: [] + * https://github.com/algolia/algoliasearch-client-js#replicas + */ + replicas?: string[]; + /** + * Limit the number of facet values returned for each facet + * default: "" + * https://github.com/algolia/algoliasearch-client-js#maxvaluesperfacet + */ + maxValuesPerFacet?: number; + /** + * Default list of attributes to highlight. If set to null, all indexed attributes are highlighted. + * default: null + * https://github.com/algolia/algoliasearch-client-js#attributestohighlight + */ + attributesToHighlight?: string[]; + /** + * Default list of attributes to snippet alongside the number of words to return + * default: null + * https://github.com/algolia/algoliasearch-client-js#attributestosnippet + */ + attributesToSnippet?: string[]; + /** + * Specify the string that is inserted before the highlighted parts in the query result + * default: + * https://github.com/algolia/algoliasearch-client-js#highlightpretag + */ + highlightPreTag?: string; + /** + * Specify the string that is inserted after the highlighted parts in the query result + * default: + * https://github.com/algolia/algoliasearch-client-js#highlightposttag + */ + highlightPostTag?: string; + /** + * String used as an ellipsis indicator when a snippet is truncated. + * default: … + * https://github.com/algolia/algoliasearch-client-js#snippetellipsistext + */ + snippetEllipsisText?: string; + /** + * If set to true, restrict arrays in highlights and snippets to items that matched the query at least partially else return all array items in highlights and snippets + * default: false + * https://github.com/algolia/algoliasearch-client-js#restricthighlightandsnippetarrays + */ + restrictHighlightAndSnippetArrays?: boolean; + /** + * Pagination parameter used to select the number of hits per page + * default: 20 + * https://github.com/algolia/algoliasearch-client-js#hitsperpage + */ + hitsPerPage?: number; + /** + * The minimum number of characters needed to accept one typo + * default: 4 + * https://github.com/algolia/algoliasearch-client-js#minwordsizefor1typo + */ + minWordSizefor1Typo?: number; + /** + * The minimum number of characters needed to accept two typos. + * default: 8 + * https://github.com/algolia/algoliasearch-client-js#highlightposttag + */ + minWordSizefor2Typos?: number; + /** + * This option allows you to control the number of typos allowed in the result set + * default: true + * 'true' The typo tolerance is enabled and all matching hits are retrieved (default behavior). + * 'false' The typo tolerance is disabled. All results with typos will be hidden. + * 'min' Only keep results with the minimum number of typos. For example, if one result matches without typos, then all results with typos will be hidden. + * 'strict' Hits matching with 2 typos are not retrieved if there are some matching without typos. + * https://github.com/algolia/algoliasearch-client-js#typotolerance + */ + typoTolerance?: any; + /** + * If set to false, disables typo tolerance on numeric tokens (numbers). + * default: true + * https://github.com/algolia/algoliasearch-client-js#allowtyposonnumerictokens + */ + allowTyposOnNumericTokens?: boolean; + /** + * If set to true, plural won't be considered as a typo + * default: false + * https://github.com/algolia/algoliasearch-client-js#ignoreplurals + */ + ignorePlurals?: boolean; + /** + * List of attributes on which you want to disable typo tolerance + * default: "" + * https://github.com/algolia/algoliasearch-client-js#disabletypotoleranceonattributes + */ + disableTypoToleranceOnAttributes?: string; + /** + * Specify the separators (punctuation characters) to index. + * default: "" + * https://github.com/algolia/algoliasearch-client-js#separatorstoindex + */ + separatorsToIndex?: string; + /** + * Selects how the query words are interpreted + * default: 'prefixLast' + * 'prefixAll' All query words are interpreted as prefixes. This option is not recommended. + * 'prefixLast' Only the last word is interpreted as a prefix (default behavior). + * 'prefixNone' No query word is interpreted as a prefix. This option is not recommended. + * https://github.com/algolia/algoliasearch-client-js#querytype + */ + queryType?: any; + /** + * This option is used to select a strategy in order to avoid having an empty result page + * default: 'none' + * 'lastWords' When a query does not return any results, the last word will be added as optional + * 'firstWords' When a query does not return any results, the first word will be added as optional + * 'allOptional' When a query does not return any results, a second trial will be made with all words as optional + * 'none' No specific processing is done when a query does not return any results + * https://github.com/algolia/algoliasearch-client-js#removewordsifnoresults + */ + removeWordsIfNoResults?: string; + /** + * Enables the advanced query syntax + * default: false + * https://github.com/algolia/algoliasearch-client-js#advancedsyntax + */ + advancedSyntax?: boolean; + /** + * A string that contains the comma separated list of words that should be considered as optional when found in the query + * default: [] + * https://github.com/algolia/algoliasearch-client-js#optionalwords + */ + optionalWords?: string[]; + /** + * Remove stop words from the query before executing it + * default: false + * true|false: enable or disable stop words for all 41 supported languages; or + * a list of language ISO codes (as a comma-separated string) for which stop words should be enable + * https://github.com/algolia/algoliasearch-client-js#removestopwords + */ + removeStopWords?: string[]; + /** + * List of attributes on which you want to apply word-splitting ("decompounding") for + * each of the languages supported (German, Dutch, and Finnish as of 05/2018) + * default: {de: [], nl: [], fi: []} + */ + decompoundedAttributes?: { [key in Partial<'nl' | 'de' | 'fi'>]: string[] }; + /** + * List of attributes on which you want to disable prefix matching + * default: [] + * https://github.com/algolia/algoliasearch-client-js#disableprefixonattributes + */ + disablePrefixOnAttributes?: string[]; + /** + * List of attributes on which you want to disable the computation of exact criteria + * default: [] + * https://github.com/algolia/algoliasearch-client-js#disableexactonattributes + */ + disableExactOnAttributes?: string[]; + /** + * This parameter control how the exact ranking criterion is computed when the query contains one word + * default: attribute + * 'none': no exact on single word query + * 'word': exact set to 1 if the query word is found in the record + * 'attribute': exact set to 1 if there is an attribute containing a string equals to the query + * https://github.com/algolia/algoliasearch-client-js#exactonsinglewordquery + */ + exactOnSingleWordQuery?: string; + /** + * Specify the list of approximation that should be considered as an exact match in the ranking formula + * default: ['ignorePlurals', 'singleWordSynonym'] + * 'ignorePlurals': alternative words added by the ignorePlurals feature + * 'singleWordSynonym': single-word synonym (For example "NY" = "NYC") + * 'multiWordsSynonym': multiple-words synonym + * https://github.com/algolia/algoliasearch-client-js#alternativesasexact + */ + alternativesAsExact?: any; + /** + * The name of the attribute used for the Distinct feature + * default: null + * https://github.com/algolia/algoliasearch-client-js#attributefordistinct + */ + attributeForDistinct?: string; + /** + * If set to 1, enables the distinct feature, disabled by default, if the attributeForDistinct index setting is set. + * https://github.com/algolia/algoliasearch-client-js#distinct + */ + distinct?: any; + /** + * All numerical attributes are automatically indexed as numerical filters + * default '' + * https://github.com/algolia/algoliasearch-client-js#numericattributestoindex + */ + numericAttributesToIndex?: string[]; + /** + * Allows compression of big integer arrays. + * default: false + * https://github.com/algolia/algoliasearch-client-js#allowcompressionofintegerarray + */ + allowCompressionOfIntegerArray?: boolean; + /** + * Specify alternative corrections that you want to consider. + * default: [] + * https://github.com/algolia/algoliasearch-client-js#altcorrections + */ + altCorrections?: {}[]; + /** + * Configure the precision of the proximity ranking criterion + * default: 1 + * https://github.com/algolia/algoliasearch-client-js#minproximity + */ + minProximity?: number; + /** + * This is an advanced use-case to define a token substitutable by a list of words without having the original token searchable + * default: '' + * https://github.com/algolia/algoliasearch-client-js#placeholders + */ + placeholders?: any; + } + + interface Response { + /** + * Contains all the hits matching the query + * https://github.com/algolia/algoliasearch-client-js#response-format + */ + hits: any[]; + /** + * Current page + * https://github.com/algolia/algoliasearch-client-js#response-format + */ + page: number; + /** + * Number of total hits matching the query + * https://github.com/algolia/algoliasearch-client-js#response-format + */ + nbHits: number; + /** + * Number of pages + * https://github.com/algolia/algoliasearch-client-js#response-format + */ + nbPages: number; + /** + * Number of hits per pages + * https://github.com/algolia/algoliasearch-client-js#response-format + */ + hitsPerPage: number; + /** + * Engine processing time (excluding network transfer) + * https://github.com/algolia/algoliasearch-client-js#response-format + */ + processingTimeMS: number; + /** + * Query used to perform the search + * https://github.com/algolia/algoliasearch-client-js#response-format + */ + query: string; + /** + * GET parameters used to perform the search + * https://github.com/algolia/algoliasearch-client-js#response-format + */ + params: string; + facets?: { + [facetName: string]: { [facetValue: string]: number }; + }; + } + + interface MultiResponse { + results: Response[]; } } @@ -1929,5 +1798,5 @@ declare function algoliasearch( applicationId: string, apiKey: string, options?: algoliasearch.ClientOptions -): algoliasearch.AlgoliaClient; +): algoliasearch.Client; export = algoliasearch; diff --git a/types/algoliasearch/lite/index.d.ts b/types/algoliasearch/lite/index.d.ts new file mode 100644 index 0000000000..588e2ac543 --- /dev/null +++ b/types/algoliasearch/lite/index.d.ts @@ -0,0 +1,624 @@ +// Type definitions for algoliasearch-client-js 3.27.0 +// Project: https://github.com/algolia/algoliasearch-client-js +// Definitions by: Baptiste Coquelle +// Haroen Viaene +// Aurélien Hervé +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.2 + +declare namespace algoliasearch { + /* + Interface for the algolia client object + */ + interface Client { + /** + * Initialization of the index + * https://github.com/algolia/algoliasearch-client-js#init-index---initindex + */ + initIndex(indexName: string): Index; + /** + * Query on multiple index + * https://github.com/algolia/algoliasearch-client-js#multiple-queries---multiplequeries + */ + search( + queries: { + indexName: string; + query: string; + params: QueryParameters; + }[], + cb: (err: Error, res: MultiResponse) => void + ): void; + /** + * Query on multiple index + * https://github.com/algolia/algoliasearch-client-js#multiple-queries---multiplequeries + */ + search( + queries: { + indexName: string; + query: string; + params: QueryParameters; + }[] + ): Promise; + /** + * Query for facet values of a specific facet + */ + searchForFacetValues( + queries: [{ indexName: string; params: SearchForFacetValues.Parameters }] + ): Promise; + /** + * clear browser cache + * https://github.com/algolia/algoliasearch-client-js#cache + */ + clearCache(): void; + /** + * Add a header to be sent with all upcoming requests + */ + setExtraHeader(name: string, value: string): void; + /** + * Get the value of an extra header + */ + getExtraHeader(name: string): string; + /** + * remove an extra header for all upcoming requests + */ + unsetExtraHeader(name: string): void; + } + /** + * Interface for the index algolia object + */ + interface Index { + /** + * Gets a specific object + * https://github.com/algolia/algoliasearch-client-js#find-by-ids---getobjects + */ + getObject(objectID: string, cb: (err: Error, res: {}) => void): void; + /** + * Gets specific attributes from an object + * https://github.com/algolia/algoliasearch-client-js#find-by-ids---getobjects + */ + getObject( + objectID: string, + attributes: string[], + cb: (err: Error, res: {}) => void + ): void; + /** + * Gets a list of objects + * https://github.com/algolia/algoliasearch-client-js#find-by-ids---getobjects + */ + getObjects( + objectIDs: string[], + cb: (err: Error, res: { results: {}[] }) => void + ): void; + /** + * Gets a list of objects + * https://github.com/algolia/algoliasearch-client-js#find-by-ids---getobjects + */ + getObjects(objectIDs: string[]): Promise<{ results: {}[] }>; + /** + * Clear cache of an index + * https://github.com/algolia/algoliasearch-client-js#cache + */ + clearCache(): void; + /** + * Search in an index + * https://github.com/algolia/algoliasearch-client-js#search-in-an-index---search + */ + search( + params: QueryParameters, + cb: (err: Error, res: Response) => void + ): void; + /** + * Search in an index + * https://github.com/algolia/algoliasearch-client-js#search-in-an-index---search + */ + search(params: QueryParameters): Promise; + /** + * Search in an index + * https://www.algolia.com/doc/api-reference/api-methods/search-for-facet-values/ + */ + searchForFacetValues( + options: SearchForFacetValues.Parameters + ): Promise; + /** + * Search in an index + * https://www.algolia.com/doc/api-reference/api-methods/search-for-facet-values/ + */ + searchForFacetValues( + options: SearchForFacetValues.Parameters, + cb: (err: Error, res: SearchForFacetValues.Response) => void + ): void; + /** + * Browse an index + * https://github.com/algolia/algoliasearch-client-js#backup--export-an-index---browse + */ + browse(query: string, cb: (err: Error, res: BrowseResponse) => void): void; + /** + * Browse an index + * https://github.com/algolia/algoliasearch-client-js#backup--export-an-index---browse + */ + browse(query: string): Promise; + /** + * Browse an index from a cursor + * https://github.com/algolia/algoliasearch-client-js#backup--export-an-index---browse + */ + browseFrom( + cursor: string, + cb: (err: Error, res: BrowseResponse) => void + ): void; + /** + * Browse an index from a cursor + * https://github.com/algolia/algoliasearch-client-js#backup--export-an-index---browse + */ + browseFrom(cursor: string): Promise; + } + /** + * Interface describing available options when initializing a client + */ + interface ClientOptions { + /** + * Timeout for requests to our servers, in milliseconds + * default: 15s (node), 2s (browser) + * https://github.com/algolia/algoliasearch-client-js#client-options + */ + timeout?: number; + /** + * Protocol to use when communicating with algolia + * default: current protocol(browser), https(node) + * https://github.com/algolia/algoliasearch-client-js#client-options + */ + protocol?: string; + /** + * (node only) httpAgent instance to use when communicating with servers. + * https://github.com/algolia/algoliasearch-client-js#client-options + */ + httpAgent?: any; + /** + * read: array of read hosts to use to call servers, computed automatically + * write: array of read hosts to use to call servers, computed automatically + * https://github.com/algolia/algoliasearch-client-js#client-options + */ + hosts?: { read?: string[]; write?: string[] }; + } + interface BrowseResponse { + cursor?: string; + hits: {}[]; + params: string; + query: string; + processingTimeMS: number; + } + + interface QueryParameters { + /** + * Query string used to perform the search + * default: '' + * https://github.com/algolia/algoliasearch-client-js#query + */ + query?: string; + /** + * Filter the query with numeric, facet or/and tag filters + * default: "" + * https://github.com/algolia/algoliasearch-client-js#filters + */ + filters?: string; + /** + * A string that contains the list of attributes you want to retrieve in order to minimize the size of the JSON answer. + * default: * + * https://github.com/algolia/algoliasearch-client-js#attributestoretrieve + */ + attributesToRetrieve?: string[]; + /** + * List of attributes you want to use for textual search + * default: attributeToIndex + * https://github.com/algolia/algoliasearch-client-js#restrictsearchableattributes + */ + restrictSearchableAttributes?: string[]; + /** + * You can use facets to retrieve only a part of your attributes declared in attributesForFaceting attributes + * default: "" + * https://github.com/algolia/algoliasearch-client-js#facets + */ + facets?: string; + /** + * Limit the number of facet values returned for each facet. + * default: "" + * https://github.com/algolia/algoliasearch-client-js#maxvaluesperfacet + */ + maxValuesPerFacet?: number; + /** + * Default list of attributes to highlight. If set to null, all indexed attributes are highlighted. + * default: null + * https://github.com/algolia/algoliasearch-client-js#attributestohighlight + */ + attributesToHighlight?: string[]; + /** + * Default list of attributes to snippet alongside the number of words to return + * default: null + * https://github.com/algolia/algoliasearch-client-js#attributestosnippet + */ + attributesToSnippet?: string[]; + /** + * Specify the string that is inserted before the highlighted parts in the query result + * default: + * https://github.com/algolia/algoliasearch-client-js#highlightpretag + */ + highlightPreTag?: string; + /** + * Specify the string that is inserted after the highlighted parts in the query result + * default: + * https://github.com/algolia/algoliasearch-client-js#highlightposttag + */ + highlightPostTag?: string; + /** + * String used as an ellipsis indicator when a snippet is truncated. + * default: … + * https://github.com/algolia/algoliasearch-client-js#snippetellipsistext + */ + snippetEllipsisText?: string; + /** + * If set to true, restrict arrays in highlights and snippets to items that matched the query at least partially else return all array items in highlights and snippets + * default: false + * https://github.com/algolia/algoliasearch-client-js#restricthighlightandsnippetarrays + */ + restrictHighlightAndSnippetArrays?: boolean; + /** + * Pagination parameter used to select the number of hits per page + * default: 20 + * https://github.com/algolia/algoliasearch-client-js#hitsperpage + */ + hitsPerPage?: number; + /** + * Pagination parameter used to select the page to retrieve. + * default: 0 + * https://github.com/algolia/algoliasearch-client-js#page + */ + page?: number; + /** + * Offset of the first hit to return + * default: null + * https://github.com/algolia/algoliasearch-client-js#offset + */ + offset?: number; + /** + * Number of hits to return. + * default: null + * https://github.com/algolia/algoliasearch-client-js#length + */ + length?: number; + /** + * The minimum number of characters needed to accept one typo. + * default: 4 + * https://github.com/algolia/algoliasearch-client-js#minwordsizefor1typo + */ + minWordSizefor1Typo?: number; + /** + * The minimum number of characters needed to accept two typo. + * fault: 8 + * https://github.com/algolia/algoliasearch-client-js#minwordsizefor2typos + */ + minWordSizefor2Typos?: number; + /** + * This option allows you to control the number of typos allowed in the result set: + * default: true + * 'true' The typo tolerance is enabled and all matching hits are retrieved + * 'false' The typo tolerance is disabled. All results with typos will be hidden. + * 'min' Only keep results with the minimum number of typos + * 'strict' Hits matching with 2 typos are not retrieved if there are some matching without typos. + * https://github.com/algolia/algoliasearch-client-js#minwordsizefor2typos + */ + typoTolerance?: boolean; + /** + * If set to false, disables typo tolerance on numeric tokens (numbers). + * default: + * https://github.com/algolia/algoliasearch-client-js#allowtyposonnumerictokens + */ + allowTyposOnNumericTokens?: boolean; + /** + * If set to true, plural won't be considered as a typo + * default: false + * https://github.com/algolia/algoliasearch-client-js#ignoreplurals + */ + ignorePlurals?: boolean; + /** + * List of attributes on which you want to disable typo tolerance + * default: "" + * https://github.com/algolia/algoliasearch-client-js#disabletypotoleranceonattributes + */ + disableTypoToleranceOnAttributes?: string; + /** + * Search for entries around a given location + * default: "" + * https://github.com/algolia/algoliasearch-client-js#aroundlatlng + */ + aroundLatLng?: string; + /** + * Search for entries around a given latitude/longitude automatically computed from user IP address. + * default: "" + * https://github.com/algolia/algoliasearch-client-js#aroundlatlngviaip + */ + aroundLatLngViaIP?: string; + /** + * Control the radius associated with a geo search. Defined in meters. + * default: null + * You can specify aroundRadius=all if you want to compute the geo distance without filtering in a geo area + * https://github.com/algolia/algoliasearch-client-js#aroundradius + */ + aroundRadius?: number | 'all'; + /** + * Control the precision of a geo search + * default: null + * https://github.com/algolia/algoliasearch-client-js#aroundprecision + */ + aroundPrecision?: number; + /** + * Define the minimum radius used for a geo search when aroundRadius is not set. + * default: null + * https://github.com/algolia/algoliasearch-client-js#minimumaroundradius + */ + minimumAroundRadius?: number; + /** + * Search entries inside a given area defined by the two extreme points of a rectangle + * default: null + * https://github.com/algolia/algoliasearch-client-js#insideboundingbox + */ + insideBoundingBox?: number[][]; + /** + * Selects how the query words are interpreted + * default: 'prefixLast' + * 'prefixAll' All query words are interpreted as prefixes. This option is not recommended. + * 'prefixLast' Only the last word is interpreted as a prefix (default behavior). + * 'prefixNone' No query word is interpreted as a prefix. This option is not recommended. + * https://github.com/algolia/algoliasearch-client-js#querytype + */ + queryType?: any; + /** + * Search entries inside a given area defined by a set of points + * defauly: '' + * https://github.com/algolia/algoliasearch-client-js#insidepolygon + */ + insidePolygon?: number[][]; + /** + * This option is used to select a strategy in order to avoid having an empty result page + * default: 'none' + * 'lastWords' When a query does not return any results, the last word will be added as optional + * 'firstWords' When a query does not return any results, the first word will be added as optional + * 'allOptional' When a query does not return any results, a second trial will be made with all words as optional + * 'none' No specific processing is done when a query does not return any results + * https://github.com/algolia/algoliasearch-client-js#removewordsifnoresults + */ + removeWordsIfNoResults?: string; + /** + * Enables the advanced query syntax + * default: false + * https://github.com/algolia/algoliasearch-client-js#advancedsyntax + */ + advancedSyntax?: boolean; + /** + * A string that contains the comma separated list of words that should be considered as optional when found in the query + * default: [] + * https://github.com/algolia/algoliasearch-client-js#optionalwords + */ + optionalWords?: string[]; + /** + * Remove stop words from the query before executing it + * default: false + * true|false: enable or disable stop words for all 41 supported languages; or + * a list of language ISO codes (as a comma-separated string) for which stop words should be enable + * https://github.com/algolia/algoliasearch-client-js#removestopwords + */ + removeStopWords?: string[]; + /** + * List of attributes on which you want to disable the computation of exact criteria + * default: [] + * https://github.com/algolia/algoliasearch-client-js#disableexactonattributes + */ + disableExactOnAttributes?: string[]; + /** + * This parameter control how the exact ranking criterion is computed when the query contains one word + * default: attribute + * 'none': no exact on single word query + * 'word': exact set to 1 if the query word is found in the record + * 'attribute': exact set to 1 if there is an attribute containing a string equals to the query + * https://github.com/algolia/algoliasearch-client-js#exactonsinglewordquery + */ + exactOnSingleWordQuery?: string; + /** + * Specify the list of approximation that should be considered as an exact match in the ranking formula + * default: ['ignorePlurals', 'singleWordSynonym'] + * 'ignorePlurals': alternative words added by the ignorePlurals feature + * 'singleWordSynonym': single-word synonym (For example "NY" = "NYC") + * 'multiWordsSynonym': multiple-words synonym + * https://github.com/algolia/algoliasearch-client-js#alternativesasexact + */ + alternativesAsExact?: any; + /** + * If set to 1, enables the distinct feature, disabled by default, if the attributeForDistinct index setting is set. + * https://github.com/algolia/algoliasearch-client-js#distinct + */ + distinct?: any; + /** + * If set to true, the result hits will contain ranking information in the _rankingInfo attribute. + * default: false + * https://github.com/algolia/algoliasearch-client-js#getrankinginfo + */ + getRankingInfo?: boolean; + /** + * All numerical attributes are automatically indexed as numerical filters + * default: '' + * https://github.com/algolia/algoliasearch-client-js#numericattributestoindex + */ + numericAttributesToIndex?: string[]; + /** + * @deprecated please use filters instead + * A string that contains the comma separated list of numeric filters you want to apply. + * https://github.com/algolia/algoliasearch-client-js#numericfilters-deprecated + */ + numericFilters?: string[]; + /** + * @deprecated + * Filter the query by a set of tags. + * https://github.com/algolia/algoliasearch-client-js#tagfilters-deprecated + */ + tagFilters?: string; + /** + * @deprecated + * Filter the query by a set of facets. + * https://github.com/algolia/algoliasearch-client-js#facetfilters-deprecated + */ + facetFilters?: string; + /** + * If set to false, this query will not be taken into account in the analytics feature. + * default true + * https://github.com/algolia/algoliasearch-client-js#analytics + */ + analytics?: boolean; + /** + * If set, tag your query with the specified identifiers + * default: null + * https://github.com/algolia/algoliasearch-client-js#analyticstags + */ + analyticsTags?: string[]; + /** + * If set to false, the search will not use the synonyms defined for the targeted index. + * default: true + * https://github.com/algolia/algoliasearch-client-js#synonyms + */ + synonyms?: boolean; + /** + * If set to false, words matched via synonym expansion will not be replaced by the matched synonym in the highlighted result. + * default: true + * https://github.com/algolia/algoliasearch-client-js#replacesynonymsinhighlight + */ + replaceSynonymsInHighlight?: boolean; + /** + * Configure the precision of the proximity ranking criterion + * default: 1 + * https://github.com/algolia/algoliasearch-client-js#minproximity + */ + minProximity?: number; + + nbShards?: number; + userData?: string | object; + } + + interface AlgoliaResponse { + /** + * Contains all the hits matching the query + * https://github.com/algolia/algoliasearch-client-js#response-format + */ + hits: any[]; + /** + * Current page + * https://github.com/algolia/algoliasearch-client-js#response-format + */ + page: number; + /** + * Number of total hits matching the query + * https://github.com/algolia/algoliasearch-client-js#response-format + */ + nbHits: number; + /** + * Number of pages + * https://github.com/algolia/algoliasearch-client-js#response-format + */ + nbPage: number; + /** + * Number of hits per pages + * https://github.com/algolia/algoliasearch-client-js#response-format + */ + hitsPerPage: number; + /** + * Engine processing time (excluding network transfer) + * https://github.com/algolia/algoliasearch-client-js#response-format + */ + processingTimeMS: number; + /** + * Query used to perform the search + * https://github.com/algolia/algoliasearch-client-js#response-format + */ + query: string; + /** + * GET parameters used to perform the search + * https://github.com/algolia/algoliasearch-client-js#response-format + */ + params: string; + facets: { + [facetName: string]: { [facetValue: string]: number }; + }; + } + + namespace SearchForFacetValues { + interface Parameters extends QueryParameters { + /** + * The facet to search in + */ + facetName: string; + /** + * The query for the search in this facet + */ + facetQuery: string; + } + + interface Response { + facetHits: { value: string; highlighted: string; count: number }[]; + exhaustiveFacetsCount: boolean; + processingTimeMS: number; + } + } + + interface Response { + /** + * Contains all the hits matching the query + * https://github.com/algolia/algoliasearch-client-js#response-format + */ + hits: any[]; + /** + * Current page + * https://github.com/algolia/algoliasearch-client-js#response-format + */ + page: number; + /** + * Number of total hits matching the query + * https://github.com/algolia/algoliasearch-client-js#response-format + */ + nbHits: number; + /** + * Number of pages + * https://github.com/algolia/algoliasearch-client-js#response-format + */ + nbPages: number; + /** + * Number of hits per pages + * https://github.com/algolia/algoliasearch-client-js#response-format + */ + hitsPerPage: number; + /** + * Engine processing time (excluding network transfer) + * https://github.com/algolia/algoliasearch-client-js#response-format + */ + processingTimeMS: number; + /** + * Query used to perform the search + * https://github.com/algolia/algoliasearch-client-js#response-format + */ + query: string; + /** + * GET parameters used to perform the search + * https://github.com/algolia/algoliasearch-client-js#response-format + */ + params: string; + facets?: { + [facetName: string]: { [facetValue: string]: number }; + }; + } + + interface MultiResponse { + results: Response[]; + } +} + +declare function algoliasearch( + applicationId: string, + apiKey: string, + options?: algoliasearch.ClientOptions +): algoliasearch.Client; +export = algoliasearch; diff --git a/types/algoliasearch/tsconfig.json b/types/algoliasearch/tsconfig.json index 3358732ba3..9a8a2a623c 100644 --- a/types/algoliasearch/tsconfig.json +++ b/types/algoliasearch/tsconfig.json @@ -18,6 +18,7 @@ }, "files": [ "index.d.ts", + "lite/index.d.ts", "algoliasearch-tests.ts" ] -} \ No newline at end of file +} diff --git a/types/angular-translate/index.d.ts b/types/angular-translate/index.d.ts index 69b1f63d72..719fcb5d5c 100644 --- a/types/angular-translate/index.d.ts +++ b/types/angular-translate/index.d.ts @@ -1,11 +1,9 @@ // Type definitions for Angular Translate (pascalprecht.translate module) 2.15 // Project: https://github.com/PascalPrecht/angular-translate -// Definitions by: Michel Salib +// Definitions by: Michel Salib , Gabriel Gil // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped // TypeScript Version: 2.3 -/// - declare var _: string; export = _; @@ -69,7 +67,7 @@ declare module 'angular' { versionInfo(): string; loaderCache(): any; isReady(): boolean; - onReady(): angular.IPromise; + onReady(fn?: () => void): angular.IPromise; resolveClientLocale(): string; getAvailableLanguageKeys(): string[]; } diff --git a/types/angular/angular-tests.ts b/types/angular/angular-tests.ts index ca9d2c7568..1dff1a0451 100644 --- a/types/angular/angular-tests.ts +++ b/types/angular/angular-tests.ts @@ -1138,7 +1138,8 @@ angular.module('multiSlotTranscludeExample', []) }; }); -angular.module('componentExample', []) +// $ExpectType IModule +const componentModule = angular.module('componentExample', []) .component('counter', { require: {ctrl: '^ctrl'}, bindings: { @@ -1160,6 +1161,16 @@ angular.module('componentExample', []) }, template: '', transclude: true + }) + .component({ + aThirdComponent: { + controller: class AThirdComponentController { + count: number; + }, + bindings: { + count: '=' + } + } }); interface ICopyExampleUser { diff --git a/types/angular/index.d.ts b/types/angular/index.d.ts index 4c896eb430..6dccefc926 100644 --- a/types/angular/index.d.ts +++ b/types/angular/index.d.ts @@ -196,6 +196,12 @@ declare namespace angular { * @param options A definition object passed into the component. */ component(name: string, options: IComponentOptions): IModule; + /** + * Use this method to register a component. + * + * @param object Object map of components where the keys are the names and the values are the component definition objects + */ + component(object: {[componentName: string]: IComponentOptions}): IModule; /** * Use this method to register work which needs to be performed on module loading. * @@ -1028,7 +1034,7 @@ declare namespace angular { all(values: [T1 | IPromise, T2 | IPromise, T3 | IPromise, T4 | IPromise ]): IPromise<[T1, T2, T3, T4]>; all(values: [T1 | IPromise, T2 | IPromise, T3 | IPromise]): IPromise<[T1, T2, T3]>; all(values: [T1 | IPromise, T2 | IPromise]): IPromise<[T1, T2]>; - all(promises: Array>): IPromise; + all(promises: Array>): IPromise; /** * Combines multiple promises into a single promise that is resolved when all of the input promises are resolved. * @@ -1273,6 +1279,7 @@ declare namespace angular { directive(object: {[directiveName: string]: Injectable>}): ICompileProvider; component(name: string, options: IComponentOptions): ICompileProvider; + component(object: {[componentName: string]: IComponentOptions}): ICompileProvider; aHrefSanitizationWhitelist(): RegExp; aHrefSanitizationWhitelist(regexp: RegExp): ICompileProvider; diff --git a/types/atlaskit__layer/atlaskit__layer-tests.tsx b/types/atlaskit__layer/atlaskit__layer-tests.tsx new file mode 100644 index 0000000000..d10ad57ff0 --- /dev/null +++ b/types/atlaskit__layer/atlaskit__layer-tests.tsx @@ -0,0 +1,15 @@ +import Layer from '@atlaskit/layer'; + +import * as React from 'react'; +import { render } from 'react-dom'; + +declare const container: Element; + +render( + Hello, world!} + autoFlip={false} + />, + container, +); diff --git a/types/atlaskit__layer/index.d.ts b/types/atlaskit__layer/index.d.ts new file mode 100644 index 0000000000..2f50a5abcf --- /dev/null +++ b/types/atlaskit__layer/index.d.ts @@ -0,0 +1,72 @@ +// Type definitions for @atlaskit/layer 3.1 +// Project: https://bitbucket.org/atlassian/atlaskit-mk-2/src/master/ +// Definitions by: Lee Standen +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.6 + +import { Component, ReactNode } from 'react'; + +export default class Layer extends Component {} + +export interface Props { + /** + * Sets whether the content auto flip when it reaches the border set it as true for default flip + * or set the custom flip positions + */ + autoFlip?: boolean | FlipPositionType | FlipPositionType[]; + /** + * Element to act as a boundary for the Layer. The Layer will not sit outside this element if it + * can help it. If, through it's normal positoning, it would end up outside the boundary the + * layer will flip positions if the autoPosition prop is set. + */ + boundariesElement?: BoundariesElementType; + /** Target to which layer is attached */ + children?: ReactNode; + /** HTML content to display in the layer. Will be aligned to the target according to the position prop. */ + content?: ReactNode; + /** + * String representing the offsets from the target element in the format "[x-offset][y-offset]", + * measured in pixels. + */ + offset?: string; + /** + * Callback that is used to know when the flipped state of Layer changes. This occurs when placing a + * Layered element in the requested position would cause Layer to be rendered outside of the + * boundariesElement (usually viewport). + */ + onFlippedChange?: ( + flipped: boolean, + actualPosition: CSSPositionType, + originalPosition: CSSPositionType, + ) => void; + /** + * Position of a layer relative to its target. The position attribute takes two positional arguments in + * the format position="edge edge-position", where edge specifies what edge to align the layer to, and + * edge-position specifies where on that edge the layer should appear. + */ + position?: PositionType; + /** z-index for the layer component */ + zIndex?: number; + /** Lock scrolling behind the layer */ + lockScroll?: boolean; +} + +export type FlipPositionType = 'top' | 'right' | 'bottom' | 'left'; + +export type PositionType = + | 'top left' + | 'top center' + | 'top right' + | 'right top' + | 'right middle' + | 'right bottom' + | 'bottom left' + | 'bottom center' + | 'bottom right' + | 'left top' + | 'left middle' + | 'left bottom'; + +export type BoundariesElementType = 'viewport' | 'window' | 'scrollParent'; + +export type CSSPositionType = 'absolute' | 'fixed'; diff --git a/types/atlaskit__layer/tsconfig.json b/types/atlaskit__layer/tsconfig.json new file mode 100644 index 0000000000..6b6a475bd3 --- /dev/null +++ b/types/atlaskit__layer/tsconfig.json @@ -0,0 +1,20 @@ +{ + "compilerOptions": { + "module": "commonjs", + "lib": ["es6", "dom"], + "noImplicitAny": true, + "noImplicitThis": true, + "strictNullChecks": true, + "strictFunctionTypes": true, + "baseUrl": "../", + "typeRoots": ["../"], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true, + "jsx": "react", + "paths": { + "@atlaskit/layer": ["atlaskit__layer"] + } + }, + "files": ["index.d.ts", "atlaskit__layer-tests.tsx"] +} diff --git a/types/atlaskit__layer/tslint.json b/types/atlaskit__layer/tslint.json new file mode 100644 index 0000000000..3db14f85ea --- /dev/null +++ b/types/atlaskit__layer/tslint.json @@ -0,0 +1 @@ +{ "extends": "dtslint/dt.json" } diff --git a/types/atlaskit__single-select/atlaskit__single-select-tests.tsx b/types/atlaskit__single-select/atlaskit__single-select-tests.tsx new file mode 100644 index 0000000000..baa25dfe1f --- /dev/null +++ b/types/atlaskit__single-select/atlaskit__single-select-tests.tsx @@ -0,0 +1,14 @@ +import SingleSelect, { StatelessSelect } from '@atlaskit/single-select'; + +import * as React from 'react'; +import { render } from 'react-dom'; + +declare const container: Element; + +render( +
+ + +
, + container, +); diff --git a/types/atlaskit__single-select/index.d.ts b/types/atlaskit__single-select/index.d.ts new file mode 100644 index 0000000000..6536869512 --- /dev/null +++ b/types/atlaskit__single-select/index.d.ts @@ -0,0 +1,125 @@ +// Type definitions for @atlaskit/single-select 4.0 +// Project: https://bitbucket.org/atlassian/atlaskit-mk-2/src/master/ +// Definitions by: Lee Standen +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.6 + +import { Component, ReactNode, SyntheticEvent } from 'react'; + +export default class SingleSelect extends Component {} +export class StatelessSelect extends Component {} + +export interface Props { + /** Subtle items do not have a background color. */ + appearance?: 'default' | 'subtle'; + /** Item to be selected on component mount. */ + defaultSelected?: ItemType; + /** Sets whether the dropdown should be constrained to the width of its trigger */ + droplistShouldFitContainer?: boolean; + /** + * Sets whether the field should be selectable. If it is, the field will be + * a text box, which will filter the items. + */ + hasAutocomplete?: boolean; + /** id property to be passed down to the html select component. */ + id?: string; + /** message to show on the dialog when isInvalid is true */ + invalidMessage?: ReactNode; + /** controls the top margin of the label component rendered. */ + isFirstChild?: boolean; + /** Sets whether the select is selectable. Changes hover state. */ + isDisabled?: boolean; + /** Sets whether the component should be open on mount. */ + isDefaultOpen?: boolean; + /** + * Sets whether form including select can be submitted without an option + * being made. + */ + isRequired?: boolean; + /** + * Set whether there is an error with the selection. Sets an orange border + * and shows the warning icon. + */ + isInvalid?: boolean; + /** + * An array of objects, each one of which must have an array of items, and + * may have a heading. All items should have content and value properties, with + * content being the displayed text. + */ + items?: GroupType[]; + /** Label to be displayed above select. */ + label?: string; + /** name property to be passed to the html select element. */ + name?: string; + /** + * Message to display in any group in items if there are no items in it, + * including if there is one item that has been selected. + */ + noMatchesFound?: string; + /** Handler to be called when the filtered items changes. */ + onFilterChange?: (filter: string) => void; + /** + * Handler to be called when an item is selected. Called with an object that + * has the item selected as a property on the object. + */ + onSelected?: (item: ItemType) => void; + /** + * Handler called when the select is opened or closed. Called with an object + * that has both the event, and the new isOpen state. + */ + onOpenChange?: ( + change: { event: SyntheticEvent; isOpen: boolean }, + ) => void; + /** Text to be shown within the select when no item is selected. */ + placeholder?: string; + /** Where the select dropdown should be displayed relative to the field position. */ + position?: string; + /** Sets whether the field will become focused. */ + shouldFocus?: boolean; + /** Sets whether the field should be constrained to the width of its trigger */ + shouldFitContainer?: boolean; + /** Sets whether the droplist should flip its position when there is not enough space. */ + shouldFlip?: boolean; + /** Set the max height of the dropdown list in pixels. */ + maxHeight?: number; +} + +export interface StatelessProps extends Props { + /** Value to be used when filtering the items. Compared against 'content'. */ + filterValue?: string; + /** Sets whether the Select dropdown is open. */ + isOpen?: boolean; + /** + * Sets whether the field is loading data. The same property is used + * for either initial fetch (when no options are available) as well for + * subsequent loading of more options. The component reacts accordingly + * based on the `items` provided. + */ + isLoading?: boolean; + /** + * Message to be displayed when the component is set to its loading state. + * The message might be displayed differently depending on whether or not + * there are items already being rendered. + */ + loadingMessage?: string; + /** The selected item data */ + selectedItem?: ItemType; +} + +export interface GroupType { + heading?: string; + items: ItemType[]; +} + +export interface ItemType { + content?: ReactNode; + description?: string; + label?: string; + tooltipDescription?: string; + tooltipPosition?: 'top' | 'bottom' | 'left'; + value?: string | number; + filterValues?: string[]; + isDisabled?: boolean; + isSelected?: boolean; + elemBefore?: ReactNode; +} diff --git a/types/atlaskit__single-select/tsconfig.json b/types/atlaskit__single-select/tsconfig.json new file mode 100644 index 0000000000..1ec4324243 --- /dev/null +++ b/types/atlaskit__single-select/tsconfig.json @@ -0,0 +1,20 @@ +{ + "compilerOptions": { + "module": "commonjs", + "lib": ["es6", "dom"], + "noImplicitAny": true, + "noImplicitThis": true, + "strictNullChecks": true, + "strictFunctionTypes": true, + "baseUrl": "../", + "typeRoots": ["../"], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true, + "jsx": "react", + "paths": { + "@atlaskit/single-select": ["atlaskit__single-select"] + } + }, + "files": ["index.d.ts", "atlaskit__single-select-tests.tsx"] +} diff --git a/types/atlaskit__single-select/tslint.json b/types/atlaskit__single-select/tslint.json new file mode 100644 index 0000000000..3db14f85ea --- /dev/null +++ b/types/atlaskit__single-select/tslint.json @@ -0,0 +1 @@ +{ "extends": "dtslint/dt.json" } diff --git a/types/auth0-lock/auth0-lock-tests.ts b/types/auth0-lock/auth0-lock-tests.ts index b3b2c81339..0c64fd361b 100644 --- a/types/auth0-lock/auth0-lock-tests.ts +++ b/types/auth0-lock/auth0-lock-tests.ts @@ -258,6 +258,7 @@ new Auth0Lock(CLIENT_ID, DOMAIN, avatarOptions); const authResult : AuthResult = { accessToken: 'fake_access_token', + expiresIn: 7200, idToken: 'fake_id_token', idTokenPayload: { aud: "EaQzyHt1Dy57l-r5iHcMeT-lh1fFZntg", @@ -267,5 +268,6 @@ const authResult : AuthResult = { sub: "auth0|aksjfkladsf" }, refreshToken: undefined, - state: "923jf092j3.FFSDJFDSKLDF" + state: "923jf092j3.FFSDJFDSKLDF", + tokenType: 'Bearer' }; diff --git a/types/auth0-lock/index.d.ts b/types/auth0-lock/index.d.ts index fec943ce02..27639834db 100644 --- a/types/auth0-lock/index.d.ts +++ b/types/auth0-lock/index.d.ts @@ -165,6 +165,8 @@ interface Auth0LockShowOptions { interface AuthResult { accessToken: string; + appState?: any; + expiresIn: number; idToken: string; idTokenPayload: { aud: string; @@ -174,8 +176,10 @@ interface AuthResult { sub: string; }; refreshToken?: string; + scope?: string; state: string; -} + tokenType: string; + } interface Auth0LockStatic { new (clientId: string, domain: string, options?: Auth0LockConstructorOptions): Auth0LockStatic; diff --git a/types/auth0/auth0-tests.ts b/types/auth0/auth0-tests.ts index 9c1bbe8856..94e7d63cb3 100644 --- a/types/auth0/auth0-tests.ts +++ b/types/auth0/auth0-tests.ts @@ -75,6 +75,25 @@ management // Handle the error. }); +// Link users +management + .createUser({ connection: 'email', email: 'hi@me.co' }) + .catch(err => console.error('Cannot create E-mail user', err)) + .then((emailUser) => { + if (!emailUser) return; + management + .createUser({ connection: 'sms', phone_number: '+1234567890' }) + .catch(err => console.error('Cannot create SMS user', err)) + .then((smsUser) => { + if (!smsUser) return; + const userId = emailUser.user_id; + const params = { user_id: smsUser.user_id, provider: 'sms' }; + management.linkUsers(userId, params) + .catch(err => console.error('Cannot link E-mail and SMS users', err)) + .then((linkedUsers) => console.log(linkedUsers)) + }) + }); + auth .requestChangePasswordEmail({ connection: 'My-Connection', diff --git a/types/auth0/index.d.ts b/types/auth0/index.d.ts index 050f463bfb..516e2cc368 100644 --- a/types/auth0/index.d.ts +++ b/types/auth0/index.d.ts @@ -1,4 +1,4 @@ -// Type definitions for auth0 2.7 +// Type definitions for auth0 2.9.1 // Project: https://github.com/auth0/node-auth0 // Definitions by: Wilson Hobbs , Seth Westphal , Amiram Korach // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped @@ -345,6 +345,14 @@ export interface Identity { user_id: string; provider: string; isSocial: boolean; + profileData?: { + email?: string; + email_verified?: boolean; + name?: string; + phone_number?: string; + phone_verified?: boolean; + request_language?: string; + } } export interface AuthenticationClientOptions { @@ -462,7 +470,7 @@ export interface UnlinkAccountsResponse { profileData?: UnlinkAccountsResponseProfile } -export interface LinkAccountsData { +export interface LinkAccountsParams { user_id: string; connection_id?: string; provider?: string; @@ -664,8 +672,8 @@ export class ManagementClient { unlinkUsers(params: UnlinkAccountsParams): Promise; unlinkUsers(params: UnlinkAccountsParams, cb: (err: Error, data: UnlinkAccountsResponse) => void): void; - linkUsers(userId: string, data: LinkAccountsData): Promise; - linkUsers(userId: string, data: LinkAccountsData, cb: (err: Error, data: any) => void): void; + linkUsers(userId: string, params: LinkAccountsParams): Promise; + linkUsers(userId: string, params: LinkAccountsParams, cb: (err: Error, data: any) => void): void; // Tokens diff --git a/types/awesomplete/awesomplete-tests.ts b/types/awesomplete/awesomplete-tests.ts index f9ff4fed77..a3c66875a4 100644 --- a/types/awesomplete/awesomplete-tests.ts +++ b/types/awesomplete/awesomplete-tests.ts @@ -11,6 +11,7 @@ new Awesomplete(input, { const awesomplete = new Awesomplete(input); awesomplete.list = ["Ada", "Java", "JavaScript", "LOLCODE", "Node.js", "Ruby on Rails"]; +awesomplete.destroy(); new Awesomplete(input, { list: [ diff --git a/types/awesomplete/index.d.ts b/types/awesomplete/index.d.ts index 149b87e9f6..e73b7cf2f3 100644 --- a/types/awesomplete/index.d.ts +++ b/types/awesomplete/index.d.ts @@ -1,6 +1,9 @@ // Type definitions for Awesomplete 1.1 // Project: https://leaverou.github.io/awesomplete/ -// Definitions by: webbiesdk , Ben Dixon , Trevor Bekolay +// Definitions by: webbiesdk +// Ben Dixon +// Trevor Bekolay +// Chris LoPresto // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped declare class Awesomplete { @@ -35,6 +38,7 @@ declare class Awesomplete { selected: boolean; open: () => void; status: HTMLElement; + destroy: () => void; } declare namespace Awesomplete { diff --git a/types/behavior3/behavior3-tests.ts b/types/behavior3/behavior3-tests.ts new file mode 100644 index 0000000000..b612209a09 --- /dev/null +++ b/types/behavior3/behavior3-tests.ts @@ -0,0 +1,73 @@ +import '../behavior3'; + +// Test decode +const blackboard = new b3.Blackboard(); +const behaviorTree = new b3.BehaviorTree(); +behaviorTree.load({ + version: "0.3.0", + scope: "tree", + id: "6bc03cd0-38ef-4a3e-8e08-54c412491525", + title: "A behavior tree", + description: "", + root: "607d29f5-9dbc-4cc4-8ebb-e57c4908d87b", + properties: {}, + nodes: { + "607d29f5-9dbc-4cc4-8ebb-e57c4908d87b": { + id: "607d29f5-9dbc-4cc4-8ebb-e57c4908d87b", + name: "Sequence", + title: "Sequence", + description: "", + properties: {}, + display: { + x: -216, + y: -36 + }, + children: [ + "09f04185-205b-40c0-8494-ffd53ffd0820", + "df7366f8-999a-4971-872c-cef57607f99f" + ] + }, + "df7366f8-999a-4971-872c-cef57607f99f": { + id: "df7366f8-999a-4971-872c-cef57607f99f", + name: "Runner", + title: "Runner", + description: "", + properties: {}, + display: { + x: -12, + y: -36 + } + }, + "e498e1a5-5295-43c3-8716-20dd6d3407f2": { + id: "e498e1a5-5295-43c3-8716-20dd6d3407f2", + name: "Succeeder", + title: "Succeeder", + description: "", + properties: {}, + display: { + x: 192, + y: -96 + } + }, + "09f04185-205b-40c0-8494-ffd53ffd0820": { + id: "09f04185-205b-40c0-8494-ffd53ffd0820", + name: "Inverter", + title: "Inverter", + description: "", + properties: {}, + display: { + x: -36, + y: -108 + }, + child: "e498e1a5-5295-43c3-8716-20dd6d3407f2" + } + }, + display: { + camera_x: 640, + camera_y: 324, + camera_z: 1, + x: -324, + y: -36 + } + }); +behaviorTree.tick(null, blackboard); diff --git a/types/behavior3/index.d.ts b/types/behavior3/index.d.ts new file mode 100644 index 0000000000..7cb3ad9deb --- /dev/null +++ b/types/behavior3/index.d.ts @@ -0,0 +1,908 @@ +// Type definitions for behavior3 0.2 +// Project: https://github.com/behavior3/behavior3js +// Definitions by: carry.wu +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +/** + * Behavior3JS + * =========== + * + * * * * + * + * **Behavior3JS** is a Behavior Tree library written in JavaScript. It + * provides structures and algorithms that assist you in the task of creating + * intelligent agents for your game or application. Check it out some features + * of Behavior3JS: + * + * - Based on the work of (Marzinotto et al., 2014), in which they propose a + * **formal**, **consistent** and **general** definition of Behavior Trees; + * - **Optimized to control multiple agents**: you can use a single behavior + * tree instance to handle hundreds of agents; + * - It was **designed to load and save trees in a JSON format**, in order to + * use, edit and test it in multiple environments, tools and languages; + * - A **cool visual editor** which you can access online; + * - Several **composite, decorator and action nodes** available within the + * library. You still can define your own nodes, including composites and + * decorators; + * - **Completely free**, the core module and the visual editor are all + * published under the MIT License, which means that you can use them for + * your open source and commercial projects; + * - **Lightweight**! + * + * Visit http://behavior3.com to know more! + * + * + * ## Core Classes and Functions + * + * This library include the following core structures... + * + * + * **Public:** + * + * - **BehaviorTree**: the structure that represents a Behavior Tree; + * - **Blackboard**: represents a "memory" in an agent and is required to to + * run a `BehaviorTree`; + * - **Composite**: base class for all composite nodes; + * - **Decorator**: base class for all decorator nodes; + * - **Action**: base class for all action nodes; + * - **Condition**: base class for all condition nodes; + * + * + * **Internal:** + * + * - **Tick**: used as container and tracking object through the tree during + * the tick signal; + * - **BaseNode**: the base class that provide all common node features; + * + * *Some classes are used internally on Behavior3JS, but you may need to access + * its functionalities eventually, specially the `Tick` object.* + * + * + * **Nodes:** + * + * - **Composite Nodes**: Sequence, Priority, MemSequence, MemPriority. + * - **Decorators**: Inverter, Limiter, MaxTime, Repeater, + * RepeaterUntilFailure, RepeaterUntilSuccess. + * - **Actions**: Succeeder, Failer, Error, Runner, Wait. + * + * ## The list of all constants in B3. + * + * NAME | VALUE + * ------------------- | ---------------------- + * VERSION | depends on the version + * | + * **Node State** | + * SUCCESS | 1 + * FAILURE | 2 + * RUNNING | 3 + * ERROR | 4 + * | + * **Node categories** | + * COMPOSITE | 'composite' + * DECORATOR | 'decorator' + * ACTION | 'action' + * CONDITION | 'condition' + * + */ +declare namespace b3 { + /** + * This function is used to create unique IDs for trees and nodes. + * + * (consult http://www.ietf.org/rfc/rfc4122.txt). + * + */ + function createUUID(): string; + + /** + * The BaseNode class is used as super class to all nodes in BehaviorJS. It + * comprises all common variables and methods that a node must have to + * execute. + * + * **IMPORTANT:** Do not inherit from this class, use `Composite`, + * `Decorator`, `Action` or `Condition`, instead. + * + * The attributes are specially designed to serialization of the node in a + * JSON format. In special, the `parameters` attribute can be set into the + * visual editor (thus, in the JSON file), and it will be used as parameter + * on the node initialization at `BehaviorTree.load`. + * + * BaseNode also provide 5 callback methods, which the node implementations + * can override. They are `enter`, `open`, `tick`, `close` and `exit`. See + * their documentation to know more. These callbacks are called inside the + * `_execute` method, which is called in the tree traversal. + * + */ + class BaseNode { + /** + * Initialization method. + */ + constructor({category, name, title, description, properties}?: {category?: string, name?: string, title?: string, description?: string, properties?: any}); + + /** + * This is the main method to propagate the tick signal to this node. This + * method calls all callbacks: `enter`, `open`, `tick`, `close`, and + * `exit`. It only opens a node if it is not already open. In the same + * way, this method only close a node if the node returned a status + * different of `RUNNING`. + * + */ + _execute(tick: Tick): number; + + /** + * Wrapper for enter method. + */ + _enter(tick: Tick): void; + + /** + * Wrapper for open method. + */ + _open(tick: Tick): void; + + /** + * Wrapper for tick method. + */ + _tick(tick: Tick): number; + + /** + * Wrapper for close method. + */ + _close(tick: Tick): void; + + /** + * Wrapper for exit method. + */ + _exit(tick: Tick): void; + + /** + * Enter method, override this to use. It is called every time a node is + * asked to execute, before the tick itself. + */ + enter(tick: Tick): void; + + /** + * Open method, override this to use. It is called only before the tick + * callback and only if the not isn't closed. + * + * Note: a node will be closed if it returned `RUNNING` in the tick. + * + */ + open(tick: Tick): void; + + /** + * Tick method, override this to use. This method must contain the real + * execution of node (perform a task, call children, etc.). It is called + * every time a node is asked to execute. + * + */ + tick(tick: Tick): void; + + /** + * Close method, override this to use. This method is called after the tick + * callback, and only if the tick return a state different from + * `RUNNING`. + * + */ + close(tick: Tick): void; + + /** + * Exit method, override this to use. Called every time in the end of the + * execution. + * + */ + exit(tick: Tick): void; + } + + /** + * Action is the base class for all action nodes. Thus, if you want to create + * new custom action nodes, you need to inherit from this class. For example, + * take a look at the Runner action: + * + * class Runner extends b3.Action { + * constructor(){ + * super({name: 'Runner'}); + * } + * tick(tick) { + * return b3.RUNNING; + * } + * }; + * + */ + class Action extends BaseNode { + /** + * Creates an instance of Action. + */ + constructor({name, title, properties}?: {name?: string, title?: string, properties?: any}); + } + + /** + * The BehaviorTree class, as the name implies, represents the Behavior Tree + * structure. + * + * There are two ways to construct a Behavior Tree: by manually setting the + * root node, or by loading it from a data structure (which can be loaded + * from a JSON). Both methods are shown in the examples below and better + * explained in the user guide. + * + * The tick method must be called periodically, in order to send the tick + * signal to all nodes in the tree, starting from the root. The method + * `BehaviorTree.tick` receives a target object and a blackboard as + * parameters. The target object can be anything: a game agent, a system, a + * DOM object, etc. This target is not used by any piece of Behavior3JS, + * i.e., the target object will only be used by custom nodes. + * + * The blackboard is obligatory and must be an instance of `Blackboard`. This + * requirement is necessary due to the fact that neither `BehaviorTree` or + * any node will store the execution variables in its own object (e.g., the + * BT does not store the target, information about opened nodes or number of + * times the tree was called). But because of this, you only need a single + * tree instance to control multiple (maybe hundreds) objects. + * + * Manual construction of a Behavior Tree + * -------------------------------------- + * + * var tree = new b3.BehaviorTree(); + * + * tree.root = new b3.Sequence({children:[ + * new b3.Priority({children:[ + * new MyCustomNode(), + * new MyCustomNode() + * ]}), + * ... + * ]}); + * + * + * Loading a Behavior Tree from data structure + * ------------------------------------------- + * + * var tree = new b3.BehaviorTree(); + * + * tree.load({ + * 'title' : 'Behavior Tree title' + * 'description' : 'My description' + * 'root' : 'node-id-1' + * 'nodes' : { + * 'node-id-1' : { + * 'name' : 'Priority', // this is the node type + * 'title' : 'Root Node', + * 'description' : 'Description', + * 'children' : ['node-id-2', 'node-id-3'], + * }, + * ... + * } + * }) + * + */ + class BehaviorTree { + /** + * Initialization method. + */ + constructor(); + + /** + * This method loads a Behavior Tree from a data structure, populating this + * object with the provided data. Notice that, the data structure must + * follow the format specified by Behavior3JS. Consult the guide to know + * more about this format. + * + * You probably want to use custom nodes in your BTs, thus, you need to + * provide the `names` object, in which this method can find the nodes by + * `names[NODE_NAME]`. This variable can be a namespace or a dictionary, + * as long as this method can find the node by its name, for example: + * + * //json + * ... + * 'node1': { + * 'name': MyCustomNode, + * 'title': ... + * } + * ... + * + * //code + * var bt = new b3.BehaviorTree(); + * bt.load(data, {'MyCustomNode':MyCustomNode}) + * + * + */ + load(data: any, names?: any): void; + + /** + * This method dump the current BT into a data structure. + * + * Note: This method does not record the current node parameters. Thus, + * it may not be compatible with load for now. + * + */ + dump(): any; + + /** + * Propagates the tick signal through the tree, starting from the root. + * + * This method receives a target object of any type (Object, Array, + * DOMElement, whatever) and a `Blackboard` instance. The target object has + * no use at all for all Behavior3JS components, but surely is important + * for custom nodes. The blackboard instance is used by the tree and nodes + * to store execution variables (e.g., last node running) and is obligatory + * to be a `Blackboard` instance (or an object with the same interface). + * + * Internally, this method creates a Tick object, which will store the + * target and the blackboard objects. + * + * Note: BehaviorTree stores a list of open nodes from last tick, if these + * nodes weren't called after the current tick, this method will close them + * automatically. + * + */ + tick(target: any, blackboard: Blackboard): string; + } + + /** + * The Blackboard is the memory structure required by `BehaviorTree` and its + * nodes. It only have 2 public methods: `set` and `get`. These methods works + * in 3 different contexts: global, per tree, and per node per tree. + * + * Suppose you have two different trees controlling a single object with a + * single blackboard, then: + * + * - In the global context, all nodes will access the stored information. + * - In per tree context, only nodes sharing the same tree share the stored + * information. + * - In per node per tree context, the information stored in the blackboard + * can only be accessed by the same node that wrote the data. + * + * The context is selected indirectly by the parameters provided to these + * methods, for example: + * + * // getting/setting variable in global context + * blackboard.set('testKey', 'value'); + * var value = blackboard.get('testKey'); + * + * // getting/setting variable in per tree context + * blackboard.set('testKey', 'value', tree.id); + * var value = blackboard.get('testKey', tree.id); + * + * // getting/setting variable in per node per tree context + * blackboard.set('testKey', 'value', tree.id, node.id); + * var value = blackboard.get('testKey', tree.id, node.id); + * + * Note: Internally, the blackboard store these memories in different + * objects, being the global on `_baseMemory`, the per tree on `_treeMemory` + * and the per node per tree dynamically create inside the per tree memory + * (it is accessed via `_treeMemory[id].nodeMemory`). Avoid to use these + * variables manually, use `get` and `set` instead. + * + */ + class Blackboard { + /** + * Initialization method. + */ + constructor(); + + /** + * Internal method to retrieve the tree context memory. If the memory does + * not exist, this method creates it. + * + */ + _getTreeMemory(treeScope: string): any; + + /** + * Internal method to retrieve the node context memory, given the tree + * memory. If the memory does not exist, this method creates is. + * + */ + _getNodeMemory(treeMemory: string, nodeScope: string): any; + + /** + * Internal method to retrieve the context memory. If treeScope and + * nodeScope are provided, this method returns the per node per tree + * memory. If only the treeScope is provided, it returns the per tree + * memory. If no parameter is provided, it returns the global memory. + * Notice that, if only nodeScope is provided, this method will still + * return the global memory. + * + */ + _getMemory(treeScope: string, nodeScope: string): any; + + /** + * Stores a value in the blackboard. If treeScope and nodeScope are + * provided, this method will save the value into the per node per tree + * memory. If only the treeScope is provided, it will save the value into + * the per tree memory. If no parameter is provided, this method will save + * the value into the global memory. Notice that, if only nodeScope is + * provided (but treeScope not), this method will still save the value into + * the global memory. + * + */ + set(key: string, value: string, treeScope: string, nodeScope: string): void; + + /** + * Retrieves a value in the blackboard. If treeScope and nodeScope are + * provided, this method will retrieve the value from the per node per tree + * memory. If only the treeScope is provided, it will retrieve the value + * from the per tree memory. If no parameter is provided, this method will + * retrieve from the global memory. If only nodeScope is provided (but + * treeScope not), this method will still try to retrieve from the global + * memory. + * + */ + get(key: string, treeScope: string, nodeScope: string): any; + } + + /** + * Composite is the base class for all composite nodes. Thus, if you want to + * create new custom composite nodes, you need to inherit from this class. + * + * When creating composite nodes, you will need to propagate the tick signal + * to the children nodes manually. To do that, override the `tick` method and + * call the `_execute` method on all nodes. For instance, take a look at how + * the Sequence node inherit this class and how it call its children: + * + * // Inherit from Composite, using the util function Class. + * class Sequence extends Composite { + * + * constructor(){ + * // Remember to set the name of the node. + * super({name: 'Sequence'}); + * } + * + * // Override the tick function + * tick(tick) { + * + * // Iterates over the children + * for (var i=0; i +bidirectionalMap.has("one"); // $ExpectType boolean +bidirectionalMap.hasValue(2); // $ExpectType boolean +bidirectionalMap.keys(); // $ExpectType IterableIterator +bidirectionalMap.values(); // $ExpectType IterableIterator diff --git a/types/bidirectional-map/index.d.ts b/types/bidirectional-map/index.d.ts new file mode 100644 index 0000000000..67662d3441 --- /dev/null +++ b/types/bidirectional-map/index.d.ts @@ -0,0 +1,22 @@ +// Type definitions for bidirectional-map 1.0 +// Project: https://github.com/educastellano/bidirectional-map +// Definitions by: Helen Anderson +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.8 + +export default class BiMap { + constructor(object?: { [i: string]: TValue }); + size: number; + + set(key: string, value: TValue): void; + get(key: string): TValue; + getKey(value: TValue): string; + clear(): void; + delete(key: string): void; + deleteValue(value: TValue): void; + entries(): IterableIterator<[string, TValue]>; + has(key: string): boolean; + hasValue(value: TValue): boolean; + keys(): IterableIterator; + values(): IterableIterator; +} diff --git a/types/bidirectional-map/tsconfig.json b/types/bidirectional-map/tsconfig.json new file mode 100644 index 0000000000..0c3b3a1cac --- /dev/null +++ b/types/bidirectional-map/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", + "bidirectional-map-tests.ts" + ] +} diff --git a/types/bidirectional-map/tslint.json b/types/bidirectional-map/tslint.json new file mode 100644 index 0000000000..3db14f85ea --- /dev/null +++ b/types/bidirectional-map/tslint.json @@ -0,0 +1 @@ +{ "extends": "dtslint/dt.json" } diff --git a/types/bluebird-retry/bluebird-retry-tests.ts b/types/bluebird-retry/bluebird-retry-tests.ts index e9beaf5562..45a665c969 100644 --- a/types/bluebird-retry/bluebird-retry-tests.ts +++ b/types/bluebird-retry/bluebird-retry-tests.ts @@ -30,3 +30,10 @@ const options: retry.Options = { }; retry(logFail, options); + +function stopErrorExample() { + console.log('retrying\n'); + throw new retry.StopError('stop retrying'); +} + +retry(stopErrorExample); diff --git a/types/bluebird-retry/index.d.ts b/types/bluebird-retry/index.d.ts index 358c75936d..b7ba96495d 100644 --- a/types/bluebird-retry/index.d.ts +++ b/types/bluebird-retry/index.d.ts @@ -20,6 +20,8 @@ declare namespace retry { context?: any; args?: any; } + + class StopError extends Error {} } export = retry; diff --git a/types/browser-sync/browser-sync-tests.ts b/types/browser-sync/browser-sync-tests.ts index 613f8aee25..c63cb0c862 100644 --- a/types/browser-sync/browser-sync-tests.ts +++ b/types/browser-sync/browser-sync-tests.ts @@ -167,8 +167,8 @@ browserSync({ browserSync({ proxy: { target: "http://yourlocal.dev", - proxyRes: function (proxyRes, req, res) { - console.log(proxyRes); + proxyRes: function (proxyResponse, req, res) { + console.log(proxyResponse); } } }); @@ -177,8 +177,28 @@ browserSync({ proxy: { target: "http://yourlocal.dev", proxyRes: [ - function (proxyRes, req, res) { - console.log(proxyRes); + function (proxyResponse, req, res) { + console.log(proxyResponse); + } + ] + } +}); + +browserSync({ + proxy: { + target: "http://yourlocal.dev", + proxyRes: function (res) { + console.log(res); + } + } +}); + +browserSync({ + proxy: { + target: "http://yourlocal.dev", + proxyRes: [ + function (res) { + console.log(res); } ] } diff --git a/types/browser-sync/index.d.ts b/types/browser-sync/index.d.ts index 3b97fc8616..de0a457266 100644 --- a/types/browser-sync/index.d.ts +++ b/types/browser-sync/index.d.ts @@ -39,7 +39,7 @@ declare namespace browserSync { * Specify which file events to respond to. * Available events: `add`, `change`, `unlink`, `addDir`, `unlinkDir` */ - watchEvents?: string[]; + watchEvents?: WatchEvents | string[]; /** * Watch files automatically. */ @@ -72,7 +72,7 @@ declare namespace browserSync { * ws - Default: undefined * middleware - Default: undefined * reqHeaders - Default: undefined - * proxyRes - Default: undefined + * proxyRes - Default: undefined (http.ServerResponse if expecting single parameter) * proxyReq - Default: undefined */ proxy?: string | ProxyOptions; @@ -91,7 +91,7 @@ declare namespace browserSync { * Default: [] * Note: Requires at least version 2.8.0. */ - serveStatic?: (string | { route?: string | string[], dir?: string | string[]})[]; + serveStatic?: StaticOptions[] | string[]; /** * Options that are passed to the serve-static middleware when you use the * string[] syntax: eg: `serveStatic: ['./app']`. @@ -120,7 +120,7 @@ declare namespace browserSync { * Can be either "info", "debug", "warn", or "silent" * Default: info */ - logLevel?: string; + logLevel?: LogLevel; /** * Change the console logging prefix. Useful if you're creating your own project based on Browsersync * Default: BS @@ -170,7 +170,7 @@ declare namespace browserSync { * Decide which URL to open automatically when Browsersync starts. Defaults to "local" if none set. * Can be true, local, external, ui, ui-external, tunnel or false */ - open?: string | boolean; + open?: OpenOptions | boolean; /** * The browser(s) to open * Default: default @@ -320,6 +320,12 @@ declare namespace browserSync { excludeFileTypes?: string[]; } + type WatchEvents = "add" | "change" | "unlink" | "addDir" | "unlinkDir"; + + type LogLevel = "info" | "debug" | "warn" | "silent"; + + type OpenOptions = "local" | "external" | "ui" | "ui-external" | "tunnel"; + interface Hash { [path: string]: T; } @@ -353,16 +359,21 @@ declare namespace browserSync { routes?: Hash; /** configure custom middleware */ middleware?: (MiddlewareHandler | PerRouteMiddleware)[]; - serveStaticOptions?: ServeStaticOptions + serveStaticOptions?: ServeStaticOptions; } interface ProxyOptions { target?: string; middleware?: MiddlewareHandler; ws?: boolean; - reqHeaders?: (config: any) => Hash; - proxyRes?: ((res: http.ServerResponse, req: http.IncomingMessage, next: Function) => any)[] | ((res: http.ServerResponse, req: http.IncomingMessage, next: Function) => any); - proxyReq?: ((res: http.ServerRequest) => any)[] | ((res: http.ServerRequest) => any); + reqHeaders?: (config: object) => Hash; + proxyRes?: ProxyResponseMiddleware | ProxyResponseMiddleware[]; + proxyReq?: ((res: http.ServerRequest) => void)[] | ((res: http.ServerRequest) => void); + error?: (err: NodeJS.ErrnoException, req: http.IncomingMessage, res: http.ServerResponse) => void; + } + + interface ProxyResponseMiddleware { + (proxyRes: http.ServerResponse | http.IncomingMessage, res: http.ServerResponse, req: http.IncomingMessage): void; } interface HttpsOptions { @@ -370,11 +381,17 @@ declare namespace browserSync { cert?: string; } + interface StaticOptions { + route: string | string[], + dir: string | string[] + } + interface MiddlewareHandler { - (req: http.IncomingMessage, res: http.ServerResponse, next: Function): any; + (req: http.IncomingMessage, res: http.ServerResponse, next: () => void): any; } interface PerRouteMiddleware { + id?: string; route: string; handle: MiddlewareHandler; } @@ -382,18 +399,23 @@ declare namespace browserSync { interface GhostOptions { clicks?: boolean; scroll?: boolean; - forms?: boolean | { - submit?: boolean; - inputs?: boolean; - toggles?: boolean; - }; + forms?: FormsOptions | boolean; + } + + interface FormsOptions { + inputs: boolean, + submit: boolean, + toggles: boolean } interface SnippetOptions { - async?: boolean, + async?: boolean; whitelist?: string[], blacklist?: string[], - rule?: { match?: RegExp; fn?: (snippet: string, match: string) => any }; + rule?: { + match?: RegExp; + fn?: (snippet: string, match: string) => any + }; } interface SocketOptions { diff --git a/types/chart.js/index.d.ts b/types/chart.js/index.d.ts index 2c5de28962..621152162a 100644 --- a/types/chart.js/index.d.ts +++ b/types/chart.js/index.d.ts @@ -166,7 +166,7 @@ declare namespace Chart { interface ChartPoint { x?: number | string | Date; - y?: number; + y?: number | string | Date; r?: number; } diff --git a/types/chrome/index.d.ts b/types/chrome/index.d.ts index 466f09107d..d2b92e4b22 100644 --- a/types/chrome/index.d.ts +++ b/types/chrome/index.d.ts @@ -263,6 +263,7 @@ declare namespace chrome.bookmarks { export interface BookmarkRemoveInfo { index: number; parentId: string; + node: BookmarkTreeNode; } export interface BookmarkMoveInfo { diff --git a/types/cleave.js/cleave.js-tests.tsx b/types/cleave.js/cleave.js-tests.tsx index 825b44a2ad..eb682d432b 100644 --- a/types/cleave.js/cleave.js-tests.tsx +++ b/types/cleave.js/cleave.js-tests.tsx @@ -2,7 +2,7 @@ import * as React from "react"; import Cleave = require("cleave.js"); import CleaveReact = require("cleave.js/react"); -const Example1 = () => { +const ExampleSelector1 = () => { const cleave = new Cleave("#my-input", { phone: true }); cleave.setPhoneRegionCode("AT"); cleave.setRawValue("foo"); @@ -11,6 +11,15 @@ const Example1 = () => { cleave.destroy(); }; +const ExampleElement1 = () => { + const input: HTMLElement = new HTMLElement(); + + const cleave = new Cleave(input, { date: true }); + cleave.setRawValue("2001/01/01"); + const formattedDate: string = cleave.getISOFormatDate(); + cleave.destroy(); +}; + const ExampleReact1 = (props: any) => { return ( , // J Giancono , // Alex Shakun // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -// TypeScript Version: 2.6 +// TypeScript Version: 2.8 import { CleaveOptions } from './options'; declare class Cleave { - constructor(selector: string, options: CleaveOptions); + constructor(selector: string | HTMLElement, options: CleaveOptions); getRawValue(): string; @@ -17,6 +17,8 @@ declare class Cleave { getFormattedValue(): string; + getISOFormatDate(): string; + destroy(): void; setPhoneRegionCode(regionCode: string): void; diff --git a/types/cloner/cloner-tests.ts b/types/cloner/cloner-tests.ts new file mode 100644 index 0000000000..63baf4b950 --- /dev/null +++ b/types/cloner/cloner-tests.ts @@ -0,0 +1,43 @@ +import cloner = require("cloner"); + +interface A { + test: string; + nest: { + test: string; + num: number; + }; +} + +interface B { + somethingElse: string; + nest: { + somethingElse: string; + notNaN: number; + }; +} + +let aO: A; +let aN: A; +let bO: B; +let bN: B; + +aO = { + test: "test", + nest: { + test: "nestTest", + num: 1 + } +}; +bO = { + somethingElse: "se", + nest: { + somethingElse: "nestSe", + notNaN: 0 + } +}; + +aN = cloner.deep.copy(aO); +bN = cloner.shallow.copy(bO); + +aN = cloner.deep.merge(aO, bO); +bN = cloner.shallow.merge(aO, bO); diff --git a/types/cloner/index.d.ts b/types/cloner/index.d.ts new file mode 100644 index 0000000000..6021c9a716 --- /dev/null +++ b/types/cloner/index.d.ts @@ -0,0 +1,45 @@ +// Type definitions for cloner 0.4 +// Project: https://github.com/WebReflection/cloner +// Definitions by: matrumz +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +/** + * Deep-style methods that will perform operations by value, instead of reference. + */ +export namespace deep { + /** + * Will loop over all own keys and deeply copy (copy by value) them to a new object. + * + * Preserves inheritance and is recursion aware, meaning it shouldn't fail with recursive properties. + * @param [obj] The object to copy. + */ + function copy(obj: T): T; + /** + * Preserves what's already in the target and merges all own keys found in one or more passed sources. + * + * Properties are merged by value. + * @param [target] Destination object for merged properties. + * @param [sources] Source object(s) for properties to merge. + */ + function merge(target: any, ...sources: any[]): any; +} +/** + * Shallow-style methods that will perform operations by reference, instead of value. + */ +export namespace shallow { + /** + * Will loop over all own keys and shallow copy (copy by reference) them to a new object. + * + * Preserves inheritance and is recursion aware, meaning it shouldn't fail with recursive properties. + * @param [obj] The object to copy. + */ + function copy(obj: T): T; + /** + * Preserves what's already in the target and merges all own keys found in one or more passed sources. + * + * Properties are merged by reference. + * @param [target] Destination object for merged properties. + * @param [sources] Source object(s) for properties to merge. + */ + function merge(target: any, ...sources: any[]): any; +} diff --git a/types/cloner/tsconfig.json b/types/cloner/tsconfig.json new file mode 100644 index 0000000000..9619614ce4 --- /dev/null +++ b/types/cloner/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", + "cloner-tests.ts" + ] +} diff --git a/types/cloner/tslint.json b/types/cloner/tslint.json new file mode 100644 index 0000000000..3db14f85ea --- /dev/null +++ b/types/cloner/tslint.json @@ -0,0 +1 @@ +{ "extends": "dtslint/dt.json" } diff --git a/types/command-line-args/command-line-args-tests.ts b/types/command-line-args/command-line-args-tests.ts index 11848ee202..89d310cb14 100644 --- a/types/command-line-args/command-line-args-tests.ts +++ b/types/command-line-args/command-line-args-tests.ts @@ -1,10 +1,24 @@ import commandLineArgs = require('command-line-args'); -const optionDefinitions = [ - { name: 'verbose', alias: 'v', type: Boolean }, - { name: 'src', type: String, multiple: true, defaultOption: true }, - { name: 'timeout', alias: 't', type: Number } +const optionDefinitions: commandLineArgs.OptionDefinition[] = [ + { + name: 'something', + alias: 's', + type: String, + defaultValue: '1', + multiple: true, + lazyMultiple: true, + defaultOption: true, + group: 'one' + } ]; -const options = commandLineArgs(optionDefinitions); +const options = commandLineArgs(optionDefinitions, { + argv: [ '--one', '1' ], + partial: true, + stopAtFirstUnknown: true, + camelCase: true +}); +const unknown = options._unknown; +const something = options.something; diff --git a/types/command-line-args/index.d.ts b/types/command-line-args/index.d.ts index 332368d827..5172a2f74a 100644 --- a/types/command-line-args/index.d.ts +++ b/types/command-line-args/index.d.ts @@ -1,87 +1,90 @@ -// Type definitions for command-line-args 4.0.7 +// Type definitions for command-line-args 5.0 // Project: https://github.com/75lb/command-line-args -// Definitions by: CzBuCHi +// Definitions by: Lloyd Brookes // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.2 /** - * Returns an object containing all options set on the command line. By default it parses the global [`process.argv`](https://nodejs.org/api/process.html#process_process_argv) array. - * - * By default, an exception is thrown if the user sets an unknown option (one without a valid [definition](#exp_module_definition--OptionDefinition)). To enable __partial parsing__, invoke `commandLineArgs` with the `partial` option - all unknown arguments will be returned in the `_unknown` property. - * - * - * @param {module:definition[]} - An array of [OptionDefinition](#exp_module_definition--OptionDefinition) objects - * @param [options] {object} - Options. - * @param [options.argv] {string[]} - An array of strings, which if passed will be parsed instead of `process.argv`. - * @param [options.partial] {boolean} - If `true`, an array of unknown arguments is returned in the `_unknown` property of the output. - * @returns {object} - * @throws `UNKNOWN_OPTION` if `options.partial` is false and the user set an undefined option - * @throws `NAME_MISSING` if an option definition is missing the required `name` property - * @throws `INVALID_TYPE` if an option definition has a `type` value that's not a function - * @throws `INVALID_ALIAS` if an alias is numeric, a hyphen or a length other than 1 - * @throws `DUPLICATE_NAME` if an option definition name was used more than once - * @throws `DUPLICATE_ALIAS` if an option definition alias was used more than once - * @throws `DUPLICATE_DEFAULT_OPTION` if more than one option definition has `defaultOption: true` - * @alias module:command-line-args + * Returns an object containing option values parsed from the command line. By default it parses the global `process.argv` array. + * Parsing is strict by default. To be more permissive, enable `partial` or `stopAtFirstUnknown` modes. */ -declare function commandLineArgs(optionDefinitions: commandLineArgs.OptionDefinition[], options?: commandLineArgs.Options): any; +declare function commandLineArgs(optionDefinitions: commandLineArgs.OptionDefinition[], options?: commandLineArgs.ParseOptions): commandLineArgs.CommandLineOptions; -declare module commandLineArgs { +declare namespace commandLineArgs { + interface CommandLineOptions { + /** + * Command-line arguments not parsed by `commandLineArgs`. + */ + _unknown?: string[]; + [propName: string]: any; + } - export interface OptionDefinition { - /** - * The only required definition property is name, the value of each option will be either a Boolean or string. - */ - name: string, - /** - * The type value is a setter function (you receive the output from this), - * enabling you to be specific about the type and value received. - */ - type?: (arg: string) => any, - /** - * getopt-style short option names. Can be any single character (unicode included) except a digit or hypen. - */ - alias?: string, - /** - * Set this flag if the option takes a list of values. You will receive an array of values, each passed - * through the type function (if specified). - */ - multiple?: boolean, - /** - * Any unclaimed command-line args will be set on this option. This flag is typically set on - * the most commonly-used option to make for more concise usage - * (i.e. $ myapp *.js instead of $ myapp --files *.js). - */ - defaultOption?: boolean, - /** - * An initial value for the option. - */ - defaultValue?: any, - /** - * When your app has a large amount of options it makes sense to organise them in groups. - * There are two automatic groups: _all (contains all options) and _none (contains options - * without a group specified in their definition). - */ - group?: string | string[], - /** - * Describes the option. - */ - description?: string, - /** - * A label for the type, e.g. . - */ - typeLabel?: string; - } + interface ParseOptions { + /** + * An array of strings which if present will be parsed instead of `process.argv`. + */ + argv?: string[]; - export interface Options { - /** - * An array of strings, which if passed will be parsed instead of `process.argv`. - */ - argv?: string[]; - /** - * If `true`, an array of unknown arguments is returned in the `_unknown` property of the output. - */ - partial?: boolean; - } + /** + * If `true`, `commandLineArgs` will not throw on unknown options or values, instead returning them in the `_unknown` property of the output. + */ + partial?: boolean; + + /** + * If `true`, `commandLineArgs` will not throw on unknown options or values. Instead, parsing will stop at the first unknown argument + * and the remaining arguments returned in the `_unknown` property of the output. If set, `partial: true` is implied. + */ + stopAtFirstUnknown?: boolean; + + /** + * If `true`, options with hypenated names (e.g. `move-to`) will be returned in camel-case (e.g. `moveTo`). + */ + camelCase?: boolean; + } + + interface OptionDefinition { + /** + * The long option name. + */ + name: string; + + /** + * A setter function (you receive the output from this) enabling you to be specific about the type and value received. Typical values + * are `String` (the default), `Number` and `Boolean` but you can use a custom function. If no option value was set you will receive `null`. + */ + type?: (input: string) => any; + + /** + * A getopt-style short option name. Can be any single character except a digit or hyphen. + */ + alias?: string; + + /** + * Set this flag if the option accepts multiple values. In the output, you will receive an array of values each passed through the `type` function. + */ + multiple?: boolean; + + /** + * Identical to `multiple` but with greedy parsing disabled. + */ + lazyMultiple?: boolean; + + /** + * Any values unaccounted for by an option definition will be set on the `defaultOption`. This flag is typically set + * on the most commonly-used option to enable more concise usage. + */ + defaultOption?: boolean; + + /** + * An initial value for the option. + */ + defaultValue?: any; + + /** + * One or more group names the option belongs to. + */ + group?: string | string[]; + } } export = commandLineArgs; diff --git a/types/command-line-args/tslint.json b/types/command-line-args/tslint.json index a41bf5d19a..495d29983d 100644 --- a/types/command-line-args/tslint.json +++ b/types/command-line-args/tslint.json @@ -1,79 +1,5 @@ { "extends": "dtslint/dt.json", "rules": { - "adjacent-overload-signatures": false, - "array-type": false, - "arrow-return-shorthand": false, - "ban-types": false, - "callable-types": false, - "comment-format": false, - "dt-header": false, - "eofline": false, - "export-just-namespace": false, - "import-spacing": false, - "interface-name": false, - "interface-over-type-literal": false, - "jsdoc-format": false, - "max-line-length": false, - "member-access": false, - "new-parens": false, - "no-any-union": false, - "no-boolean-literal-compare": false, - "no-conditional-assignment": false, - "no-consecutive-blank-lines": false, - "no-construct": false, - "no-declare-current-package": false, - "no-duplicate-imports": false, - "no-duplicate-variable": false, - "no-empty-interface": false, - "no-for-in-array": false, - "no-inferrable-types": false, - "no-internal-module": false, - "no-irregular-whitespace": false, - "no-mergeable-namespace": false, - "no-misused-new": false, - "no-namespace": false, - "no-object-literal-type-assertion": false, - "no-padding": false, - "no-redundant-jsdoc": false, - "no-redundant-jsdoc-2": false, - "no-redundant-undefined": false, - "no-reference-import": false, - "no-relative-import-in-test": false, - "no-self-import": false, - "no-single-declare-module": false, - "no-string-throw": false, - "no-unnecessary-callback-wrapper": false, - "no-unnecessary-class": false, - "no-unnecessary-generics": false, - "no-unnecessary-qualifier": false, - "no-unnecessary-type-assertion": false, - "no-useless-files": false, - "no-var-keyword": false, - "no-var-requires": false, - "no-void-expression": false, - "no-trailing-whitespace": false, - "object-literal-key-quotes": false, - "object-literal-shorthand": false, - "one-line": false, - "one-variable-per-declaration": false, - "only-arrow-functions": false, - "prefer-conditional-expression": false, - "prefer-const": false, - "prefer-declare-function": false, - "prefer-for-of": false, - "prefer-method-signature": false, - "prefer-template": false, - "radix": false, - "semicolon": false, - "space-before-function-paren": false, - "space-within-parens": false, - "strict-export-declare-modifiers": false, - "trim-file": false, - "triple-equals": false, - "typedef-whitespace": false, - "unified-signatures": false, - "void-return": false, - "whitespace": false } } diff --git a/types/command-line-args/v4/command-line-args-tests.ts b/types/command-line-args/v4/command-line-args-tests.ts new file mode 100644 index 0000000000..c99d64b1a2 --- /dev/null +++ b/types/command-line-args/v4/command-line-args-tests.ts @@ -0,0 +1,21 @@ +import commandLineArgs = require('command-line-args'); + +const optionDefinitions: commandLineArgs.OptionDefinition[] = [ + { + name: 'something', + alias: 's', + type: String, + defaultValue: '1', + multiple: true, + defaultOption: true, + group: 'one' + } +]; + +const options = commandLineArgs(optionDefinitions, { + argv: [ '--one', '1' ], + partial: true +}); + +const unknown = options._unknown; +const something = options.something; diff --git a/types/command-line-args/v4/index.d.ts b/types/command-line-args/v4/index.d.ts new file mode 100644 index 0000000000..a5c8250827 --- /dev/null +++ b/types/command-line-args/v4/index.d.ts @@ -0,0 +1,73 @@ +// Type definitions for command-line-args 4.0 +// Project: https://github.com/75lb/command-line-args +// Definitions by: CzBuCHi , Lloyd Brookes +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.2 + +/** + * Returns an object containing option values parsed from the command line. By default it parses the global `process.argv` array. + */ +declare function commandLineArgs(optionDefinitions: commandLineArgs.OptionDefinition[], options?: commandLineArgs.ParseOptions): commandLineArgs.CommandLineOptions; + +declare namespace commandLineArgs { + interface CommandLineOptions { + /** + * Command-line arguments not parsed by `commandLineArgs`. + */ + _unknown?: string[]; + [propName: string]: any; + } + + interface ParseOptions { + /** + * An array of strings which if present will be parsed instead of `process.argv`. + */ + argv?: string[]; + + /** + * If `true`, `commandLineArgs` will not throw on unknown options or values, instead returning them in the `_unknown` property of the output. + */ + partial?: boolean; + } + + interface OptionDefinition { + /** + * The long option name. + */ + name: string; + + /** + * A setter function (you receive the output from this) enabling you to be specific about the type and value received. Typical values + * are `String` (the default), `Number` and `Boolean` but you can use a custom function. If no option value was set you will receive `null`. + */ + type?: (input: string) => any; + + /** + * A getopt-style short option name. Can be any single character except a digit or hyphen. + */ + alias?: string; + + /** + * Set this flag if the option accepts multiple values. In the output, you will receive an array of values each passed through the `type` function. + */ + multiple?: boolean; + + /** + * Any values unaccounted for by an option definition will be set on the `defaultOption`. This flag is typically set + * on the most commonly-used option to enable more concise usage. + */ + defaultOption?: boolean; + + /** + * An initial value for the option. + */ + defaultValue?: any; + + /** + * One or more group names the option belongs to. + */ + group?: string | string[]; + } +} + +export = commandLineArgs; diff --git a/types/command-line-args/v4/tsconfig.json b/types/command-line-args/v4/tsconfig.json new file mode 100644 index 0000000000..3517f0823e --- /dev/null +++ b/types/command-line-args/v4/tsconfig.json @@ -0,0 +1,26 @@ +{ + "compilerOptions": { + "module": "commonjs", + "lib": [ + "es6" + ], + "noImplicitAny": true, + "noImplicitThis": true, + "strictNullChecks": false, + "strictFunctionTypes": true, + "baseUrl": "../../", + "typeRoots": [ + "../../" + ], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true, + "paths": { + "command-line-args": [ "command-line-args/v4" ] + } + }, + "files": [ + "index.d.ts", + "command-line-args-tests.ts" + ] +} diff --git a/types/command-line-args/v4/tslint.json b/types/command-line-args/v4/tslint.json new file mode 100644 index 0000000000..495d29983d --- /dev/null +++ b/types/command-line-args/v4/tslint.json @@ -0,0 +1,5 @@ +{ + "extends": "dtslint/dt.json", + "rules": { + } +} diff --git a/types/d3-dispatch/d3-dispatch-tests.ts b/types/d3-dispatch/d3-dispatch-tests.ts index a9f29ef75d..4e8d2cfb31 100644 --- a/types/d3-dispatch/d3-dispatch-tests.ts +++ b/types/d3-dispatch/d3-dispatch-tests.ts @@ -16,6 +16,9 @@ interface Datum { } let dispatch: d3Dispatch.Dispatch; +let callback: (this: HTMLElement, ...args: any[]) => void; +let callbackOrUndef: ((this: HTMLElement, ...args: any[]) => void) | undefined; +let undef: undefined; // Signature Tests ---------------------------------------- @@ -33,9 +36,15 @@ function cbFn2(this: SVGElement, d: Datum, i: number) { } dispatch.on('foo', cbFn); -// dispatch.on('foo', cbFn2); // test fails as 'this' context type is mismatched between dispatch and callback function +// $ExpectError +dispatch.on('foo', cbFn2); // test fails as 'this' context type is mismatched between dispatch and callback function -dispatch.on('bar', dispatch.on('bar')); +callback = dispatch.on('bar')!; +callbackOrUndef = dispatch.on('bar'); +callbackOrUndef = dispatch.on('unknown'); +undef = dispatch.on('unknown') as undefined; + +dispatch.on('bar', dispatch.on('bar')!); dispatch.call('foo'); dispatch.call('foo', document.body); @@ -49,4 +58,5 @@ dispatch.on('bar', null); // Copy dispatch ----------------------------------------------- const copy: d3Dispatch.Dispatch = dispatch.copy(); -// const copy2: d3Dispatch.Dispatch = dispatch.copy(); // test fails type mismatch of underlying event target +// $ExpectError +const copy2: d3Dispatch.Dispatch = dispatch.copy(); // test fails type mismatch of underlying event target diff --git a/types/d3-dispatch/index.d.ts b/types/d3-dispatch/index.d.ts index 1e6e82e06f..c8beb28a5a 100644 --- a/types/d3-dispatch/index.d.ts +++ b/types/d3-dispatch/index.d.ts @@ -1,18 +1,74 @@ // Type definitions for D3JS d3-dispatch module 1.0 // Project: https://github.com/d3/d3-dispatch/ -// Definitions by: Tom Wanzek , Alex Ford , Boris Yankov +// Definitions by: Tom Wanzek +// Alex Ford +// Boris Yankov +// denisname // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -// Last module patch version validated against: 1.0.1 +// Last module patch version validated against: 1.0.3 export interface Dispatch { + /** + * Like `function.apply`, invokes each registered callback for the specified type, + * passing the callback the specified arguments, with `that` as the `this` context. + * + * @param type A specified event type. + * @param that The `this` context for the callback. + * @param args Additional arguments to be passed to the callback. + * @throws "unknown type" on unknown event type. + */ apply(type: string, that?: T, args?: any[]): void; - call(type: string, that?: T, ...args: any[]): void; + + /** + * Like `function.call`, invokes each registered callback for the specified type, + * passing the callback the specified arguments, with `that` as the `this` context. + * See dispatch.apply for more information. + * + * @param type A specified event type. + * @param that The `this` context for the callback. + * @param args Additional arguments to be passed to the callback. + * @throws "unknown type" on unknown event type. + */ + call(type: string, that?: T, ...args: any[]): void; + + /** + * Returns a copy of this dispatch object. + * Changes to this dispatch do not affect the returned copy and vice versa. + */ copy(): Dispatch; - on(typenames: string): (this: T, ...args: any[]) => void; + /** + * Returns the callback for the specified typenames, if any. + * If multiple typenames are specified, the first matching callback is returned. + * + * @param types An event typename. + * @param callback A callback. + */ + on(typenames: string): ((this: T, ...args: any[]) => void) | undefined; + /** + * Removes the callback for the specified typenames. + * To remove all callbacks for a given name `foo`, say `dispatch.on(".foo", null).` + * + * @param types An event typename. + */ on(typenames: string, callback: null): this; + /** + * Adds the callback for the specified typenames. + * The callback is registered for the specified (fully-qualified) typenames. + * If a callback was already registered for the given typenames, + * the existing callback is removed before the new callback is added. + * + * @param types An event typename. + * @param callback A callback. + */ on(typenames: string, callback: (this: T, ...args: any[]) => void): this; } +/** + * Creates a new dispatch for the specified event types. Each type is a string, such as "start" or "end". + * + * @param types The event types. + * @throws "illegal type" on empty string or duplicated event types. + */ export function dispatch(...types: string[]): Dispatch; diff --git a/types/d3-dispatch/tsconfig.json b/types/d3-dispatch/tsconfig.json index b270a9c1a0..88000f85e4 100644 --- a/types/d3-dispatch/tsconfig.json +++ b/types/d3-dispatch/tsconfig.json @@ -7,7 +7,7 @@ ], "noImplicitAny": true, "noImplicitThis": true, - "strictNullChecks": false, + "strictNullChecks": true, "strictFunctionTypes": true, "baseUrl": "../", "typeRoots": [ diff --git a/types/d3-hsv/d3-hsv-tests.ts b/types/d3-hsv/d3-hsv-tests.ts index 0d3e564360..7aa6fb7817 100644 --- a/types/d3-hsv/d3-hsv-tests.ts +++ b/types/d3-hsv/d3-hsv-tests.ts @@ -6,19 +6,23 @@ * are not intended as functional tests. */ -import { hsv, HSVColor } from 'd3-hsv'; -import { rgb, RGBColor } from 'd3-color'; +import { hsv, HSVColor, interpolateHsv, interpolateHsvLong } from 'd3-hsv'; +import { rgb, hcl, RGBColor } from 'd3-color'; -let c: RGBColor; +let cRGB: RGBColor; let cHSV: HSVColor; let displayable: boolean; let cString: string; +let iString: (t: number) => string; +let nil: null; + +// Hsv signature -// hsv signature cHSV = hsv(120, 0.4, 0.5); cHSV = hsv(120, 0.4, 0.5, 0.5); -// specifier signature +// Specifier signature + cHSV = hsv('rgb(255, 255, 255)'); cHSV = hsv('rgb(10%, 20%, 30%)'); cHSV = hsv('rgba(255, 255, 255, 0.4)'); @@ -28,13 +32,16 @@ cHSV = hsv('hsla(120, 50%, 20%, 0.4)'); cHSV = hsv('#ffeeaa'); cHSV = hsv('#fea'); cHSV = hsv('steelblue'); +cHSV = hsv(''); -// color signature -c = rgb('steelblue'); -cHSV = hsv(c); +// Color signature + +cRGB = rgb('steelblue'); +cHSV = hsv(cRGB); cHSV = hsv(cHSV); -// method signatures +// Method signatures + cHSV = cHSV.brighter(); cHSV = cHSV.brighter(0.2); cHSV = cHSV.darker(); @@ -43,3 +50,25 @@ displayable = cHSV.displayable(); cString = cHSV.toString(); console.log('Channels = (h : %d, s: %d, v: %d)', cHSV.h, cHSV.s, cHSV.v); console.log('Opacity = %d', cHSV.opacity); + +// Interpolater + +iString = interpolateHsv('seagreen', 'steelblue'); +iString = interpolateHsv(rgb('seagreen'), hcl('steelblue')); +iString = interpolateHsv(rgb('seagreen'), hsv('steelblue')); + +iString = interpolateHsvLong('seagreen', 'steelblue'); +iString = interpolateHsvLong(rgb('seagreen'), hcl('steelblue')); +iString = interpolateHsvLong(rgb('seagreen'), hsv('steelblue')); + +// Prototype, instanceof and typeguard + +declare let color: RGBColor | HSVColor | null; + +if (color instanceof rgb) { + cRGB = color; +} else if (color instanceof hsv) { + cHSV = color; +} else { + nil = color; +} diff --git a/types/d3-hsv/index.d.ts b/types/d3-hsv/index.d.ts index 6a7a2c8560..1728af0874 100644 --- a/types/d3-hsv/index.d.ts +++ b/types/d3-hsv/index.d.ts @@ -1,28 +1,89 @@ -// Type definitions for D3JS d3-hsv module 0.0 +// Type definitions for D3JS d3-hsv module 0.1 // Project: https://github.com/d3/d3-hsv/ -// Definitions by: Yuri Feldman +// Definitions by: Yuri Feldman , denisname // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -// Last module patch version validated against: 0.0.3 +// Last module patch version validated against: 0.1.0 import { Color, RGBColor, ColorSpaceObject, ColorCommonInstance } from 'd3-color'; export type ColorSpaceObjectWithHSV = ColorSpaceObject | HSVColor; export interface HSVColorFactory extends Function { + /** + * Constructs a new HSV color. + * @param h The hue of the returned color. + * @param s The saturation of the returned color. + * @param v The value of the returned color. + * @param opacity The opacity of the returned color. + */ (h: number, s: number, v: number, opacity?: number): HSVColor; + /** + * Constructs a new HSV color. + * @param cssColorSpecifier A CSS Color Module Level 3 specifier string, + * it is parsed and then converted to the HSV color space. + */ (cssColorSpecifier: string): HSVColor; + /** + * Constructs a new HSV color. + * @param color A color instance, it will be converted to the RGB color space + * using `color.rgb` and then converted to HSV. + */ (color: HSVColor | ColorSpaceObject | ColorCommonInstance): HSVColor; + + readonly prototype: HSVColor; } export interface HSVColor extends Color { + /** + * The color hue. + */ h: number; + /** + * The color saturation. + */ s: number; + /** + * The color value. + */ v: number; + /** + * The color opacity. + */ opacity: number; + + /** + * Returns a brighter copy of this color. + * @param k Controls how much brighter the returned color should be (defaults to 1). + */ brighter(k?: number): this; + + /** + * Returns a darker copy of this color. + * @param k Controls how much darker the returned color should be (defaults to 1). + */ darker(k?: number): this; + + /** + * Returns the RGB equivalent of this color. + */ rgb(): RGBColor; } export const hsv: HSVColorFactory; + +/** + * Returns an HSV color space interpolator between the two colors a and b. + * If either color’s hue or chroma is NaN, the opposing color’s channel value is used. + * The shortest path between hues is used. The return value of the interpolator is an RGB string. + * @param a The starting color; it will be converted to HSV using `d3.hsv`. + * @param b The ending color; it will be converted to HSV using `d3.hsv`. + */ +export function interpolateHsv(a: string | ColorCommonInstance, b: string | ColorCommonInstance): (t: number) => string; + +/** + * Like `interpolateHsv`, but does not use the shortest path between hues. + * @param a The starting color; it will be converted to HSV using `d3.hsv`. + * @param b The ending color; it will be converted to HSV using `d3.hsv`. + */ +export function interpolateHsvLong(a: string | ColorCommonInstance, b: string | ColorCommonInstance): (t: number) => string; diff --git a/types/d3-hsv/tsconfig.json b/types/d3-hsv/tsconfig.json index c92ce346b2..0f7de85da1 100644 --- a/types/d3-hsv/tsconfig.json +++ b/types/d3-hsv/tsconfig.json @@ -7,7 +7,7 @@ ], "noImplicitAny": true, "noImplicitThis": true, - "strictNullChecks": false, + "strictNullChecks": true, "strictFunctionTypes": true, "baseUrl": "../", "typeRoots": [ diff --git a/types/draft-js/index.d.ts b/types/draft-js/index.d.ts index e83de2b303..4064c9b8a0 100644 --- a/types/draft-js/index.d.ts +++ b/types/draft-js/index.d.ts @@ -610,6 +610,7 @@ declare namespace Draft { import DraftBlockType = Draft.Model.Constants.DraftBlockType; import DraftEntityMutability = Draft.Model.Constants.DraftEntityMutability; import DraftEntityType = Draft.Model.Constants.DraftEntityType; + import DraftEntityInstance = Draft.Model.Entity.DraftEntityInstance; import DraftDecoratorType = Draft.Model.Decorators.DraftDecoratorType; @@ -754,6 +755,8 @@ declare namespace Draft { getEntity(key: string): EntityInstance; getLastCreatedEntityKey(): string; mergeEntityData(key: string, toMerge: { [key: string]: any }): ContentState; + replaceEntityData(key: string, toMerge: { [key: string]: any }): ContentState; + addEntity(instance: DraftEntityInstance): ContentState; getBlockMap(): BlockMap; diff --git a/types/elasticsearch/elasticsearch-tests.ts b/types/elasticsearch/elasticsearch-tests.ts index e21f84dc48..3236a181a1 100644 --- a/types/elasticsearch/elasticsearch-tests.ts +++ b/types/elasticsearch/elasticsearch-tests.ts @@ -1,10 +1,22 @@ import * as elasticsearch from "elasticsearch"; +import HttpConnector = require("elasticsearch/src/lib/connectors/http"); + +class MyHttpConnector extends HttpConnector { + constructor(host: any, config: any) { + super(host, config); + } +} let client = new elasticsearch.Client({ host: 'localhost:9200', log: 'trace' }); +client = new elasticsearch.Client({ + host: 'localhost:9200', + connectionClass: MyHttpConnector +}); + client = new elasticsearch.Client({ hosts: [ 'box1.server.org', diff --git a/types/elasticsearch/index.d.ts b/types/elasticsearch/index.d.ts index e60e8d86c3..7973b598ab 100644 --- a/types/elasticsearch/index.d.ts +++ b/types/elasticsearch/index.d.ts @@ -12,6 +12,8 @@ // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped // TypeScript Version: 2.2 +import HttpConnector = require("./src/lib/connectors/http"); + export class Client { constructor(params: ConfigOptions); cat: Cat; @@ -111,7 +113,7 @@ export interface ConfigOptions { keepAlive?: boolean; maxSockets?: number; suggestCompression?: boolean; - connectionClass?: string; + connectionClass?: string | typeof HttpConnector; sniffedNodesProtocol?: string; ssl?: object; selector?: any; diff --git a/types/elasticsearch/src/lib/connectors/http.d.ts b/types/elasticsearch/src/lib/connectors/http.d.ts new file mode 100644 index 0000000000..94d1e4e58c --- /dev/null +++ b/types/elasticsearch/src/lib/connectors/http.d.ts @@ -0,0 +1,13 @@ +// HttpConnector for elasticsearch + +export = HttpConnector; + +declare class HttpConnector { + constructor(host: any, config: any); + + // onStatusSet(handler: (status: any) => void): void; + createAgent(config: any): any; + makeAgentConfig(config: any): any; + makeReqParams(params: any): any; + request(params: any, callback: (error: any, response: any, status: any, headers: any) => void): void; +} diff --git a/types/esprima/esprima-tests.ts b/types/esprima/esprima-tests.ts index 2032702979..08a3214a95 100644 --- a/types/esprima/esprima-tests.ts +++ b/types/esprima/esprima-tests.ts @@ -29,6 +29,7 @@ program = esprima.parseScript('answer = 42 // TODO: why', { comment: true, range // Tokenizing token = esprima.tokenize('code')[0]; token = esprima.tokenize('code', {range: true})[0]; +token = esprima.tokenize('/E\/\w*/.exec("e")', { tolerant: true })[0]; // Syntax Delegate esprima.parseScript('answer = 42', {}, (node) => { diff --git a/types/esprima/index.d.ts b/types/esprima/index.d.ts index 7817465742..cc612b12d1 100644 --- a/types/esprima/index.d.ts +++ b/types/esprima/index.d.ts @@ -30,6 +30,7 @@ export interface ParseOptions { } export interface TokenizeOptions { + tolerant?: boolean; range?: boolean; loc?: boolean; comment?: boolean; diff --git a/types/evaporate/evaporate-tests.ts b/types/evaporate/evaporate-tests.ts index ea4a4ac9bf..3140cd9ea9 100644 --- a/types/evaporate/evaporate-tests.ts +++ b/types/evaporate/evaporate-tests.ts @@ -1,7 +1,27 @@ -import Evaporate = require("evaporate"); +import Evaporate = require('evaporate'); -function test_upload() { - var evaporate = new Evaporate({}); - var uploadId = evaporate.add({}); - evaporate.cancel(uploadId); -} +const newEvaporate = new Evaporate({ + bucket: 'abc', +}); + +Evaporate.create({ + bucket: 'abc', +}) + .then((evaporate) => { + evaporate.add({ + name: 'gwejlf', + file: new File(['abcd'], 'efg'), + started: (file_key) => { + evaporate.pause(file_key); + }, + paused: (file_key) => { + evaporate.resume(file_key); + }, + resumed: (file_key) => { + evaporate.cancel(file_key); + } + }) + .then((awsS3ObjectKey) => { + console.log(awsS3ObjectKey + '!!!'); + }); + }); diff --git a/types/evaporate/index.d.ts b/types/evaporate/index.d.ts index bf4b52aae3..1c415769b8 100644 --- a/types/evaporate/index.d.ts +++ b/types/evaporate/index.d.ts @@ -1,12 +1,112 @@ -// Type definitions for EvaporateJS +// Type definitions for EvaporateJS 2.1 // Project: https://github.com/TTLabs/EvaporateJS -// Definitions by: Andrew Kuklewicz , Chris Rhoden +// Definitions by: Andrew Kuklewicz +// Chris Rhoden +// Junyoung Clare Jang // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.8 export = Evaporate; declare class Evaporate { - cancel(id:string): boolean; - constructor(config:any); - add(config:any): string; + constructor(config: Evaporate.CreateConfig); + supported: boolean; + add(config: Evaporate.AddConfig, options?: Evaporate.AddOverrideOptions): Promise; + pause(file_key?: string, options?: object): Promise; + resume(file_key?: string): Promise; + cancel(file_key?: string): Promise; +} + +declare namespace Evaporate { + function create(config: CreateConfig): Promise; + + interface CreateConfig { + readableStreams?: boolean; + readableStreamPartMethod?: null | ((file: File, start: number, end: number) => ReadableStream); + bucket: string; + logging?: boolean; + maxConcurrentParts?: number; + partSize?: number; + retryBackoffPower?: number; + maxRetryBackoffSecs?: number; + progressIntervalMS?: number; + cloudfront?: boolean; + s3Acceleration?: boolean; + mockLocalStorage?: boolean; + encodeFilename?: boolean; + computeContentMd5?: false; + allowS3ExistenceOptimization?: boolean; + onlyRetryForSameFileName?: boolean; + timeUrl?: string; + cryptoMd5Method?: null | ((data: ArrayBuffer) => string); + cryptoHexEncodedHash256?: null | ((data: ArrayBuffer) => string); + aws_url?: string; + aws_key?: string; + awsRegion?: string; + awsSignatureVersion?: '2' | '4'; + signerUrl?: string; + sendCanonicalRequestToSignerUrl?: boolean; + s3FileCacheHoursAgo?: null | number; + signParams?: object; + signHeaders?: object; + customAuthMethod?: null | (( + signParams: string, + signHeaders: string, + stringToSign: () => string | undefined, + signatureDateTime: string, + canonicalRequest: string + ) => Promise); + maxFileSize?: number; + signResponseHandler?: null | ((response: any, stringToSign: string, signatureDateTime: string) => Promise); + xhrWithCredentials?: boolean; + localTimeOffset?: number; + evaporateChanged?: (evaporate: Evaporate, evaporatingCount: number) => void; + abortCompletionThrottlingMs?: number; + } + + interface TransferStats { + speed: number; + readableSpeed: string; + loaded: number; + totalUploaded: number; + remainingSize: number; + secondsLeft: number; + fileSize: number; + } + + interface AddConfig { + name: string; + file: File; + xAmzHeadersAtInitiate?: { [key: string]: string }; + notSignedHeadersAtInitiate?: { [key: string]: string }; + xAmzHeadersAtUpload?: { [key: string]: string }; + xAmzHeadersAtComplete?: { [key: string]: string }; + xAmzHeadersCommon?: { [key: string]: string }; + started?: (file_key: string) => void; + uploadInitiated?: (s3UploadId?: string) => void; + paused?: (file_key: string) => void; + resumed?: (file_key: string) => void; + pausing?: (file_key: string) => void; + cancelled?: () => void; + complete?: (xhr: XMLHttpRequest, awsObjectKey: string, stats: TransferStats) => void; + nameChanged?: (awsObjectKey: string) => void; + info?: (msg: string) => void; + warn?: (msg: string) => void; + error?: (msg: string) => void; + progress?: (p: number, stats: TransferStats) => void; + contentType?: string; + beforeSigner?: (xhr: XMLHttpRequest, url: string) => void; + } + + type ImmutableOptionKeys = + | 'maxConcurrentParts' | 'logging' | 'cloudfront' | 'encodeFilename' + | 'computeContentMd5' | 'allowS3ExistenceOptimization' | 'onlyRetryForSameFileName' + | 'timeUrl' | 'cryptoMd5Method' | 'cryptoHexEncodedHash256' | 'awsRegion' | 'awsSignatureVersion' + | 'evaporateChanged'; + type AddOverrideOptionKeys = Exclude; + interface AddOverrideOptions extends Pick {} + + interface PauseConfig { + force?: boolean; + } } diff --git a/types/evaporate/tsconfig.json b/types/evaporate/tsconfig.json index 9164730455..c932b3ca2f 100644 --- a/types/evaporate/tsconfig.json +++ b/types/evaporate/tsconfig.json @@ -1,23 +1,24 @@ { "compilerOptions": { - "module": "commonjs", + "baseUrl": "../", + "forceConsistentCasingInFileNames": true, "lib": [ - "es6" + "es6", + "dom" ], + "module": "commonjs", + "noEmit": true, "noImplicitAny": true, "noImplicitThis": true, - "strictNullChecks": false, + "strictNullChecks": true, "strictFunctionTypes": true, - "baseUrl": "../", "typeRoots": [ "../" ], - "types": [], - "noEmit": true, - "forceConsistentCasingInFileNames": true + "types": [] }, "files": [ "index.d.ts", "evaporate-tests.ts" ] -} \ No newline at end of file +} diff --git a/types/evaporate/tslint.json b/types/evaporate/tslint.json index a41bf5d19a..f93cf8562a 100644 --- a/types/evaporate/tslint.json +++ b/types/evaporate/tslint.json @@ -1,79 +1,3 @@ { - "extends": "dtslint/dt.json", - "rules": { - "adjacent-overload-signatures": false, - "array-type": false, - "arrow-return-shorthand": false, - "ban-types": false, - "callable-types": false, - "comment-format": false, - "dt-header": false, - "eofline": false, - "export-just-namespace": false, - "import-spacing": false, - "interface-name": false, - "interface-over-type-literal": false, - "jsdoc-format": false, - "max-line-length": false, - "member-access": false, - "new-parens": false, - "no-any-union": false, - "no-boolean-literal-compare": false, - "no-conditional-assignment": false, - "no-consecutive-blank-lines": false, - "no-construct": false, - "no-declare-current-package": false, - "no-duplicate-imports": false, - "no-duplicate-variable": false, - "no-empty-interface": false, - "no-for-in-array": false, - "no-inferrable-types": false, - "no-internal-module": false, - "no-irregular-whitespace": false, - "no-mergeable-namespace": false, - "no-misused-new": false, - "no-namespace": false, - "no-object-literal-type-assertion": false, - "no-padding": false, - "no-redundant-jsdoc": false, - "no-redundant-jsdoc-2": false, - "no-redundant-undefined": false, - "no-reference-import": false, - "no-relative-import-in-test": false, - "no-self-import": false, - "no-single-declare-module": false, - "no-string-throw": false, - "no-unnecessary-callback-wrapper": false, - "no-unnecessary-class": false, - "no-unnecessary-generics": false, - "no-unnecessary-qualifier": false, - "no-unnecessary-type-assertion": false, - "no-useless-files": false, - "no-var-keyword": false, - "no-var-requires": false, - "no-void-expression": false, - "no-trailing-whitespace": false, - "object-literal-key-quotes": false, - "object-literal-shorthand": false, - "one-line": false, - "one-variable-per-declaration": false, - "only-arrow-functions": false, - "prefer-conditional-expression": false, - "prefer-const": false, - "prefer-declare-function": false, - "prefer-for-of": false, - "prefer-method-signature": false, - "prefer-template": false, - "radix": false, - "semicolon": false, - "space-before-function-paren": false, - "space-within-parens": false, - "strict-export-declare-modifiers": false, - "trim-file": false, - "triple-equals": false, - "typedef-whitespace": false, - "unified-signatures": false, - "void-return": false, - "whitespace": false - } + "extends": "dtslint/dt.json" } diff --git a/types/expo/expo-tests.tsx b/types/expo/expo-tests.tsx index 5df51127da..36eb5fc22c 100644 --- a/types/expo/expo-tests.tsx +++ b/types/expo/expo-tests.tsx @@ -600,6 +600,8 @@ Permissions.CONTACTS === 'contacts'; Permissions.NOTIFICATIONS === 'remoteNotifications'; Permissions.REMOTE_NOTIFICATIONS === 'remoteNotifications'; Permissions.SYSTEM_BRIGHTNESS === 'systemBrightness'; +Permissions.USER_FACING_NOTIFICATIONS === 'userFacingNotifications'; +Permissions.REMINDERS === 'reminders'; async () => { const result = await Permissions.askAsync(Permissions.CAMERA); diff --git a/types/expo/index.d.ts b/types/expo/index.d.ts index e660a4e582..d10ffea9d4 100644 --- a/types/expo/index.d.ts +++ b/types/expo/index.d.ts @@ -1778,8 +1778,9 @@ export namespace Pedometer { * Permissions */ export namespace Permissions { - type PermissionType = 'remoteNotifications' | 'location' | - 'camera' | 'contacts' | 'audioRecording' | 'calendar'; + type PermissionType = 'audioRecording' | 'calendar' | + 'cameraRoll' | 'camera' | 'contacts' | 'location' | 'reminders' | + 'remoteNotifications' | 'systemBrightness' | 'userFacingNotifications'; type PermissionStatus = 'undetermined' | 'granted' | 'denied'; type PermissionExpires = 'never'; @@ -1803,15 +1804,17 @@ export namespace Permissions { type RemoteNotificationPermission = 'remoteNotifications'; - const CAMERA: 'camera'; - const CAMERA_ROLL: 'cameraRoll'; const AUDIO_RECORDING: 'audioRecording'; - const LOCATION: 'location'; - const REMOTE_NOTIFICATIONS: RemoteNotificationPermission; - const NOTIFICATIONS: RemoteNotificationPermission; - const CONTACTS: 'contacts'; - const SYSTEM_BRIGHTNESS: 'systemBrightness'; const CALENDAR: 'calendar'; + const CAMERA_ROLL: 'cameraRoll'; + const CAMERA: 'camera'; + const CONTACTS: 'contacts'; + const LOCATION: 'location'; + const NOTIFICATIONS: RemoteNotificationPermission; + const REMINDERS = 'reminders'; + const REMOTE_NOTIFICATIONS: RemoteNotificationPermission; + const SYSTEM_BRIGHTNESS: 'systemBrightness'; + const USER_FACING_NOTIFICATIONS = 'userFacingNotifications'; } /** diff --git a/types/express-jsonschema/express-jsonschema-tests.ts b/types/express-jsonschema/express-jsonschema-tests.ts new file mode 100644 index 0000000000..85a3852d75 --- /dev/null +++ b/types/express-jsonschema/express-jsonschema-tests.ts @@ -0,0 +1,71 @@ +import { + JsonSchemaCustomPropertyError, + JsonSchemaValidation, + addSchemaProperties, + validate, +} from "express-jsonschema"; + +import { Request, Response, NextFunction } from "express"; +import { JSONSchema4 } from "json-schema"; + +let jsonSchema: JSONSchema4; +let expressMiddleware: (req: Request, res: Response, next: NextFunction) => void; + +jsonSchema = { + id: 'foo', + $ref: 'foo/bar', + $schema: 'http://json-schema.org/schema#', + title: 'foo', + description: 'bar', + default: 42, + multipleOf: 3, + maximum: 4, + exclusiveMaximum: true, + minimum: 5, + exclusiveMinimum: false, + maxLength: 6, + minLength: 7, + pattern: 'baz', + additionalItems: true, + items: [ + { items: [{ minLength: 4 }] } + ], + maxItems: 4, + minItems: 5, + uniqueItems: true, + maxProperties: 10, + minProperties: 11, + required: ['foo', 'bar'], + additionalProperties: false, + definitions: { + foo: { type: 'string' } + }, + properties: { + bar: { type: 'boolean' } + }, + patternProperties: { + foo: { type: 'integer' } + }, + dependencies: { + baz: { type: 'integer' } + }, + enum: ['foo', 42], + type: 'string', + allOf: [{}], + anyOf: [{}], + oneOf: [{}], + not: {}, + extends: 'foo', + bar: 4, + format: 'date-time', +}; + +expressMiddleware = validate({ test: jsonSchema }, [ jsonSchema ]); +addSchemaProperties({ + test: () => "This is an error with message...", + conditional: (instance: any, schema: JSONSchema4) => { + if (!instance) { + return "An instance should be present"; + } + } +}); diff --git a/types/express-jsonschema/index.d.ts b/types/express-jsonschema/index.d.ts new file mode 100644 index 0000000000..f089e1033e --- /dev/null +++ b/types/express-jsonschema/index.d.ts @@ -0,0 +1,54 @@ +// Type definitions for express-jsonschema 1.1 +// Project: https://github.com/trainiac/express-jsonschema#readme +// Definitions by: Arne Schubert +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.2 + +import { Request, Response, NextFunction } from "express"; +import { JSONSchema4 } from "json-schema"; + +export class JsonSchemaCustomPropertyError { + name: string; + message: string; + constructor(propertyName: string); +} + +export class JsonSchemaValidation { + name: string; + message: string; + validations: {[requestProperty: string]: Array<{ value: any, property: string, messages: string[]}> }; + constructor(validations: { [requestProperty: string]: { instance: any, property: string, message: string }}); +} + +/** + * Updates customProperties with the newProperties param. Provides a way for client to extend JSON Schema validations. + * + * @param newProperties - An object where the keys are the + * names of the new schema properties and the values are the respective + * functions that implement the validation. + * @throws Client tries to override an existing JSON Schema property. + */ +export function addSchemaProperties(newProperties: { [attribute: string]: (instance: any, schema: JSONSchema4, options: any, ctx: any) => void | string }): void; + +/** + * Accepts an object where the keys are request properties and the + * values are their respective schemas. Optionally, you may provide + * dependency schemas that are referenced by your schemas using `$ref` + * (see https://www.npmjs.com/package/jsonschema#complex-example-with-split-schemas-and-references + * for more details). + * Returns a middleware function that validates the given + * request properties when a request is made. If there is any invalid + * data a JsonSchemaValidation instance is passed to the next middleware. + * If the data is valid the next middleware is called with no params. + * + * @param schemas - An object where the keys are request properties + * and the values are their respective schemas. + * @param schemaDependencies - A list of schemas on which + * schemas in `schemas` parameter are dependent. These will be added + * to the `jsonschema` validator. + * @returns A middleware function. + */ +export function validate( + schemas: { [requestProperty: string]: JSONSchema4 }, + schemaDependencies?: JSONSchema4[], +): (req: Request, res: Response, next: NextFunction) => void; diff --git a/types/express-jsonschema/tsconfig.json b/types/express-jsonschema/tsconfig.json new file mode 100644 index 0000000000..964ad62e02 --- /dev/null +++ b/types/express-jsonschema/tsconfig.json @@ -0,0 +1,23 @@ +{ + "compilerOptions": { + "module": "commonjs", + "lib": [ + "es6" + ], + "noImplicitAny": true, + "noImplicitThis": true, + "strictNullChecks": true, + "strictFunctionTypes": true, + "baseUrl": "../", + "typeRoots": [ + "../" + ], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true + }, + "files": [ + "index.d.ts", + "express-jsonschema-tests.ts" + ] +} diff --git a/types/express-jsonschema/tslint.json b/types/express-jsonschema/tslint.json new file mode 100644 index 0000000000..3db14f85ea --- /dev/null +++ b/types/express-jsonschema/tslint.json @@ -0,0 +1 @@ +{ "extends": "dtslint/dt.json" } diff --git a/types/express-routemap/express-routemap-tests.ts b/types/express-routemap/express-routemap-tests.ts new file mode 100644 index 0000000000..e169a614b9 --- /dev/null +++ b/types/express-routemap/express-routemap-tests.ts @@ -0,0 +1,7 @@ +import express = require('express'); +import displayRoutes = require('express-routemap'); + +const server = express(); +server.listen(3000, () => { + displayRoutes(server); // $ExpectType void +}); diff --git a/types/express-routemap/index.d.ts b/types/express-routemap/index.d.ts new file mode 100644 index 0000000000..a2e80499b0 --- /dev/null +++ b/types/express-routemap/index.d.ts @@ -0,0 +1,10 @@ +// Type definitions for express-routemap 1.1 +// Project: https://github.com/izelnakri/express-routemap#readme +// Definitions by: icopp +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.2 + +import { Application } from 'express'; + +declare function displayRoutes(app: Application, filename?: string): void; +export = displayRoutes; diff --git a/types/express-routemap/tsconfig.json b/types/express-routemap/tsconfig.json new file mode 100644 index 0000000000..44638d2eb4 --- /dev/null +++ b/types/express-routemap/tsconfig.json @@ -0,0 +1,23 @@ +{ + "compilerOptions": { + "module": "commonjs", + "lib": [ + "es6" + ], + "noImplicitAny": true, + "noImplicitThis": true, + "strictNullChecks": true, + "strictFunctionTypes": true, + "baseUrl": "../", + "typeRoots": [ + "../" + ], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true + }, + "files": [ + "index.d.ts", + "express-routemap-tests.ts" + ] +} diff --git a/types/express-routemap/tslint.json b/types/express-routemap/tslint.json new file mode 100644 index 0000000000..3db14f85ea --- /dev/null +++ b/types/express-routemap/tslint.json @@ -0,0 +1 @@ +{ "extends": "dtslint/dt.json" } diff --git a/types/feather-icons/feather-icons-tests.ts b/types/feather-icons/feather-icons-tests.ts new file mode 100644 index 0000000000..fc71f25798 --- /dev/null +++ b/types/feather-icons/feather-icons-tests.ts @@ -0,0 +1,7 @@ +import * as feather from "feather-icons"; + +feather.replace(); // $ExpectType void +feather.icons[""].toSvg(); // $ExpectType string +feather.icons[""].name; // $ExpectType string +feather.icons[""].contents; // $ExpectType string +feather.icons[""].tags; // $ExpectType string[] diff --git a/types/feather-icons/index.d.ts b/types/feather-icons/index.d.ts new file mode 100644 index 0000000000..34acfb80aa --- /dev/null +++ b/types/feather-icons/index.d.ts @@ -0,0 +1,22 @@ +// Type definitions for feather-icons 4.7 +// Project: https://github.com/feathericons/feather#readme +// Definitions by: Jinesh Shah +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +export as namespace feather; + +export interface FeatherAttributes { + [key: string]: string | number; +} + +export function replace(options?: FeatherAttributes): void; + +export const icons: { + [key: string]: { + name: string; + contents: string; + tags: string[]; + attrs: FeatherAttributes; + toSvg: (options?: FeatherAttributes) => string; + }; +}; diff --git a/types/feather-icons/tsconfig.json b/types/feather-icons/tsconfig.json new file mode 100644 index 0000000000..ab8237b4de --- /dev/null +++ b/types/feather-icons/tsconfig.json @@ -0,0 +1,16 @@ +{ + "compilerOptions": { + "module": "commonjs", + "lib": ["es6"], + "noImplicitAny": true, + "noImplicitThis": true, + "strictNullChecks": true, + "baseUrl": "../", + "typeRoots": ["../"], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true, + "strictFunctionTypes": true + }, + "files": ["index.d.ts", "feather-icons-tests.ts"] +} diff --git a/types/feather-icons/tslint.json b/types/feather-icons/tslint.json new file mode 100644 index 0000000000..3db14f85ea --- /dev/null +++ b/types/feather-icons/tslint.json @@ -0,0 +1 @@ +{ "extends": "dtslint/dt.json" } diff --git a/types/flowjs/flowjs-tests.ts b/types/flowjs/flowjs-tests.ts index efb2c30f5b..6167e7f58f 100644 --- a/types/flowjs/flowjs-tests.ts +++ b/types/flowjs/flowjs-tests.ts @@ -4,7 +4,7 @@ var flowObject: flowjs.IFlow; var bool: boolean = flowObject.support; bool = flowObject.supportDirectory; -var obj: Object = flowObject.opts; +var flowOpts: flowjs.IFlowOptions = flowObject.opts; var flowFileArray: flowjs.IFlowFile[] = flowObject.files; flowObject.assignBrowse( [], false, false, {}); diff --git a/types/flowjs/index.d.ts b/types/flowjs/index.d.ts index 7d1f922330..0a6c361c73 100644 --- a/types/flowjs/index.d.ts +++ b/types/flowjs/index.d.ts @@ -7,7 +7,7 @@ declare namespace flowjs { interface IFlow { support: boolean; supportDirectory: boolean; - opts: Object; + opts: IFlowOptions; files: IFlowFile[]; assignBrowse(domNodes: HTMLElement[], isDirectory: boolean, singleFile: boolean, attributes: Object): void; diff --git a/types/fork-ts-checker-webpack-plugin/fork-ts-checker-webpack-plugin-tests.ts b/types/fork-ts-checker-webpack-plugin/fork-ts-checker-webpack-plugin-tests.ts new file mode 100644 index 0000000000..78ead793b4 --- /dev/null +++ b/types/fork-ts-checker-webpack-plugin/fork-ts-checker-webpack-plugin-tests.ts @@ -0,0 +1,24 @@ +import { Configuration } from 'webpack'; +import * as ForkTsCheckerWebpackPlugin from 'fork-ts-checker-webpack-plugin'; + +let config: Configuration = { + plugins: [ + new ForkTsCheckerWebpackPlugin() + ] +}; + +config = { + plugins: [ + new ForkTsCheckerWebpackPlugin({}) + ] +}; + +config = { + plugins: [ + new ForkTsCheckerWebpackPlugin({ + vue: true + }) + ] +}; + +export default config; diff --git a/types/fork-ts-checker-webpack-plugin/index.d.ts b/types/fork-ts-checker-webpack-plugin/index.d.ts new file mode 100644 index 0000000000..ace3db5b24 --- /dev/null +++ b/types/fork-ts-checker-webpack-plugin/index.d.ts @@ -0,0 +1,104 @@ +// Type definitions for fork-ts-checker-webpack-plugin 0.4 +// Project: https://github.com/Realytics/fork-ts-checker-webpack-plugin#readme +// Definitions by: JounQin +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.3 + +/// + +import { RuleFailure } from 'tslint'; +import { Diagnostic } from 'typescript'; +import { Plugin } from 'webpack'; + +declare namespace ForkTsCheckerWebpackPlugin { + type ErrorType = 'diagnostic' | 'lint'; + type Severity = 'error' | 'warning'; + + interface NormalizedMessageJson { + type: ErrorType; + code: string | number; + severity: Severity; + content: string; + file: string; + line: number; + character: number; + } + + class NormalizedMessage { + static TYPE_DIAGNOSTIC: ErrorType; + static TYPE_LINT: ErrorType; + static SEVERITY_ERROR: Severity; + static SEVERITY_WARNING: Severity; + type: ErrorType; + code: string | number; + severity: Severity; + content: string; + file: string; + line: number; + character: number; + constructor(data: NormalizedMessageJson); + static createFromDiagnostic(diagnostic: Diagnostic): NormalizedMessage; + static createFromLint(lint: RuleFailure): NormalizedMessage; + static createFromJSON(json: NormalizedMessageJson): NormalizedMessage; + static compare( + messageA: NormalizedMessage, + messageB: NormalizedMessage, + ): number; + static equals( + messageA: NormalizedMessage, + messageB: NormalizedMessage, + ): boolean; + static deduplicate(messages: NormalizedMessage[]): NormalizedMessage[]; + static compareTypes(typeA: ErrorType, typeB: ErrorType): number; + static compareSeverities( + severityA: Severity, + severityB: Severity, + ): number; + static compareOptionalStrings(stringA: string, stringB: string): number; + static compareNumbers(numberA: number, numberB: number): number; + toJSON(): NormalizedMessageJson; + getType(): ErrorType; + isDiagnosticType(): boolean; + isLintType(): boolean; + getCode(): string | number; + getFormattedCode(): string | number; + getSeverity(): Severity; + isErrorSeverity(): boolean; + isWarningSeverity(): boolean; + getContent(): string; + getFile(): string; + getLine(): number; + getCharacter(): number; + } + + type Formatter = (message: NormalizedMessage, useColors: boolean) => string; + + interface Options { + tsconfig?: string; + tslint?: string | true; + watch?: string | string[]; + async?: boolean; + ignoreDiagnostics?: number[]; + ignoreLints?: string[]; + colors?: boolean; + logger?: Console; + formatter?: 'default' | 'codeframe' | Formatter; + formatterOptions?: { + highlightCode?: boolean + linesAbove?: number + linesBelow?: number + forceColor?: boolean + }; + silent?: boolean; + checkSyntacticErrors?: boolean; + memoryLimit?: number; + workers?: number; + vue?: boolean; + } +} + +declare class ForkTsCheckerWebpackPlugin extends Plugin { + constructor(options?: ForkTsCheckerWebpackPlugin.Options); +} + +export = ForkTsCheckerWebpackPlugin; diff --git a/types/fork-ts-checker-webpack-plugin/tsconfig.json b/types/fork-ts-checker-webpack-plugin/tsconfig.json new file mode 100644 index 0000000000..cfd6ee81db --- /dev/null +++ b/types/fork-ts-checker-webpack-plugin/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", + "fork-ts-checker-webpack-plugin-tests.ts" + ] +} diff --git a/types/fork-ts-checker-webpack-plugin/tslint.json b/types/fork-ts-checker-webpack-plugin/tslint.json new file mode 100644 index 0000000000..3db14f85ea --- /dev/null +++ b/types/fork-ts-checker-webpack-plugin/tslint.json @@ -0,0 +1 @@ +{ "extends": "dtslint/dt.json" } diff --git a/types/fs-extra-promise-es6/fs-extra-promise-es6-tests.ts b/types/fs-extra-promise-es6/fs-extra-promise-es6-tests.ts index 337dd1ca0f..bdff193912 100644 --- a/types/fs-extra-promise-es6/fs-extra-promise-es6-tests.ts +++ b/types/fs-extra-promise-es6/fs-extra-promise-es6-tests.ts @@ -14,7 +14,7 @@ declare const dir: string; declare const path: string; declare const data: any; declare const object: any; -let buffer: NodeBuffer; +let buffer: Buffer; declare const modeNum: number; declare const modeStr: string; declare const encoding: string; @@ -148,19 +148,19 @@ fs.futimes(fd, atime, mtime, errorCallback); fs.futimesSync(fd, atime, mtime); fs.fsync(fd, errorCallback); fs.fsyncSync(fd); -fs.write(fd, buffer, offset, length, position, (err: Error, written: number, buffer: NodeBuffer) => { +fs.write(fd, buffer, offset, length, position, (err: Error, written: number, buffer: Buffer) => { }); num = fs.writeSync(fd, buffer, offset, length, position); -fs.read(fd, buffer, offset, length, position, (err: Error, bytesRead: number, buffer: NodeBuffer) => { +fs.read(fd, buffer, offset, length, position, (err: Error, bytesRead: number, buffer: Buffer) => { }); num = fs.readSync(fd, buffer, offset, length, position); -fs.readFile(filename, (err: Error, data: NodeBuffer) => { +fs.readFile(filename, (err: Error, data: Buffer) => { }); fs.readFile(filename, encoding, (err: Error, data: string) => { }); fs.readFile(filename, openOpts, (err: Error, data: string) => { }); -fs.readFile(filename, (err: Error, data: NodeBuffer) => { +fs.readFile(filename, (err: Error, data: Buffer) => { }); buffer = fs.readFileSync(filename); str = fs.readFileSync(filename, encoding); diff --git a/types/fs-extra-promise-es6/index.d.ts b/types/fs-extra-promise-es6/index.d.ts index 0f52b5c02e..2b7dacd108 100644 --- a/types/fs-extra-promise-es6/index.d.ts +++ b/types/fs-extra-promise-es6/index.d.ts @@ -113,13 +113,13 @@ export function futimes(fd: number, atime: number, mtime: number, callback?: (er export function futimesSync(fd: number, atime: number, mtime: number): void; export function fsync(fd: number, callback?: (err: Error) => void): void; export function fsyncSync(fd: number): void; -export function write(fd: number, buffer: NodeBuffer, offset: number, length: number, position: number, callback?: (err: Error, written: number, buffer: NodeBuffer) => void): void; -export function writeSync(fd: number, buffer: NodeBuffer, offset: number, length: number, position: number): number; -export function read(fd: number, buffer: NodeBuffer, offset: number, length: number, position: number, callback?: (err: Error, bytesRead: number, buffer: NodeBuffer) => void): void; -export function readSync(fd: number, buffer: NodeBuffer, offset: number, length: number, position: number): number; +export function write(fd: number, buffer: Buffer, offset: number, length: number, position: number, callback?: (err: Error, written: number, buffer: Buffer) => void): void; +export function writeSync(fd: number, buffer: Buffer, offset: number, length: number, position: number): number; +export function read(fd: number, buffer: Buffer, offset: number, length: number, position: number, callback?: (err: Error, bytesRead: number, buffer: Buffer) => void): void; +export function readSync(fd: number, buffer: Buffer, offset: number, length: number, position: number): number; export function readFile(filename: string, options: OpenOptions | string, callback: (err: Error, data: string) => void): void; -export function readFile(filename: string, callback: (err: Error, data: NodeBuffer) => void): void; -export function readFileSync(filename: string): NodeBuffer; +export function readFile(filename: string, callback: (err: Error, data: Buffer) => void): void; +export function readFileSync(filename: string): Buffer; export function readFileSync(filename: string, options: OpenOptions | string): string; export function writeFile(filename: string, data: any, callback?: (err: Error) => void): void; export function writeFile(filename: string, data: any, options: OpenOptions | string, callback?: (err: Error) => void): void; @@ -201,10 +201,10 @@ export function openAsync(path: string, flags: string, mode?: string): Promise; export function futimesAsync(fd: number, atime: number, mtime: number): Promise; export function fsyncAsync(fd: number): Promise; -export function writeAsync(fd: number, buffer: NodeBuffer, offset: number, length: number, position: number): Promise<[number, NodeBuffer]>; -export function readAsync(fd: number, buffer: NodeBuffer, offset: number, length: number, position: number): Promise<[number, NodeBuffer]>; +export function writeAsync(fd: number, buffer: Buffer, offset: number, length: number, position: number): Promise<[number, Buffer]>; +export function readAsync(fd: number, buffer: Buffer, offset: number, length: number, position: number): Promise<[number, Buffer]>; export function readFileAsync(filename: string, options: OpenOptions | string): Promise; -export function readFileAsync(filename: string): Promise; +export function readFileAsync(filename: string): Promise; export function writeFileAsync(filename: string, data: any, options?: OpenOptions | string): Promise; export function appendFileAsync(filename: string, data: any, option?: OpenOptions | string): Promise; diff --git a/types/fs-extra-promise/fs-extra-promise-tests.ts b/types/fs-extra-promise/fs-extra-promise-tests.ts index f273d6efb6..61549a55ad 100644 --- a/types/fs-extra-promise/fs-extra-promise-tests.ts +++ b/types/fs-extra-promise/fs-extra-promise-tests.ts @@ -16,7 +16,7 @@ declare const data: any; declare const object: object; declare const buf: Buffer; let strOrBuf: string | Buffer; -let buffer: NodeBuffer; +let buffer: Buffer; declare const modeNum: number; declare const modeStr: string; declare const encoding: string; @@ -148,19 +148,19 @@ fs.futimes(fd, atime, mtime, errorCallback); fs.futimesSync(fd, atime, mtime); fs.fsync(fd, errorCallback); fs.fsyncSync(fd); -fs.write(fd, buffer, offset, length, position, (err: Error, written: number, buffer: NodeBuffer) => { +fs.write(fd, buffer, offset, length, position, (err: Error, written: number, buffer: Buffer) => { }); num = fs.writeSync(fd, buffer, offset, length, position); -fs.read(fd, buffer, offset, length, position, (err: Error, bytesRead: number, buffer: NodeBuffer) => { +fs.read(fd, buffer, offset, length, position, (err: Error, bytesRead: number, buffer: Buffer) => { }); num = fs.readSync(fd, buffer, offset, length, position); -fs.readFile(filename, (err: Error, data: NodeBuffer) => { +fs.readFile(filename, (err: Error, data: Buffer) => { }); fs.readFile(filename, encoding, (err: Error, data: string) => { }); fs.readFile(filename, openOpts, (err: NodeJS.ErrnoException, data: Buffer) => { }); -fs.readFile(filename, (err: Error, data: NodeBuffer) => { +fs.readFile(filename, (err: Error, data: Buffer) => { }); buffer = fs.readFileSync(filename); str = fs.readFileSync(filename, encoding); diff --git a/types/fs-extra-promise/index.d.ts b/types/fs-extra-promise/index.d.ts index de47c81a1e..b4ac5be133 100644 --- a/types/fs-extra-promise/index.d.ts +++ b/types/fs-extra-promise/index.d.ts @@ -65,10 +65,10 @@ export function openAsync(path: string, flags: string, mode?: string): Promise; export function futimesAsync(fd: number, atime: number, mtime: number): Promise; export function fsyncAsync(fd: number): Promise; -export function writeAsync(fd: number, buffer: NodeBuffer, offset: number, length: number, position: number): Promise<[number, NodeBuffer]>; -export function readAsync(fd: number, buffer: NodeBuffer, offset: number, length: number, position: number): Promise<[number, NodeBuffer]>; +export function writeAsync(fd: number, buffer: Buffer, offset: number, length: number, position: number): Promise<[number, Buffer]>; +export function readAsync(fd: number, buffer: Buffer, offset: number, length: number, position: number): Promise<[number, Buffer]>; export function readFileAsync(filename: string, options: string | ReadOptions): Promise; -export function readFileAsync(filename: string): Promise; +export function readFileAsync(filename: string): Promise; export function writeFileAsync(filename: string, data: any, options?: string | WriteOptions): Promise; export function appendFileAsync(filename: string, data: any, option?: string | WriteOptions): Promise; diff --git a/types/google-apps-script/google-apps-script.calendar.d.ts b/types/google-apps-script/google-apps-script.calendar.d.ts index 34a3d46a11..21770b6efb 100644 --- a/types/google-apps-script/google-apps-script.calendar.d.ts +++ b/types/google-apps-script/google-apps-script.calendar.d.ts @@ -1,6 +1,7 @@ -// Type definitions for Google Apps Script 2017-05-12 +// Type definitions for Google Apps Script 2018-05-03 // Project: https://developers.google.com/apps-script/ // Definitions by: motemen +// linlex // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped /// @@ -24,6 +25,7 @@ declare namespace GoogleAppsScript { deleteCalendar(): void; getColor(): string; getDescription(): string; + getEventById(iCalId: string): CalendarEvent; getEventSeriesById(iCalId: string): CalendarEventSeries; getEvents(startTime: Date, endTime: Date): CalendarEvent[]; getEvents(startTime: Date, endTime: Date, options: Object): CalendarEvent[]; diff --git a/types/google-apps-script/google-apps-script.spreadsheet.d.ts b/types/google-apps-script/google-apps-script.spreadsheet.d.ts index 7cd1cb8946..b656032a96 100644 --- a/types/google-apps-script/google-apps-script.spreadsheet.d.ts +++ b/types/google-apps-script/google-apps-script.spreadsheet.d.ts @@ -1,6 +1,7 @@ -// Type definitions for Google Apps Script 2017-05-12 +// Type definitions for Google Apps Script 2018-05-03 // Project: https://developers.google.com/apps-script/ // Definitions by: motemen +// linlex // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped /// @@ -11,7 +12,7 @@ declare namespace GoogleAppsScript { /** * This service allows scripts to create, access, and modify Google Sheets files. See also the guide to storing data in spreadsheets. - * + * * https://developers.google.com/apps-script/guides/sheets */ export module Spreadsheet { @@ -858,6 +859,7 @@ declare namespace GoogleAppsScript { autoResizeColumn(columnPosition: Integer): Sheet; clear(): Sheet; clear(options: Object): Sheet; + clearConditionalFormatRules(): void; clearContents(): Sheet; clearFormats(): Sheet; clearNotes(): Sheet; @@ -870,6 +872,7 @@ declare namespace GoogleAppsScript { getActiveRange(): Range; getCharts(): EmbeddedChart[]; getColumnWidth(columnPosition: Integer): Integer; + getConditionalFormatRules(): ConditionalFormatRule[]; getDataRange(): Range; getFrozenColumns(): Integer; getFrozenRows(): Integer; @@ -923,6 +926,8 @@ declare namespace GoogleAppsScript { setActiveSelection(range: Range): Range; setActiveSelection(a1Notation: string): Range; setColumnWidth(columnPosition: Integer, width: Integer): Sheet; + setConditionalFormatRules(rules: ReadonlyArray): void; + setCurrentCell(cell: Range): void; setFrozenColumns(columns: Integer): void; setFrozenRows(rows: Integer): void; setName(name: string): Sheet; @@ -1066,6 +1071,14 @@ declare namespace GoogleAppsScript { * An enumeration representing the data-validation criteria that can be set on a range. */ DataValidationCriteria: typeof DataValidationCriteria; + /** + * An enumeration representing the interpolation options for calculating a value to be used in a GradientCondition in a ConditionalFormatRule. + */ + InterpolationType: typeof InterpolationType; + /** + * An enumeration representing the boolean criteria that can be used in conditional format or filter. + */ + BooleanCriteria: typeof BooleanCriteria; /** * An enumeration representing the parts of a spreadsheet that can be protected from edits. */ @@ -1111,27 +1124,408 @@ declare namespace GoogleAppsScript { */ open(file: Drive.File): Spreadsheet; /** - * Opens the spreadsheet with the given ID. + * Opens the spreadsheet with the given ID. */ openById(id: string): Spreadsheet; /** - * Opens the spreadsheet with the given url. + * Opens the spreadsheet with the given url. */ openByUrl(url: string): Spreadsheet; /** - * Sets the active range for the application. + * Sets the active range for the application. */ setActiveRange(range: Range): Range; /** - * Sets the active sheet in a spreadsheet. + * Sets the active sheet in a spreadsheet. */ setActiveSheet(sheet: Sheet): Sheet; /** - * Sets the active spreadsheet. + * Sets the active spreadsheet. */ setActiveSpreadsheet(newActiveSpreadsheet: Spreadsheet): void; + /** + * Creates a builder for a conditional formatting rule. + */ + newConditionalFormatRule(): ConditionalFormatRuleBuilder; } + /** + * Access conditional formatting rules. To create a new rule, use SpreadsheetApp.newConditionalFormatRule() and + * ConditionalFormatRuleBuilder. You can use Sheet.setConditionalFormatRules(rules) to set the rules for a given + * sheet. + */ + export interface ConditionalFormatRule { + /** + * Returns a rule builder preset with this rule's settings. + */ + copy(): ConditionalFormatRuleBuilder; + + /** + * Retrieves the rule's BooleanCondition information if this rule uses boolean condition criteria. + */ + getBooleanCondition(): BooleanCondition; + + /** + * Retrieves the rule's GradientCondition information, if this rule uses gradient condition criteria. + */ + getGradientCondition(): GradientCondition; + + /** + * Retrieves the ranges to which this conditional format rule is applied. + */ + getRanges(): Range[]; + } + + /** + * Builder for conditional format rules. + */ + export interface ConditionalFormatRuleBuilder { + + /** + * Constructs a conditional format rule from the settings applied to the builder. + */ + build(): ConditionalFormatRule; + + /** + * Returns a rule builder preset with this rule's settings. + */ + copy(): ConditionalFormatRuleBuilder; + + /** + * Retrieves the rule's BooleanCondition information if this rule uses boolean condition criteria. + */ + getBooleanCondition(): BooleanCondition; + + /** + * Retrieves the rule's GradientCondition information, if this rule uses gradient condition criteria. + */ + getGradientCondition(): GradientCondition; + + /** + * Retrieves the ranges to which this conditional format rule is applied. + */ + getRanges(): Range[]; + + /** + * Sets the background color for the conditional format rule's format. + */ + setBackground(color: string): ConditionalFormatRuleBuilder; + + /** + * Sets text bolding for the conditional format rule's format. + */ + setBold(bold: boolean): ConditionalFormatRuleBuilder; + + /** + * Sets the font color for the conditional format rule's format. + */ + setFontColor(color: string): ConditionalFormatRuleBuilder; + + /** + * Clears the conditional format rule's gradient maxpoint value, and instead uses the maximum value in the rule's ranges. + */ + setGradientMaxpoint(color: string): ConditionalFormatRuleBuilder; + + /** + * Sets the conditional format rule's gradient maxpoint fields. + */ + setGradientMaxpointWithValue(color: string, type: InterpolationType, value: string): ConditionalFormatRuleBuilder; + + /** + * Sets the conditional format rule's gradient midpoint fields. + */ + setGradientMidpointWithValue(color: string, type: InterpolationType, value: string): ConditionalFormatRuleBuilder; + + /** + * Clears the conditional format rule's gradient minpoint value, and instead uses the minimum value in the rule's ranges. + */ + setGradientMinpoint(color: string): ConditionalFormatRuleBuilder; + + /** + * Sets the conditional format rule's gradient minpoint fields. + */ + setGradientMinpointWithValue(color: string, type: SpreadsheetApp.InterpolationType, value: string): ConditionalFormatRuleBuilder; + + /** + * Sets text italics for the conditional format rule's format. + */ + setItalic(italic: boolean): ConditionalFormatRuleBuilder; + + /** + * Sets one or more ranges to which this conditional format rule is applied. + */ + setRanges(ranges: ReadonlyArray): ConditionalFormatRuleBuilder; + + /** + * Sets text strikethrough for the conditional format rule's format. + */ + setStrikethrough(strikethrough: boolean): ConditionalFormatRuleBuilder; + + /** + * Sets text underlining for the conditional format rule's format. + */ + setUnderline(underline: boolean): ConditionalFormatRuleBuilder; + + /** + * Sets the conditional format rule to trigger when the cell is empty. + */ + whenCellEmpty(): ConditionalFormatRuleBuilder; + + /** + * Sets the conditional format rule to trigger when the cell is not empty. + */ + whenCellNotEmpty(): ConditionalFormatRuleBuilder; + + /** + * Sets the conditional format rule to trigger when a date is after the given value. + */ + whenDateAfter(date: Date): ConditionalFormatRuleBuilder; + + /** + * Sets the conditional format rule to trigger when a date is after the given relative date. + */ + whenDateAfter(date: Date): ConditionalFormatRuleBuilder; + + /** + * Sets the conditional format rule to trigger when a date is before the given date. + */ + whenDateBefore(date: Date): ConditionalFormatRuleBuilder; + + /** + * Sets the conditional format rule to trigger when a date is before the given relative date. + */ + whenDateBefore(date: Date): ConditionalFormatRuleBuilder; + + /** + * Sets the conditional format rule to trigger when a date is equal to the given date. + */ + whenDateEqualTo(date: Date): ConditionalFormatRuleBuilder; + + /** + * Sets the conditional format rule to trigger when a date is equal to the given relative date. + */ + whenDateEqualTo(date: Date): ConditionalFormatRuleBuilder; + + /** + * Sets the conditional format rule to trigger when that the given formula evaluates to true. + */ + whenFormulaSatisfied(formula: string): ConditionalFormatRuleBuilder; + + /** + * Sets the conditional format rule to trigger when a number falls between, or is either of, two specified values. + */ + whenNumberBetween(start: number, end: number): ConditionalFormatRuleBuilder; + + /** + * Sets the conditional format rule to trigger when a number is equal to the given value. + */ + whenNumberEqualTo(number: number): ConditionalFormatRuleBuilder; + + /** + * Sets the conditional format rule to trigger when a number is greater than the given value. + */ + whenNumberGreaterThan(number: number): ConditionalFormatRuleBuilder; + + /** + * Sets the conditional format rule to trigger when a number is greater than or equal to the given value. + */ + whenNumberGreaterThanOrEqualTo(number: number): ConditionalFormatRuleBuilder; + + /** + * Sets the conditional conditional format rule to trigger when a number less than the given value. + */ + whenNumberLessThan(number: number): ConditionalFormatRuleBuilder; + + /** + * Sets the conditional format rule to trigger when a number less than or equal to the given value. + */ + whenNumberLessThanOrEqualTo(number: number): ConditionalFormatRuleBuilder; + + /** + * Sets the conditional format rule to trigger when a number does not fall between, and is neither of, two specified values. + */ + whenNumberNotBetween(start: number, end: number): ConditionalFormatRuleBuilder; + + /** + * Sets the conditional format rule to trigger when a number is not equal to the given value. + */ + whenNumberNotEqualTo(number: number): ConditionalFormatRuleBuilder; + + /** + * Sets the conditional format rule to trigger when that the input contains the given value. + */ + whenTextContains(text: string): ConditionalFormatRuleBuilder; + + /** + * Sets the conditional format rule to trigger when that the input does not contain the given value. + */ + whenTextDoesNotContain(text: string): ConditionalFormatRuleBuilder; + + /** + * Sets the conditional format rule to trigger when that the input ends with the given value. + */ + whenTextEndsWith(text: string): ConditionalFormatRuleBuilder; + + /** + * Sets the conditional format rule to trigger when that the input is equal to the given value. + */ + whenTextEqualTo(text: string): ConditionalFormatRuleBuilder; + + /** + * Sets the conditional format rule to trigger when that the input starts with the given value. + */ + whenTextStartsWith(text: string): ConditionalFormatRuleBuilder; + + /** + * Sets the conditional format rule to criteria defined by BooleanCriteria values, typically taken from the criteria and arguments of an existing rule. + */ + withCriteria(criteria: BooleanCriteria, args: ReadonlyArray): ConditionalFormatRuleBuilder; + } + + /** + * An enumeration representing the boolean criteria that can be used in conditional format or filter. + */ + export enum BooleanCriteria { + /** + * The criteria is met when a cell is empty. + */ + CELL_EMPTY, + + /** + * The criteria is met when a cell is not empty. + */ + CELL_NOT_EMPTY, + + /** + * The criteria is met when a date is after the given value. + */ + DATE_AFTER, + + /** + * The criteria is met when a date is before the given value. + */ + DATE_BEFORE, + + /** + * The criteria is met when a date is equal to the given value. + */ + DATE_EQUAL_TO, + + /** + * The criteria is met when a date is after the relative date value. + */ + DATE_AFTER_RELATIVE, + + /** + * The criteria is met when a date is before the relative date value. + */ + DATE_BEFORE_RELATIVE, + + /** + * The criteria is met when a date is equal to the relative date value. + */ + DATE_EQUAL_TO_RELATIVE, + + /** + * The criteria is met when a number that is between the given values. + */ + NUMBER_BETWEEN, + + /** + * The criteria is met when a number that is equal to the given value. + */ + NUMBER_EQUAL_TO, + + /** + * The criteria is met when a number that is greater than the given value. + */ + NUMBER_GREATER_THAN, + + /** + * The criteria is met when a number that is greater than or equal to the given value. + */ + NUMBER_GREATER_THAN_OR_EQUAL_TO, + + /** + * The criteria is met when a number that is less than the given value. + */ + NUMBER_LESS_THAN, + + /** + * The criteria is met when a number that is less than or equal to the given value. + */ + NUMBER_LESS_THAN_OR_EQUAL_TO, + + /** + * The criteria is met when a number that is not between the given values. + */ + NUMBER_NOT_BETWEEN, + + /** + * The criteria is met when a number that is not equal to the given value. + */ + NUMBER_NOT_EQUAL_TO, + + /** + * The criteria is met when the input contains the given value. + */ + TEXT_CONTAINS, + + /** + * The criteria is met when the input does not contain the given value. + */ + TEXT_DOES_NOT_CONTAIN, + + /** + * The criteria is met when the input is equal to the given value. + */ + TEXT_EQUAL_TO, + + /** + * The criteria is met when the input begins with the given value. + */ + TEXT_STARTS_WITH, + + /** + * The criteria is met when the input ends with the given value. + */ + TEXT_ENDS_WITH, + + /** + * The criteria is met when the input makes the given formula evaluate to true. + */ + CUSTOM_FORMULA + } + + /** + * An enumeration representing the interpolation options for calculating a value to be used in a GradientCondition in a ConditionalFormatRule. + */ + export enum InterpolationType { + /** + * Use the number as as specific interpolation point for a gradient condition. + */ + NUMBER, + + /** + * Use the number as a percentage interpolation point for a gradient condition. + */ + PERCENT, + + /** + * Use the number as a percentile interpolation point for a gradient condition. + */ + PERCENTILE, + + /** + * Infer the minimum number as a specific interpolation point for a gradient condition. + */ + MIN, + + /** + * Infer the maximum number as a specific interpolation point for a gradient condition. + */ + MAX + } } } diff --git a/types/got/got-tests.ts b/types/got/got-tests.ts index 8c88cef3bc..1eb2d89aa8 100644 --- a/types/got/got-tests.ts +++ b/types/got/got-tests.ts @@ -1,10 +1,12 @@ import got = require('got'); import cookie = require('cookie'); import FormData = require('form-data'); +import Keyv = require('keyv'); import * as fs from 'fs'; import * as http from 'http'; import * as https from 'https'; import * as url from 'url'; +import QuickLRU = require('quick-lru'); let str: string; let buf: Buffer; @@ -242,7 +244,15 @@ got('todomvc', { }); got('todomvc', { - cache: new Map() + cache: new Map(), +}).then(res => res.fromCache); + +got('todomvc', { + cache: new Keyv(), +}).then(res => res.fromCache); + +got('todomvc', { + cache: new QuickLRU(), }).then(res => res.fromCache); got(new url.URL('http://todomvc.com')); diff --git a/types/got/index.d.ts b/types/got/index.d.ts index 47c281fb53..f786af118e 100644 --- a/types/got/index.d.ts +++ b/types/got/index.d.ts @@ -119,7 +119,7 @@ declare namespace got { followRedirect?: boolean; decompress?: boolean; useElectronNet?: boolean; - cache?: Map; + cache?: Cache; agent?: http.Agent | boolean | AgentOptions; throwHttpErrors?: boolean; } @@ -137,6 +137,12 @@ declare namespace got { type RetryFunction = (retry: number, error: any) => number; + interface Cache { + set(key: string, value: any, ttl?: number): any; + get(key: string): any; + delete(key: string): any; + } + interface Response extends http.IncomingMessage { body: B; url: string; diff --git a/types/hapi/index.d.ts b/types/hapi/index.d.ts index f0730e6f67..d8edc40685 100644 --- a/types/hapi/index.d.ts +++ b/types/hapi/index.d.ts @@ -544,7 +544,7 @@ export interface Request extends Podium { * @return void * [See docs](https://hapijs.com/api/17.0.1#-requestseturlurl-striptrailingslash) */ - setUrl(url: string | url.URL, stripTrailingSlash?: boolean): void; + setUrl(url: string | url.Url, stripTrailingSlash?: boolean): void; } /* + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/types/http-proxy/http-proxy-tests.ts b/types/http-proxy/http-proxy-tests.ts index 70ea803da6..1610befc7d 100644 --- a/types/http-proxy/http-proxy-tests.ts +++ b/types/http-proxy/http-proxy-tests.ts @@ -24,3 +24,11 @@ proxy.on("start", (req, res, target) => { http.createServer((req, res) => { proxy.web(req, res); }); + +const newProxy = HttpProxy.createProxyServer({ + target: { + host: 'localhost', + port: '9015' + }, + ws: true +}); diff --git a/types/http-proxy/index.d.ts b/types/http-proxy/index.d.ts index e9ef9a572d..fb7eb26abc 100644 --- a/types/http-proxy/index.d.ts +++ b/types/http-proxy/index.d.ts @@ -1,6 +1,8 @@ // Type definitions for node-http-proxy 1.16 // Project: https://github.com/nodejitsu/node-http-proxy -// Definitions by: Maxime LUCE , Florian Oellerich +// Definitions by: Maxime LUCE +// Florian Oellerich +// Daniel Schmidt // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped /// @@ -166,9 +168,9 @@ declare namespace Server { /** Buffer */ buffer?: stream.Stream; /** URL string to be parsed with the url module. */ - target?: string; + target?: ProxyTargetUrl; /** URL string to be parsed with the url module. */ - forward?: string; + forward?: ProxyTargetUrl; /** Object to be passed to http(s).request. */ agent?: any; /** Object to be passed to https.createServer(). */ diff --git a/types/idyll-ast/idyll-ast-tests.ts b/types/idyll-ast/idyll-ast-tests.ts new file mode 100644 index 0000000000..6b3eb7d651 --- /dev/null +++ b/types/idyll-ast/idyll-ast-tests.ts @@ -0,0 +1,99 @@ +import { AST, Property, TreeNode, Node } from "idyll-compiler"; + +import { + appendNode, + getNodesByName, + appendNodes, + prependNode, + prependNodes, + createNode, + getChildren, + walkNodes, + findNodes, + modifyChildren, + filterChildren, + filterNodes, + modifyNodesByName, + getProperty, + getProperties, + getPropertiesByType, + removeNodesByName, + setProperty, + setProperties, + removeProperty +} from "idyll-ast"; + +const ast: AST = [ + ["h2", [], []], + "world", + ["h1", [], ["child1", ["child2", [], []]]] +]; +const prop: Property = ["className", ["value", "hello"]]; + +// $ExpectType Node[] +appendNode(ast, "hello"); + +// $ExpectType Node[] +appendNode(getNodesByName(ast, "div"), "test"); + +// $ExpectType Node[] +appendNodes(ast, [["strong", [], ["div", ["pre", [], []]]], "test"]); + +// $ExpectType Node[] +prependNode(getNodesByName(ast, "div"), "test"); + +// $ExpectType Node[] +prependNodes(ast, [["strong", [], ["div", ["pre", [], []]]], "test"]); + +// $ExpectType TreeNode +createNode("div", { prop1: "prop1", prop2: ["expression", "x=2"] }, []); + +// $ExpectType Node[] +getChildren(ast[0]); + +// $ExpectType void +walkNodes(ast, (n: Node) => { + (n as TreeNode)[0] = "funky-name"; +}); + +// $ExpectType Node[] +findNodes(ast, n => n instanceof Array); + +// $ExpectType Node +modifyChildren(ast[0], (n: Node) => { + if (typeof n === "object") { + n[0] = "somename"; + } +}); +// $ExpectType Node[] +getNodesByName(ast, "h1"); + +// $ExpectType Node +filterChildren(ast[1], n => n === "world"); + +// $ExpectType Node[] +filterNodes(ast, n => (n instanceof Object ? n[0] === "h1" : false)); + +// $ExpectType Node[] +modifyNodesByName(ast, "h2", n => { + typeof n === "object" ? (n[1] = []) : undefined; +}); + +// $ExpectType [PropType, PropData] | null +getProperty(ast[1], "someProp"); +// $ExpectType [string, [PropType, PropData]] +getProperties(ast[1])[0]; +// $ExpectType [string, [PropType, PropData]][] +getPropertiesByType(["h1", [], []], "variable"); + +// $ExpectType Node[] +removeNodesByName(ast, "h1"); + +// $ExpectType Node +setProperty(ast[0], "prop", 9); + +// $ExpectType Node +setProperties(ast[1], { prop1: ["expression", "x"], prop2: 3 }); + +// $ExpectType Node +removeProperty(ast[0], "prop1"); diff --git a/types/idyll-ast/index.d.ts b/types/idyll-ast/index.d.ts new file mode 100644 index 0000000000..4a46320b82 --- /dev/null +++ b/types/idyll-ast/index.d.ts @@ -0,0 +1,137 @@ +// Type definitions for idyll-ast 1.3 +// Project: https://github.com/idyll-lang/idyll/tree/master/packages/idyll-ast +// Definitions by: Thanh Ngo +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.8 + +import { + AST, + Node, + TreeNode, + PropValue, + Property, + PropType +} from "idyll-compiler"; + +/** + * appends a single node to the AST + */ +export function appendNode(ast: AST, node: Node): AST; +/** + * appends multiple nodes to the AST + */ +export function appendNodes(ast: AST, nodes: AST): AST; +/** + * creates a node + */ +export function createNode( + name: string, + props: Record, + children: Node[] +): TreeNode; +/** + * gets all children of the node if there is any + * returns an empty array if there is no child + */ +export function getChildren(node: Node): Node[]; +/** + * executes func against every node + */ +export function walkNodes(ast: AST | null, func: (n: Node) => void): void; +/** + * deeply walks the AST tree and returns all the nodes that satisfies the + * given filter + */ +export function findNodes(ast: AST, filter: (n: Node) => boolean): Node[]; +/** + * visits each child of the node and modifies them using the modifier + */ +export function modifyChildren(node: Node, modifier: (n: Node) => void): Node; +/** + * get all nodes by name + */ +export function getNodesByName(ast: AST, name: string): Node[]; +/** + * filters and returns the same node where all children + * satisfy the given filter + */ +export function filterChildren( + node: Node, + filter: (child: Node) => boolean +): Node; + +/** + * filters every node in the AST and returns a new AST whose nodes + * satisfy the given filter + */ +export function filterNodes(ast: AST, filter: (node: Node) => boolean): AST; + +/** + * applies the modifier against node whose name is the given name + * Returns a new ast with the modified nodes + * + * Names are case-insensitive + */ +export function modifyNodesByName( + ast: AST, + name: string, + modifier: (node: Node) => void +): AST; + +/** + * gets the node's property value + * + * returns null if node is a string node + */ +export function getProperty(node: Node, key: string): PropValue | null; + +/** + * returns all node's properties + * + * returns empty array if node is a string node + */ +export function getProperties(node: Node): Property[]; + +/** + * returns all properties having the given property's type + */ +export function getPropertiesByType(node: Node, type: PropType): Property[]; + +export function prependNode(ast: AST, node: Node): AST; +export function prependNodes(ast: AST, nodes: Node[]): AST; + +/** + * returns a new AST with nodes having the given name + * + * Names are case-insensitive + */ +export function removeNodesByName(ast: AST, name: string): AST; + +/** + * sets the property of the node + * + * if value is an array, the property's type is assumed to be included in it + * otherwise, "value" will be the property's type, and parameter value + * is the property's value + * + */ +export function setProperty( + node: Node, + key: string, + value: PropValue | PropValue[1] +): Node; + +/** + * sets the properties of the node + * + * also see setProperty() + */ +export function setProperties( + node: Node, + properties: Record +): Node; + +/** + * removes the node's property which has the given key + */ +export function removeProperty(node: Node, key: string): Node; diff --git a/types/idyll-ast/tsconfig.json b/types/idyll-ast/tsconfig.json new file mode 100644 index 0000000000..1e026c3377 --- /dev/null +++ b/types/idyll-ast/tsconfig.json @@ -0,0 +1,16 @@ +{ + "compilerOptions": { + "module": "commonjs", + "lib": ["es6"], + "noImplicitAny": true, + "noImplicitThis": true, + "strictNullChecks": true, + "baseUrl": "../", + "typeRoots": ["../"], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true, + "strictFunctionTypes": true + }, + "files": ["index.d.ts", "idyll-ast-tests.ts"] +} diff --git a/types/idyll-ast/tslint.json b/types/idyll-ast/tslint.json new file mode 100644 index 0000000000..f93cf8562a --- /dev/null +++ b/types/idyll-ast/tslint.json @@ -0,0 +1,3 @@ +{ + "extends": "dtslint/dt.json" +} diff --git a/types/idyll-compiler/idyll-compiler-tests.ts b/types/idyll-compiler/idyll-compiler-tests.ts new file mode 100644 index 0000000000..c131a8600d --- /dev/null +++ b/types/idyll-compiler/idyll-compiler-tests.ts @@ -0,0 +1,13 @@ +import compile from "idyll-compiler"; + +// Dummy log +const log = (msg: string) => {}; + +// $ExpectType Node[] | Promise +compile("*italics*", { async: false }, () => log("window")); + +// $ExpectType Node[] | Promise +compile("Simple **idyll**", { async: false }); + +// $ExpectType Node[] | Promise +compile(`# Test`); diff --git a/types/idyll-compiler/index.d.ts b/types/idyll-compiler/index.d.ts new file mode 100644 index 0000000000..577dae2070 --- /dev/null +++ b/types/idyll-compiler/index.d.ts @@ -0,0 +1,55 @@ +// Type definitions for idyll-compiler 3.1 +// Project: https://github.com/idyll-lang/idyll/tree/master/packages/idyll-compiler +// Definitions by: Thanh Ngo +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.8 + +export type PropType = "variable" | "value" | "expression"; +export type PropData = string | number | boolean; +export type PropKey = string; +export type PropValue = [PropType, PropData]; +export type Property = [PropKey, PropValue]; +type __RecursiveNode = [string, Property[], T[]]; +export interface TreeNode extends __RecursiveNode {} +export type Node = TreeNode | string; +export type AST = Node[]; + +export type PostProcessor = + | ((ast: AST) => AST) + | ((ast: AST, callback: (err: any, value: AST) => void) => void); + +export interface Options { + spellcheck?: boolean; + + smartquotes?: boolean; + + /** + * If false and there is no postprocessors, compiler returns the AST synchronously + * Otherwise, a promise is returned + * + */ + async?: boolean; + + /** + * compiler plugins + * If provided, compiler always compiles asynchronously + */ + postProcessors?: PostProcessor[]; +} + +/** + * Compiles the given idyllMarkup and returns an AST either synchronously + * or asynchronously. + * + * If postProcessors are provided or options.async is set to true: + * compiler returns a promise + * Otherwise, compile returns the AST synchronously + * + */ +declare function compiler( + input: string, + options?: Options, + callback?: () => void +): Promise | AST; + +export default compiler; diff --git a/types/idyll-compiler/tsconfig.json b/types/idyll-compiler/tsconfig.json new file mode 100644 index 0000000000..bb08224d15 --- /dev/null +++ b/types/idyll-compiler/tsconfig.json @@ -0,0 +1,16 @@ +{ + "compilerOptions": { + "module": "commonjs", + "lib": ["es6"], + "noImplicitAny": true, + "noImplicitThis": true, + "strictNullChecks": true, + "baseUrl": "../", + "typeRoots": ["../"], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true, + "strictFunctionTypes": true + }, + "files": ["index.d.ts", "idyll-compiler-tests.ts"] +} diff --git a/types/idyll-compiler/tslint.json b/types/idyll-compiler/tslint.json new file mode 100644 index 0000000000..f93cf8562a --- /dev/null +++ b/types/idyll-compiler/tslint.json @@ -0,0 +1,3 @@ +{ + "extends": "dtslint/dt.json" +} diff --git a/types/idyll-document/idyll-document-tests.ts b/types/idyll-document/idyll-document-tests.ts new file mode 100644 index 0000000000..880e017013 --- /dev/null +++ b/types/idyll-document/idyll-document-tests.ts @@ -0,0 +1,5 @@ +import IdyllDocument, { IdyllDocumentProps } from "idyll-document"; +import { createElement } from "react"; + +// $ExpectType ReactElement +createElement(IdyllDocument); diff --git a/types/idyll-document/index.d.ts b/types/idyll-document/index.d.ts new file mode 100644 index 0000000000..47ba1f7845 --- /dev/null +++ b/types/idyll-document/index.d.ts @@ -0,0 +1,62 @@ +// Type definitions for idyll-document 2.9 +// Project: https://github.com/idyll-lang/idyll/tree/master/packages/idyll-document +// Definitions by: Thanh Ngo +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.8 + +import { PureComponent, ReactType } from "react"; +import { Options as CompilerOptions, AST } from "idyll-compiler"; + +export interface IdyllDocumentProps { + /** + * Components to be rendered with + */ + components: any; + /** + * the AST to be rendered on the page + * If provided, this will be used insteaed of + * the markup + */ + ast?: AST; + /** + * The Idyll markup to be compiled into AST + */ + markup?: string; + /** + * Initial data set + */ + datasets?: object; + + /** + * The theme for idyll document + * Will correspond to one theme in idyll-theme package + */ + theme?: string; + /** + * The layout for idyll document + * Will correspond to one one layout in idyll-layouts package + */ + layout?: string; + /** + * Callback function if error happens during compilation + */ + onError?: (err: Error) => void; + /** + * The React component rendered when an error occurs + */ + errorComponent?: ReactType<{ + className?: string; + children: Error["message"] | null; + }>; + /** + * Compiler option for Idyll compiler when compiling markup + */ + compilerOptions?: CompilerOptions; + + context?: (context: any) => void; + initialState?: any; +} + +declare class IdyllDocument extends PureComponent {} + +export default IdyllDocument; diff --git a/types/idyll-document/tsconfig.json b/types/idyll-document/tsconfig.json new file mode 100644 index 0000000000..6e3da4c990 --- /dev/null +++ b/types/idyll-document/tsconfig.json @@ -0,0 +1,16 @@ +{ + "compilerOptions": { + "module": "commonjs", + "lib": ["es6"], + "noImplicitAny": true, + "noImplicitThis": true, + "strictNullChecks": true, + "baseUrl": "../", + "typeRoots": ["../"], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true, + "strictFunctionTypes": true + }, + "files": ["index.d.ts", "idyll-document-tests.ts"] +} diff --git a/types/idyll-document/tslint.json b/types/idyll-document/tslint.json new file mode 100644 index 0000000000..f93cf8562a --- /dev/null +++ b/types/idyll-document/tslint.json @@ -0,0 +1,3 @@ +{ + "extends": "dtslint/dt.json" +} diff --git a/types/idyll/idyll-tests.ts b/types/idyll/idyll-tests.ts new file mode 100644 index 0000000000..3f4b90c18c --- /dev/null +++ b/types/idyll/idyll-tests.ts @@ -0,0 +1,7 @@ +import idyll = require("idyll"); + +// $ExpectType IdyllInstance +idyll({ + watch: true, + datasets: "." +}); diff --git a/types/idyll/index.d.ts b/types/idyll/index.d.ts new file mode 100644 index 0000000000..a2f1846a7a --- /dev/null +++ b/types/idyll/index.d.ts @@ -0,0 +1,130 @@ +// Type definitions for idyll 2.10 +// Project: https://github.com/idyll-lang/idyll/tree/master/packages/idyll-cli +// Definitions by: Thanh Ngo +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.8 + +import { EventEmitter } from "events"; +import { Options as CompilerOptions } from "idyll-compiler"; + +interface Options { + /** + * Monitor input files and rebuild on changes + */ + watch?: boolean; + /** + * The datasets directory + */ + datasets?: string; + /** + * Whether to minify output build + */ + minify?: boolean; + /** + * + * Pre-render HTML as part of the build + */ + ssr?: boolean; + /** + * The components directory + */ + components?: boolean; + /** + * The default component directory + * This corresponds to where the idyll-components package stays + */ + defaultComponents?: boolean; + /** + * The layout defined in idyll-layouts package + */ + layout?: string; + /** + * The theme defined in idyll-theme package + */ + theme?: string; + /** + * The output directory for compiled documents + */ + output?: string; + /** + * Custom port to bind the local server to. + */ + port?: number; + /** + * Temporary directory used by idyll + */ + temp?: string; + /** + * path to HTML template + * + */ + template?: string; + + /** + * Custom CSS file to include in output + */ + css?: string; + /** + * Custom browserify transforms to apply. + */ + transform?: string[]; + /** + * Compiler options + */ + compiler?: CompilerOptions; + /** + * the idyll file to be compiled into + */ + inputFile?: string; + + /** + * used internally by IdyllInstance + */ + inputConfig?: { + components: any; + transform: any[]; + compiler: CompilerOptions; + }; +} + +type PredefinedFile = + | "APP_PATH" + | "CSS_INPUT_FILE" + | "DATA_DIR" + | "HTML_TEMPLATE_FILE" + | "IDYLL_INPUT_FILE" + | "INPUT_DIR" + | "PACKAGE_FILE" + | "OUTPUT_DIR" + | "TMP_DIR" + | "CSS_OUTPUT_FILE" + | "HTML_OUTPUT_FILE" + | "JS_OUTPUT_FILE"; + +type ComponentFiles = "COMPONENT_DIRS" | "DEFAULT_COMPONENT_DIRS"; + +type Paths = Record & Record; + +declare class IdyllInstance extends EventEmitter { + /** + * Returns internal paths used by idyll-cli + */ + getPaths(): Paths; + /** + * Returns idyll compiling's options + */ + getOptions(): Options; + /** + * + * if indexIdyllMarkup is provided, compiles it + * + * Otherwise, compiles and optionally watches + * the idyll file at IOptions.inputFile + * + */ + build(indexIdyllMarkup?: string | null): this; +} + +declare function idyll(options: Options, callback?: () => void): IdyllInstance; + +export = idyll; diff --git a/types/idyll/tsconfig.json b/types/idyll/tsconfig.json new file mode 100644 index 0000000000..6e24200367 --- /dev/null +++ b/types/idyll/tsconfig.json @@ -0,0 +1,16 @@ +{ + "compilerOptions": { + "module": "commonjs", + "lib": ["es6"], + "noImplicitAny": true, + "noImplicitThis": true, + "strictNullChecks": true, + "baseUrl": "../", + "typeRoots": ["../"], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true, + "strictFunctionTypes": true + }, + "files": ["index.d.ts", "idyll-tests.ts"] +} diff --git a/types/idyll/tslint.json b/types/idyll/tslint.json new file mode 100644 index 0000000000..f93cf8562a --- /dev/null +++ b/types/idyll/tslint.json @@ -0,0 +1,3 @@ +{ + "extends": "dtslint/dt.json" +} diff --git a/types/intercom-client/index.d.ts b/types/intercom-client/index.d.ts new file mode 100644 index 0000000000..b68dc87e71 --- /dev/null +++ b/types/intercom-client/index.d.ts @@ -0,0 +1,13 @@ +// Type definitions for intercom-client 2.9 +// Project: https://github.com/intercom/intercom-node +// Definitions by: Jinesh Shah +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +export interface IdentityVerificationOptions { + secretKey: string; + identifier: string; +} + +export const IdentityVerification: { + userHash(opts: IdentityVerificationOptions): string; +}; diff --git a/types/intercom-client/intercom-client-tests.ts b/types/intercom-client/intercom-client-tests.ts new file mode 100644 index 0000000000..e74dab4f53 --- /dev/null +++ b/types/intercom-client/intercom-client-tests.ts @@ -0,0 +1,3 @@ +import * as intercom from "intercom-client"; + +intercom.IdentityVerification.userHash({ secretKey: "", identifier: "" }); // $ExpectType string diff --git a/types/intercom-client/tsconfig.json b/types/intercom-client/tsconfig.json new file mode 100644 index 0000000000..a74d113775 --- /dev/null +++ b/types/intercom-client/tsconfig.json @@ -0,0 +1,16 @@ +{ + "compilerOptions": { + "module": "commonjs", + "lib": ["es6"], + "noImplicitAny": true, + "noImplicitThis": true, + "strictNullChecks": true, + "baseUrl": "../", + "typeRoots": ["../"], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true, + "strictFunctionTypes": true + }, + "files": ["index.d.ts", "intercom-client-tests.ts"] +} diff --git a/types/intercom-client/tslint.json b/types/intercom-client/tslint.json new file mode 100644 index 0000000000..3db14f85ea --- /dev/null +++ b/types/intercom-client/tslint.json @@ -0,0 +1 @@ +{ "extends": "dtslint/dt.json" } diff --git a/types/ip/index.d.ts b/types/ip/index.d.ts index 602a71eed9..c51a8d37f5 100644 --- a/types/ip/index.d.ts +++ b/types/ip/index.d.ts @@ -3,7 +3,7 @@ // Definitions by: Peter Harris // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -interface NodeBuffer { } +/// interface SubnetInfo { networkAddress: string; @@ -26,16 +26,16 @@ declare module "ip" { /** * Convert an IP string into a buffer. **/ - export function toBuffer(ip: string, buffer?: number, offset?: number): NodeBuffer; + export function toBuffer(ip: string, buffer?: number, offset?: number): Buffer; /** * Convert an IP buffer into a string. **/ - export function toString(ip: NodeBuffer, offset?: number, length?: number): string; + export function toString(ip: Buffer, offset?: number, length?: number): string; /** * Get the subnet mask from a CIDR prefix length. - * + * * @param family The IP family is infered from the prefixLength, but can be explicity specified as either "ipv4" or "ipv6". **/ export function fromPrefixLen(prefixLength: number, family?:string): string; @@ -79,15 +79,15 @@ declare module "ip" { * Check whether an IP is a IPv4 address. **/ export function isV4Format(ip: string): boolean; - + /** * Check whether an IP is a IPv6 address. **/ export function isV6Format(ip: string): boolean; - + /** * Get the loopback address for an IP family. - * + * * @param family The family can be either "ipv4" or "ipv6". Default: "ipv4". **/ export function loopback(family?: string): string; @@ -95,7 +95,7 @@ declare module "ip" { /** * Get the address for the network interface on the current system with the specified 'name'. * If no interface name is specified, the first IPv4 address or loopback address is returned. - * + * * @param name The name can be any named interface, or 'public' or 'private'. * @param family The family can be either "ipv4" or "ipv6". Default: "ipv4". **/ diff --git a/types/jasmine/index.d.ts b/types/jasmine/index.d.ts index f3e0407bab..cd1d5de31e 100644 --- a/types/jasmine/index.d.ts +++ b/types/jasmine/index.d.ts @@ -130,6 +130,7 @@ declare function waits(timeout?: number): void; declare namespace jasmine { type Expected = T | ObjectContaining | Any | Spy; + type SpyObjMethodNames = string[] | {[methodName: string]: any}; var clock: () => Clock; @@ -144,12 +145,11 @@ declare namespace jasmine { function objectContaining(sample: Partial): ObjectContaining; function createSpy(name?: string, originalFn?: Function): Spy; - function createSpyObj(baseName: string, methodNames: any[] | {[methodName: string]: any}): any; - function createSpyObj(baseName: string, methodNames: any[] | {[methodName: string]: any}): SpyObj; + function createSpyObj(baseName: string, methodNames: SpyObjMethodNames): any; + function createSpyObj(baseName: string, methodNames: SpyObjMethodNames): SpyObj; - function createSpyObj(baseName: string, methodNames: any): any; - function createSpyObj(methodNames: any[]): any; - function createSpyObj(methodNames: any): any; + function createSpyObj(methodNames: SpyObjMethodNames): any; + function createSpyObj(methodNames: SpyObjMethodNames): SpyObj; function pp(value: any): string; diff --git a/types/jasmine/jasmine-tests.ts b/types/jasmine/jasmine-tests.ts index b54269aa61..54e97ed73e 100644 --- a/types/jasmine/jasmine-tests.ts +++ b/types/jasmine/jasmine-tests.ts @@ -1109,7 +1109,17 @@ describe("createSpyObj", function () { expect(spyObj.method2.and.identity()).toEqual('BaseName.method2'); }); - it("should allow you to omit the baseName", function () { + it("should allow you to omit the baseName and takes only an object", function () { + var spyObj = jasmine.createSpyObj({ 'method1': 42, 'method2': 'special sauce' }); + + expect(spyObj.method1()).toEqual(42); + expect(spyObj.method1.and.identity()).toEqual('unknown.method1'); + + expect(spyObj.method2()).toEqual('special sauce'); + expect(spyObj.method2.and.identity()).toEqual('unknown.method2'); + }); + + it("should allow you to omit the baseName and takes only a list of methods", function () { var spyObj = jasmine.createSpyObj(['method1', 'method2']); expect(spyObj).toEqual({ method1: jasmine.any(Function), method2: jasmine.any(Function) }); @@ -1117,12 +1127,6 @@ describe("createSpyObj", function () { expect(spyObj.method2.and.identity()).toEqual('unknown.method2'); }); - it("should throw if you do not pass an array or object argument", function () { - expect(function () { - jasmine.createSpyObj('BaseName'); - }).toThrow("createSpyObj requires a non-empty array or object of method names to create spies for"); - }); - it("should throw if you pass an empty array argument", function () { expect(function () { jasmine.createSpyObj('BaseName', []); diff --git a/types/jquery-focus-exit/index.d.ts b/types/jquery-focus-exit/index.d.ts new file mode 100644 index 0000000000..8787136a4e --- /dev/null +++ b/types/jquery-focus-exit/index.d.ts @@ -0,0 +1,20 @@ +// Type definitions for JQuery Focus Exit 1.0 +// Project: https://github.com/makeup-jquery/jquery-focus-exit +// Definitions by: Anderson Friaça +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.3 + +/// + +export interface FocusElements { + lostFocus?: HTMLElement; + gainedFocus: HTMLElement; +} + +declare global { + interface JQuery { + focusExit(options?: { debug: boolean }): JQuery; + on(event: 'focusExit', handler: ((event: JQuery.Event, data: FocusElements) => void)): JQuery; + one(event: 'focusin', handler: ((event: JQuery.Event) => void)): JQuery; + } +} diff --git a/types/jquery-focus-exit/jquery-focus-exit-tests.ts b/types/jquery-focus-exit/jquery-focus-exit-tests.ts new file mode 100644 index 0000000000..497e44dd97 --- /dev/null +++ b/types/jquery-focus-exit/jquery-focus-exit-tests.ts @@ -0,0 +1,8 @@ +$('.test').one('focusin', e => { + $(e.currentTarget).addClass('focusin'); +}); + +$('.test').focusExit({debug: true}).on('focusExit', (e, data) => { + console.log(e, data); + $(e.currentTarget).removeClass('focusin'); +}); diff --git a/types/jquery-focus-exit/tsconfig.json b/types/jquery-focus-exit/tsconfig.json new file mode 100644 index 0000000000..b9448645b8 --- /dev/null +++ b/types/jquery-focus-exit/tsconfig.json @@ -0,0 +1,25 @@ +{ + "compilerOptions": { + "module": "commonjs", + "lib": [ + "es6", + "dom" + ], + "noImplicitAny": true, + "noImplicitThis": true, + "strictNullChecks": true, + "strictFunctionTypes": true, + "baseUrl": "../", + "typeRoots": [ + "../" + ], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true, + "esModuleInterop": true + }, + "files": [ + "index.d.ts", + "jquery-focus-exit-tests.ts" + ] +} \ No newline at end of file diff --git a/types/jquery-focus-exit/tslint.json b/types/jquery-focus-exit/tslint.json new file mode 100644 index 0000000000..d04fe2e1fa --- /dev/null +++ b/types/jquery-focus-exit/tslint.json @@ -0,0 +1 @@ +{"extends": "dtslint/dt.json"} \ No newline at end of file diff --git a/types/jquery/jquery-tests.ts b/types/jquery/jquery-tests.ts index 6773f923ef..5d6aaf0680 100644 --- a/types/jquery/jquery-tests.ts +++ b/types/jquery/jquery-tests.ts @@ -655,9 +655,9 @@ function JQueryStatic() { } function isNumeric() { - function type_guard(obj: boolean) { + function type_guard(obj: boolean | number) { if ($.isNumeric(obj)) { - // $ExpectType (true & number) | (false & number) + // $ExpectType number obj; } else { // $ExpectType boolean diff --git a/types/jquery/test/longdesc-tests.ts b/types/jquery/test/longdesc-tests.ts index 23ff500d24..3405bb83b5 100644 --- a/types/jquery/test/longdesc-tests.ts +++ b/types/jquery/test/longdesc-tests.ts @@ -1437,7 +1437,7 @@ function longdesc() { $.getJSON('ajax/test.json', function(data) { var items: string[] = []; $.each(data, function(key, val) { - items.push('
  • ' + val + '
  • '); + items.push('
  • ' + val + '
  • '); }); $('
      ', { diff --git a/types/jwplayer/index.d.ts b/types/jwplayer/index.d.ts index 58c656956c..aee22c16f1 100644 --- a/types/jwplayer/index.d.ts +++ b/types/jwplayer/index.d.ts @@ -261,49 +261,181 @@ interface JWPlayer { load(playlist: any[]): void; load(playlist: string): void; on(event: 'adClick', callback: EventCallback): void; + once(event: 'adClick', callback: EventCallback): void; + off(event: 'adClick'): void; + trigger(event: 'adClick', args: AdProgressParam): void; on(event: 'adCompanions', callback: EventCallback): void; + once(event: 'adCompanions', callback: EventCallback): void; + off(event: 'adCompanions'): void; + trigger(event: 'adCompanions', args: AdCompanionsParam): void; on(event: 'adComplete', callback: EventCallback): void; + once(event: 'adComplete', callback: EventCallback): void; + off(event: 'adComplete'): void; + trigger(event: 'adComplete', args: AdProgressParam): void; on(event: 'adSkipped', callback: EventCallback): void; + once(event: 'adSkipped', callback: EventCallback): void; + off(event: 'adSkipped'): void; + trigger(event: 'adSkipped', args: AdProgressParam): void; on(event: 'adError', callback: EventCallback): void; + once(event: 'adError', callback: EventCallback): void; + off(event: 'adError'): void; + trigger(event: 'adError', args: AdErrorParam): void; on(event: 'adBlock', callback: () => void): void; + once(event: 'adBlock', callback: () => void): void; + off(event: 'adBlock'): void; + trigger(event: 'adBlock'): void; on(event: 'adRequest', callback: EventCallback): void; + once(event: 'adRequest', callback: EventCallback): void; + off(event: 'adRequest'): void; + trigger(event: 'adRequest', args: AdRequestParam): void; on(event: 'adStarted', callback: EventCallback): void; + once(event: 'adStarted', callback: EventCallback): void; + off(event: 'adStarted'): void; + trigger(event: 'adStarted', args: AdStartedParam): void; on(event: 'adImpression', callback: EventCallback): void; + once(event: 'adImpression', callback: EventCallback): void; + off(event: 'adImpression'): void; + trigger(event: 'adImpression', args: AdImpressionParam): void; on(event: 'adPlay', callback: EventCallback): void; + once(event: 'adPlay', callback: EventCallback): void; + off(event: 'adPlay'): void; + trigger(event: 'adPlay', args: AdPlayParam): void; on(event: 'adPause', callback: EventCallback): void; + once(event: 'adPause', callback: EventCallback): void; + off(event: 'adPause'): void; + trigger(event: 'adPause', args: AdPlayParam): void; on(event: 'adTime', callback: EventCallback): void; + once(event: 'adTime', callback: EventCallback): void; + off(event: 'adTime'): void; + trigger(event: 'adTime', args: AdTimeParam): void; on(event: 'meta', callback: EventCallback): void; + once(event: 'meta', callback: EventCallback): void; + off(event: 'meta'): void; + trigger(event: 'meta', args: MetadataParam): void; on(event: 'audioTracks', callback: EventCallback): void; + once(event: 'audioTracks', callback: EventCallback): void; + off(event: 'audioTracks'): void; + trigger(event: 'audioTracks', args: AudioTracksParam): void; on(event: 'audioTrackChanged', callback: EventCallback): void; + once(event: 'audioTrackChanged', callback: EventCallback): void; + off(event: 'audioTrackChanged'): void; + trigger(event: 'audioTrackChanged', args: AudioTrackChangedParam): void; on(event: 'beforeComplete', callback: () => void): void; + once(event: 'beforeComplete', callback: () => void): void; + off(event: 'beforeComplete'): void; + trigger(event: 'beforeComplete'): void; on(event: 'complete', callback: () => void): void; + once(event: 'complete', callback: () => void): void; + off(event: 'complete'): void; + trigger(event: 'complete'): void; on(event: 'firstFrame', callback: EventCallback): void; + once(event: 'firstFrame', callback: EventCallback): void; + off(event: 'firstFrame'): void; + trigger(event: 'firstFrame', args: FirstFrameParam): void; on(event: 'beforePlay', callback: () => void): void; + once(event: 'beforePlay', callback: () => void): void; + off(event: 'beforePlay'): void; + trigger(event: 'beforePlay'): void; on(event: 'buffer', callback: EventCallback): void; + once(event: 'buffer', callback: EventCallback): void; + off(event: 'buffer'): void; + trigger(event: 'buffer', args: BufferParam): void; on(event: 'bufferChange', callback: EventCallback): void; + once(event: 'bufferChange', callback: EventCallback): void; + off(event: 'bufferChange'): void; + trigger(event: 'bufferChange', args: BufferChangeParam): void; on(event: 'captionsChanged', callback: EventCallback): void; + once(event: 'captionsChanged', callback: EventCallback): void; + off(event: 'captionsChanged'): void; + trigger(event: 'captionsChanged', args: CaptionsChangedParam): void; on(event: 'captionsList', callback: EventCallback): void; + once(event: 'captionsList', callback: EventCallback): void; + off(event: 'captionsList'): void; + trigger(event: 'captionsList', args: CaptionsListParam): void; on(event: 'controls', callback: EventCallback): void; + once(event: 'controls', callback: EventCallback): void; + off(event: 'controls'): void; + trigger(event: 'controls', args: ControlsParam): void; on(event: 'displayClick', callback: () => void): void; + once(event: 'displayClick', callback: () => void): void; + off(event: 'displayClick'): void; + trigger(event: 'displayClick'): void; on(event: 'error', callback: EventCallback): void; + once(event: 'error', callback: EventCallback): void; + off(event: 'error'): void; + trigger(event: 'error', args: ErrorParam): void; on(event: 'fullscreen', callback: EventCallback): void; + once(event: 'fullscreen', callback: EventCallback): void; + off(event: 'fullscreen'): void; + trigger(event: 'fullscreen', args: FullscreenParam): void; on(event: 'idle', callback: EventCallback): void; + once(event: 'idle', callback: EventCallback): void; + off(event: 'idle'): void; + trigger(event: 'idle', args: IdleParam): void; on(event: 'levelsChanged', callback: EventCallback): void; + once(event: 'levelsChanged', callback: EventCallback): void; + off(event: 'levelsChanged'): void; + trigger(event: 'levelsChanged', args: LevelsChangedParam): void; on(event: 'mute', callback: EventCallback): void; + once(event: 'mute', callback: EventCallback): void; + off(event: 'mute'): void; + trigger(event: 'mute', args: MuteParam): void; on(event: 'volume', callback: EventCallback): void; + once(event: 'volume', callback: EventCallback): void; + off(event: 'volume'): void; + trigger(event: 'volume', args: VolumeParam): void; on(event: 'pause', callback: EventCallback): void; + once(event: 'pause', callback: EventCallback): void; + off(event: 'pause'): void; + trigger(event: 'pause', args: PlayParam): void; on(event: 'play', callback: EventCallback): void; + once(event: 'play', callback: EventCallback): void; + off(event: 'play'): void; + trigger(event: 'play', args: PlayParam): void; on(event: 'playlist', callback: EventCallback): void; + once(event: 'playlist', callback: EventCallback): void; + off(event: 'playlist'): void; + trigger(event: 'playlist', args: PlaylistParam): void; on(event: 'playlistItem', callback: EventCallback): void; + once(event: 'playlistItem', callback: EventCallback): void; + off(event: 'playlistItem'): void; + trigger(event: 'playlistItem', args: PlaylistItemParam): void; on(event: 'playlistComplete', callback: () => void): void; + once(event: 'playlistComplete', callback: () => void): void; + off(event: 'playlistComplete'): void; + trigger(event: 'playlistComplete'): void; on(event: 'ready', callback: EventCallback): void; + once(event: 'ready', callback: EventCallback): void; + off(event: 'ready'): void; + trigger(event: 'ready'): void; on(event: 'resize', callback: EventCallback): void; + once(event: 'resize', callback: EventCallback): void; + off(event: 'resize'): void; + trigger(event: 'resize', args: ResizeParam): void; on(event: 'visualQuality', callback: EventCallback): void; + once(event: 'visualQuality', callback: EventCallback): void; + off(event: 'visualQuality'): void; + trigger(event: 'visualQuality', args: VisualQualityParam): void; on(event: 'levels', callback: EventCallback): void; + once(event: 'levels', callback: EventCallback): void; + off(event: 'levels'): void; + trigger(event: 'levels', args: LevelsParam): void; on(event: 'seek', callback: EventCallback): void; + once(event: 'seek', callback: EventCallback): void; + off(event: 'seek'): void; + trigger(event: 'seek', args: SeekParam): void; on(event: 'setupError', callback: EventCallback): void; + once(event: 'setupError', callback: EventCallback): void; + off(event: 'setupError'): void; + trigger(event: 'setupError', args: ErrorParam): void; on(event: 'remove', callback: () => void): void; + once(event: 'remove', callback: () => void): void; + off(event: 'remove'): void; + trigger(event: 'remove'): void; on(event: 'time', callback: EventCallback): void; + once(event: 'time', callback: EventCallback): void; + off(event: 'time'): void; + trigger(event: 'time', args: TimeParam): void; pause(state?: boolean): void; play(state?: boolean): void; playAd(tag: string): void; diff --git a/types/keyv/index.d.ts b/types/keyv/index.d.ts index 9d0e2c6404..69e644c2d9 100644 --- a/types/keyv/index.d.ts +++ b/types/keyv/index.d.ts @@ -3,9 +3,7 @@ // Definitions by: AryloYeung // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped // TypeScript Version: 2.1 - /// - interface KeyvOptions { /** Namespace for the current instance. */ namespace?: string; @@ -35,6 +33,9 @@ declare class Keyv extends NodeJS.EventEmitter { * @param opts The options object is also passed through to the storage adapter. Check your storage adapter docs for any extra options. */ constructor(uri?: string, opts?: KeyvOptions); + /** Returns the namespace of a key */ + _getKeyPrefix(key: string): string; + /** Returns the value. */ get(key: string): Promise; /** @@ -42,7 +43,7 @@ declare class Keyv extends NodeJS.EventEmitter { * * By default keys are persistent. You can set an expiry TTL in milliseconds. */ - set(key: string, value: any, ttl?: number): Promise; + set(key: string, value: any, ttl?: number): (Promise | undefined); /** * Deletes an entry. * diff --git a/types/knockout/index.d.ts b/types/knockout/index.d.ts index d4031b2337..5076a05231 100644 --- a/types/knockout/index.d.ts +++ b/types/knockout/index.d.ts @@ -1,10 +1,10 @@ // Type definitions for Knockout v3.4.0 // Project: http://knockoutjs.com -// Definitions by: Boris Yankov , -// Igor Oleinikov , -// Clément Bourgeois , -// Matt Brooks , -// Benjamin Eckardt , +// Definitions by: Boris Yankov , +// Igor Oleinikov , +// Clément Bourgeois , +// Matt Brooks , +// Benjamin Eckardt , // Mathias Lorenzen // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped // TypeScript Version: 2.3 @@ -150,10 +150,10 @@ interface KnockoutAllBindingsAccessor { has(name: string): boolean; } -interface KnockoutBindingHandler { +interface KnockoutBindingHandler { after?: Array; - init?: (element: any, valueAccessor: () => any, allBindingsAccessor: KnockoutAllBindingsAccessor, viewModel: any, bindingContext: KnockoutBindingContext) => void | { controlsDescendantBindings: boolean; }; - update?: (element: any, valueAccessor: () => any, allBindingsAccessor: KnockoutAllBindingsAccessor, viewModel: any, bindingContext: KnockoutBindingContext) => void; + init?: (element: E, valueAccessor: () => V, allBindingsAccessor: KnockoutAllBindingsAccessor, viewModel: VM, bindingContext: KnockoutBindingContext) => void | { controlsDescendantBindings: boolean; }; + update?: (element: E, valueAccessor: () => V, allBindingsAccessor: KnockoutAllBindingsAccessor, viewModel: VM, bindingContext: KnockoutBindingContext) => void; options?: any; preprocess?: (value: string, name: string, addBindingCallback?: (name: string, value: string) => void) => string; [s: string]: any; @@ -440,7 +440,7 @@ interface KnockoutStatic { contextFor(node: any): any; isSubscribable(instance: any): instance is KnockoutSubscribable; toJSON(viewModel: any, replacer?: Function, space?: any): string; - + toJS(viewModel: any): any; isObservable(instance: any): instance is KnockoutObservable; @@ -451,7 +451,7 @@ interface KnockoutStatic { isComputed(instance: any): instance is KnockoutComputed; isComputed(instance: KnockoutObservable | T): instance is KnockoutComputed; - + dataFor(node: any): any; removeNode(node: Node): void; cleanNode(node: Node): Node; diff --git a/types/knockout/test/index.ts b/types/knockout/test/index.ts index a106d7af9b..38f439efb7 100644 --- a/types/knockout/test/index.ts +++ b/types/knockout/test/index.ts @@ -192,7 +192,7 @@ function test_bindings() { var value = ko.utils.unwrapObservable(valueAccessor()); $(element).toggle(value); } - }; + } as KnockoutBindingHandler | boolean>; ko.bindingHandlers.hasFocus = { init: function (element, valueAccessor) { $(element).focus(function () { @@ -211,7 +211,7 @@ function test_bindings() { else element.blur(); } - }; + } as KnockoutBindingHandler>; ko.bindingHandlers.allowBindings = { init: function (elem, valueAccessor) { var shouldAllowBindings = ko.utils.unwrapObservable(valueAccessor()); @@ -749,4 +749,4 @@ interface MyObservableArray extends KnockoutObservableArray { interface MyComputed extends KnockoutComputed { isBeautiful?: boolean; -} \ No newline at end of file +} diff --git a/types/koa-response-time/index.d.ts b/types/koa-response-time/index.d.ts new file mode 100644 index 0000000000..17c3525682 --- /dev/null +++ b/types/koa-response-time/index.d.ts @@ -0,0 +1,8 @@ +// Type definitions for koa-response-time 2.0 +// Project: https://github.com/koajs/response-time#readme +// Definitions by: Thor Sedeke +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.3 + +declare function koa_response_time(): any; +export = koa_response_time; diff --git a/types/koa-response-time/koa-response-time-tests.ts b/types/koa-response-time/koa-response-time-tests.ts new file mode 100644 index 0000000000..6b35c60f9a --- /dev/null +++ b/types/koa-response-time/koa-response-time-tests.ts @@ -0,0 +1,4 @@ +import koaResponseTime = require('koa-response-time'); +import Koa = require('koa'); + +new Koa().use(koaResponseTime()); diff --git a/types/koa-response-time/tsconfig.json b/types/koa-response-time/tsconfig.json new file mode 100644 index 0000000000..cd6c50be36 --- /dev/null +++ b/types/koa-response-time/tsconfig.json @@ -0,0 +1,23 @@ +{ + "compilerOptions": { + "module": "commonjs", + "lib": [ + "es6" + ], + "noImplicitAny": true, + "noImplicitThis": true, + "strictNullChecks": true, + "strictFunctionTypes": true, + "baseUrl": "../", + "typeRoots": [ + "../" + ], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true + }, + "files": [ + "index.d.ts", + "koa-response-time-tests.ts" + ] +} diff --git a/types/koa-response-time/tslint.json b/types/koa-response-time/tslint.json new file mode 100644 index 0000000000..3db14f85ea --- /dev/null +++ b/types/koa-response-time/tslint.json @@ -0,0 +1 @@ +{ "extends": "dtslint/dt.json" } diff --git a/types/mobx-devtools-mst/index.d.ts b/types/mobx-devtools-mst/index.d.ts new file mode 100644 index 0000000000..54a3f09bf6 --- /dev/null +++ b/types/mobx-devtools-mst/index.d.ts @@ -0,0 +1,8 @@ +// Type definitions for mobx-devtools-mst 0.9 +// Project: https://mobxjs.github.io/mobx +// Definitions by: Alan Plum +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.2 + +declare function makeInspectable(state: object): void; +export = makeInspectable; diff --git a/types/mobx-devtools-mst/mobx-devtools-mst-tests.ts b/types/mobx-devtools-mst/mobx-devtools-mst-tests.ts new file mode 100644 index 0000000000..a00d1c36af --- /dev/null +++ b/types/mobx-devtools-mst/mobx-devtools-mst-tests.ts @@ -0,0 +1,7 @@ +import makeInspectable = require("mobx-devtools-mst"); + +const myModel = { + /* some mst instance */ +}; + +makeInspectable(myModel); diff --git a/types/mobx-devtools-mst/tsconfig.json b/types/mobx-devtools-mst/tsconfig.json new file mode 100644 index 0000000000..06ccbf6965 --- /dev/null +++ b/types/mobx-devtools-mst/tsconfig.json @@ -0,0 +1,16 @@ +{ + "compilerOptions": { + "module": "commonjs", + "lib": ["es6"], + "noImplicitAny": true, + "noImplicitThis": true, + "strictNullChecks": true, + "strictFunctionTypes": true, + "baseUrl": "../", + "typeRoots": ["../"], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true + }, + "files": ["index.d.ts", "mobx-devtools-mst-tests.ts"] +} diff --git a/types/mobx-devtools-mst/tslint.json b/types/mobx-devtools-mst/tslint.json new file mode 100644 index 0000000000..3db14f85ea --- /dev/null +++ b/types/mobx-devtools-mst/tslint.json @@ -0,0 +1 @@ +{ "extends": "dtslint/dt.json" } diff --git a/types/mongodb/index.d.ts b/types/mongodb/index.d.ts index 5147de1de4..d1c47eff64 100644 --- a/types/mongodb/index.d.ts +++ b/types/mongodb/index.d.ts @@ -30,7 +30,7 @@ export { Binary, Double, Long, Decimal128, MaxKey, MinKey, ObjectID, ObjectId, T // Class documentation : http://mongodb.github.io/node-mongodb-native/3.0/api/MongoClient.html export class MongoClient extends EventEmitter { - constructor(); + constructor(uri: string, options?: MongoClientOptions); /** http://mongodb.github.io/node-mongodb-native/3.0/api/MongoClient.html#.connect */ static connect(uri: string, callback: MongoCallback): void; static connect(uri: string, options?: MongoClientOptions): Promise; @@ -238,6 +238,8 @@ export interface ReplSetOptions extends SSLOptions, HighAvailabilityOptions { socketOptions?: SocketOptions; } +export type ProfilingLevel = 'off' | 'slow_only' | 'all'; + // Class documentation : http://mongodb.github.io/node-mongodb-native/3.0/api/Db.html export class Db extends EventEmitter { constructor(databaseName: string, serverConfig: Server | ReplSet | Mongos, options?: DbCreateOptions); @@ -292,13 +294,14 @@ export class Db extends EventEmitter { /** http://mongodb.github.io/node-mongodb-native/3.0/api/Db.html#listCollections */ listCollections(filter?: Object, options?: { batchSize?: number, readPreference?: ReadPreference | string }): CommandCursor; /** http://mongodb.github.io/node-mongodb-native/3.0/api/Db.html#profilingInfo */ + /** @deprecated Query the system.profile collection directly. */ profilingInfo(callback: MongoCallback): void; profilingInfo(options?: { session?: ClientSession }): Promise; profilingInfo(options: { session?: ClientSession }, callback: MongoCallback): void; /** http://mongodb.github.io/node-mongodb-native/3.0/api/Db.html#profilingLevel */ - profilingLevel(callback: MongoCallback): void; - profilingLevel(options?: { session?: ClientSession }): Promise; - profilingLevel(options: { session?: ClientSession }, callback: MongoCallback): void; + profilingLevel(callback: MongoCallback): void; + profilingLevel(options?: { session?: ClientSession }): Promise; + profilingLevel(options: { session?: ClientSession }, callback: MongoCallback): void; /** http://mongodb.github.io/node-mongodb-native/3.0/api/Db.html#removeUser */ removeUser(username: string, callback: MongoCallback): void; removeUser(username: string, options?: CommonOptions): Promise; @@ -308,9 +311,9 @@ export class Db extends EventEmitter { renameCollection(fromCollection: string, toCollection: string, options?: { dropTarget?: boolean }): Promise>; renameCollection(fromCollection: string, toCollection: string, options: { dropTarget?: boolean }, callback: MongoCallback>): void; /** http://mongodb.github.io/node-mongodb-native/3.0/api/Db.html#setProfilingLevel */ - profilingLevel(level: string, callback: MongoCallback): void; - profilingLevel(level: string, options?: { session?: ClientSession }): Promise; - profilingLevel(level: string, options: { session?: ClientSession }, callback: MongoCallback): void; + setProfilingLevel(level: ProfilingLevel, callback: MongoCallback): void; + setProfilingLevel(level: ProfilingLevel, options?: { session?: ClientSession }): Promise; + setProfilingLevel(level: ProfilingLevel, options: { session?: ClientSession }, callback: MongoCallback): void; /** http://mongodb.github.io/node-mongodb-native/3.0/api/Db.html#stats */ stats(callback: MongoCallback): void; stats(options?: { scale?: number }): Promise; @@ -1527,7 +1530,7 @@ export interface LoggerState { } /** http://mongodb.github.io/node-mongodb-native/3.0/api/Logger.html */ -export class Logger{ +export class Logger { constructor(className: string, options?: LoggerOptions) // Log a message at the debug level debug(message: string, state: LoggerState):void diff --git a/types/mongoose/index.d.ts b/types/mongoose/index.d.ts index 5723a9a881..362f549e67 100644 --- a/types/mongoose/index.d.ts +++ b/types/mongoose/index.d.ts @@ -2714,6 +2714,16 @@ declare module "mongoose" { insertMany(doc: any, callback?: (error: any, doc: T) => void): Promise; insertMany(doc: any, options?: { ordered?: boolean, rawResult?: boolean }, callback?: (error: any, doc: T) => void): Promise; + /** + * Performs any async initialization of this model against MongoDB. + * This function is called automatically, so you don't need to call it. + * This function is also idempotent, so you may call it to get back a promise + * that will resolve when your indexes are finished building as an alternative + * to `MyModel.on('index')` + * @param callback optional + */ + init(callback?: (err: any) => void): Promise; + /** * Executes a mapReduce command. * @param o an object specifying map-reduce options diff --git a/types/mongoose/mongoose-tests.ts b/types/mongoose/mongoose-tests.ts index a6fe9f406a..95f50a6e6f 100644 --- a/types/mongoose/mongoose-tests.ts +++ b/types/mongoose/mongoose-tests.ts @@ -1420,6 +1420,7 @@ var MongoModel = mongoose.model('MongoModel', new mongoose.Schema({ required: true } }), 'myCollection', true); +MongoModel.init().then(cb); MongoModel.find({}).$where('indexOf("val") !== -1').exec(function (err, docs) { docs[0].save(); docs[0].__v; diff --git a/types/murmurhash/index.d.ts b/types/murmurhash/index.d.ts new file mode 100644 index 0000000000..31c663fd33 --- /dev/null +++ b/types/murmurhash/index.d.ts @@ -0,0 +1,29 @@ +// Type definitions for murmurhash 0.0 +// Project: https://github.com/perezd/node-murmurhash +// Definitions by: Arne Schubert +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +export = murmurhash; + +/** + * JS Implementation of MurmurHash3 (r136) (as of May 20, 2011) + * + * @param key - ASCII only + * @param seed - Positive integer only + * @return - 32-bit positive integer hash + */ +declare function murmurhash(key: string, seed: number): number; + +declare namespace murmurhash { + // Circular reference from murmurhash + function v3(key: string, seed: number): number; + + /** + * JS Implementation of MurmurHash2 + * + * @param str - ASCII only + * @param seed - Positive integer only + * @return - 32-bit positive integer hash + */ + function v2(str: string, seed: number): number; +} diff --git a/types/murmurhash/murmurhash-tests.ts b/types/murmurhash/murmurhash-tests.ts new file mode 100644 index 0000000000..ebbbf09cab --- /dev/null +++ b/types/murmurhash/murmurhash-tests.ts @@ -0,0 +1,8 @@ +import murmurhash = require('murmurhash'); + +const stringValue = "test"; +let numberValue = 123; + +numberValue = murmurhash(stringValue, numberValue); +numberValue = murmurhash.v2(stringValue, numberValue); +numberValue = murmurhash.v3(stringValue, numberValue); diff --git a/types/murmurhash/tsconfig.json b/types/murmurhash/tsconfig.json new file mode 100644 index 0000000000..1778d66a72 --- /dev/null +++ b/types/murmurhash/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", + "murmurhash-tests.ts" + ] +} diff --git a/types/murmurhash/tslint.json b/types/murmurhash/tslint.json new file mode 100644 index 0000000000..3db14f85ea --- /dev/null +++ b/types/murmurhash/tslint.json @@ -0,0 +1 @@ +{ "extends": "dtslint/dt.json" } diff --git a/types/noble/noble-tests.ts b/types/noble/noble-tests.ts index 5e00105433..0c8dcf6c20 100644 --- a/types/noble/noble-tests.ts +++ b/types/noble/noble-tests.ts @@ -59,7 +59,7 @@ peripheral.discoverAllServicesAndCharacteristics(); peripheral.discoverAllServicesAndCharacteristics((error: string, services: noble.Service[], characteristics: noble.Characteristic[]): void => {}); peripheral.discoverSomeServicesAndCharacteristics(["180d"], ["2a38"]); peripheral.discoverSomeServicesAndCharacteristics(["180d"], ["2a38"], (error: string, services: noble.Service[], characteristics: noble.Characteristic[]): void => {}); -peripheral.readHandle(new Buffer(1), (error: string, data: NodeBuffer): void => {}); +peripheral.readHandle(new Buffer(1), (error: string, data: Buffer): void => {}); peripheral.writeHandle(new Buffer(1), new Buffer(1), true, (error: string): void => {}); peripheral.on("connect", (error: string): void => {}); peripheral.on("disconnect", (error: string): void => {}); @@ -84,7 +84,7 @@ characteristic.name = ""; characteristic.type = ""; characteristic.properties = ["read", "notify"]; characteristic.read(); -characteristic.read((error: string, data: NodeBuffer): void => {}); +characteristic.read((error: string, data: Buffer): void => {}); characteristic.write(new Buffer(1), true); characteristic.write(new Buffer(1), true, (error: string): void => {}); characteristic.broadcast(true); @@ -93,7 +93,7 @@ characteristic.notify(true); characteristic.notify(true, (error: string): void => {}); characteristic.discoverDescriptors(); characteristic.discoverDescriptors((error: string, descriptors: noble.Descriptor[]): void => {}); -characteristic.on("read", (data: NodeBuffer, isNotification: boolean): void => {}); +characteristic.on("read", (data: Buffer, isNotification: boolean): void => {}); characteristic.on("write", true, (error: string): void => {}); characteristic.on("broadcast", (state: string): void => {}); characteristic.on("notify", (state: string): void => {}); @@ -108,9 +108,9 @@ descriptor.uuid = ""; descriptor.name = ""; descriptor.type = ""; descriptor.readValue(); -descriptor.readValue((error: string, data: NodeBuffer): void => {}); +descriptor.readValue((error: string, data: Buffer): void => {}); descriptor.writeValue(new Buffer(1)); descriptor.writeValue(new Buffer(1), (error: string): void => {}); -descriptor.on("valueRead", (error: string, data: NodeBuffer): void => {}); +descriptor.on("valueRead", (error: string, data: Buffer): void => {}); descriptor.on("valueWrite", (error: string): void => {}); diff --git a/types/node-telegram-bot-api/index.d.ts b/types/node-telegram-bot-api/index.d.ts index cfc55d2d33..cacc064abd 100644 --- a/types/node-telegram-bot-api/index.d.ts +++ b/types/node-telegram-bot-api/index.d.ts @@ -35,7 +35,7 @@ declare namespace TelegramBot { interface WebHookOptions { host?: string; - post?: number; + port?: number; key: string; cert: string; pfx: string; diff --git a/types/node/index.d.ts b/types/node/index.d.ts index 4fc49dfedb..4fd2bf8dc7 100644 --- a/types/node/index.d.ts +++ b/types/node/index.d.ts @@ -32,17 +32,101 @@ // This needs to be global to avoid TS2403 in case lib.dom.d.ts is present in the same build interface Console { Console: NodeJS.ConsoleConstructor; + /** + * A simple assertion test that verifies whether `value` is truthy. + * If it is not, an `AssertionError` is thrown. + * If provided, the error `message` is formatted using `util.format()` and used as the error message. + */ assert(value: any, message?: string, ...optionalParams: any[]): void; - dir(obj: any, options?: NodeJS.InspectOptions): void; + /** + * When `stdout` is a TTY, calling `console.clear()` will attempt to clear the TTY. + * When `stdout` is not a TTY, this method does nothing. + */ + clear(): void; + /** + * Maintains an internal counter specific to `label` and outputs to `stdout` the number of times `console.count()` has been called with the given `label`. + */ + count(label?: string): void; + /** + * Resets the internal counter specific to `label`. + */ + countReset(label?: string): void; + /** + * The `console.debug()` function is an alias for {@link console.log()}. + */ debug(message?: any, ...optionalParams: any[]): void; + /** + * Uses {@link util.inspect()} on `obj` and prints the resulting string to `stdout`. + * This function bypasses any custom `inspect()` function defined on `obj`. + */ + dir(obj: any, options?: NodeJS.InspectOptions): void; + /** + * This method calls {@link console.log()} passing it the arguments received. Please note that this method does not produce any XML formatting + */ + dirxml(...data: any[]): void; + /** + * Prints to `stderr` with newline. + */ error(message?: any, ...optionalParams: any[]): void; + /** + * Increases indentation of subsequent lines by two spaces. + * If one or more `label`s are provided, those are printed first without the additional indentation. + */ + group(...label: any[]): void; + /** + * The `console.groupCollapsed()` function is an alias for {@link console.group()}. + */ + groupCollapsed(): void; + /** + * Decreases indentation of subsequent lines by two spaces. + */ + groupEnd(): void; + /** + * The {@link console.info()} function is an alias for {@link console.log()}. + */ info(message?: any, ...optionalParams: any[]): void; + /** + * Prints to `stdout` with newline. + */ log(message?: any, ...optionalParams: any[]): void; - time(label: string): void; - timeEnd(label: string): void; - trace(message?: any, ...optionalParams: any[]): void; - warn(message?: any, ...optionalParams: any[]): void; + /** + * This method does not display anything unless used in the inspector. + * Prints to `stdout` the array `array` formatted as a table. + */ table(tabularData: any, properties?: string[]): void; + /** + * Starts a timer that can be used to compute the duration of an operation. Timers are identified by a unique `label`. + */ + time(label?: string): void; + /** + * Stops a timer that was previously started by calling {@link console.time()} and prints the result to `stdout`. + */ + timeEnd(label?: string): void; + /** + * Prints to `stderr` the string 'Trace :', followed by the {@link util.format()} formatted message and stack trace to the current position in the code. + */ + trace(message?: any, ...optionalParams: any[]): void; + /** + * The {@link console.warn()} function is an alias for {@link console.error()}. + */ + warn(message?: any, ...optionalParams: any[]): void; + + // --- Inspector mode only --- + /** + * This method does not display anything unless used in the inspector. + * Starts a JavaScript CPU profile with an optional label. + */ + profile(label?: string): void; + /** + * This method does not display anything unless used in the inspector. + * Stops the current JavaScript CPU profiling session if one has been started and prints the report to the Profiles panel of the inspector. + */ + profileEnd(): void; + /** + * This method does not display anything unless used in the inspector. + * Adds an event with the label `label` to the Timeline panel of the inspector. + */ + timeStamp(label?: string): void; } interface Error { @@ -175,7 +259,61 @@ declare var SlowBuffer: { // Buffer class type BufferEncoding = "ascii" | "utf8" | "utf16le" | "ucs2" | "base64" | "latin1" | "binary" | "hex"; -interface Buffer extends NodeBuffer { } +interface Buffer extends Uint8Array { + write(string: string, offset?: number, length?: number, encoding?: string): number; + toString(encoding?: string, start?: number, end?: number): string; + toJSON(): { type: 'Buffer', data: any[] }; + equals(otherBuffer: Buffer): boolean; + compare(otherBuffer: Buffer, targetStart?: number, targetEnd?: number, sourceStart?: number, sourceEnd?: number): number; + copy(targetBuffer: Buffer, targetStart?: number, sourceStart?: number, sourceEnd?: number): number; + slice(start?: number, end?: number): Buffer; + writeUIntLE(value: number, offset: number, byteLength: number, noAssert?: boolean): number; + writeUIntBE(value: number, offset: number, byteLength: number, noAssert?: boolean): number; + writeIntLE(value: number, offset: number, byteLength: number, noAssert?: boolean): number; + writeIntBE(value: number, offset: number, byteLength: number, noAssert?: boolean): number; + readUIntLE(offset: number, byteLength: number, noAssert?: boolean): number; + readUIntBE(offset: number, byteLength: number, noAssert?: boolean): number; + readIntLE(offset: number, byteLength: number, noAssert?: boolean): number; + readIntBE(offset: number, byteLength: number, noAssert?: boolean): number; + readUInt8(offset: number, noAssert?: boolean): number; + readUInt16LE(offset: number, noAssert?: boolean): number; + readUInt16BE(offset: number, noAssert?: boolean): number; + readUInt32LE(offset: number, noAssert?: boolean): number; + readUInt32BE(offset: number, noAssert?: boolean): number; + readInt8(offset: number, noAssert?: boolean): number; + readInt16LE(offset: number, noAssert?: boolean): number; + readInt16BE(offset: number, noAssert?: boolean): number; + readInt32LE(offset: number, noAssert?: boolean): number; + readInt32BE(offset: number, noAssert?: boolean): number; + readFloatLE(offset: number, noAssert?: boolean): number; + readFloatBE(offset: number, noAssert?: boolean): number; + readDoubleLE(offset: number, noAssert?: boolean): number; + readDoubleBE(offset: number, noAssert?: boolean): number; + swap16(): Buffer; + swap32(): Buffer; + swap64(): Buffer; + writeUInt8(value: number, offset: number, noAssert?: boolean): number; + writeUInt16LE(value: number, offset: number, noAssert?: boolean): number; + writeUInt16BE(value: number, offset: number, noAssert?: boolean): number; + writeUInt32LE(value: number, offset: number, noAssert?: boolean): number; + writeUInt32BE(value: number, offset: number, noAssert?: boolean): number; + writeInt8(value: number, offset: number, noAssert?: boolean): number; + writeInt16LE(value: number, offset: number, noAssert?: boolean): number; + writeInt16BE(value: number, offset: number, noAssert?: boolean): number; + writeInt32LE(value: number, offset: number, noAssert?: boolean): number; + writeInt32BE(value: number, offset: number, noAssert?: boolean): number; + writeFloatLE(value: number, offset: number, noAssert?: boolean): number; + writeFloatBE(value: number, offset: number, noAssert?: boolean): number; + writeDoubleLE(value: number, offset: number, noAssert?: boolean): number; + writeDoubleBE(value: number, offset: number, noAssert?: boolean): number; + fill(value: any, offset?: number, end?: number): this; + indexOf(value: string | number | Buffer, byteOffset?: number, encoding?: string): number; + lastIndexOf(value: string | number | Buffer, byteOffset?: number, encoding?: string): number; + entries(): IterableIterator<[number, number]>; + includes(value: string | number | Buffer, byteOffset?: number, encoding?: string): boolean; + keys(): IterableIterator; + values(): IterableIterator; +} /** * Raw data is stored in instances of the Buffer class. @@ -829,65 +967,6 @@ declare namespace NodeJS { interface IterableIterator { } -/** - * @deprecated - */ -interface NodeBuffer extends Uint8Array { - write(string: string, offset?: number, length?: number, encoding?: string): number; - toString(encoding?: string, start?: number, end?: number): string; - toJSON(): { type: 'Buffer', data: any[] }; - equals(otherBuffer: Buffer): boolean; - compare(otherBuffer: Buffer, targetStart?: number, targetEnd?: number, sourceStart?: number, sourceEnd?: number): number; - copy(targetBuffer: Buffer, targetStart?: number, sourceStart?: number, sourceEnd?: number): number; - slice(start?: number, end?: number): Buffer; - writeUIntLE(value: number, offset: number, byteLength: number, noAssert?: boolean): number; - writeUIntBE(value: number, offset: number, byteLength: number, noAssert?: boolean): number; - writeIntLE(value: number, offset: number, byteLength: number, noAssert?: boolean): number; - writeIntBE(value: number, offset: number, byteLength: number, noAssert?: boolean): number; - readUIntLE(offset: number, byteLength: number, noAssert?: boolean): number; - readUIntBE(offset: number, byteLength: number, noAssert?: boolean): number; - readIntLE(offset: number, byteLength: number, noAssert?: boolean): number; - readIntBE(offset: number, byteLength: number, noAssert?: boolean): number; - readUInt8(offset: number, noAssert?: boolean): number; - readUInt16LE(offset: number, noAssert?: boolean): number; - readUInt16BE(offset: number, noAssert?: boolean): number; - readUInt32LE(offset: number, noAssert?: boolean): number; - readUInt32BE(offset: number, noAssert?: boolean): number; - readInt8(offset: number, noAssert?: boolean): number; - readInt16LE(offset: number, noAssert?: boolean): number; - readInt16BE(offset: number, noAssert?: boolean): number; - readInt32LE(offset: number, noAssert?: boolean): number; - readInt32BE(offset: number, noAssert?: boolean): number; - readFloatLE(offset: number, noAssert?: boolean): number; - readFloatBE(offset: number, noAssert?: boolean): number; - readDoubleLE(offset: number, noAssert?: boolean): number; - readDoubleBE(offset: number, noAssert?: boolean): number; - swap16(): Buffer; - swap32(): Buffer; - swap64(): Buffer; - writeUInt8(value: number, offset: number, noAssert?: boolean): number; - writeUInt16LE(value: number, offset: number, noAssert?: boolean): number; - writeUInt16BE(value: number, offset: number, noAssert?: boolean): number; - writeUInt32LE(value: number, offset: number, noAssert?: boolean): number; - writeUInt32BE(value: number, offset: number, noAssert?: boolean): number; - writeInt8(value: number, offset: number, noAssert?: boolean): number; - writeInt16LE(value: number, offset: number, noAssert?: boolean): number; - writeInt16BE(value: number, offset: number, noAssert?: boolean): number; - writeInt32LE(value: number, offset: number, noAssert?: boolean): number; - writeInt32BE(value: number, offset: number, noAssert?: boolean): number; - writeFloatLE(value: number, offset: number, noAssert?: boolean): number; - writeFloatBE(value: number, offset: number, noAssert?: boolean): number; - writeDoubleLE(value: number, offset: number, noAssert?: boolean): number; - writeDoubleBE(value: number, offset: number, noAssert?: boolean): number; - fill(value: any, offset?: number, end?: number): this; - indexOf(value: string | number | Buffer, byteOffset?: number, encoding?: string): number; - lastIndexOf(value: string | number | Buffer, byteOffset?: number, encoding?: string): number; - entries(): IterableIterator<[number, number]>; - includes(value: string | number | Buffer, byteOffset?: number, encoding?: string): boolean; - keys(): IterableIterator; - values(): IterableIterator; -} - /************************************************ * * * MODULES * @@ -2101,7 +2180,7 @@ declare module "child_process" { windowsHide?: boolean; } - export function spawn(command: string, args?: string[], options?: SpawnOptions): ChildProcess; + export function spawn(command: string, args?: ReadonlyArray, options?: SpawnOptions): ChildProcess; export interface ExecOptions { cwd?: string; @@ -5871,8 +5950,8 @@ declare module "stream" { highWaterMark?: number; decodeStrings?: boolean; objectMode?: boolean; - write?: (chunk: string | Buffer, encoding: string, callback: Function) => any; - writev?: (chunks: Array<{ chunk: string | Buffer, encoding: string }>, callback: Function) => any; + write?: (chunk: any, encoding: string, callback: Function) => any; + writev?: (chunks: Array<{ chunk: any, encoding: string }>, callback: Function) => any; destroy?: (error?: Error) => any; final?: (callback: (error?: Error) => void) => void; } @@ -5989,14 +6068,16 @@ declare module "stream" { uncork(): void; } + type TransformCallback = (err?: Error, data?: any) => void; + export interface TransformOptions extends DuplexOptions { - transform?: (chunk: string | Buffer, encoding: string, callback: Function) => any; - flush?: (callback: Function) => any; + transform?: (chunk: any, encoding: string, callback: TransformCallback) => any; + flush?: (callback: TransformCallback) => any; } export class Transform extends Duplex { constructor(opts?: TransformOptions); - _transform(chunk: any, encoding: string, callback: Function): void; + _transform(chunk: any, encoding: string, callback: TransformCallback): void; destroy(error?: Error): void; } @@ -6079,6 +6160,7 @@ declare module "util" { /** @deprecated since v4.0.0 - use `value === undefined` instead. */ export function isUndefined(object: any): object is undefined; export function deprecate(fn: T, message: string): T; + export function isDeepStrictEqual(val1: any, val2: any): boolean; export interface CustomPromisify extends Function { __promisify__: TCustom; diff --git a/types/node/node-tests.ts b/types/node/node-tests.ts index 7a055c620e..efc00ef201 100644 --- a/types/node/node-tests.ts +++ b/types/node/node-tests.ts @@ -851,6 +851,9 @@ namespace util_tests { util.deprecate(foo, 'foo() is deprecated, use bar() instead'); // $ExpectType (fn: T, message: string) => T util.deprecate(util.deprecate, 'deprecate() is deprecated, use bar() instead'); + + // util.isDeepStrictEqual + util.isDeepStrictEqual({foo: 'bar'}, {foo: 'bar'}); } } diff --git a/types/node/v0/index.d.ts b/types/node/v0/index.d.ts index ef1c485d2d..37f92cbc50 100644 --- a/types/node/v0/index.d.ts +++ b/types/node/v0/index.d.ts @@ -881,7 +881,7 @@ declare module "child_process" { unref(): void; } - export function spawn(command: string, args?: string[], options?: { + export function spawn(command: string, args?: ReadonlyArray, options?: { cwd?: string; stdio?: any; custom?: any; diff --git a/types/node/v4/index.d.ts b/types/node/v4/index.d.ts index 4793b4e9f7..db5518575d 100644 --- a/types/node/v4/index.d.ts +++ b/types/node/v4/index.d.ts @@ -1240,7 +1240,7 @@ declare module "child_process" { gid?: number; shell?: boolean | string; } - export function spawn(command: string, args?: string[], options?: SpawnOptions): ChildProcess; + export function spawn(command: string, args?: ReadonlyArray, options?: SpawnOptions): ChildProcess; export interface ExecOptions { cwd?: string; @@ -2365,8 +2365,8 @@ declare module "stream" { highWaterMark?: number; decodeStrings?: boolean; objectMode?: boolean; - write?: (chunk: string | Buffer, encoding: string, callback: Function) => any; - writev?: (chunks: { chunk: string | Buffer, encoding: string }[], callback: Function) => any; + write?: (chunk: any, encoding: string, callback: Function) => any; + writev?: (chunks: { chunk: any, encoding: string }[], callback: Function) => any; } export class Writable extends Stream implements NodeJS.WritableStream { diff --git a/types/node/v6/index.d.ts b/types/node/v6/index.d.ts index 8cde8ee611..9859d0ba09 100644 --- a/types/node/v6/index.d.ts +++ b/types/node/v6/index.d.ts @@ -1787,7 +1787,7 @@ declare module "child_process" { gid?: number; shell?: boolean | string; } - export function spawn(command: string, args?: string[], options?: SpawnOptions): ChildProcess; + export function spawn(command: string, args?: ReadonlyArray, options?: SpawnOptions): ChildProcess; export interface ExecOptions { cwd?: string; @@ -3710,8 +3710,8 @@ declare module "stream" { highWaterMark?: number; decodeStrings?: boolean; objectMode?: boolean; - write?: (chunk: string | Buffer, encoding: string, callback: Function) => any; - writev?: (chunks: { chunk: string | Buffer, encoding: string }[], callback: Function) => any; + write?: (chunk: any, encoding: string, callback: Function) => any; + writev?: (chunks: { chunk: any, encoding: string }[], callback: Function) => any; } export class Writable extends Stream implements NodeJS.WritableStream { diff --git a/types/node/v7/index.d.ts b/types/node/v7/index.d.ts index e8290f204c..7d2d34cd8b 100644 --- a/types/node/v7/index.d.ts +++ b/types/node/v7/index.d.ts @@ -1847,7 +1847,7 @@ declare module "child_process" { gid?: number; shell?: boolean | string; } - export function spawn(command: string, args?: string[], options?: SpawnOptions): ChildProcess; + export function spawn(command: string, args?: ReadonlyArray, options?: SpawnOptions): ChildProcess; export interface ExecOptions { cwd?: string; @@ -3818,8 +3818,8 @@ declare module "stream" { highWaterMark?: number; decodeStrings?: boolean; objectMode?: boolean; - write?: (chunk: string | Buffer, encoding: string, callback: Function) => any; - writev?: (chunks: { chunk: string | Buffer, encoding: string }[], callback: Function) => any; + write?: (chunk: any, encoding: string, callback: Function) => any; + writev?: (chunks: { chunk: any, encoding: string }[], callback: Function) => any; } export class Writable extends Stream implements NodeJS.WritableStream { diff --git a/types/node/v8/index.d.ts b/types/node/v8/index.d.ts index 2d705270ef..647d479683 100644 --- a/types/node/v8/index.d.ts +++ b/types/node/v8/index.d.ts @@ -2091,7 +2091,7 @@ declare module "child_process" { windowsHide?: boolean; } - export function spawn(command: string, args?: string[], options?: SpawnOptions): ChildProcess; + export function spawn(command: string, args?: ReadonlyArray, options?: SpawnOptions): ChildProcess; export interface ExecOptions { cwd?: string; @@ -5368,8 +5368,8 @@ declare module "stream" { highWaterMark?: number; decodeStrings?: boolean; objectMode?: boolean; - write?: (chunk: string | Buffer, encoding: string, callback: Function) => any; - writev?: (chunks: Array<{ chunk: string | Buffer, encoding: string }>, callback: Function) => any; + write?: (chunk: any, encoding: string, callback: Function) => any; + writev?: (chunks: Array<{ chunk: any, encoding: string }>, callback: Function) => any; destroy?: (error?: Error) => any; final?: (callback: (error?: Error) => void) => void; } diff --git a/types/node/v9/index.d.ts b/types/node/v9/index.d.ts index 50a17ddb76..66a96401c3 100644 --- a/types/node/v9/index.d.ts +++ b/types/node/v9/index.d.ts @@ -32,16 +32,101 @@ // This needs to be global to avoid TS2403 in case lib.dom.d.ts is present in the same build interface Console { Console: NodeJS.ConsoleConstructor; + /** + * A simple assertion test that verifies whether `value` is truthy. + * If it is not, an `AssertionError` is thrown. + * If provided, the error `message` is formatted using `util.format()` and used as the error message. + */ assert(value: any, message?: string, ...optionalParams: any[]): void; - dir(obj: any, options?: NodeJS.InspectOptions): void; + /** + * When `stdout` is a TTY, calling `console.clear()` will attempt to clear the TTY. + * When `stdout` is not a TTY, this method does nothing. + */ + clear(): void; + /** + * Maintains an internal counter specific to `label` and outputs to `stdout` the number of times `console.count()` has been called with the given `label`. + */ + count(label?: string): void; + /** + * Resets the internal counter specific to `label`. + */ + countReset(label?: string): void; + /** + * The `console.debug()` function is an alias for {@link console.log()}. + */ debug(message?: any, ...optionalParams: any[]): void; + /** + * Uses {@link util.inspect()} on `obj` and prints the resulting string to `stdout`. + * This function bypasses any custom `inspect()` function defined on `obj`. + */ + dir(obj: any, options?: NodeJS.InspectOptions): void; + /** + * This method calls {@link console.log()} passing it the arguments received. Please note that this method does not produce any XML formatting + */ + dirxml(...data: any[]): void; + /** + * Prints to `stderr` with newline. + */ error(message?: any, ...optionalParams: any[]): void; + /** + * Increases indentation of subsequent lines by two spaces. + * If one or more `label`s are provided, those are printed first without the additional indentation. + */ + group(...label: any[]): void; + /** + * The `console.groupCollapsed()` function is an alias for {@link console.group()}. + */ + groupCollapsed(): void; + /** + * Decreases indentation of subsequent lines by two spaces. + */ + groupEnd(): void; + /** + * The {@link console.info()} function is an alias for {@link console.log()}. + */ info(message?: any, ...optionalParams: any[]): void; + /** + * Prints to `stdout` with newline. + */ log(message?: any, ...optionalParams: any[]): void; - time(label: string): void; - timeEnd(label: string): void; + /** + * Starts a timer that can be used to compute the duration of an operation. Timers are identified by a unique `label`. + */ + time(label?: string): void; + /** + * Stops a timer that was previously started by calling {@link console.time()} and prints the result to `stdout`. + */ + timeEnd(label?: string): void; + /** + * Prints to `stderr` the string 'Trace :', followed by the {@link util.format()} formatted message and stack trace to the current position in the code. + */ trace(message?: any, ...optionalParams: any[]): void; + /** + * The {@link console.warn()} function is an alias for {@link console.error()}. + */ warn(message?: any, ...optionalParams: any[]): void; + + // --- Inspector mode only --- + /** + * This method does not display anything unless used in the inspector. + * Starts a JavaScript CPU profile with an optional label. + */ + profile(label?: string): void; + /** + * This method does not display anything unless used in the inspector. + * Stops the current JavaScript CPU profiling session if one has been started and prints the report to the Profiles panel of the inspector. + */ + profileEnd(): void; + /** + * This method does not display anything unless used in the inspector. + * Prints to `stdout` the array `array` formatted as a table. + */ + table(tabularData: any, properties?: string[]): void; + /** + * This method does not display anything unless used in the inspector. + * Adds an event with the label `label` to the Timeline panel of the inspector. + */ + timeStamp(label?: string): void; } interface Error { @@ -172,7 +257,61 @@ declare var SlowBuffer: { // Buffer class type BufferEncoding = "ascii" | "utf8" | "utf16le" | "ucs2" | "base64" | "latin1" | "binary" | "hex"; -interface Buffer extends NodeBuffer { } +interface Buffer extends Uint8Array { + write(string: string, offset?: number, length?: number, encoding?: string): number; + toString(encoding?: string, start?: number, end?: number): string; + toJSON(): { type: 'Buffer', data: any[] }; + equals(otherBuffer: Buffer): boolean; + compare(otherBuffer: Buffer, targetStart?: number, targetEnd?: number, sourceStart?: number, sourceEnd?: number): number; + copy(targetBuffer: Buffer, targetStart?: number, sourceStart?: number, sourceEnd?: number): number; + slice(start?: number, end?: number): Buffer; + writeUIntLE(value: number, offset: number, byteLength: number, noAssert?: boolean): number; + writeUIntBE(value: number, offset: number, byteLength: number, noAssert?: boolean): number; + writeIntLE(value: number, offset: number, byteLength: number, noAssert?: boolean): number; + writeIntBE(value: number, offset: number, byteLength: number, noAssert?: boolean): number; + readUIntLE(offset: number, byteLength: number, noAssert?: boolean): number; + readUIntBE(offset: number, byteLength: number, noAssert?: boolean): number; + readIntLE(offset: number, byteLength: number, noAssert?: boolean): number; + readIntBE(offset: number, byteLength: number, noAssert?: boolean): number; + readUInt8(offset: number, noAssert?: boolean): number; + readUInt16LE(offset: number, noAssert?: boolean): number; + readUInt16BE(offset: number, noAssert?: boolean): number; + readUInt32LE(offset: number, noAssert?: boolean): number; + readUInt32BE(offset: number, noAssert?: boolean): number; + readInt8(offset: number, noAssert?: boolean): number; + readInt16LE(offset: number, noAssert?: boolean): number; + readInt16BE(offset: number, noAssert?: boolean): number; + readInt32LE(offset: number, noAssert?: boolean): number; + readInt32BE(offset: number, noAssert?: boolean): number; + readFloatLE(offset: number, noAssert?: boolean): number; + readFloatBE(offset: number, noAssert?: boolean): number; + readDoubleLE(offset: number, noAssert?: boolean): number; + readDoubleBE(offset: number, noAssert?: boolean): number; + swap16(): Buffer; + swap32(): Buffer; + swap64(): Buffer; + writeUInt8(value: number, offset: number, noAssert?: boolean): number; + writeUInt16LE(value: number, offset: number, noAssert?: boolean): number; + writeUInt16BE(value: number, offset: number, noAssert?: boolean): number; + writeUInt32LE(value: number, offset: number, noAssert?: boolean): number; + writeUInt32BE(value: number, offset: number, noAssert?: boolean): number; + writeInt8(value: number, offset: number, noAssert?: boolean): number; + writeInt16LE(value: number, offset: number, noAssert?: boolean): number; + writeInt16BE(value: number, offset: number, noAssert?: boolean): number; + writeInt32LE(value: number, offset: number, noAssert?: boolean): number; + writeInt32BE(value: number, offset: number, noAssert?: boolean): number; + writeFloatLE(value: number, offset: number, noAssert?: boolean): number; + writeFloatBE(value: number, offset: number, noAssert?: boolean): number; + writeDoubleLE(value: number, offset: number, noAssert?: boolean): number; + writeDoubleBE(value: number, offset: number, noAssert?: boolean): number; + fill(value: any, offset?: number, end?: number): this; + indexOf(value: string | number | Buffer, byteOffset?: number, encoding?: string): number; + lastIndexOf(value: string | number | Buffer, byteOffset?: number, encoding?: string): number; + entries(): IterableIterator<[number, number]>; + includes(value: string | number | Buffer, byteOffset?: number, encoding?: string): boolean; + keys(): IterableIterator; + values(): IterableIterator; +} /** * Raw data is stored in instances of the Buffer class. @@ -819,65 +958,6 @@ declare namespace NodeJS { interface IterableIterator { } -/** - * @deprecated - */ -interface NodeBuffer extends Uint8Array { - write(string: string, offset?: number, length?: number, encoding?: string): number; - toString(encoding?: string, start?: number, end?: number): string; - toJSON(): { type: 'Buffer', data: any[] }; - equals(otherBuffer: Buffer): boolean; - compare(otherBuffer: Buffer, targetStart?: number, targetEnd?: number, sourceStart?: number, sourceEnd?: number): number; - copy(targetBuffer: Buffer, targetStart?: number, sourceStart?: number, sourceEnd?: number): number; - slice(start?: number, end?: number): Buffer; - writeUIntLE(value: number, offset: number, byteLength: number, noAssert?: boolean): number; - writeUIntBE(value: number, offset: number, byteLength: number, noAssert?: boolean): number; - writeIntLE(value: number, offset: number, byteLength: number, noAssert?: boolean): number; - writeIntBE(value: number, offset: number, byteLength: number, noAssert?: boolean): number; - readUIntLE(offset: number, byteLength: number, noAssert?: boolean): number; - readUIntBE(offset: number, byteLength: number, noAssert?: boolean): number; - readIntLE(offset: number, byteLength: number, noAssert?: boolean): number; - readIntBE(offset: number, byteLength: number, noAssert?: boolean): number; - readUInt8(offset: number, noAssert?: boolean): number; - readUInt16LE(offset: number, noAssert?: boolean): number; - readUInt16BE(offset: number, noAssert?: boolean): number; - readUInt32LE(offset: number, noAssert?: boolean): number; - readUInt32BE(offset: number, noAssert?: boolean): number; - readInt8(offset: number, noAssert?: boolean): number; - readInt16LE(offset: number, noAssert?: boolean): number; - readInt16BE(offset: number, noAssert?: boolean): number; - readInt32LE(offset: number, noAssert?: boolean): number; - readInt32BE(offset: number, noAssert?: boolean): number; - readFloatLE(offset: number, noAssert?: boolean): number; - readFloatBE(offset: number, noAssert?: boolean): number; - readDoubleLE(offset: number, noAssert?: boolean): number; - readDoubleBE(offset: number, noAssert?: boolean): number; - swap16(): Buffer; - swap32(): Buffer; - swap64(): Buffer; - writeUInt8(value: number, offset: number, noAssert?: boolean): number; - writeUInt16LE(value: number, offset: number, noAssert?: boolean): number; - writeUInt16BE(value: number, offset: number, noAssert?: boolean): number; - writeUInt32LE(value: number, offset: number, noAssert?: boolean): number; - writeUInt32BE(value: number, offset: number, noAssert?: boolean): number; - writeInt8(value: number, offset: number, noAssert?: boolean): number; - writeInt16LE(value: number, offset: number, noAssert?: boolean): number; - writeInt16BE(value: number, offset: number, noAssert?: boolean): number; - writeInt32LE(value: number, offset: number, noAssert?: boolean): number; - writeInt32BE(value: number, offset: number, noAssert?: boolean): number; - writeFloatLE(value: number, offset: number, noAssert?: boolean): number; - writeFloatBE(value: number, offset: number, noAssert?: boolean): number; - writeDoubleLE(value: number, offset: number, noAssert?: boolean): number; - writeDoubleBE(value: number, offset: number, noAssert?: boolean): number; - fill(value: any, offset?: number, end?: number): this; - indexOf(value: string | number | Buffer, byteOffset?: number, encoding?: string): number; - lastIndexOf(value: string | number | Buffer, byteOffset?: number, encoding?: string): number; - entries(): IterableIterator<[number, number]>; - includes(value: string | number | Buffer, byteOffset?: number, encoding?: string): boolean; - keys(): IterableIterator; - values(): IterableIterator; -} - /************************************************ * * * MODULES * @@ -2091,7 +2171,7 @@ declare module "child_process" { windowsHide?: boolean; } - export function spawn(command: string, args?: string[], options?: SpawnOptions): ChildProcess; + export function spawn(command: string, args?: ReadonlyArray, options?: SpawnOptions): ChildProcess; export interface ExecOptions { cwd?: string; @@ -5499,14 +5579,16 @@ declare module "stream" { uncork(): void; } + type TransformCallback = (err?: Error, data?: any) => void; + export interface TransformOptions extends DuplexOptions { - transform?: (chunk: string | Buffer, encoding: string, callback: Function) => any; - flush?: (callback: Function) => any; + transform?: (chunk: any, encoding: string, callback: TransformCallback) => any; + flush?: (callback: TransformCallback) => any; } export class Transform extends Duplex { constructor(opts?: TransformOptions); - _transform(chunk: any, encoding: string, callback: Function): void; + _transform(chunk: any, encoding: string, callback: TransformCallback): void; destroy(error?: Error): void; } @@ -5554,6 +5636,7 @@ declare module "util" { export function isSymbol(object: any): object is symbol; export function isUndefined(object: any): object is undefined; export function deprecate(fn: T, message: string): T; + export function isDeepStrictEqual(val1: any, val2: any): boolean; export interface CustomPromisify extends Function { __promisify__: TCustom; diff --git a/types/node/v9/node-tests.ts b/types/node/v9/node-tests.ts index 7a055c620e..efc00ef201 100644 --- a/types/node/v9/node-tests.ts +++ b/types/node/v9/node-tests.ts @@ -851,6 +851,9 @@ namespace util_tests { util.deprecate(foo, 'foo() is deprecated, use bar() instead'); // $ExpectType (fn: T, message: string) => T util.deprecate(util.deprecate, 'deprecate() is deprecated, use bar() instead'); + + // util.isDeepStrictEqual + util.isDeepStrictEqual({foo: 'bar'}, {foo: 'bar'}); } } diff --git a/types/office-js/index.d.ts b/types/office-js/index.d.ts index e08e0f1ee0..629ccacb21 100644 --- a/types/office-js/index.d.ts +++ b/types/office-js/index.d.ts @@ -20,6 +20,13 @@ declare namespace Office { * @param reason Indicates how the app was initialized */ export function initialize(reason: InitializationReason): void; + /** + * Ensures that the Office JavaScript APIs are ready to be called by the add-in. If the framework hasn't initialized yet, the callback or promise will wait until the Office host is ready to accept API calls. + * Note that though this API is intended to be used inside an Office add-in, it can also be used outside the add-in. In that case, once Office.js determines that it is running outside of an Office host application, it will call the callback and resolve the promise with "null" for both the host and platform. + * @param callback - An optional callback method, that will receive the host and platform info. Alternatively, rather than use a callback, an add-in may simply wait for the Promise returned by the function to resolve. + * @returns A Promise that contains the host and platform info, once initialization is completed. + */ + export function onReady(callback?: (info: { host: HostType, platform: PlatformType} ) => any): Promise<{ host: HostType, platform: PlatformType }>; /** * Indicates if the large namespace for objects will be used or not. * @param useShortNamespace Indicates if 'true' that the short namespace will be used diff --git a/types/papaparse/index.d.ts b/types/papaparse/index.d.ts index ddad5970cb..d97a25010b 100644 --- a/types/papaparse/index.d.ts +++ b/types/papaparse/index.d.ts @@ -74,6 +74,9 @@ export class Parser { // Gets the cursor position getCharIndex(): number; + + pause(): void; + resume(): void; } export interface ParseConfig { diff --git a/types/parsimmon/index.d.ts b/types/parsimmon/index.d.ts index c25ab020de..96909be96a 100644 --- a/types/parsimmon/index.d.ts +++ b/types/parsimmon/index.d.ts @@ -61,6 +61,10 @@ declare namespace Parsimmon { value: T; } + interface Node extends Mark { + name: Name; + } + type Result = Success | Failure; interface Success { @@ -126,7 +130,7 @@ declare namespace Parsimmon { * returns wrapper(this) from the parser. Useful for custom functions used * to wrap your parsers, while keeping with Parsimmon chaining style. */ - thru(call: (wrapper: Parser) => Parser): Parser; + thru(call: (wrapper: Parser) => Parser): Parser; /** * expects anotherParser before and after parser, yielding the result of parser */ @@ -181,9 +185,15 @@ declare namespace Parsimmon { */ atLeast(n: number): Parser; /** - * returns a new parser whose failure message is the passed description. + * Yields an object with `start`, `value`, and `end` keys, where `value` is the original + * value yielded by the parser, and `start` and `end` indicate the `Index` objects representing + * the range of the parse result. */ mark(): Parser>; + /** + * Like `mark()`, but yields an object with an additional `name` key to use as an AST. + */ + node(name: Name): Parser>; /** * Returns a new parser whose failure message is description. * For example, string('x').desc('the letter x') will indicate that 'the letter x' was expected. diff --git a/types/parsimmon/parsimmon-tests.ts b/types/parsimmon/parsimmon-tests.ts index c6dbaec22c..dbcf3d0753 100644 --- a/types/parsimmon/parsimmon-tests.ts +++ b/types/parsimmon/parsimmon-tests.ts @@ -192,6 +192,28 @@ strPar = P.test((a: string) => false); strPar = P.takeWhile((a: string) => true); +// Slightly modified from the documentation example for 'parser.thru(wrapper)'. +function makeNode(name: Name) { + return (parser: P.Parser): P.Parser> => { + return P.seqMap( + P.index, + parser, + P.index, + (start, value, end) => { + return { + name, + start, + value, + end, + }; + }, + ); + }; +} + +let node: P.Parser> = P.letters.node('identifier'); +node = P.letters.thru(makeNode('identifier')); + // -- -- -- -- -- -- -- -- -- -- -- -- -- let language: Language; diff --git a/types/pify/index.d.ts b/types/pify/index.d.ts index b0c8ce4b92..cceb0e9ef0 100644 --- a/types/pify/index.d.ts +++ b/types/pify/index.d.ts @@ -1,6 +1,6 @@ // Type definitions for pify 3.0.0 // Project: https://github.com/sindresorhus/pify -// Definitions by: Sam Verschueren , [Michael Müller] +// Definitions by: Sam Verschueren , [Michael Müller] , Christoph Müller // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped interface PromiseModule { diff --git a/types/pify/pify-tests.ts b/types/pify/pify-tests.ts index cadf3ba408..573872c9ad 100644 --- a/types/pify/pify-tests.ts +++ b/types/pify/pify-tests.ts @@ -27,7 +27,7 @@ const fsP = pify(fs); fsP.readFile('foo.txt').then((result: string) => assert(result, 'foo')); pify(fs.readFile)('foo.txt').then((result: string) => assert(result, 'foo')); -pify(fs.readFile, { promiseModule: Promise})('bar.txt').then((result: string) => assert(result, 'bar')); +pify(fs.readFile, { promiseModule: Promise })('bar.txt').then((result: string) => assert(result, 'bar')); pify(fs.exists, { errorFirst: false })('foo.txt').then((result: boolean) => assert(result.toString(), true.toString())); @@ -45,6 +45,6 @@ if (include.f2 === module.f2) throw new Error(); if (include.f3 !== module.f3) throw new Error(); const exclude = pify(module, { exclude: ['f1', 'f2'] }); -if (include.f1 !== module.f1) throw new Error(); -if (include.f2 !== module.f2) throw new Error(); -if (include.f3 === module.f3) throw new Error(); +if (exclude.f1 !== module.f1) throw new Error(); +if (exclude.f2 !== module.f2) throw new Error(); +if (exclude.f3 === module.f3) throw new Error(); diff --git a/types/prettier/index.d.ts b/types/prettier/index.d.ts index e2fc00be38..0daaa14cca 100644 --- a/types/prettier/index.d.ts +++ b/types/prettier/index.d.ts @@ -109,9 +109,11 @@ export interface ParserOptions extends RequiredOptions { } export interface Plugin { - languages: SupportLanguage; + languages: SupportLanguage[]; parsers: { [parserName: string]: Parser }; printers: { [astFormat: string]: Printer }; + options?: SupportOption[]; + defaultOptions?: Partial; } export interface Parser { @@ -120,6 +122,7 @@ export interface Parser { hasPragma?: (text: string) => boolean; locStart: (node: any) => number; locEnd: (node: any) => number; + preprocess?: (text: string, options: ParserOptions) => string; } export interface Printer { @@ -232,7 +235,7 @@ export function clearConfigCache(): void; export interface SupportLanguage { name: string; - since: string; + since?: string; parsers: string[]; group?: string; tmScope: string; @@ -247,7 +250,7 @@ export interface SupportLanguage { } export interface SupportOption { - since: string; + since?: string; type: 'int' | 'boolean' | 'choice' | 'path'; array?: boolean; deprecated?: string; diff --git a/types/prosemirror-collab/index.d.ts b/types/prosemirror-collab/index.d.ts index cb4949bcba..6412b4b2e2 100644 --- a/types/prosemirror-collab/index.d.ts +++ b/types/prosemirror-collab/index.d.ts @@ -47,7 +47,7 @@ export function sendableSteps( steps: Array>; clientID: number | string; origins: Array>; -} | null | void; +} | null | undefined; /** * Get the version up to which the collab plugin has synced with the * central authority. diff --git a/types/prosemirror-collab/prosemirror-collab-tests.ts b/types/prosemirror-collab/prosemirror-collab-tests.ts index 9d892ca707..60dd42d7d9 100644 --- a/types/prosemirror-collab/prosemirror-collab-tests.ts +++ b/types/prosemirror-collab/prosemirror-collab-tests.ts @@ -10,3 +10,4 @@ plugin = collab.collab({ version: 1 }); plugin = collab.collab({ clientID: 1 }); const sendableSteps = collab.sendableSteps(state); +sendableSteps!.clientID; diff --git a/types/prosemirror-inputrules/index.d.ts b/types/prosemirror-inputrules/index.d.ts index 7c405530e0..7d14305ea6 100644 --- a/types/prosemirror-inputrules/index.d.ts +++ b/types/prosemirror-inputrules/index.d.ts @@ -42,7 +42,7 @@ export class InputRule { match: string[], start: number, end: number - ) => Transaction | null | void) + ) => Transaction | null) ); } /** @@ -81,7 +81,7 @@ export function undoInputRule( export function wrappingInputRule( regexp: RegExp, nodeType: NodeType, - getAttrs?: { [key: string]: any } | ((p: string[]) => { [key: string]: any } | null | void), + getAttrs?: { [key: string]: any } | ((p: string[]) => { [key: string]: any } | null | undefined), joinPredicate?: (p1: string[], p2: ProsemirrorNode) => boolean ): InputRule; /** @@ -95,7 +95,7 @@ export function wrappingInputRule( export function textblockTypeInputRule( regexp: RegExp, nodeType: NodeType, - getAttrs?: { [key: string]: any } | ((p: string[]) => { [key: string]: any } | null | void) + getAttrs?: { [key: string]: any } | ((p: string[]) => { [key: string]: any } | null | undefined) ): InputRule; /** * Converts double dashes to an emdash. diff --git a/types/prosemirror-inputrules/prosemirror-inputrules-tests.ts b/types/prosemirror-inputrules/prosemirror-inputrules-tests.ts index 0d59a02be7..25fa52e6af 100644 --- a/types/prosemirror-inputrules/prosemirror-inputrules-tests.ts +++ b/types/prosemirror-inputrules/prosemirror-inputrules-tests.ts @@ -1,5 +1,8 @@ import * as inputrules from 'prosemirror-inputrules'; import { NodeType } from 'prosemirror-model'; +import { Transaction } from 'prosemirror-state'; const nodeType = new NodeType(); -const rule: inputrules.InputRule = inputrules.wrappingInputRule(/^\$/, nodeType); +const rule1: inputrules.InputRule = inputrules.wrappingInputRule(/^\$/, nodeType); +const rule2 = new inputrules.InputRule(/^$/, 'str'); +const rule3 = new inputrules.InputRule(/^$/, () => null); diff --git a/types/prosemirror-model/index.d.ts b/types/prosemirror-model/index.d.ts index adb8a6141c..095b88f3ba 100644 --- a/types/prosemirror-model/index.d.ts +++ b/types/prosemirror-model/index.d.ts @@ -35,12 +35,12 @@ export class ContentMatch { * Match a node type and marks, returning a match after that node * if successful. */ - matchType(type: NodeType): ContentMatch | null | void; + matchType(type: NodeType): ContentMatch | null | undefined; /** * Try to match a fragment. Returns the resulting match when * successful. */ - matchFragment(frag: Fragment, start?: number, end?: number): ContentMatch | null | void; + matchFragment(frag: Fragment, start?: number, end?: number): ContentMatch | null | undefined; /** * Try to match the given fragment, and if that fails, see if it can * be made to match by inserting nodes in front of it. When @@ -49,14 +49,14 @@ export class ContentMatch { * return a fragment if the resulting match goes to the end of the * content expression. */ - fillBefore(after: Fragment, toEnd?: boolean, startIndex?: number): Fragment | null | void; + fillBefore(after: Fragment, toEnd?: boolean, startIndex?: number): Fragment | null | undefined; /** * Find a set of wrapping node types that would allow a node of the * given type to appear at this position. The result may be empty * (when it fits directly) and will be null when no such wrapping * exists. */ - findWrapping(target: NodeType): Array> | null | void; + findWrapping(target: NodeType): Array> | null | undefined; /** * Get the _n_th outgoing edge from this node in the finite automaton * that describes the content expression. @@ -89,7 +89,7 @@ export class Fragment { start: number, parent: ProsemirrorNode, index: number - ) => boolean | null | void, + ) => boolean | null | undefined | void, startPos?: number ): void; /** @@ -101,7 +101,7 @@ export class Fragment { node: ProsemirrorNode, pos: number, parent: ProsemirrorNode - ) => boolean | null | void + ) => boolean | null | undefined | void ): void; /** * Create a new fragment containing the combined content of this @@ -141,7 +141,7 @@ export class Fragment { /** * Get the child node at the given index, if it exists. */ - maybeChild(index: number): ProsemirrorNode | null | void; + maybeChild(index: number): ProsemirrorNode | null | undefined; /** * Call `f` for every child node, passing the node, its offset * into this parent node, and its index. @@ -151,14 +151,14 @@ export class Fragment { * Find the first position at which this fragment and another * fragment differ, or `null` if they are the same. */ - findDiffStart(other: Fragment): number | null | void; + findDiffStart(other: Fragment): number | null | undefined; /** * Find the first position, searching from the end, at which this * fragment and the given fragment differ, or `null` if they are the * same. Since this position will not be the same in both nodes, an * object with two separate positions is returned. */ - findDiffEnd(other: ProsemirrorNode): { a: number; b: number } | null | void; + findDiffEnd(other: ProsemirrorNode): { a: number; b: number } | null | undefined; /** * Return a debugging string that describes this fragment. */ @@ -166,7 +166,7 @@ export class Fragment { /** * Create a JSON-serializeable representation of this fragment. */ - toJSON(): { [key: string]: any } | null | void; + toJSON(): { [key: string]: any } | null | undefined; /** * Deserialize a fragment from its JSON representation. */ @@ -326,7 +326,7 @@ export interface ParseRule { * Called with a DOM Element for `tag` rules, and with a string (the * style's value) for `style` rules. */ - getAttrs?: ((p: Node | string) => { [key: string]: any } | false | null | void) | null; + getAttrs?: ((p: Node | string) => { [key: string]: any } | false | null | undefined) | null; /** * For `tag` rules that produce non-leaf nodes or marks, by default * the content of the DOM element is parsed as content of the mark @@ -507,7 +507,7 @@ declare class ProsemirrorNode { /** * Get the child node at the given index, if it exists. */ - maybeChild(index: number): ProsemirrorNode | null | void; + maybeChild(index: number): ProsemirrorNode | null | undefined; /** * Call `f` for every child node, passing the node, its offset * into this parent node, and its index. @@ -529,7 +529,7 @@ declare class ProsemirrorNode { pos: number, parent: ProsemirrorNode, index: number - ) => boolean | null | void, + ) => boolean | null | undefined | void, startPos?: number ): void; /** @@ -541,7 +541,7 @@ declare class ProsemirrorNode { node: ProsemirrorNode, pos: number, parent: ProsemirrorNode - ) => boolean | null | void + ) => boolean | null | undefined | void ): void; /** * Concatenates all the text nodes found in this fragment and its @@ -612,7 +612,7 @@ declare class ProsemirrorNode { /** * Find the node starting at the given position. */ - nodeAt(pos: number): ProsemirrorNode | null | void; + nodeAt(pos: number): ProsemirrorNode | null | undefined; /** * Find the (direct) child node after the given offset, if any, * and return it along with its index and offset relative to this @@ -769,7 +769,7 @@ export class Slice { /** * Convert a slice to a JSON-serializable representation. */ - toJSON(): { [key: string]: any } | null | void; + toJSON(): { [key: string]: any } | null | undefined; /** * Deserialize a slice from its JSON representation. */ @@ -892,7 +892,7 @@ export class ResolvedPos { * its parent node or its parent node isn't a textblock (in which * case no marks should be preserved). */ - marksAcross($end: ResolvedPos): Array> | null | void; + marksAcross($end: ResolvedPos): Array> | null | undefined; /** * The depth up to which this position and the given (non-resolved) * position share the same parent nodes. @@ -910,7 +910,7 @@ export class ResolvedPos { blockRange( other?: ResolvedPos, pred?: (p: ProsemirrorNode) => boolean - ): NodeRange | null | void; + ): NodeRange | null | undefined; /** * Query whether the given position shares the same parent node. */ @@ -1061,7 +1061,7 @@ export class NodeType { attrs?: { [key: string]: any }, content?: Fragment | ProsemirrorNode | Array>, marks?: Array> - ): ProsemirrorNode | null | void; + ): ProsemirrorNode | null | undefined; /** * Returns true if the given fragment is valid content for this node * type with the given attributes. @@ -1113,7 +1113,7 @@ export class MarkType { /** * Tests whether there is a mark of this type in the given set. */ - isInSet(set: Array>): Mark | null | void; + isInSet(set: Array>): Mark | null | undefined; /** * Queries whether a given mark type is * [excluded](#model.MarkSpec.excludes) by this one. diff --git a/types/prosemirror-model/prosemirror-model-tests.ts b/types/prosemirror-model/prosemirror-model-tests.ts index 98460d4313..b9041597e7 100644 --- a/types/prosemirror-model/prosemirror-model-tests.ts +++ b/types/prosemirror-model/prosemirror-model-tests.ts @@ -37,6 +37,48 @@ export const nodeSpec: model.NodeSpec = { } }; -const node = new model.Node(); -node.nodesBetween(0, 1, () => {}); -node.descendants(() => {}); +// Verify that non-null assertion operator can be used. + +const res1_1 = new model.Node(); +res1_1.nodesBetween(0, 1, () => {}); +res1_1.nodesBetween(0, 1, () => null); +res1_1.nodesBetween(0, 1, () => undefined); +res1_1.nodesBetween(0, 1, () => true); +res1_1.descendants(() => {}); +res1_1.descendants(() => null); +res1_1.descendants(() => undefined); +res1_1.descendants(() => true); +const res1_2: model.Node = res1_1.maybeChild(0)!; +const res1_3: model.Node = res1_1.nodeAt(0)!; + +const cm1 = new model.ContentMatch(); +const cm2: model.ContentMatch = cm1.matchType({} as any)!; +const cm3: model.ContentMatch = cm1.matchFragment({} as any)!; +const cm4: model.Fragment = cm1.fillBefore({} as any)!; +const cm5: model.NodeType[] = cm1.findWrapping({} as any)!; + +const f1 = new model.Fragment(); +f1.nodesBetween(0, 0, () => {}); +f1.nodesBetween(0, 0, () => null); +f1.nodesBetween(0, 0, () => undefined); +f1.nodesBetween(0, 0, () => true); + +f1.descendants(() => {}); +f1.descendants(() => null); +f1.descendants(() => undefined); +f1.descendants(() => true); + +const res2_1: model.Node = f1.maybeChild(0)!; +const res2_2: number = f1.findDiffStart(f1)!; +const res2_3: { a: number, b: number } = f1.findDiffEnd({} as any)!; +const res2_4: object = f1.toJSON()!; + +const res3_1 = new model.ResolvedPos(); +const res3_2: model.Mark[] = res3_1.marksAcross(res3_1)!; +const res3_3: model.NodeRange = res3_1.blockRange(res3_1)!; + +const res4_1 = new model.NodeType(); +const res4_2: model.Node = res4_1.createAndFill()!; + +const res5_1 = new model.MarkType(); +const res5_2: model.Mark = res5_1.isInSet([])!; diff --git a/types/prosemirror-state/index.d.ts b/types/prosemirror-state/index.d.ts index 6b210a73e1..db5a16e9d3 100644 --- a/types/prosemirror-state/index.d.ts +++ b/types/prosemirror-state/index.d.ts @@ -74,7 +74,7 @@ export interface PluginSpec { transactions: Transaction[], oldState: EditorState, newState: EditorState - ) => Transaction | null | void) + ) => Transaction | null | undefined | void) | null; } /** @@ -147,11 +147,11 @@ export class PluginKey { * Get the active plugin with this key, if any, from an editor * state. */ - get(state: EditorState): Plugin | null | void; + get(state: EditorState): Plugin | null | undefined; /** * Get the plugin's state from an editor state. */ - getState(state: EditorState): any | null | void; + getState(state: EditorState): any | null | undefined; } /** * Superclass for editor selections. Every selection type should @@ -263,7 +263,7 @@ export class Selection { $pos: ResolvedPos, dir: number, textOnly?: boolean - ): Selection | null | void; + ): Selection | null | undefined; /** * Find a valid cursor or leaf node selection near the given * position. Searches forward first by default, but if `bias` is diff --git a/types/prosemirror-state/prosemirror-state-tests.ts b/types/prosemirror-state/prosemirror-state-tests.ts index 0c1cddc24e..1668b844af 100644 --- a/types/prosemirror-state/prosemirror-state-tests.ts +++ b/types/prosemirror-state/prosemirror-state-tests.ts @@ -40,3 +40,15 @@ transaction = transaction.setNodeMarkup(0); transaction = transaction.split(0); transaction = transaction.join(0); transaction = transaction.step(step); + +const res1_1: state.PluginSpec["appendTransaction"] = null; +const res1_2: state.PluginSpec["appendTransaction"] = () => {}; +const res1_3: state.PluginSpec["appendTransaction"] = () => null; +const res1_4: state.PluginSpec["appendTransaction"] = () => undefined; +const res1_5: state.PluginSpec["appendTransaction"] = () => ({} as state.Transaction); + +const res2_1 = new state.PluginKey(); +const res2_2: state.Plugin = res2_1.get({} as state.EditorState)!; + +const res3_1 = new state.Selection({} as any, {} as any); +const res3_2: state.Selection = state.Selection.findFrom({} as model.ResolvedPos, 0)!; diff --git a/types/prosemirror-transform/index.d.ts b/types/prosemirror-transform/index.d.ts index c0b63136f4..e74fd9c094 100644 --- a/types/prosemirror-transform/index.d.ts +++ b/types/prosemirror-transform/index.d.ts @@ -403,7 +403,7 @@ export function replaceStep( from: number, to?: number, slice?: Slice -): Step | null | void; +): Step | null | undefined; /** * A step object represents an atomic change. It generally applies * only to the document it was created for, since the positions @@ -439,13 +439,13 @@ export class Step { * version of that step with its positions adjusted, or `null` if * the step was entirely deleted by the mapping. */ - map(mapping: Mappable): Step | null | void; + map(mapping: Mappable): Step | null | undefined; /** * Try to merge this step with another one, to be applied directly * after it. Returns the merged step when possible, null if the * steps can't be merged. */ - merge(other: Step): Step | null | void; + merge(other: Step): Step | null | undefined; /** * Create a JSON-serializeable representation of this step. When * defining this for a custom subclass, make sure the result object @@ -504,7 +504,7 @@ export class StepResult { * can be lifted. Will not go across * [isolating](#model.NodeSpec.isolating) parent nodes. */ -export function liftTarget(range: NodeRange): number | null | void; +export function liftTarget(range: NodeRange): number | null | undefined; /** * Try to find a valid way to wrap the content in the given range in a * node of the given type. May introduce extra nodes around and inside @@ -515,7 +515,7 @@ export function findWrapping( range: NodeRange, nodeType: NodeType, attrs?: { [key: string]: any } -): Array<{ type: NodeType; attrs?: { [key: string]: any } | null }> | null | void; +): Array<{ type: NodeType; attrs?: { [key: string]: any } | null }> | null | undefined; /** * Check whether splitting at the given position is allowed. */ @@ -535,7 +535,7 @@ export function canJoin(doc: ProsemirrorNode, pos: number): boolean; * block before (or after if `dir` is positive). Returns the joinable * point, if any. */ -export function joinPoint(doc: ProsemirrorNode, pos: number, dir?: number): number | null | void; +export function joinPoint(doc: ProsemirrorNode, pos: number, dir?: number): number | null | undefined; /** * Try to find a point where a node of the given type can be inserted * near `pos`, by searching up the node hierarchy when `pos` itself @@ -546,4 +546,4 @@ export function insertPoint( doc: ProsemirrorNode, pos: number, nodeType: NodeType -): number | null | void; +): number | null | undefined; diff --git a/types/prosemirror-transform/prosemirror-transform-tests.ts b/types/prosemirror-transform/prosemirror-transform-tests.ts index c3a18ef916..a61108a2a9 100644 --- a/types/prosemirror-transform/prosemirror-transform-tests.ts +++ b/types/prosemirror-transform/prosemirror-transform-tests.ts @@ -1,3 +1,17 @@ import * as transform from 'prosemirror-transform'; const stepmap = new transform.StepMap([]); + +// Verify non-null assertion operator can be used. + +const res1_1: transform.Step = transform.replaceStep({} as any, 0)!; +const res1_2: transform.Step = res1_1.map({} as any)!; +const res1_3: transform.Step = res1_1.merge({} as any)!; + +const res2_1: number = transform.liftTarget({} as any)!; + +const res3_1: any[] = transform.findWrapping({} as any, {} as any)!; + +const res4_1: number = transform.joinPoint({} as any, 0)!; + +const res5_1: number = transform.insertPoint({} as any, 0, {} as any)!; diff --git a/types/prosemirror-view/index.d.ts b/types/prosemirror-view/index.d.ts index f24a5270d1..dba4fb8aec 100644 --- a/types/prosemirror-view/index.d.ts +++ b/types/prosemirror-view/index.d.ts @@ -237,7 +237,7 @@ export class EditorView { posAtCoords(coords: { left: number; top: number; - }): { pos: number; inside: number } | null | void; + }): { pos: number; inside: number } | null | undefined; /** * Returns the viewport rectangle at a given document position. `left` * and `right` will be the same number, as this returns a flat @@ -404,7 +404,7 @@ export interface EditorProps { view: EditorView, anchor: ResolvedPos, head: ResolvedPos - ) => Selection | null | void) + ) => Selection | null | undefined) | null; /** * The [parser](#model.DOMParser) to use when reading editor changes @@ -482,7 +482,7 @@ export interface EditorProps { * A set of [document decorations](#view.Decoration) to show in the * view. */ - decorations?: ((state: EditorState) => DecorationSet | null | void) | null; + decorations?: ((state: EditorState) => DecorationSet | null | undefined) | null; /** * When this returns false, the content of the view is not directly * editable. @@ -500,7 +500,7 @@ export interface EditorProps { */ attributes?: | { [name: string]: string } - | ((p: EditorState) => { [name: string]: string } | null | void) + | ((p: EditorState) => { [name: string]: string } | null | undefined | void) | null; /** * Determines the distance (in pixels) between the cursor and the diff --git a/types/prosemirror-view/prosemirror-view-tests.ts b/types/prosemirror-view/prosemirror-view-tests.ts index fd6c0538eb..a3e76946b8 100644 --- a/types/prosemirror-view/prosemirror-view-tests.ts +++ b/types/prosemirror-view/prosemirror-view-tests.ts @@ -1,3 +1,15 @@ import * as view from 'prosemirror-view'; +import * as state from 'prosemirror-state'; const decoration = new view.Decoration(); + +const res1_1 = new view.EditorView({} as any, {} as any); +const res1_2: { pos: number, inside: number } = res1_1.posAtCoords({ left: 0, top: 0})!; + +const res2_1: view.EditorProps = {} as any; +const res2_2: state.Selection = res2_1.createSelectionBetween!({} as any, {} as any, {} as any)!; +const res2_3: view.DecorationSet = res2_1.decorations!({} as any)!; + +const res3_1: view.EditorProps["attributes"] = () => {}; +const res3_2: view.EditorProps["attributes"] = () => null; +const res3_3: view.EditorProps["attributes"] = () => undefined; diff --git a/types/puppeteer/index.d.ts b/types/puppeteer/index.d.ts index 899a24eef6..54ef9b722a 100644 --- a/types/puppeteer/index.d.ts +++ b/types/puppeteer/index.d.ts @@ -1,4 +1,4 @@ -// Type definitions for puppeteer 1.2 +// Type definitions for puppeteer 1.3 // Project: https://github.com/GoogleChrome/puppeteer#readme // Definitions by: Marvin Hagemeister // Christopher Deutsch @@ -94,7 +94,7 @@ export interface Touchscreen { */ export interface Tracing { start(options: TracingStartOptions): Promise; - stop(): Promise; + stop(): Promise; } export interface TracingStartOptions { @@ -136,6 +136,7 @@ export interface ConsoleMessage { } export type PageEvents = + | "close" | "console" | "dialog" | "error" @@ -430,6 +431,24 @@ export interface BoundingBox { height: number; } +export interface BoxModel { + /** Content box, represented as an array of {x, y} points. */ + content: Box[]; + /** Padding box, represented as an array of {x, y} points. */ + padding: Box[]; + /** Border box, represented as an array of {x, y} points. */ + border: Box[]; + /** Margin box, represented as an array of {x, y} points. */ + margin: Box[]; + width: number; + height: number; +} + +export interface Box { + x: number; + y: number; +} + /** * Represents an in-page DOM element. ElementHandles can be created with the page.$ method. */ @@ -454,6 +473,11 @@ export interface ElementHandle extends JSHandle { * This method returns the value resolve to the bounding box of the element (relative to the main frame), or null if the element is not visible. */ boundingBox(): Promise; + /** + * This method returns boxes of the element, or null if the element is not visible. + * Boxes are represented as an array of points; each Point is an object {x, y}. Box points are sorted clock-wise. + */ + boxModel(): Promise; /** * This method scrolls element into view if needed, and then uses page.mouse to click in the center of the element. * If the element is detached from DOM, the method throws an error. @@ -780,6 +804,15 @@ export interface FrameBase { /** Adds a `` tag into the page with the desired url or a `