From ed76f54ebda70c0ebe7d0eeba4f479b596154732 Mon Sep 17 00:00:00 2001 From: Ian Phillips Date: Tue, 20 Jun 2017 09:58:18 -0700 Subject: [PATCH 001/828] Add Backbone.Collection.clone() http://backbonejs.org/#Collection-clone --- types/backbone/index.d.ts | 1 + 1 file changed, 1 insertion(+) diff --git a/types/backbone/index.d.ts b/types/backbone/index.d.ts index f151b2f42e..e2abd94568 100644 --- a/types/backbone/index.d.ts +++ b/types/backbone/index.d.ts @@ -229,6 +229,7 @@ declare namespace Backbone { **/ get(id: number|string|Model): TModel; has(key: number|string|Model): boolean; + clone(): Collection; create(attributes: any, options?: ModelSaveOptions): TModel; pluck(attribute: string): any[]; push(model: TModel, options?: AddOptions): TModel; From 374d649fde3bcd95d90f0983589e29af4cf08a9a Mon Sep 17 00:00:00 2001 From: Daniel Lebrecht Date: Wed, 23 Aug 2017 16:38:35 +0200 Subject: [PATCH 002/828] added inputs to transaction builder --- types/bitcoinjs-lib/index.d.ts | 8 ++++++++ 1 file changed, 8 insertions(+) diff --git a/types/bitcoinjs-lib/index.d.ts b/types/bitcoinjs-lib/index.d.ts index 986bb75e0b..20e7162ecf 100644 --- a/types/bitcoinjs-lib/index.d.ts +++ b/types/bitcoinjs-lib/index.d.ts @@ -206,6 +206,14 @@ export class Transaction { export class TransactionBuilder { constructor(network?: Network, maximumFeeRate?: number); + inputs: Array<{ pubKeys: Buffer[], + signatures: ECSignature[], + prevOutScript: Buffer, + prevOutType: string, + signType: string, + signScript: Buffer, + witness: boolean} >; + addInput(txhash: Buffer | string | Transaction, vout: number, sequence?: number, prevOutScript?: Buffer): number; addOutput(scriptPubKey: Buffer, value: number): number; From 52d0fb07b21c20ec437665c3cfbea89cbe6f9029 Mon Sep 17 00:00:00 2001 From: voxmatt Date: Sun, 3 Sep 2017 12:38:18 -0700 Subject: [PATCH 003/828] adding types for relay-runtime --- types/relay-runtime/index.d.ts | 1102 +++++++++++++++++++++++++++++ types/relay-runtime/tsconfig.json | 26 + 2 files changed, 1128 insertions(+) create mode 100644 types/relay-runtime/index.d.ts create mode 100644 types/relay-runtime/tsconfig.json diff --git a/types/relay-runtime/index.d.ts b/types/relay-runtime/index.d.ts new file mode 100644 index 0000000000..7e57ef036b --- /dev/null +++ b/types/relay-runtime/index.d.ts @@ -0,0 +1,1102 @@ +/// + +declare namespace __Relay.Common { + /** + * SOURCE: + * Relay 1.3.0 + * https://github.com/facebook/relay/blob/b85a1d69bb72be4ace67179f55c2a54a8d761c8b/packages/react-relay/classic/environment/RelayCombinedEnvironmentTypes.js + */ + // ~~~~~~~~~~~~~~~~~~~~~ + // Util + // ~~~~~~~~~~~~~~~~~~~~~ + type Maybe = T | void; + + // ~~~~~~~~~~~~~~~~~~~~~ + // Maybe Fix + // ~~~~~~~~~~~~~~~~~~~~~ + type RelayConcreteNode = any; + type RelayMutationTransaction = any; + type RelayMutationRequest = any; + type RelayQueryRequest = any; + type ConcreteFragment = any; + type ConcreteBatch = any; + type ConcreteFragmentDefinition = Object; + type ConcreteOperationDefinition = Object; + + /** + * FIXME: RelayContainer used to be typed with ReactClass, but + * ReactClass is broken and allows for access to any property. For example + * ReactClass.getFragment('foo') is valid even though ReactClass has no + * such getFragment() type definition. When ReactClass is fixed this causes a + * lot of errors in Relay code since methods like getFragment() are used often + * but have no definition in Relay's types. Suppressing for now. + */ + export type RelayContainer = any; + // ~~~~~~~~~~~~~~~~~~~~~ + // RelayQL + // ~~~~~~~~~~~~~~~~~~~~~ + type RelayQL = ( + strings: Array, + ...substitutions: Array + ) => Common.RelayConcreteNode; + + // ~~~~~~~~~~~~~~~~~~~~~ + // RelayModernGraphQLTag + // ~~~~~~~~~~~~~~~~~~~~~ + type GeneratedNodeMap = {[key: string]: GraphQLTaggedNode}; + type GraphQLTaggedNode = + (() => ConcreteFragment | ConcreteBatch) | + { + modern: () => ConcreteFragment | ConcreteBatch, + classic: (relayQL: RelayQL) => + | ConcreteFragmentDefinition + | ConcreteOperationDefinition, + }; + // ~~~~~~~~~~~~~~~~~~~~~ + // General Usage + // ~~~~~~~~~~~~~~~~~~~~~ + export type DataID = string; + export type Variables = {[name: string]: any}; + export type Uploadable = File | Blob; + export type UploadableMap = {[key: string]: Uploadable}; + + + // ~~~~~~~~~~~~~~~~~~~~~ + // RelayNetworkTypes + // Version: Relay 1.3.0 + // File: https://github.com/facebook/relay/blob/master/packages/relay-runtime/network/RelayNetworkTypes.js + // ~~~~~~~~~~~~~~~~~~~~~ + + export type LegacyObserver = { + onCompleted?: (() => void) | void, + onError?: ((error: Error) => void) | void, + onNext?: ((data: T) => void) | void, + }; + export type PayloadError = { + message: string, + locations?: Array<{ + line: number, + column: number, + }>, + }; + + + // ~~~~~~~~~~~~~~~~~~~~~ + // RelayStoreTypes + // Version: Relay 1.3.0 + // File: https://github.com/facebook/relay/blob/master/packages/relay-runtime/store/RelayStoreTypes.js + // ~~~~~~~~~~~~~~~~~~~~~ + /** + * A function that receives a proxy over the store and may trigger side-effects + * (indirectly) by calling `set*` methods on the store or its record proxies. + */ + export type StoreUpdater = (store: RecordSourceProxy) => void; + + /** + * Similar to StoreUpdater, but accepts a proxy tied to a specific selector in + * order to easily access the root fields of a query/mutation as well as a + * second argument of the response object of the mutation. + */ + export type SelectorStoreUpdater = ( + store: RecordSourceSelectorProxy, + // Actually RelayCombinedEnvironmentTypes#SelectorData, but mixed is + // inconvenient to access deeply in product code. + data: any, // FLOW FIXME + ) => void; + + /** + * Extends the RecordSourceProxy interface with methods for accessing the root + * fields of a Selector. + */ + export interface RecordSourceSelectorProxy { + create(dataID: DataID, typeName: string): RecordProxy, + delete(dataID: DataID): void, + get(dataID: DataID): RecordProxy | void, + getRoot(): RecordProxy, + getRootField(fieldName: string): RecordProxy | void, + getPluralRootField(fieldName: string): RecordProxy[] | void, + } + + export interface RecordProxy { + copyFieldsFrom(source: RecordProxy): void, + getDataID(): DataID, + getLinkedRecord(name: string, args?: Variables | void): RecordProxy | void, + getLinkedRecords(name: string, args?: Variables | void): (RecordProxy | void)[] | void, + getOrCreateLinkedRecord( + name: string, + typeName: string, + args?: Variables | void, + ): RecordProxy, + getType(): string, + getValue(name: string, args?: Variables | void): any, + setLinkedRecord( + record: RecordProxy, + name: string, + args?: Variables | void, + ): RecordProxy, + setLinkedRecords( + records: (RecordProxy | void)[] | void, + name: string, + args?: Variables | void, + ): RecordProxy, + setValue(value: any, name: string, args?: Variables | void): RecordProxy, + } + + export interface RecordSourceProxy { + create(dataID: DataID, typeName: string): RecordProxy, + delete(dataID: DataID): void, + get(dataID: DataID): (RecordProxy | void)[] | void, + getRoot(): RecordProxy, + } + + export type HandleFieldPayload = { + // The arguments that were fetched. + args: Variables, + // The __id of the record containing the source/handle field. + dataID: DataID, + // The (storage) key at which the original server data was written. + fieldKey: string, + // The name of the handle. + handle: string, + // The (storage) key at which the handle's data should be written by the + // handler. + handleKey: string, + }; + + export type Handler = { + update: (store: RecordSourceProxy, fieldPayload: HandleFieldPayload) => void, + }; + + + // ~~~~~~~~~~~~~~~~~~~~~ + // RelayCombinedEnvironmentTypes + // Version: Relay 1.3.0 + // File: https://github.com/facebook/relay/blob/b85a1d69bb72be4ace67179f55c2a54a8d761c8b/packages/react-relay/classic/environment/RelayCombinedEnvironmentTypes.js + // ~~~~~~~~~~~~~~~~~~~~~ + /** + * Settings for how a query response may be cached. + * + * - `force`: causes a query to be issued unconditionally, irrespective of the + * state of any configured response cache. + * - `poll`: causes a query to live update by polling at the specified interval + in milliseconds. (This value will be passed to setTimeout.) + */ + export type CacheConfig = { + force?: boolean | void, + poll?: number | void, + }; + + /** + * Represents any resource that must be explicitly disposed of. The most common + * use-case is as a return value for subscriptions, where calling `dispose()` + * would cancel the subscription. + */ + export type Disposable = { + dispose(): void, + }; + + + /** + * Arbitrary data e.g. received by a container as props. + */ + export type Props = {[key: string]: any}; + + /* + * An individual cached graph object. + */ + export type Record = {[key: string]: any}; + + /** + * A collection of records keyed by id. + */ + export type RecordMap = {[dataID: string]: Record | void}; + + /** + * A selector defines the starting point for a traversal into the graph for the + * purposes of targeting a subgraph. + */ + export type CSelector = { + dataID: DataID, + node: TNode, + variables: Variables, + }; + + /** + * A representation of a selector and its results at a particular point in time. + */ + export type CSnapshot = CSelector & { + data: SelectorData | void, + seenRecords: RecordMap, + }; + + /** + * The results of a selector given a store/RecordSource. + */ + export type SelectorData = {[key: string]: any}; + + /** + * The results of reading the results of a FragmentMap given some input + * `Props`. + */ + export type FragmentSpecResults = {[key: string]: any}; + + /** + * A utility for resolving and subscribing to the results of a fragment spec + * (key -> fragment mapping) given some "props" that determine the root ID + * and variables to use when reading each fragment. When props are changed via + * `setProps()`, the resolver will update its results and subscriptions + * accordingly. Internally, the resolver: + * - Converts the fragment map & props map into a map of `Selector`s. + * - Removes any resolvers for any props that became null. + * - Creates resolvers for any props that became non-null. + * - Updates resolvers with the latest props. + */ + export interface FragmentSpecResolver { + /** + * Stop watching for changes to the results of the fragments. + */ + dispose(): void, + + /** + * Get the current results. + */ + resolve(): FragmentSpecResults, + + /** + * Update the resolver with new inputs. Call `resolve()` to get the updated + * results. + */ + setProps(props: Props): void, + + /** + * Override the variables used to read the results of the fragments. Call + * `resolve()` to get the updated results. + */ + setVariables(variables: Variables): void, + } + + export type CFragmentMap = {[key: string]: TFragment}; + + /** + * An operation selector describes a specific instance of a GraphQL operation + * with variables applied. + * + * - `root`: a selector intended for processing server results or retaining + * response data in the store. + * - `fragment`: a selector intended for use in reading or subscribing to + * the results of the the operation. + */ + export type COperationSelector = { + fragment: CSelector, + node: TOperation, + root: CSelector, + variables: Variables, + }; + + /** + * The public API of Relay core. Represents an encapsulated environment with its + * own in-memory cache. + */ + export interface CEnvironment< + TEnvironment, + TFragment, + TGraphQLTaggedNode, + TNode, + TOperation, + TPayload, + > { + /** + * Read the results of a selector from in-memory records in the store. + */ + lookup(selector: CSelector): CSnapshot, + + /** + * Subscribe to changes to the results of a selector. The callback is called + * when data has been committed to the store that would cause the results of + * the snapshot's selector to change. + */ + subscribe( + snapshot: CSnapshot, + callback: (snapshot: CSnapshot) => void, + ): Disposable, + + /** + * Ensure that all the records necessary to fulfill the given selector are + * retained in-memory. The records will not be eligible for garbage collection + * until the returned reference is disposed. + * + * Note: This is a no-op in the classic core. + */ + retain(selector: CSelector): Disposable, + + /** + * Send a query to the server with request/response semantics: the query will + * either complete successfully (calling `onNext` and `onCompleted`) or fail + * (calling `onError`). + * + * Note: Most applications should use `streamQuery` in order to + * optionally receive updated information over time, should that feature be + * supported by the network/server. A good rule of thumb is to use this method + * if you would otherwise immediately dispose the `streamQuery()` + * after receving the first `onNext` result. + */ + sendQuery(config: { + cacheConfig?: CacheConfig | void, + onCompleted?: Maybe<() => void>, + onError?: Maybe<(error: Error) => void>, + onNext?: Maybe<(payload: TPayload) => void>, + operation: COperationSelector, + }): Disposable, + + /** + * Send a query to the server with request/subscription semantics: one or more + * responses may be returned (via `onNext`) over time followed by either + * the request completing (`onCompleted`) or an error (`onError`). + * + * Networks/servers that support subscriptions may choose to hold the + * subscription open indefinitely such that `onCompleted` is not called. + */ + streamQuery(config: { + cacheConfig?: Maybe, + onCompleted?: Maybe<() => void>, + onError?: Maybe<(error: Error) => void>, + onNext?: Maybe<(payload: TPayload) => void>, + operation: COperationSelector, + }): Disposable, + + unstable_internal: CUnstableEnvironmentCore< + TEnvironment, + TFragment, + TGraphQLTaggedNode, + TNode, + TOperation + >, + } + + export interface CUnstableEnvironmentCore< + TEnvironment, + TFragment, + TGraphQLTaggedNode, + TNode, + TOperation, + > { + /** + * Create an instance of a FragmentSpecResolver. + * + * TODO: The FragmentSpecResolver *can* be implemented via the other methods + * defined here, so this could be moved out of core. It's convenient to have + * separate implementations until the experimental core is in OSS. + */ + createFragmentSpecResolver: ( + context: CRelayContext, + containerName: string, + fragments: CFragmentMap, + props: Props, + callback: () => void, + ) => FragmentSpecResolver, + + /** + * Creates an instance of an OperationSelector given an operation definition + * (see `getOperation`) and the variables to apply. The input variables are + * filtered to exclude variables that do not matche defined arguments on the + * operation, and default values are populated for null values. + */ + createOperationSelector: ( + operation: TOperation, + variables: Variables, + ) => COperationSelector, + + /** + * Given a graphql`...` tagged template, extract a fragment definition usable + * by this version of Relay core. Throws if the value is not a fragment. + */ + getFragment: (node: TGraphQLTaggedNode) => TFragment, + + /** + * Given a graphql`...` tagged template, extract an operation definition + * usable by this version of Relay core. Throws if the value is not an + * operation. + */ + getOperation: (node: TGraphQLTaggedNode) => TOperation, + + /** + * Determine if two selectors are equal (represent the same selection). Note + * that this function returns `false` when the two queries/fragments are + * different objects, even if they select the same fields. + */ + areEqualSelectors: (a: CSelector, b: CSelector) => boolean, + + /** + * Given the result `item` from a parent that fetched `fragment`, creates a + * selector that can be used to read the results of that fragment for that item. + * + * Example: + * + * Given two fragments as follows: + * + * ``` + * fragment Parent on User { + * id + * ...Child + * } + * fragment Child on User { + * name + * } + * ``` + * + * And given some object `parent` that is the results of `Parent` for id "4", + * the results of `Child` can be accessed by first getting a selector and then + * using that selector to `lookup()` the results against the environment: + * + * ``` + * const childSelector = getSelector(queryVariables, Child, parent); + * const childData = environment.lookup(childSelector).data; + * ``` + */ + getSelector: ( + operationVariables: Variables, + fragment: TFragment, + prop: any, + ) => CSelector | void, + + /** + * Given the result `items` from a parent that fetched `fragment`, creates a + * selector that can be used to read the results of that fragment on those + * items. This is similar to `getSelector` but for "plural" fragments that + * expect an array of results and therefore return an array of selectors. + */ + getSelectorList: ( + operationVariables: Variables, + fragment: TFragment, + props: Array, + ) => Array> | void, + + /** + * Given a mapping of keys -> results and a mapping of keys -> fragments, + * extracts the selectors for those fragments from the results. + * + * The canonical use-case for this function are Relay Containers, which + * use this function to convert (props, fragments) into selectors so that they + * can read the results to pass to the inner component. + */ + getSelectorsFromObject: ( + operationVariables: Variables, + fragments: CFragmentMap, + props: Props, + ) => {[key: string]: Maybe<(CSelector | Array>)>}, + + /** + * Given a mapping of keys -> results and a mapping of keys -> fragments, + * extracts a mapping of keys -> id(s) of the results. + * + * Similar to `getSelectorsFromObject()`, this function can be useful in + * determining the "identity" of the props passed to a component. + */ + getDataIDsFromObject: ( + fragments: CFragmentMap, + props: Props, + ) => {[key: string]: Maybe<(DataID | Array)>}, + + /** + * Given a mapping of keys -> results and a mapping of keys -> fragments, + * extracts the merged variables that would be in scope for those + * fragments/results. + * + * This can be useful in determing what varaibles were used to fetch the data + * for a Relay container, for example. + */ + getVariablesFromObject: ( + operationVariables: Variables, + fragments: CFragmentMap, + props: Props, + ) => Variables, + } + + /** + * The type of the `relay` property set on React context by the React/Relay + * integration layer (e.g. QueryRenderer, FragmentContainer, etc). + */ + export type CRelayContext = { + environment: TEnvironment, + variables: Variables, + }; + + + // ~~~~~~~~~~~~~~~~~~~~~ + // RelayTypes + /** + * Version: Relay 1.3.0 + * File: + * https://github.com/facebook/relay/blob/fa9f48ea209ee2402d433b59a84d1cbc046574e2/packages/react-relay/classic/tools/RelayTypes.js + */ + // ~~~~~~~~~~~~~~~~~~~~~ + export type RerunParam = { + param: string, + import: string, + max_runs: number, + }; + + export type RelayMutationConfig = + | { + type: 'FIELDS_CHANGE', + fieldIDs: {[fieldName: string]: DataID | Array}, + } + | { + type: 'RANGE_ADD', + parentName?: string, + parentID?: string, + connectionInfo?: Array<{ + key: string, + filters?: Variables, + rangeBehavior: string, + }>, + connectionName?: string, + edgeName: string, + rangeBehaviors?: RangeBehaviors, + } + | { + type: 'NODE_DELETE', + parentName?: string, + parentID?: string, + connectionName?: string, + deletedIDFieldName: string, + } + | { + type: 'RANGE_DELETE', + parentName?: string, + parentID?: string, + connectionKeys?: Array<{ + key: string, + filters?: Variables, + }>, + connectionName?: string, + deletedIDFieldName: string | Array, + pathToConnection: Array, + } + | { + type: 'REQUIRED_CHILDREN', + children: Array, + }; + + export type RelayMutationTransactionCommitCallbacks = { + onFailure?: RelayMutationTransactionCommitFailureCallback, + onSuccess?: RelayMutationTransactionCommitSuccessCallback, + }; + export type RelayMutationTransactionCommitFailureCallback = ( + transaction: RelayMutationTransaction, + preventAutoRollback: () => void, + ) => void; + export type RelayMutationTransactionCommitSuccessCallback = (response: { + [key: string]: Object, + }) => void; + export type NetworkLayer = { + sendMutation(request: RelayMutationRequest): Promise | void, + sendQueries(requests: Array): Promise | void, + supports(...options: Array): boolean, + }; + export type QueryResult = { + error?: Error | void, + ref_params?: {[name: string]: any} | void, + response: QueryPayload, + }; + export type ReadyState = { + aborted: boolean, + done: boolean, + error: Error | void, + events: Array, + ready: boolean, + stale: boolean, + }; + type RelayContainerErrorEventType = + | 'CACHE_RESTORE_FAILED' + | 'NETWORK_QUERY_ERROR'; + type RelayContainerLoadingEventType = + | 'ABORT' + | 'CACHE_RESTORED_REQUIRED' + | 'CACHE_RESTORE_START' + | 'NETWORK_QUERY_RECEIVED_ALL' + | 'NETWORK_QUERY_RECEIVED_REQUIRED' + | 'NETWORK_QUERY_START' + | 'STORE_FOUND_ALL' + | 'STORE_FOUND_REQUIRED'; + export type ReadyStateChangeCallback = (readyState: ReadyState) => void; + export type ReadyStateEvent = { + type: RelayContainerLoadingEventType | RelayContainerErrorEventType, + error?: Error, + }; + export type Abortable = { + abort(): void, + }; + + + // ~~~~~~~~~~~~~~~~~~~~~ + // RelayInternalTypes + /** + * Version: Relay 1.3.0 + * File: + * https://github.com/facebook/relay/blob/master/packages/react-relay/classic/tools/RelayInternalTypes.js + */ + // ~~~~~~~~~~~~~~~~~~~~~ + export type QueryPayload = {[key: string]: any}; + export type RelayQuerySet = {[queryName: string]: any}; + type RangeBehaviorsFunction = (connectionArgs: { + [argName: string]: any, + }) => 'APPEND' | 'IGNORE' | 'PREPEND' | 'REFETCH' | 'REMOVE'; + type RangeBehaviorsObject = { + [key: string]: 'APPEND' | 'IGNORE' | 'PREPEND' | 'REFETCH' | 'REMOVE'; + }; + export type RangeBehaviors = RangeBehaviorsFunction | RangeBehaviorsObject; + } + + + + +declare namespace __Relay.Runtime { + // ~~~~~~~~~~~~~~~~~~~~~ + // Maybe Fix + // ~~~~~~~~~~~~~~~~~~~~~ + type RelayDebugger = any; + type OptimisticUpdate = any; + type OperationSelector = Common.COperationSelector; + type Selector = Common.CSelector; + type PayloadData = any; + type Snapshot = Common.CSnapshot; + type RelayResponsePayload = any; + type MutableRecordSource = RecordSource; + + /** + * A function that returns an Observable representing the response of executing + * a GraphQL operation. + */ + type ExecuteFunction = ( + operation: Object, + variables: Common.Variables, + cacheConfig: Common.CacheConfig, + uploadables?: Common.UploadableMap | void, + ) => Promise; + type RelayNetwork = { + execute: ExecuteFunction, + }; + + // ~~~~~~~~~~~~~~~~~~~~~ + // RelayDefaultHandlerProvider + // ~~~~~~~~~~~~~~~~~~~~~ + type HandlerProvider = (name: string) => Common.Handler | void; + + // ~~~~~~~~~~~~~~~~~~~~~ + // RelayModernEnvironment + // ~~~~~~~~~~~~~~~~~~~~~ + type EnvironmentConfig = { + configName?: string, + handlerProvider?: HandlerProvider, + network: Network, + store: Store, + }; + class Environment { + constructor (config: EnvironmentConfig); + getStore(): Store; + getDebugger(): RelayDebugger; + applyUpdate(optimisticUpdate: OptimisticUpdate): Common.Disposable; + revertUpdate(update: OptimisticUpdate): void; + replaceUpdate(update: OptimisticUpdate, newUpdate: OptimisticUpdate): void; + applyMutation(config: { + operation: OperationSelector, + optimisticUpdater?: Common.SelectorStoreUpdater, + optimisticResponse?: Object, + }): Common.Disposable; + check(readSelector: Selector): boolean; + commitPayload( + operationSelector: OperationSelector, + payload: PayloadData, + ): void; + commitUpdate(updater: Common.StoreUpdater): void; + lookup(readSelector: Selector): Snapshot; + subscribe( + snapshot: Snapshot, + callback: (snapshot: Snapshot) => void, + ): Common.Disposable; + retain(selector: Selector): Common.Disposable; + execute(config: { + operation: OperationSelector, + cacheConfig?: Common.CacheConfig | void, + updater?: Common.SelectorStoreUpdater | void, + }): RelayObservable; + executeMutation(config: { + operation: OperationSelector, + optimisticUpdater?: Common.SelectorStoreUpdater | void, + optimisticResponse?: Object | void, + updater?: Common.SelectorStoreUpdater | void, + uploadables?: Common.UploadableMap | void, + }): RelayObservable; + } + + // ~~~~~~~~~~~~~~~~~~~~~ + // RelayInMemoryRecordSource + // ~~~~~~~~~~~~~~~~~~~~~ + type Record = {[key: string]: any}; + type RecordMap = {[dataID: string]: Record | void}; + + // ~~~~~~~~~~~~~~~~~~~~~ + // Network + // ~~~~~~~~~~~~~~~~~~~~~ + interface Network { + /** + * Creates an implementation of the `Network` interface defined in + * `RelayNetworkTypes` given `fetch` and `subscribe` functions. + */ + create: (fetchFn: any, subscribeFn: any) => RelayNetwork; + } + + // ~~~~~~~~~~~~~~~~~~~~~ + // Network + // ~~~~~~~~~~~~~~~~~~~~~ + class RecordSource { + constructor(records?: RecordMap); + clear(): void; + delete(dataID: Common.DataID): void; + get(dataID: Common.DataID): Record | void; + getRecordIDs(): Common.DataID[]; + getStatus(dataID: Common.DataID): 'EXISTENT' | 'NONEXISTENT' | 'UNKNOWN'; + has(dataID: Common.DataID): boolean; + load( + dataID: Common.DataID, + callback: (error: Error | void, record: Record | void) => void, + ): void; + remove(dataID: Common.DataID): void; + set(dataID: Common.DataID, record: Record): void; + size(): number; + toJSON(): RecordMap; + } + + // ~~~~~~~~~~~~~~~~~~~~~ + // ModernStore + // ~~~~~~~~~~~~~~~~~~~~~ + class Store { + constructor(source: RecordSource); + getSource(): MutableRecordSource; + check(selector: Selector): boolean; + retain(selector: Selector): Common.Disposable; + lookup(selector: Selector): Snapshot; + notify(): void; + publish(source: RecordSource): void; + subscribe( + snapshot: Snapshot, + callback: (snapshot: Snapshot) => void, + ): Common.Disposable; + } + + // ~~~~~~~~~~~~~~~~~~~~~ + // RelayRecordSourceInspector + // ~~~~~~~~~~~~~~~~~~~~~ + /** + * An internal class to provide a console-friendly string representation of a + * Record. + */ + class RecordSummary { + id: Common.DataID; + type: string | void; + static createFromRecord(id: Common.DataID, record: any): RecordSummary; + constructor(id: Common.DataID, type: string | void); + toString(): string; + } + /** + * Internal class for inspecting a single Record. + */ + class RecordInspector { + constructor(sourceInspector: RelayRecordSourceInspector, record: Record); + /** + * Get the cache id of the given record. For types that implement the `Node` + * interface (or that have an `id`) this will be `id`, for other types it will be + * a synthesized identifier based on the field path from the nearest ancestor + * record that does have an `id`. + */ + getDataID(): Common.DataID; + + /** + * Returns a list of the fields that have been fetched on the current record. + */ + getFields(): Array; + + /** + * Returns the type of the record. + */ + getType(): string; + + /** + * Returns a copy of the internal representation of the record. + */ + inspect(): any; + + /** + * Returns the value of a scalar field. May throw if the given field is + * present but not actually scalar. + */ + getValue(name: string, args?: Common.Variables | void): any; + + /** + * Returns an inspector for the given scalar "linked" field (a field whose + * value is another Record instead of a scalar). May throw if the field is + * present but not a scalar linked record. + */ + getLinkedRecord(name: string, args?: Common.Variables | void): RecordInspector | void; + + /** + * Returns an array of inspectors for the given plural "linked" field (a field + * whose value is an array of Records instead of a scalar). May throw if the + * field is present but not a plural linked record. + */ + getLinkedRecords(name: string, args?: Common.Variables | void): RecordInspector[] | void; + } + + class RelayRecordSourceInspector { + constructor(source: RecordSource); + static getForEnvironment(environment: Environment): RelayRecordSourceInspector; + /** + * Returns an inspector for the record with the given id, or null/undefined if + * that record is deleted/unfetched. + */ + get(dataID: Common.DataID): RecordInspector | void; + /** + * Returns a list of ": " for each record in the store that has an + * `id`. + */ + getNodes(): Array; + /** + * Returns a list of ": " for all records in the store including + * those that do not have an `id`. + */ + getRecords(): Array; + + /** + * Returns an inspector for the synthesized "root" object, allowing access to + * e.g. the `viewer` object or the results of other fields on the "Query" + * type. + */ + getRoot(): RecordInspector; + } + + + // ~~~~~~~~~~~~~~~~~~~~~ + // RelayObservable + // ~~~~~~~~~~~~~~~~~~~~~ + type Subscription = { + unsubscribe: () => void, + readonly closed: boolean, + }; + type Observer = { + start?: ((subscription: Subscription) => any) | void, + next?: ((nextThing: T) => any) | void, + error?: ((error: Error) => any) | void, + complete?: (() => any) | void, + unsubscribe?: ((subscription: Subscription) => any) | void, + }; + type Source = () => any; + interface Subscribable { + subscribe(observer: Observer): Subscription, + } + export type ObservableFromValue = RelayObservable | Promise | T; + class RelayObservable implements Subscribable { + _source: Source; + + constructor(source: Source); + + /** + * When an unhandled error is detected, it is reported to the host environment + * (the ESObservable spec refers to this method as "HostReportErrors()"). + * + * The default implementation in development builds re-throws errors in a + * separate frame, and from production builds does nothing (swallowing + * uncaught errors). + * + * Called during application initialization, this method allows + * application-specific handling of uncaught errors. Allowing, for example, + * integration with error logging or developer tools. + */ + static onUnhandledError(callback: (error: Error) => any): void; + + /** + * Accepts various kinds of data sources, and always returns a RelayObservable + * useful for accepting the result of a user-provided FetchFunction. + */ + static from(obj: ObservableFromValue): RelayObservable; + + /** + * Creates a RelayObservable, given a function which expects a legacy + * Relay Observer as the last argument and which returns a Disposable. + * + * To support migration to Observable, the function may ignore the + * legacy Relay observer and directly return an Observable instead. + */ + static fromLegacy( + callback: (legacyObserver: Common.LegacyObserver) => Common.Disposable | RelayObservable, + ): RelayObservable; + + /** + * Returns a new Observable which returns the same values as this one, but + * modified so that the provided Observer is called to perform a side-effects + * for all events emitted by the source. + * + * Any errors that are thrown in the side-effect Observer are unhandled, and + * do not affect the source Observable or its Observer. + * + * This is useful for when debugging your Observables or performing other + * side-effects such as logging or performance monitoring. + */ + do(observer: Observer): RelayObservable; + + /** + * Returns a new Observable which returns the same values as this one, but + * modified so that the finally callback is performed after completion, + * whether normal or due to error or unsubscription. + * + * This is useful for cleanup such as resource finalization. + */ + finally(fn: () => any): RelayObservable; + + /** + * Returns a new Observable which is identical to this one, unless this + * Observable completes before yielding any values, in which case the new + * Observable will yield the values from the alternate Observable. + * + * If this Observable does yield values, the alternate is never subscribed to. + * + * This is useful for scenarios where values may come from multiple sources + * which should be tried in order, i.e. from a cache before a network. + */ + ifEmpty(alternate: RelayObservable): RelayObservable; + + /** + * Observable's primary API: returns an unsubscribable Subscription to the + * source of this Observable. + */ + subscribe(observer: Observer): Subscription; + + /** + * Supports subscription of a legacy Relay Observer, returning a Disposable. + */ + subscribeLegacy(legacyObserver: Common.LegacyObserver): Common.Disposable; + + /** + * Returns a new Observerable where each value has been transformed by + * the mapping function. + */ + map(fn: (thing: T) => U): RelayObservable; + + /** + * Returns a new Observable where each value is replaced with a new Observable + * by the mapping function, the results of which returned as a single + * concattenated Observable. + */ + concatMap(fn: (thing: T) => ObservableFromValue): RelayObservable; + + /** + * Returns a new Observable which first mirrors this Observable, then when it + * completes, waits for `pollInterval` milliseconds before re-subscribing to + * this Observable again, looping in this manner until unsubscribed. + * + * The returned Observable never completes. + */ + poll(pollInterval: number): RelayObservable; + + /** + * Returns a Promise which resolves when this Observable yields a first value + * or when it completes with no value. + */ + toPromise(): Promise; + } + + + // ~~~~~~~~~~~~~~~~~~~~~ + // commitLocalUpdate + // ~~~~~~~~~~~~~~~~~~~~~ + // exposed through RelayModern, not Runtime directly + type commitLocalUpdate = ( + environment: Environment, + updater: Common.StoreUpdater, + ) => void; + + // ~~~~~~~~~~~~~~~~~~~~~ + // commitRelayModernMutation + // ~~~~~~~~~~~~~~~~~~~~~ + // exposed through RelayModern, not Runtime directly + type MutationConfig = { + configs?: Array, + mutation: Common.GraphQLTaggedNode, + variables: Common.Variables, + uploadables?: Common.UploadableMap, + onCompleted?: (response: T, errors: Array | void) => void, + onError?: (error?: Error) => void, + optimisticUpdater?: Common.SelectorStoreUpdater | void, + optimisticResponse?: Object, + updater?: Common.SelectorStoreUpdater | void, + }; + type commitRelayModernMutation = ( + environment: Environment, + config: MutationConfig, + ) => Common.Disposable; + + // ~~~~~~~~~~~~~~~~~~~~~ + // applyRelayModernOptimisticMutation + // ~~~~~~~~~~~~~~~~~~~~~ + // exposed through RelayModern, not Runtime directly + type OptimisticMutationConfig = { + configs?: Array, + mutation: Common.GraphQLTaggedNode, + variables: Common.Variables, + optimisticUpdater?: Common.SelectorStoreUpdater, + optimisticResponse?: Object, + }; + + // ~~~~~~~~~~~~~~~~~~~~~ + // fetchRelayModernQuery + // ~~~~~~~~~~~~~~~~~~~~~ + // exposed through RelayModern, not Runtime directly + /** + * A helper function to fetch the results of a query. Note that results for + * fragment spreads are masked: fields must be explicitly listed in the query in + * order to be accessible in the result object. + * + * NOTE: This module is primarily intended for integrating with classic APIs. + * Most product code should use a Renderer or Container. + * + * TODO(t16875667): The return type should be `Promise`, but + * that's not really helpful as `SelectorData` is essentially just `mixed`. We + * can probably leverage generated flow types here to return the real expected + * shape. + */ + function fetchRelayModernQuery( + environment: any, // FIXME - $FlowFixMe in facebook source code + taggedNode: Common.GraphQLTaggedNode, + variables: Common.Variables, + cacheConfig?: Common.CacheConfig | void, + ): Promise; // FIXME - $FlowFixMe in facebook source code + + + // ~~~~~~~~~~~~~~~~~~~~~ + // requestRelaySubscription + // ~~~~~~~~~~~~~~~~~~~~~ + // exposed through RelayModern, not Runtime directly + export type GraphQLSubscriptionConfig = { + configs?: Array, + subscription: Common.GraphQLTaggedNode, + variables: Common.Variables, + onCompleted?: () => void, + onError?: (error: Error) => void, + onNext?: (response: Object | void) => void, + updater?: (store: Common.RecordSourceSelectorProxy) => void, + }; + type requestRelaySubscription = ( + environment: Environment, + config: GraphQLSubscriptionConfig, + ) => Common.Disposable; + } + + declare module 'relay-runtime' { + export import Environment = __Relay.Runtime.Environment; + export import Network = __Relay.Runtime.Network; + export import RecordSource = __Relay.Runtime.RecordSource; + export import Store = __Relay.Runtime.Store; + export import Observable = __Relay.Runtime.RelayObservable; + // note RecordSourceInspector is only available in dev environment + export import RecordSourceInspector = __Relay.Runtime.RelayRecordSourceInspector; + } diff --git a/types/relay-runtime/tsconfig.json b/types/relay-runtime/tsconfig.json new file mode 100644 index 0000000000..8224ba918b --- /dev/null +++ b/types/relay-runtime/tsconfig.json @@ -0,0 +1,26 @@ +{ + "files": [ + "index.d.ts", + "relay-runtime-tests.tsx" + ], + "compilerOptions": { + "module": "commonjs", + "lib": [ + "es6", + "dom" + ], + "noImplicitAny": true, + "noImplicitThis": true, + "strictNullChecks": true, + "baseUrl": "../", + "jsx": "react", + "experimentalDecorators": true, + "forceConsistentCasingInFileNames": true, + "typeRoots": [ + "../" + ], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true + } +} From ce1d72c1e6b606954f15dfa411d7d8e33130c06e Mon Sep 17 00:00:00 2001 From: voxmatt Date: Sun, 3 Sep 2017 12:38:59 -0700 Subject: [PATCH 004/828] removing reference path --- types/relay-runtime/index.d.ts | 2 -- 1 file changed, 2 deletions(-) diff --git a/types/relay-runtime/index.d.ts b/types/relay-runtime/index.d.ts index 7e57ef036b..961ff8b181 100644 --- a/types/relay-runtime/index.d.ts +++ b/types/relay-runtime/index.d.ts @@ -1,5 +1,3 @@ -/// - declare namespace __Relay.Common { /** * SOURCE: From 26b04cb2c68a685f6605965db941de0711a6d1fd Mon Sep 17 00:00:00 2001 From: voxmatt Date: Sun, 3 Sep 2017 12:39:58 -0700 Subject: [PATCH 005/828] adding info to top of relay-runtime definitions --- types/relay-runtime/index.d.ts | 6 ++++++ 1 file changed, 6 insertions(+) diff --git a/types/relay-runtime/index.d.ts b/types/relay-runtime/index.d.ts index 961ff8b181..ee11757a25 100644 --- a/types/relay-runtime/index.d.ts +++ b/types/relay-runtime/index.d.ts @@ -1,3 +1,9 @@ +// Type definitions for react-relay 1.3.0 +// Project: https://github.com/facebook/relay +// Definitions by: Matt Martin +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.5 + declare namespace __Relay.Common { /** * SOURCE: From 21915dba1385a03531175945a7b7a5a9a5c68d9b Mon Sep 17 00:00:00 2001 From: voxmatt Date: Sun, 3 Sep 2017 12:52:17 -0700 Subject: [PATCH 006/828] adding new relay files but haven't configged file paths yet --- types/react-relay/index.d.ts | 268 +++++++++++++++++++++++++++++++- types/react-relay/tsconfig.json | 2 +- types/relay-runtime/index.d.ts | 2 +- 3 files changed, 267 insertions(+), 5 deletions(-) diff --git a/types/react-relay/index.d.ts b/types/react-relay/index.d.ts index 4f9f49e5e7..6bedf10030 100644 --- a/types/react-relay/index.d.ts +++ b/types/react-relay/index.d.ts @@ -1,10 +1,272 @@ -// Type definitions for react-relay 0.9.2 +// Type definitions for react-relay 1.3.0 // Project: https://github.com/facebook/relay // Definitions by: Johannes Schickling +// Matt Martin // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -// TypeScript Version: 2.3 +// TypeScript Version: 2.5 -declare module "react-relay" { +/// +/// + +//////////////////////////// +// RELAY MODERN TYPES +/////////////////////////// + +declare namespace __Relay.Modern { + // ~~~~~~~~~~~~~~~~~~~~~ + // Maybe Fix + // ~~~~~~~~~~~~~~~~~~~~~ + type ConcreteFragment = any; + type ConcreteBatch = any; + type ConcreteFragmentDefinition = Object; + type ConcreteOperationDefinition = Object; + type ReactBaseComponent = React.ComponentClass | React.StatelessComponent; + + // ~~~~~~~~~~~~~~~~~~~~~ + // RelayQL + // ~~~~~~~~~~~~~~~~~~~~~ + type RelayQL = ( + strings: Array, + ...substitutions: Array + ) => Common.RelayConcreteNode; + + // ~~~~~~~~~~~~~~~~~~~~~ + // RelayModernGraphQLTag + // ~~~~~~~~~~~~~~~~~~~~~ + type GeneratedNodeMap = {[key: string]: GraphQLTaggedNode}; + type GraphQLTaggedNode = + | (() => ConcreteFragment | ConcreteBatch) + | { + modern: () => ConcreteFragment | ConcreteBatch, + classic: (relayQL: RelayQL) => + | ConcreteFragmentDefinition + | ConcreteOperationDefinition, + }; + /** + * Runtime function to correspond to the `graphql` tagged template function. + * All calls to this function should be transformed by the plugin. + */ + function graphql(strings: Array): GraphQLTaggedNode; + + // ~~~~~~~~~~~~~~~~~~~~~ + // ReactRelayQueryRenderer + // ~~~~~~~~~~~~~~~~~~~~~ + type QueryRendererProps = { + cacheConfig?: __Relay.Common.CacheConfig | void, + environment: __Relay.Runtime.Environment | any, + query: GraphQLTaggedNode, + render: (readyState: ReadyState) => React.ReactElement | void, + variables: Common.Variables, + rerunParamExperimental?: Common.RerunParam, + }; + export type ReadyState = { + error: Error | void, + props: Object | void, + retry: (() => void) | void, + }; + type QueryRendererState = { + readyState: ReadyState, + }; + class ReactRelayQueryRenderer extends React.Component {} + + // ~~~~~~~~~~~~~~~~~~~~~ + // createFragmentContainer + // ~~~~~~~~~~~~~~~~~~~~~ + function createFragmentContainer( + Component: ReactBaseComponent, + fragmentSpec: GraphQLTaggedNode | GeneratedNodeMap, + ): ReactBaseComponent; + + // ~~~~~~~~~~~~~~~~~~~~~ + // createPaginationContainer + // ~~~~~~~~~~~~~~~~~~~~~ + type PageInfo = { + endCursor: string | void, + hasNextPage: boolean, + hasPreviousPage: boolean, + startCursor: string | void, + }; + type ConnectionData = { + edges?: any[], + pageInfo?: PageInfo | void, + }; + type FragmentVariablesGetter = ( + prevVars: Common.Variables, + totalCount: number, + ) => Common.Variables; + type ConnectionConfig = { + direction?: 'backward' | 'forward', + getConnectionFromProps?: (props: Object) => ConnectionData | void, + getFragmentVariables?: FragmentVariablesGetter, + getVariables: ( + props: Object, + paginationInfo: {count: number, cursor: string | void}, + fragmentVariables: Common.Variables, + ) => Common.Variables, + query: GraphQLTaggedNode, + }; + function createPaginationContainer( + Component: ReactBaseComponent, + fragmentSpec: GraphQLTaggedNode | GeneratedNodeMap, + connectionConfig: ConnectionConfig, + ): ReactBaseComponent; + + // ~~~~~~~~~~~~~~~~~~~~~ + // createFragmentContainer + // ~~~~~~~~~~~~~~~~~~~~~ + function createRefetchContainer( + Component: ReactBaseComponent, + fragmentSpec: GraphQLTaggedNode | GeneratedNodeMap, + taggedNode: GraphQLTaggedNode, + ): ReactBaseComponent; +} + + + +//////////////////////////// +// RELAY CLASSIC TYPES +/////////////////////////// +// note: the namespace here is really for use inside of +// relay-compat; the module declaration below +// uses the old, pre-existing types +declare namespace __Relay.Classic { + // ~~~~~~~~~~~~~~~~~~~~~ + // Maybe Fix + // ~~~~~~~~~~~~~~~~~~~~~ + type StoreReaderData = any; + type StoreReaderOptions = any; + type RelayStoreData = any; + type RelayQuery = { Fragment: any; Node: any; Root: any;}; + + // ~~~~~~~~~~~~~~~~~~~~~ + // Environment + // ~~~~~~~~~~~~~~~~~~~~~ + type FragmentResolver = { + dispose(): void, + resolve( + fragment: RelayQuery["Fragment"], + dataIDs: Common.DataID | Array, + ): (StoreReaderData | Array) | void, + }; + interface RelayEnvironmentInterface { + forceFetch( + querySet: Common.RelayQuerySet, + onReadyStateChange: Common.ReadyStateChangeCallback, + ): Common.Abortable, + getFragmentResolver( + fragment: RelayQuery["Fragment"], + onNext: () => void, + ): FragmentResolver, + getStoreData(): RelayStoreData, + primeCache( + querySet: Common.RelayQuerySet, + onReadyStateChange: Common.ReadyStateChangeCallback, + ): Common.Abortable, + read( + node: RelayQuery["Node"], + dataID: Common.DataID, + options?: StoreReaderOptions, + ): StoreReaderData | void, + readQuery( + root: RelayQuery["Root"], + options?: StoreReaderOptions, + ): Array | void, + } + } + +//////////////////////////// +// RELAY COMPAT TYPES +/////////////////////////// + +declare namespace __Relay.Compat { + // ~~~~~~~~~~~~~~~~~~~~~ + // Maybe Fix + // ~~~~~~~~~~~~~~~~~~~~~ + type ConcreteFragment = any; + type ConcreteBatch = any; + type ConcreteFragmentDefinition = Object; + type ConcreteOperationDefinition = Object; + + + // ~~~~~~~~~~~~~~~~~~~~~ + // Util + // ~~~~~~~~~~~~~~~~~~~~~ + type getFragment = (q: string, v?: Common.Variables) => string; + interface ComponentWithFragment extends React.ComponentClass { + getFragment: getFragment; + } + interface StatelessWithFragment extends React.StatelessComponent { + getFragment: getFragment; + } + type ReactFragmentComponent = ComponentWithFragment | StatelessWithFragment; + type ReactBaseComponent = React.ComponentClass | React.StatelessComponent; + type RelayClassicEnvironment = Classic.RelayEnvironmentInterface; + + // ~~~~~~~~~~~~~~~~~~~~~ + // RelayCompatTypes + // ~~~~~~~~~~~~~~~~~~~~~ + type CompatEnvironment = Runtime.Environment | RelayClassicEnvironment; + + // ~~~~~~~~~~~~~~~~~~~~~ + // RelayCompatMutations + // ~~~~~~~~~~~~~~~~~~~~~ + function commitUpdate( + environment: CompatEnvironment, + config: Runtime.MutationConfig, + ): Common.Disposable; + function applyUpdate( + environment: CompatEnvironment, + config: Runtime.OptimisticMutationConfig, + ): Common.Disposable; + + // ~~~~~~~~~~~~~~~~~~~~~ + // RelayCompatContainer + // ~~~~~~~~~~~~~~~~~~~~~ + export type GeneratedNodeMap = {[key: string]: Modern.GraphQLTaggedNode}; + function createContainer( + Component: ReactBaseComponent, + fragmentSpec: Modern.GraphQLTaggedNode | GeneratedNodeMap, + ): ReactFragmentComponent; + + // ~~~~~~~~~~~~~~~~~~~~~ + // injectDefaultVariablesProvider + // ~~~~~~~~~~~~~~~~~~~~~ + type VariablesProvider = () => Common.Variables; + function injectDefaultVariablesProvider(variablesProvider: VariablesProvider): void; +} + + +//////////////////////////// +// MODULES +/////////////////////////// + +declare module 'react-relay' { + export import QueryRenderer = __Relay.Modern.ReactRelayQueryRenderer; + export import createFragmentContainer = __Relay.Modern.createFragmentContainer; + export import createPaginationContainer = __Relay.Modern.createPaginationContainer; + export import createRefetchContainer = __Relay.Modern.createRefetchContainer; + export import graphql = __Relay.Modern.graphql; + + export import commitLocalUpdate = __Relay.Runtime.commitLocalUpdate; + export import commitMutation = __Relay.Runtime.commitRelayModernMutation; + export import fetchQuery = __Relay.Runtime.fetchRelayModernQuery; + export import requestSubscription = __Relay.Runtime.requestRelaySubscription; +} + +declare module 'react-relay/compat' { + export import applyOptimisticMutation = __Relay.Compat.applyUpdate; + export import commitMutation = __Relay.Compat.commitUpdate; + export import createFragmentContainer = __Relay.Compat.createContainer; + export import createPaginationContainer = __Relay.Compat.createContainer; + export import createRefetchContainer = __Relay.Compat.createContainer; + export import injectDefaultVariablesProvider = __Relay.Compat.injectDefaultVariablesProvider; + export import QueryRenderer = __Relay.Modern.ReactRelayQueryRenderer; + export import graphql = __Relay.Modern.graphql; + export import fetchQuery = __Relay.Runtime.fetchRelayModernQuery; + } + + +declare module "react-relay/classic" { import * as React from "react"; type ClientMutationID = string; diff --git a/types/react-relay/tsconfig.json b/types/react-relay/tsconfig.json index 90680fbafc..5d225c2016 100644 --- a/types/react-relay/tsconfig.json +++ b/types/react-relay/tsconfig.json @@ -21,4 +21,4 @@ "index.d.ts", "react-relay-tests.tsx" ] -} \ No newline at end of file +} diff --git a/types/relay-runtime/index.d.ts b/types/relay-runtime/index.d.ts index ee11757a25..848cf15927 100644 --- a/types/relay-runtime/index.d.ts +++ b/types/relay-runtime/index.d.ts @@ -1,4 +1,4 @@ -// Type definitions for react-relay 1.3.0 +// Type definitions for relay-runtime 1.3.0 // Project: https://github.com/facebook/relay // Definitions by: Matt Martin // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped From df16535a8cdb39ac8cd4a12424fad5ad74405d20 Mon Sep 17 00:00:00 2001 From: voxmatt Date: Sat, 9 Sep 2017 15:44:07 -1000 Subject: [PATCH 007/828] relay-runtime tests in place --- types/react-relay/index.d.ts | 46 +++++----- .../react-relay/react-relay-classic-tests.tsx | 92 +++++++++++++++++++ .../react-relay/react-relay-compat-tests.tsx | 0 types/react-relay/react-relay-tests.tsx | 92 ------------------- types/react-relay/tsconfig.json | 4 +- types/relay-runtime/index.d.ts | 57 +++++++++--- types/relay-runtime/relay-runtime-tests.tsx | 66 +++++++++++++ 7 files changed, 227 insertions(+), 130 deletions(-) create mode 100644 types/react-relay/react-relay-classic-tests.tsx create mode 100644 types/react-relay/react-relay-compat-tests.tsx create mode 100644 types/relay-runtime/relay-runtime-tests.tsx diff --git a/types/react-relay/index.d.ts b/types/react-relay/index.d.ts index 6bedf10030..2541d7aa20 100644 --- a/types/react-relay/index.d.ts +++ b/types/react-relay/index.d.ts @@ -25,10 +25,10 @@ declare namespace __Relay.Modern { // ~~~~~~~~~~~~~~~~~~~~~ // RelayQL // ~~~~~~~~~~~~~~~~~~~~~ - type RelayQL = ( + export function RelayQL( strings: Array, ...substitutions: Array - ) => Common.RelayConcreteNode; + ): Common.RelayConcreteNode; // ~~~~~~~~~~~~~~~~~~~~~ // RelayModernGraphQLTag @@ -38,7 +38,7 @@ declare namespace __Relay.Modern { | (() => ConcreteFragment | ConcreteBatch) | { modern: () => ConcreteFragment | ConcreteBatch, - classic: (relayQL: RelayQL) => + classic: (relayQL: typeof RelayQL) => | ConcreteFragmentDefinition | ConcreteOperationDefinition, }; @@ -46,7 +46,7 @@ declare namespace __Relay.Modern { * Runtime function to correspond to the `graphql` tagged template function. * All calls to this function should be transformed by the plugin. */ - function graphql(strings: Array): GraphQLTaggedNode; + function graphql(strings: Array | TemplateStringsArray): GraphQLTaggedNode; // ~~~~~~~~~~~~~~~~~~~~~ // ReactRelayQueryRenderer @@ -72,7 +72,7 @@ declare namespace __Relay.Modern { // ~~~~~~~~~~~~~~~~~~~~~ // createFragmentContainer // ~~~~~~~~~~~~~~~~~~~~~ - function createFragmentContainer( + export function createFragmentContainer( Component: ReactBaseComponent, fragmentSpec: GraphQLTaggedNode | GeneratedNodeMap, ): ReactBaseComponent; @@ -90,14 +90,14 @@ declare namespace __Relay.Modern { edges?: any[], pageInfo?: PageInfo | void, }; - type FragmentVariablesGetter = ( + export function FragmentVariablesGetter( prevVars: Common.Variables, totalCount: number, - ) => Common.Variables; + ): Common.Variables; type ConnectionConfig = { direction?: 'backward' | 'forward', getConnectionFromProps?: (props: Object) => ConnectionData | void, - getFragmentVariables?: FragmentVariablesGetter, + getFragmentVariables?: typeof FragmentVariablesGetter, getVariables: ( props: Object, paginationInfo: {count: number, cursor: string | void}, @@ -105,7 +105,7 @@ declare namespace __Relay.Modern { ) => Common.Variables, query: GraphQLTaggedNode, }; - function createPaginationContainer( + export function createPaginationContainer( Component: ReactBaseComponent, fragmentSpec: GraphQLTaggedNode | GeneratedNodeMap, connectionConfig: ConnectionConfig, @@ -114,7 +114,7 @@ declare namespace __Relay.Modern { // ~~~~~~~~~~~~~~~~~~~~~ // createFragmentContainer // ~~~~~~~~~~~~~~~~~~~~~ - function createRefetchContainer( + export function createRefetchContainer( Component: ReactBaseComponent, fragmentSpec: GraphQLTaggedNode | GeneratedNodeMap, taggedNode: GraphQLTaggedNode, @@ -191,30 +191,30 @@ declare namespace __Relay.Compat { // ~~~~~~~~~~~~~~~~~~~~~ // Util // ~~~~~~~~~~~~~~~~~~~~~ - type getFragment = (q: string, v?: Common.Variables) => string; + export function getFragment(q: string, v?: Common.Variables): string; interface ComponentWithFragment extends React.ComponentClass { - getFragment: getFragment; + getFragment: typeof getFragment; } interface StatelessWithFragment extends React.StatelessComponent { - getFragment: getFragment; + getFragment: typeof getFragment; } type ReactFragmentComponent = ComponentWithFragment | StatelessWithFragment; type ReactBaseComponent = React.ComponentClass | React.StatelessComponent; - type RelayClassicEnvironment = Classic.RelayEnvironmentInterface; + export type RelayClassicEnvironment = Classic.RelayEnvironmentInterface; // ~~~~~~~~~~~~~~~~~~~~~ // RelayCompatTypes // ~~~~~~~~~~~~~~~~~~~~~ - type CompatEnvironment = Runtime.Environment | RelayClassicEnvironment; + export type CompatEnvironment = Runtime.Environment | RelayClassicEnvironment; // ~~~~~~~~~~~~~~~~~~~~~ // RelayCompatMutations // ~~~~~~~~~~~~~~~~~~~~~ - function commitUpdate( + export function commitUpdate( environment: CompatEnvironment, config: Runtime.MutationConfig, ): Common.Disposable; - function applyUpdate( + export function applyUpdate( environment: CompatEnvironment, config: Runtime.OptimisticMutationConfig, ): Common.Disposable; @@ -223,7 +223,7 @@ declare namespace __Relay.Compat { // RelayCompatContainer // ~~~~~~~~~~~~~~~~~~~~~ export type GeneratedNodeMap = {[key: string]: Modern.GraphQLTaggedNode}; - function createContainer( + export function createContainer( Component: ReactBaseComponent, fragmentSpec: Modern.GraphQLTaggedNode | GeneratedNodeMap, ): ReactFragmentComponent; @@ -232,7 +232,7 @@ declare namespace __Relay.Compat { // injectDefaultVariablesProvider // ~~~~~~~~~~~~~~~~~~~~~ type VariablesProvider = () => Common.Variables; - function injectDefaultVariablesProvider(variablesProvider: VariablesProvider): void; + export function injectDefaultVariablesProvider(variablesProvider: VariablesProvider): void; } @@ -339,10 +339,10 @@ declare module "react-relay/classic" { supports(...options: string[]): boolean } - function createContainer(component: React.ComponentClass | React.StatelessComponent, params?: CreateContainerOpts): RelayContainerClass - function injectNetworkLayer(networkLayer: RelayNetworkLayer): any - function isContainer(component: React.ComponentClass): boolean - function QL(...args: any[]): string + export function createContainer(component: React.ComponentClass | React.StatelessComponent, params?: CreateContainerOpts): RelayContainerClass + export function injectNetworkLayer(networkLayer: RelayNetworkLayer): any + export function isContainer(component: React.ComponentClass): boolean + export function QL(...args: any[]): string class Route { constructor(params?: RelayVariables) diff --git a/types/react-relay/react-relay-classic-tests.tsx b/types/react-relay/react-relay-classic-tests.tsx new file mode 100644 index 0000000000..f231381817 --- /dev/null +++ b/types/react-relay/react-relay-classic-tests.tsx @@ -0,0 +1,92 @@ +import * as React from "react"; +import * as Relay from "react-relay/classic"; + +interface Props { + text: string + userId: string +} + +interface Response { +} + +export default class AddTweetMutation extends Relay.Mutation { + + getMutation () { + return Relay.QL`mutation{addTweet}` + } + + getFatQuery () { + return Relay.QL` + fragment on AddTweetPayload { + tweetEdge + user + } + ` + } + + getConfigs () { + return [{ + type: "RANGE_ADD", + parentName: "user", + parentID: this.props.userId, + connectionName: "tweets", + edgeName: "tweetEdge", + rangeBehaviors: { + "": "append", + }, + }] + } + + getVariables () { + return this.props + } +} + +interface ArtworkProps { + artwork: { + title: string + }, + relay: Relay.RelayProp, +} + +class Artwork extends React.Component { + render() { + return ( + + {this.props.artwork.title} + + ) + } +} + +const ArtworkContainer = Relay.createContainer(Artwork, { + fragments: { + artwork: () => Relay.QL` + fragment on Artwork { + title + } + ` + } +}) + +class StubbedArtwork extends React.Component { + render() { + const props = { + artwork: { title: "CHAMPAGNE FORMICA FLAG" }, + relay: { + route: { + name: "champagne" + }, + variables: { + artworkID: "champagne-formica-flag", + }, + setVariables: () => {}, + forceFetch: () => {}, + hasOptimisticUpdate: () => false, + getPendingTransactions: (): Relay.RelayMutationTransaction[] => undefined, + commitUpdate: () => {}, + } + } + return + } +} diff --git a/types/react-relay/react-relay-compat-tests.tsx b/types/react-relay/react-relay-compat-tests.tsx new file mode 100644 index 0000000000..e69de29bb2 diff --git a/types/react-relay/react-relay-tests.tsx b/types/react-relay/react-relay-tests.tsx index 90425156cc..e69de29bb2 100644 --- a/types/react-relay/react-relay-tests.tsx +++ b/types/react-relay/react-relay-tests.tsx @@ -1,92 +0,0 @@ -import * as React from "react" -import * as Relay from "react-relay" - -interface Props { - text: string - userId: string -} - -interface Response { -} - -export default class AddTweetMutation extends Relay.Mutation { - - getMutation () { - return Relay.QL`mutation{addTweet}` - } - - getFatQuery () { - return Relay.QL` - fragment on AddTweetPayload { - tweetEdge - user - } - ` - } - - getConfigs () { - return [{ - type: "RANGE_ADD", - parentName: "user", - parentID: this.props.userId, - connectionName: "tweets", - edgeName: "tweetEdge", - rangeBehaviors: { - "": "append", - }, - }] - } - - getVariables () { - return this.props - } -} - -interface ArtworkProps { - artwork: { - title: string - }, - relay: Relay.RelayProp, -} - -class Artwork extends React.Component { - render() { - return ( - - {this.props.artwork.title} - - ) - } -} - -const ArtworkContainer = Relay.createContainer(Artwork, { - fragments: { - artwork: () => Relay.QL` - fragment on Artwork { - title - } - ` - } -}) - -class StubbedArtwork extends React.Component { - render() { - const props = { - artwork: { title: "CHAMPAGNE FORMICA FLAG" }, - relay: { - route: { - name: "champagne" - }, - variables: { - artworkID: "champagne-formica-flag", - }, - setVariables: () => {}, - forceFetch: () => {}, - hasOptimisticUpdate: () => false, - getPendingTransactions: (): Relay.RelayMutationTransaction[] => undefined, - commitUpdate: () => {}, - } - } - return - } -} diff --git a/types/react-relay/tsconfig.json b/types/react-relay/tsconfig.json index 5d225c2016..825d91a0c2 100644 --- a/types/react-relay/tsconfig.json +++ b/types/react-relay/tsconfig.json @@ -19,6 +19,8 @@ }, "files": [ "index.d.ts", - "react-relay-tests.tsx" + "react-relay-tests.tsx", + "react-relay-classic-tests.tsx", + "react-relay-compat-tests.tsx" ] } diff --git a/types/relay-runtime/index.d.ts b/types/relay-runtime/index.d.ts index 848cf15927..b54688f080 100644 --- a/types/relay-runtime/index.d.ts +++ b/types/relay-runtime/index.d.ts @@ -27,6 +27,7 @@ declare namespace __Relay.Common { type ConcreteFragmentDefinition = Object; type ConcreteOperationDefinition = Object; + /** * FIXME: RelayContainer used to be typed with ReactClass, but * ReactClass is broken and allows for access to any property. For example @@ -83,6 +84,31 @@ declare namespace __Relay.Common { column: number, }>, }; + /** + * A function that executes a GraphQL operation with request/response semantics. + * + * May return an Observable or Promise of a raw server response. + */ + export function FetchFunction( + operation: ConcreteBatch, + variables: Variables, + cacheConfig: CacheConfig, + uploadables?: Common.UploadableMap, + ): Runtime.ObservableFromValue; + + /** + * A function that executes a GraphQL subscription operation, returning one or + * more raw server responses over time. + * + * May return an Observable, otherwise must call the callbacks found in the + * fourth parameter. + */ + export type SubscribeFunction = ( + operation: ConcreteBatch, + variables: Variables, + cacheConfig: CacheConfig, + observer: LegacyObserver, + ) => Runtime.RelayObservable | Disposable; // ~~~~~~~~~~~~~~~~~~~~~ @@ -166,10 +192,11 @@ declare namespace __Relay.Common { // handler. handleKey: string, }; - - export type Handler = { - update: (store: RecordSourceProxy, fieldPayload: HandleFieldPayload) => void, + interface IHandler { + update: (store: RecordSourceProxy, fieldPayload: HandleFieldPayload): void; + [functionName: string]: Function; }; + export const Handler: IHandler; // ~~~~~~~~~~~~~~~~~~~~~ @@ -685,14 +712,14 @@ declare namespace __Relay.Runtime { // ~~~~~~~~~~~~~~~~~~~~~ // RelayDefaultHandlerProvider // ~~~~~~~~~~~~~~~~~~~~~ - type HandlerProvider = (name: string) => Common.Handler | void; + export function HandlerProvider(name: string): Common.Handler | void; // ~~~~~~~~~~~~~~~~~~~~~ // RelayModernEnvironment // ~~~~~~~~~~~~~~~~~~~~~ type EnvironmentConfig = { configName?: string, - handlerProvider?: HandlerProvider, + handlerProvider?: typeof HandlerProvider, network: Network, store: Store, }; @@ -743,12 +770,12 @@ declare namespace __Relay.Runtime { // ~~~~~~~~~~~~~~~~~~~~~ // Network // ~~~~~~~~~~~~~~~~~~~~~ - interface Network { - /** - * Creates an implementation of the `Network` interface defined in - * `RelayNetworkTypes` given `fetch` and `subscribe` functions. - */ - create: (fetchFn: any, subscribeFn: any) => RelayNetwork; + class Network { + /** + * Creates an implementation of the `Network` interface defined in + * `RelayNetworkTypes` given `fetch` and `subscribe` functions. + */ + static create(fetchFn: typeof Common.FetchFunction, subscribeFn?: Common.SubscribeFunction): RelayNetwork; } // ~~~~~~~~~~~~~~~~~~~~~ @@ -898,7 +925,7 @@ declare namespace __Relay.Runtime { interface Subscribable { subscribe(observer: Observer): Subscription, } - export type ObservableFromValue = RelayObservable | Promise | T; + type ObservableFromValue = RelayObservable | Promise | T; class RelayObservable implements Subscribable { _source: Source; @@ -1034,10 +1061,10 @@ declare namespace __Relay.Runtime { optimisticResponse?: Object, updater?: Common.SelectorStoreUpdater | void, }; - type commitRelayModernMutation = ( + function commitRelayModernMutation( environment: Environment, config: MutationConfig, - ) => Common.Disposable; + ): Common.Disposable; // ~~~~~~~~~~~~~~~~~~~~~ // applyRelayModernOptimisticMutation @@ -1103,4 +1130,6 @@ declare namespace __Relay.Runtime { export import Observable = __Relay.Runtime.RelayObservable; // note RecordSourceInspector is only available in dev environment export import RecordSourceInspector = __Relay.Runtime.RelayRecordSourceInspector; + export import ConnectionHandler = __Relay.Common.Handler; + export import ViewerHandler = __Relay.Common.Handler; } diff --git a/types/relay-runtime/relay-runtime-tests.tsx b/types/relay-runtime/relay-runtime-tests.tsx new file mode 100644 index 0000000000..609399f079 --- /dev/null +++ b/types/relay-runtime/relay-runtime-tests.tsx @@ -0,0 +1,66 @@ +import { + Environment, + Network, + RecordSource, + Store, +} from 'relay-runtime'; + +const source = new RecordSource(); +const store = new Store(source); + +// ~~~~~~~~~~~~~~~~~~~~~ +// Network Layer +// ~~~~~~~~~~~~~~~~~~~~~ +// Define a function that fetches the results of an operation (query/mutation/etc) +// and returns its results as a Promise: +function fetchQuery( + operation: any, + variables: { [key: string]: string }, + cacheConfig: {}, +) { + return fetch('/graphql', { + method: 'POST', + headers: { + // Add authentication and other headers here + 'content-type': 'application/json' + }, + body: JSON.stringify({ + query: operation.text, // GraphQL text from input + variables, + }), + }).then(response => { + return response.json(); + }); +} + +// Create a network layer from the fetch function +const network = Network.create(fetchQuery); + +// ~~~~~~~~~~~~~~~~~~~~~ +// Environment +// ~~~~~~~~~~~~~~~~~~~~~ +const environment = new Environment({ + handlerProvider, // Can omit. + network, + store, +}); + +// ~~~~~~~~~~~~~~~~~~~~~ +// Handler Provider +// ~~~~~~~~~~~~~~~~~~~~~ + +import { + ConnectionHandler, + ViewerHandler, +} from 'relay-runtime'; + +function handlerProvider(handle: any) { + switch (handle) { + // Augment (or remove from) this list: + case 'connection': return ConnectionHandler; + case 'viewer': return ViewerHandler; + } + throw new Error( + `handlerProvider: No handler provided for ${handle}` + ); +} From 27b933935ee9924870bde294dd259d0e58107d1a Mon Sep 17 00:00:00 2001 From: voxmatt Date: Sat, 9 Sep 2017 17:13:12 -1000 Subject: [PATCH 008/828] complete set of relay modern tests --- types/react-relay/index.d.ts | 52 +++- types/react-relay/react-relay-tests.tsx | 350 ++++++++++++++++++++++++ types/relay-runtime/index.d.ts | 48 ++-- 3 files changed, 425 insertions(+), 25 deletions(-) diff --git a/types/react-relay/index.d.ts b/types/react-relay/index.d.ts index 2541d7aa20..3b073666f9 100644 --- a/types/react-relay/index.d.ts +++ b/types/react-relay/index.d.ts @@ -22,6 +22,14 @@ declare namespace __Relay.Modern { type ConcreteOperationDefinition = Object; type ReactBaseComponent = React.ComponentClass | React.StatelessComponent; + // ~~~~~~~~~~~~~~~~~~~~~ + // RelayProp + // ~~~~~~~~~~~~~~~~~~~~~ + // note: refetch and pagination containers augment this + export type RelayProp = { + environment: Runtime.Environment, + }; + // ~~~~~~~~~~~~~~~~~~~~~ // RelayQL // ~~~~~~~~~~~~~~~~~~~~~ @@ -46,14 +54,18 @@ declare namespace __Relay.Modern { * Runtime function to correspond to the `graphql` tagged template function. * All calls to this function should be transformed by the plugin. */ - function graphql(strings: Array | TemplateStringsArray): GraphQLTaggedNode; + interface IGraphql { + (strings: Array | TemplateStringsArray): GraphQLTaggedNode; + experimental: (strings: Array | TemplateStringsArray) => GraphQLTaggedNode; + } + export const graphql: IGraphql; // ~~~~~~~~~~~~~~~~~~~~~ // ReactRelayQueryRenderer // ~~~~~~~~~~~~~~~~~~~~~ type QueryRendererProps = { cacheConfig?: __Relay.Common.CacheConfig | void, - environment: __Relay.Runtime.Environment | any, + environment: __Relay.Runtime.Environment, query: GraphQLTaggedNode, render: (readyState: ReadyState) => React.ReactElement | void, variables: Common.Variables, @@ -61,7 +73,7 @@ declare namespace __Relay.Modern { }; export type ReadyState = { error: Error | void, - props: Object | void, + props: { [propName: string]: any } | void, retry: (() => void) | void, }; type QueryRendererState = { @@ -90,6 +102,20 @@ declare namespace __Relay.Modern { edges?: any[], pageInfo?: PageInfo | void, }; + export type RelayPaginationProp = RelayProp & { + hasMore: () => boolean, + isLoading: () => boolean, + loadMore: ( + pageSize: number, + callback: (error?: Error) => void, + options?: RefetchOptions, + ) => Common.Disposable | void, + refetchConnection: ( + totalCount: number, + callback: (error?: Error | void) => void, + refetchVariables?: Common.Variables | void, + ) => Common.Disposable | void, + }; export function FragmentVariablesGetter( prevVars: Common.Variables, totalCount: number, @@ -114,11 +140,26 @@ declare namespace __Relay.Modern { // ~~~~~~~~~~~~~~~~~~~~~ // createFragmentContainer // ~~~~~~~~~~~~~~~~~~~~~ + export type RefetchOptions = { + force?: boolean, + rerunParamExperimental?: Common.RerunParam, + }; + export type RelayRefetchProp = RelayProp & { + refetch: ( + refetchVariables: Common.Variables | ((fragmentVariables: Common.Variables) => Common.Variables), + renderVariables: Common.Variables | void, + callback?: (error: Error | void) => void, + options?: RefetchOptions, + ) => Common.Disposable, + }; export function createRefetchContainer( Component: ReactBaseComponent, fragmentSpec: GraphQLTaggedNode | GeneratedNodeMap, taggedNode: GraphQLTaggedNode, ): ReactBaseComponent; + + + } @@ -251,6 +292,11 @@ declare module 'react-relay' { export import commitMutation = __Relay.Runtime.commitRelayModernMutation; export import fetchQuery = __Relay.Runtime.fetchRelayModernQuery; export import requestSubscription = __Relay.Runtime.requestRelaySubscription; + + // exported for convenience — not exports in the original module + export import RelayProp = __Relay.Modern.RelayProp; + export import RelayPaginationProp = __Relay.Modern.RelayPaginationProp; + export import RelayRefetchProp = __Relay.Modern.RelayRefetchProp; } declare module 'react-relay/compat' { diff --git a/types/react-relay/react-relay-tests.tsx b/types/react-relay/react-relay-tests.tsx index e69de29bb2..fb70b04118 100644 --- a/types/react-relay/react-relay-tests.tsx +++ b/types/react-relay/react-relay-tests.tsx @@ -0,0 +1,350 @@ +import * as React from "react"; +import { + Environment, + Network, + RecordSource, + Store, + ConnectionHandler, +} from 'relay-runtime'; +import { + graphql, + commitMutation, + createFragmentContainer, + createPaginationContainer, + createRefetchContainer, + requestSubscription, + QueryRenderer, + RelayPaginationProp, + RelayRefetchProp +} from "react-relay"; + + +//////////////////////////// +// ENVIRONMENT +/////////////////////////// +let network: __Relay.Runtime.RelayNetwork; +const source = new RecordSource(); +const store = new Store(source); +const modernEnvironment = new Environment({ network, store }); + + +//////////////////////////// +// QUERY RENDERER +/////////////////////////// +const MyQueryRenderer = (props: { name: string}) => ( + { + if (error) { + return
{error.message}
; + } else if (props) { + return
{props.name} is great!
; + } + return
Loading
; + }} + /> +); + +//////////////////////////// +// FRAGMENT CONTAINER +/////////////////////////// +const MyFragmentContainer = createFragmentContainer( + class TodoListView extends React.Component { + render() { + return
; + } + }, + { + item: graphql` + fragment TodoItem_item on Todo { + text + isComplete + } + `, + } +); + + +//////////////////////////// +// REFETCH CONTAINER +/////////////////////////// +interface IStory { id: string } +interface IFeedStoriesProps { + relay: RelayRefetchProp; + feed: { + stories: { edges: { node: IStory }[] } + } +} +class Story extends React.Component<{ story: IStory }, {}> {} +class FeedStories extends React.Component { + render() { + return ( +
+ {this.props.feed.stories.edges.map( + edge => + )} +
+ ); + } + + _loadMore() { + // Increments the number of stories being rendered by 10. + const refetchVariables = (fragmentVariables: {count: number }) => ({ + count: fragmentVariables.count + 10, + }); + this.props.relay.refetch(refetchVariables, null); + } + } + +const FeedRefetchContainer = createRefetchContainer( + FeedStories, + { + feed: graphql.experimental` + fragment FeedStories_feed on Feed + @argumentDefinitions( + count: {type: "Int", defaultValue: 10} + ) { + stories(first: $count) { + edges { + node { + id + ...Story_story + } + } + } + } + ` + }, + graphql.experimental` + query FeedStoriesRefetchQuery($count: Int) { + feed { + ...FeedStories_feed @arguments(count: $count) + } + } + `, + ); + + + +//////////////////////////// +// PAGINATION CONTAINER +/////////////////////////// +interface IFeedProps { + user: { feed: { edges: { node: IStory}[]}} + relay: RelayPaginationProp; +} +class Feed extends React.Component { + render() { + return (
+ {this.props.user.feed.edges.map( + edge => + )} +
); + } + + _loadMore() { + if (!this.props.relay.hasMore() || this.props.relay.isLoading()) { + return; + } + + this.props.relay.loadMore( + 10, // Fetch the next 10 feed items + e => { + console.log(e); + }, + ); + } +} + +const FeedPaginationContainer = createPaginationContainer( + Feed, + { + user: graphql` + fragment Feed_user on User { + feed( + first: $count + after: $cursor + orderby: $orderBy # other variables + ) @connection(key: "Feed_feed") { + edges { + node { + id + ...Story_story + } + } + } + } + `, + }, + { + direction: 'forward', + getConnectionFromProps(props: { user: {feed: any}}) { + return props.user && props.user.feed; + }, + getFragmentVariables(prevVars, totalCount) { + return { + ...prevVars, + count: totalCount, + }; + }, + getVariables(props, {count, cursor}, fragmentVariables) { + return { + count, + cursor, + // in most cases, for variables other than connection filters like + // `first`, `after`, etc. you may want to use the previous values. + orderBy: fragmentVariables.orderBy, + }; + }, + query: graphql` + query FeedPaginationQuery( + $count: Int! + $cursor: String + $orderby: String! + ) { + user { + # You could reference the fragment defined previously. + ...Feed_user + } + } + ` + } +); + + +//////////////////////////// +// MUTATIONS +/////////////////////////// + +const mutation = graphql` +mutation MarkReadNotificationMutation( + $input: MarkReadNotificationData! +) { + markReadNotification(data: $input) { + notification { + seenState + } + } +} +`; + +const optimisticResponse = { + markReadNotification: { + notification: { + seenState: 'SEEN', + }, + }, +}; + +const configs = [{ + type: 'NODE_DELETE' as 'NODE_DELETE', + deletedIDFieldName: 'destroyedShipId', +}, { + type: 'RANGE_ADD' as 'RANGE_ADD', + parentID: 'shipId', + connectionInfo: [{ + key: 'AddShip_ships', + rangeBehavior: 'append', + }], + edgeName: 'newShipEdge', +}, { + type: 'RANGE_DELETE' as 'RANGE_DELETE', + parentID: 'todoId', + connectionKeys: [{ + key: 'RemoveTags_tags', + rangeBehavior: 'append', + }], + pathToConnection: ['todo', 'tags'], + deletedIDFieldName: 'removedTagId' +}]; + +function markNotificationAsRead(source: string, storyID: string) { + const variables = { + input: { + source, + storyID, + }, + }; + + commitMutation( + modernEnvironment, + { + configs, + mutation, + optimisticResponse, + variables, + onCompleted: (response, errors) => { + console.log('Response received from server.') + }, + onError: err => console.error(err), + }, + ); +} + + + +//////////////////////////// +// SUBSCRIPTIONS +/////////////////////////// + +const subscription = graphql` + subscription MarkReadNotificationSubscription( + $storyID: ID! + ) { + markReadNotification(storyID: $storyID) { + notification { + seenState + } + } + } +`; + +const variables = { + storyID: '123', +}; + +requestSubscription( + modernEnvironment, // see Environment docs + { + subscription, + variables, + // optional but recommended: + onCompleted: () => {}, + onError: error => console.error(error), + // example of a custom updater + updater: store => { + // Get the notification + const rootField = store.getRootField('markReadNotification'); + const notification = !!rootField && rootField.getLinkedRecord('notification'); + // Add it to a connection + const viewer = store.getRoot().getLinkedRecord('viewer'); + const notifications = + ConnectionHandler.getConnection(viewer, 'notifications'); + const edge = ConnectionHandler.createEdge( + store, + notifications, + notification, + '', + ); + ConnectionHandler.insertEdgeAfter(notifications, edge); + }, + } +); diff --git a/types/relay-runtime/index.d.ts b/types/relay-runtime/index.d.ts index b54688f080..cc60e34add 100644 --- a/types/relay-runtime/index.d.ts +++ b/types/relay-runtime/index.d.ts @@ -193,9 +193,9 @@ declare namespace __Relay.Common { handleKey: string, }; interface IHandler { - update: (store: RecordSourceProxy, fieldPayload: HandleFieldPayload): void; + update: (store: RecordSourceProxy, fieldPayload: HandleFieldPayload) => void; [functionName: string]: Function; - }; + } export const Handler: IHandler; @@ -566,48 +566,52 @@ declare namespace __Relay.Common { import: string, max_runs: number, }; - - export type RelayMutationConfig = - | { + interface FIELDS_CHANGE { type: 'FIELDS_CHANGE', fieldIDs: {[fieldName: string]: DataID | Array}, - } - | { + } + interface RANGE_ADD { type: 'RANGE_ADD', parentName?: string, parentID?: string, connectionInfo?: Array<{ - key: string, - filters?: Variables, - rangeBehavior: string, + key: string, + filters?: Variables, + rangeBehavior: string, }>, connectionName?: string, edgeName: string, rangeBehaviors?: RangeBehaviors, - } - | { + } + interface NODE_DELETE { type: 'NODE_DELETE', parentName?: string, parentID?: string, connectionName?: string, deletedIDFieldName: string, - } - | { + } + interface RANGE_DELETE { type: 'RANGE_DELETE', parentName?: string, parentID?: string, connectionKeys?: Array<{ - key: string, - filters?: Variables, + key: string, + filters?: Variables, }>, connectionName?: string, deletedIDFieldName: string | Array, pathToConnection: Array, - } - | { + } + interface REQUIRED_CHILDREN { type: 'REQUIRED_CHILDREN', children: Array, - }; + } + export type RelayMutationConfig = + FIELDS_CHANGE | + RANGE_ADD | + NODE_DELETE | + RANGE_DELETE | + REQUIRED_CHILDREN; export type RelayMutationTransactionCommitCallbacks = { onFailure?: RelayMutationTransactionCommitFailureCallback, @@ -712,7 +716,7 @@ declare namespace __Relay.Runtime { // ~~~~~~~~~~~~~~~~~~~~~ // RelayDefaultHandlerProvider // ~~~~~~~~~~~~~~~~~~~~~ - export function HandlerProvider(name: string): Common.Handler | void; + export function HandlerProvider(name: string): typeof Common.Handler | void; // ~~~~~~~~~~~~~~~~~~~~~ // RelayModernEnvironment @@ -1116,10 +1120,10 @@ declare namespace __Relay.Runtime { onNext?: (response: Object | void) => void, updater?: (store: Common.RecordSourceSelectorProxy) => void, }; - type requestRelaySubscription = ( + export function requestRelaySubscription( environment: Environment, config: GraphQLSubscriptionConfig, - ) => Common.Disposable; + ): Common.Disposable; } declare module 'relay-runtime' { From 99e85e6f62166d61e6b5e113a3e9f87be04fbe0a Mon Sep 17 00:00:00 2001 From: voxmatt Date: Sat, 9 Sep 2017 17:17:54 -1000 Subject: [PATCH 009/828] apparently DT only allows one test file per directory --- .../react-relay/react-relay-classic-tests.tsx | 92 ----------- .../react-relay/react-relay-compat-tests.tsx | 0 types/react-relay/react-relay-tests.tsx | 153 +++++++++++++++--- 3 files changed, 127 insertions(+), 118 deletions(-) delete mode 100644 types/react-relay/react-relay-classic-tests.tsx delete mode 100644 types/react-relay/react-relay-compat-tests.tsx diff --git a/types/react-relay/react-relay-classic-tests.tsx b/types/react-relay/react-relay-classic-tests.tsx deleted file mode 100644 index f231381817..0000000000 --- a/types/react-relay/react-relay-classic-tests.tsx +++ /dev/null @@ -1,92 +0,0 @@ -import * as React from "react"; -import * as Relay from "react-relay/classic"; - -interface Props { - text: string - userId: string -} - -interface Response { -} - -export default class AddTweetMutation extends Relay.Mutation { - - getMutation () { - return Relay.QL`mutation{addTweet}` - } - - getFatQuery () { - return Relay.QL` - fragment on AddTweetPayload { - tweetEdge - user - } - ` - } - - getConfigs () { - return [{ - type: "RANGE_ADD", - parentName: "user", - parentID: this.props.userId, - connectionName: "tweets", - edgeName: "tweetEdge", - rangeBehaviors: { - "": "append", - }, - }] - } - - getVariables () { - return this.props - } -} - -interface ArtworkProps { - artwork: { - title: string - }, - relay: Relay.RelayProp, -} - -class Artwork extends React.Component { - render() { - return ( - - {this.props.artwork.title} - - ) - } -} - -const ArtworkContainer = Relay.createContainer(Artwork, { - fragments: { - artwork: () => Relay.QL` - fragment on Artwork { - title - } - ` - } -}) - -class StubbedArtwork extends React.Component { - render() { - const props = { - artwork: { title: "CHAMPAGNE FORMICA FLAG" }, - relay: { - route: { - name: "champagne" - }, - variables: { - artworkID: "champagne-formica-flag", - }, - setVariables: () => {}, - forceFetch: () => {}, - hasOptimisticUpdate: () => false, - getPendingTransactions: (): Relay.RelayMutationTransaction[] => undefined, - commitUpdate: () => {}, - } - } - return - } -} diff --git a/types/react-relay/react-relay-compat-tests.tsx b/types/react-relay/react-relay-compat-tests.tsx deleted file mode 100644 index e69de29bb2..0000000000 diff --git a/types/react-relay/react-relay-tests.tsx b/types/react-relay/react-relay-tests.tsx index fb70b04118..86ec270627 100644 --- a/types/react-relay/react-relay-tests.tsx +++ b/types/react-relay/react-relay-tests.tsx @@ -6,6 +6,13 @@ import { Store, ConnectionHandler, } from 'relay-runtime'; + + + + +//////////////////////////// +// RELAY MODERN TESTS +/////////////////////////// import { graphql, commitMutation, @@ -19,18 +26,18 @@ import { } from "react-relay"; -//////////////////////////// -// ENVIRONMENT -/////////////////////////// +// ~~~~~~~~~~~~~~~~~~~~~ +// Modern Environment +// ~~~~~~~~~~~~~~~~~~~~~ let network: __Relay.Runtime.RelayNetwork; const source = new RecordSource(); const store = new Store(source); const modernEnvironment = new Environment({ network, store }); -//////////////////////////// -// QUERY RENDERER -/////////////////////////// +// ~~~~~~~~~~~~~~~~~~~~~ +// Modern QueryRenderer +// ~~~~~~~~~~~~~~~~~~~~~ const MyQueryRenderer = (props: { name: string}) => ( ( /> ); -//////////////////////////// -// FRAGMENT CONTAINER -/////////////////////////// +// ~~~~~~~~~~~~~~~~~~~~~ +// Modern FragmentContainer +// ~~~~~~~~~~~~~~~~~~~~~ const MyFragmentContainer = createFragmentContainer( class TodoListView extends React.Component { render() { @@ -75,9 +82,9 @@ const MyFragmentContainer = createFragmentContainer( ); -//////////////////////////// -// REFETCH CONTAINER -/////////////////////////// +// ~~~~~~~~~~~~~~~~~~~~~ +// Modern RefetchContainer +// ~~~~~~~~~~~~~~~~~~~~~ interface IStory { id: string } interface IFeedStoriesProps { relay: RelayRefetchProp; @@ -140,9 +147,9 @@ const FeedRefetchContainer = createRefetchContainer( -//////////////////////////// -// PAGINATION CONTAINER -/////////////////////////// +// ~~~~~~~~~~~~~~~~~~~~~ +// Modern PaginationContainer +// ~~~~~~~~~~~~~~~~~~~~~ interface IFeedProps { user: { feed: { edges: { node: IStory}[]}} relay: RelayPaginationProp; @@ -230,10 +237,9 @@ const FeedPaginationContainer = createPaginationContainer( ); -//////////////////////////// -// MUTATIONS -/////////////////////////// - +// ~~~~~~~~~~~~~~~~~~~~~ +// Modern Mutations +// ~~~~~~~~~~~~~~~~~~~~~ const mutation = graphql` mutation MarkReadNotificationMutation( $input: MarkReadNotificationData! @@ -300,11 +306,9 @@ function markNotificationAsRead(source: string, storyID: string) { } - -//////////////////////////// -// SUBSCRIPTIONS -/////////////////////////// - +// ~~~~~~~~~~~~~~~~~~~~~ +// Modern Subscriptions +// ~~~~~~~~~~~~~~~~~~~~~ const subscription = graphql` subscription MarkReadNotificationSubscription( $storyID: ID! @@ -316,11 +320,9 @@ const subscription = graphql` } } `; - const variables = { storyID: '123', }; - requestSubscription( modernEnvironment, // see Environment docs { @@ -348,3 +350,102 @@ requestSubscription( }, } ); + + + + +//////////////////////////// +// RELAY-CLASSIC TESTS +/////////////////////////// + +import * as Relay from "react-relay/classic"; + +interface Props { + text: string + userId: string +} + +interface Response { +} + +export default class AddTweetMutation extends Relay.Mutation { + + getMutation () { + return Relay.QL`mutation{addTweet}` + } + + getFatQuery () { + return Relay.QL` + fragment on AddTweetPayload { + tweetEdge + user + } + ` + } + + getConfigs () { + return [{ + type: "RANGE_ADD", + parentName: "user", + parentID: this.props.userId, + connectionName: "tweets", + edgeName: "tweetEdge", + rangeBehaviors: { + "": "append", + }, + }] + } + + getVariables () { + return this.props + } +} + +interface ArtworkProps { + artwork: { + title: string + }, + relay: Relay.RelayProp, +} + +class Artwork extends React.Component { + render() { + return ( + + {this.props.artwork.title} + + ) + } +} + +const ArtworkContainer = Relay.createContainer(Artwork, { + fragments: { + artwork: () => Relay.QL` + fragment on Artwork { + title + } + ` + } +}) + +class StubbedArtwork extends React.Component { + render() { + const props = { + artwork: { title: "CHAMPAGNE FORMICA FLAG" }, + relay: { + route: { + name: "champagne" + }, + variables: { + artworkID: "champagne-formica-flag", + }, + setVariables: () => {}, + forceFetch: () => {}, + hasOptimisticUpdate: () => false, + getPendingTransactions: (): Relay.RelayMutationTransaction[] => undefined, + commitUpdate: () => {}, + } + } + return + } +} From 80d08efbc7ae438d8774fce275dd9ee071ea26b8 Mon Sep 17 00:00:00 2001 From: voxmatt Date: Sat, 9 Sep 2017 17:22:01 -1000 Subject: [PATCH 010/828] updating tsconfig --- types/react-relay/tsconfig.json | 4 +--- 1 file changed, 1 insertion(+), 3 deletions(-) diff --git a/types/react-relay/tsconfig.json b/types/react-relay/tsconfig.json index 825d91a0c2..5d225c2016 100644 --- a/types/react-relay/tsconfig.json +++ b/types/react-relay/tsconfig.json @@ -19,8 +19,6 @@ }, "files": [ "index.d.ts", - "react-relay-tests.tsx", - "react-relay-classic-tests.tsx", - "react-relay-compat-tests.tsx" + "react-relay-tests.tsx" ] } From 4a30f049202025b0bc1ed28857015dd91dbab261 Mon Sep 17 00:00:00 2001 From: voxmatt Date: Sat, 9 Sep 2017 17:31:16 -1000 Subject: [PATCH 011/828] removing Object and trying to eliminate unnecessary Function usage --- types/react-relay/index.d.ts | 12 ++++++------ types/relay-runtime/index.d.ts | 22 +++++++++++----------- 2 files changed, 17 insertions(+), 17 deletions(-) diff --git a/types/react-relay/index.d.ts b/types/react-relay/index.d.ts index 3b073666f9..072496d849 100644 --- a/types/react-relay/index.d.ts +++ b/types/react-relay/index.d.ts @@ -18,8 +18,8 @@ declare namespace __Relay.Modern { // ~~~~~~~~~~~~~~~~~~~~~ type ConcreteFragment = any; type ConcreteBatch = any; - type ConcreteFragmentDefinition = Object; - type ConcreteOperationDefinition = Object; + type ConcreteFragmentDefinition = object; + type ConcreteOperationDefinition = object; type ReactBaseComponent = React.ComponentClass | React.StatelessComponent; // ~~~~~~~~~~~~~~~~~~~~~ @@ -122,10 +122,10 @@ declare namespace __Relay.Modern { ): Common.Variables; type ConnectionConfig = { direction?: 'backward' | 'forward', - getConnectionFromProps?: (props: Object) => ConnectionData | void, + getConnectionFromProps?: (props: object) => ConnectionData | void, getFragmentVariables?: typeof FragmentVariablesGetter, getVariables: ( - props: Object, + props: {[propName: string]: any }, paginationInfo: {count: number, cursor: string | void}, fragmentVariables: Common.Variables, ) => Common.Variables, @@ -225,8 +225,8 @@ declare namespace __Relay.Compat { // ~~~~~~~~~~~~~~~~~~~~~ type ConcreteFragment = any; type ConcreteBatch = any; - type ConcreteFragmentDefinition = Object; - type ConcreteOperationDefinition = Object; + type ConcreteFragmentDefinition = object; + type ConcreteOperationDefinition = object; // ~~~~~~~~~~~~~~~~~~~~~ diff --git a/types/relay-runtime/index.d.ts b/types/relay-runtime/index.d.ts index cc60e34add..09c456b980 100644 --- a/types/relay-runtime/index.d.ts +++ b/types/relay-runtime/index.d.ts @@ -24,8 +24,8 @@ declare namespace __Relay.Common { type RelayQueryRequest = any; type ConcreteFragment = any; type ConcreteBatch = any; - type ConcreteFragmentDefinition = Object; - type ConcreteOperationDefinition = Object; + type ConcreteFragmentDefinition = object; + type ConcreteOperationDefinition = object; /** @@ -622,7 +622,7 @@ declare namespace __Relay.Common { preventAutoRollback: () => void, ) => void; export type RelayMutationTransactionCommitSuccessCallback = (response: { - [key: string]: Object, + [key: string]: any, }) => void; export type NetworkLayer = { sendMutation(request: RelayMutationRequest): Promise | void, @@ -693,9 +693,9 @@ declare namespace __Relay.Runtime { type RelayDebugger = any; type OptimisticUpdate = any; type OperationSelector = Common.COperationSelector; - type Selector = Common.CSelector; + type Selector = Common.CSelector; type PayloadData = any; - type Snapshot = Common.CSnapshot; + type Snapshot = Common.CSnapshot; type RelayResponsePayload = any; type MutableRecordSource = RecordSource; @@ -704,7 +704,7 @@ declare namespace __Relay.Runtime { * a GraphQL operation. */ type ExecuteFunction = ( - operation: Object, + operation: object, variables: Common.Variables, cacheConfig: Common.CacheConfig, uploadables?: Common.UploadableMap | void, @@ -737,7 +737,7 @@ declare namespace __Relay.Runtime { applyMutation(config: { operation: OperationSelector, optimisticUpdater?: Common.SelectorStoreUpdater, - optimisticResponse?: Object, + optimisticResponse?: object, }): Common.Disposable; check(readSelector: Selector): boolean; commitPayload( @@ -759,7 +759,7 @@ declare namespace __Relay.Runtime { executeMutation(config: { operation: OperationSelector, optimisticUpdater?: Common.SelectorStoreUpdater | void, - optimisticResponse?: Object | void, + optimisticResponse?: object | void, updater?: Common.SelectorStoreUpdater | void, uploadables?: Common.UploadableMap | void, }): RelayObservable; @@ -1062,7 +1062,7 @@ declare namespace __Relay.Runtime { onCompleted?: (response: T, errors: Array | void) => void, onError?: (error?: Error) => void, optimisticUpdater?: Common.SelectorStoreUpdater | void, - optimisticResponse?: Object, + optimisticResponse?: object, updater?: Common.SelectorStoreUpdater | void, }; function commitRelayModernMutation( @@ -1079,7 +1079,7 @@ declare namespace __Relay.Runtime { mutation: Common.GraphQLTaggedNode, variables: Common.Variables, optimisticUpdater?: Common.SelectorStoreUpdater, - optimisticResponse?: Object, + optimisticResponse?: object, }; // ~~~~~~~~~~~~~~~~~~~~~ @@ -1117,7 +1117,7 @@ declare namespace __Relay.Runtime { variables: Common.Variables, onCompleted?: () => void, onError?: (error: Error) => void, - onNext?: (response: Object | void) => void, + onNext?: (response: object | void) => void, updater?: (store: Common.RecordSourceSelectorProxy) => void, }; export function requestRelaySubscription( From b6a411db2a68e170d7c9467218b0cae582a0fffd Mon Sep 17 00:00:00 2001 From: voxmatt Date: Sat, 9 Sep 2017 17:45:37 -1000 Subject: [PATCH 012/828] moving things inline with the dt generator script and downgrading typescript version to acceptable 2.4 --- types/react-relay/index.d.ts | 5 ++--- types/react-relay/tsconfig.json | 2 +- types/react-relay/tslint.json | 1 + types/relay-runtime/index.d.ts | 2 +- types/relay-runtime/tsconfig.json | 15 +++++++-------- types/relay-runtime/tslint.json | 1 + 6 files changed, 13 insertions(+), 13 deletions(-) create mode 100644 types/react-relay/tslint.json create mode 100644 types/relay-runtime/tslint.json diff --git a/types/react-relay/index.d.ts b/types/react-relay/index.d.ts index 072496d849..de3def9a00 100644 --- a/types/react-relay/index.d.ts +++ b/types/react-relay/index.d.ts @@ -1,9 +1,8 @@ // Type definitions for react-relay 1.3.0 // Project: https://github.com/facebook/relay -// Definitions by: Johannes Schickling -// Matt Martin +// Definitions by: Johannes Schickling , Matt Martin // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -// TypeScript Version: 2.5 +// TypeScript Version: 2.4 /// /// diff --git a/types/react-relay/tsconfig.json b/types/react-relay/tsconfig.json index 5d225c2016..9cabc08c4a 100644 --- a/types/react-relay/tsconfig.json +++ b/types/react-relay/tsconfig.json @@ -7,7 +7,7 @@ ], "noImplicitAny": true, "noImplicitThis": true, - "strictNullChecks": false, + "strictNullChecks": true, "baseUrl": "../", "typeRoots": [ "../" diff --git a/types/react-relay/tslint.json b/types/react-relay/tslint.json new file mode 100644 index 0000000000..3db14f85ea --- /dev/null +++ b/types/react-relay/tslint.json @@ -0,0 +1 @@ +{ "extends": "dtslint/dt.json" } diff --git a/types/relay-runtime/index.d.ts b/types/relay-runtime/index.d.ts index 09c456b980..5e86ed0681 100644 --- a/types/relay-runtime/index.d.ts +++ b/types/relay-runtime/index.d.ts @@ -2,7 +2,7 @@ // Project: https://github.com/facebook/relay // Definitions by: Matt Martin // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -// TypeScript Version: 2.5 +// TypeScript Version: 2.4 declare namespace __Relay.Common { /** diff --git a/types/relay-runtime/tsconfig.json b/types/relay-runtime/tsconfig.json index 8224ba918b..dd77fca0e4 100644 --- a/types/relay-runtime/tsconfig.json +++ b/types/relay-runtime/tsconfig.json @@ -1,8 +1,4 @@ { - "files": [ - "index.d.ts", - "relay-runtime-tests.tsx" - ], "compilerOptions": { "module": "commonjs", "lib": [ @@ -13,14 +9,17 @@ "noImplicitThis": true, "strictNullChecks": true, "baseUrl": "../", - "jsx": "react", - "experimentalDecorators": true, - "forceConsistentCasingInFileNames": true, "typeRoots": [ "../" ], "types": [], "noEmit": true, + "jsx": "react", + "experimentalDecorators": true, "forceConsistentCasingInFileNames": true - } + }, + "files": [ + "index.d.ts", + "relay-runtime-tests.tsx" + ] } diff --git a/types/relay-runtime/tslint.json b/types/relay-runtime/tslint.json new file mode 100644 index 0000000000..3db14f85ea --- /dev/null +++ b/types/relay-runtime/tslint.json @@ -0,0 +1 @@ +{ "extends": "dtslint/dt.json" } From 7f407c876e5c01bc293493bc78004215bb0eb106 Mon Sep 17 00:00:00 2001 From: voxmatt Date: Sat, 9 Sep 2017 17:51:02 -1000 Subject: [PATCH 013/828] fixing a couple errors --- types/react-relay/index.d.ts | 2 +- types/react-relay/react-relay-tests.tsx | 6 +++--- 2 files changed, 4 insertions(+), 4 deletions(-) diff --git a/types/react-relay/index.d.ts b/types/react-relay/index.d.ts index de3def9a00..a165229584 100644 --- a/types/react-relay/index.d.ts +++ b/types/react-relay/index.d.ts @@ -146,7 +146,7 @@ declare namespace __Relay.Modern { export type RelayRefetchProp = RelayProp & { refetch: ( refetchVariables: Common.Variables | ((fragmentVariables: Common.Variables) => Common.Variables), - renderVariables: Common.Variables | void, + renderVariables?: Common.Variables, callback?: (error: Error | void) => void, options?: RefetchOptions, ) => Common.Disposable, diff --git a/types/react-relay/react-relay-tests.tsx b/types/react-relay/react-relay-tests.tsx index 86ec270627..2b76bc7860 100644 --- a/types/react-relay/react-relay-tests.tsx +++ b/types/react-relay/react-relay-tests.tsx @@ -29,7 +29,7 @@ import { // ~~~~~~~~~~~~~~~~~~~~~ // Modern Environment // ~~~~~~~~~~~~~~~~~~~~~ -let network: __Relay.Runtime.RelayNetwork; +const network = {} as __Relay.Runtime.RelayNetwork; const source = new RecordSource(); const store = new Store(source); const modernEnvironment = new Environment({ network, store }); @@ -113,7 +113,7 @@ class FeedStories extends React.Component { const refetchVariables = (fragmentVariables: {count: number }) => ({ count: fragmentVariables.count + 10, }); - this.props.relay.refetch(refetchVariables, null); + this.props.relay.refetch(refetchVariables); } } @@ -442,7 +442,7 @@ class StubbedArtwork extends React.Component { setVariables: () => {}, forceFetch: () => {}, hasOptimisticUpdate: () => false, - getPendingTransactions: (): Relay.RelayMutationTransaction[] => undefined, + getPendingTransactions: (): any => undefined, commitUpdate: () => {}, } } From 068231de36daefce9e14e7a3110e2eaf14ab3d08 Mon Sep 17 00:00:00 2001 From: voxmatt Date: Sun, 10 Sep 2017 09:47:01 -1000 Subject: [PATCH 014/828] working my way through relay-runtime linting errors --- types/relay-runtime/index.d.ts | 2234 ++++++++++++++++---------------- 1 file changed, 1117 insertions(+), 1117 deletions(-) diff --git a/types/relay-runtime/index.d.ts b/types/relay-runtime/index.d.ts index 5e86ed0681..80ea0dcdea 100644 --- a/types/relay-runtime/index.d.ts +++ b/types/relay-runtime/index.d.ts @@ -4,1129 +4,1129 @@ // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped // TypeScript Version: 2.4 -declare namespace __Relay.Common { - /** - * SOURCE: - * Relay 1.3.0 - * https://github.com/facebook/relay/blob/b85a1d69bb72be4ace67179f55c2a54a8d761c8b/packages/react-relay/classic/environment/RelayCombinedEnvironmentTypes.js - */ - // ~~~~~~~~~~~~~~~~~~~~~ - // Util - // ~~~~~~~~~~~~~~~~~~~~~ - type Maybe = T | void; +declare namespace __Relay { + namespace Common { - // ~~~~~~~~~~~~~~~~~~~~~ - // Maybe Fix - // ~~~~~~~~~~~~~~~~~~~~~ - type RelayConcreteNode = any; - type RelayMutationTransaction = any; - type RelayMutationRequest = any; - type RelayQueryRequest = any; - type ConcreteFragment = any; - type ConcreteBatch = any; - type ConcreteFragmentDefinition = object; - type ConcreteOperationDefinition = object; - - - /** - * FIXME: RelayContainer used to be typed with ReactClass, but - * ReactClass is broken and allows for access to any property. For example - * ReactClass.getFragment('foo') is valid even though ReactClass has no - * such getFragment() type definition. When ReactClass is fixed this causes a - * lot of errors in Relay code since methods like getFragment() are used often - * but have no definition in Relay's types. Suppressing for now. - */ - export type RelayContainer = any; - // ~~~~~~~~~~~~~~~~~~~~~ - // RelayQL - // ~~~~~~~~~~~~~~~~~~~~~ - type RelayQL = ( - strings: Array, - ...substitutions: Array - ) => Common.RelayConcreteNode; - - // ~~~~~~~~~~~~~~~~~~~~~ - // RelayModernGraphQLTag - // ~~~~~~~~~~~~~~~~~~~~~ - type GeneratedNodeMap = {[key: string]: GraphQLTaggedNode}; - type GraphQLTaggedNode = - (() => ConcreteFragment | ConcreteBatch) | - { - modern: () => ConcreteFragment | ConcreteBatch, - classic: (relayQL: RelayQL) => - | ConcreteFragmentDefinition - | ConcreteOperationDefinition, - }; - // ~~~~~~~~~~~~~~~~~~~~~ - // General Usage - // ~~~~~~~~~~~~~~~~~~~~~ - export type DataID = string; - export type Variables = {[name: string]: any}; - export type Uploadable = File | Blob; - export type UploadableMap = {[key: string]: Uploadable}; - - - // ~~~~~~~~~~~~~~~~~~~~~ - // RelayNetworkTypes - // Version: Relay 1.3.0 - // File: https://github.com/facebook/relay/blob/master/packages/relay-runtime/network/RelayNetworkTypes.js - // ~~~~~~~~~~~~~~~~~~~~~ - - export type LegacyObserver = { - onCompleted?: (() => void) | void, - onError?: ((error: Error) => void) | void, - onNext?: ((data: T) => void) | void, - }; - export type PayloadError = { - message: string, - locations?: Array<{ - line: number, - column: number, - }>, - }; - /** - * A function that executes a GraphQL operation with request/response semantics. - * - * May return an Observable or Promise of a raw server response. - */ - export function FetchFunction( - operation: ConcreteBatch, - variables: Variables, - cacheConfig: CacheConfig, - uploadables?: Common.UploadableMap, - ): Runtime.ObservableFromValue; - - /** - * A function that executes a GraphQL subscription operation, returning one or - * more raw server responses over time. - * - * May return an Observable, otherwise must call the callbacks found in the - * fourth parameter. - */ - export type SubscribeFunction = ( - operation: ConcreteBatch, - variables: Variables, - cacheConfig: CacheConfig, - observer: LegacyObserver, - ) => Runtime.RelayObservable | Disposable; - - - // ~~~~~~~~~~~~~~~~~~~~~ - // RelayStoreTypes - // Version: Relay 1.3.0 - // File: https://github.com/facebook/relay/blob/master/packages/relay-runtime/store/RelayStoreTypes.js - // ~~~~~~~~~~~~~~~~~~~~~ - /** - * A function that receives a proxy over the store and may trigger side-effects - * (indirectly) by calling `set*` methods on the store or its record proxies. - */ - export type StoreUpdater = (store: RecordSourceProxy) => void; - - /** - * Similar to StoreUpdater, but accepts a proxy tied to a specific selector in - * order to easily access the root fields of a query/mutation as well as a - * second argument of the response object of the mutation. - */ - export type SelectorStoreUpdater = ( - store: RecordSourceSelectorProxy, - // Actually RelayCombinedEnvironmentTypes#SelectorData, but mixed is - // inconvenient to access deeply in product code. - data: any, // FLOW FIXME - ) => void; - - /** - * Extends the RecordSourceProxy interface with methods for accessing the root - * fields of a Selector. - */ - export interface RecordSourceSelectorProxy { - create(dataID: DataID, typeName: string): RecordProxy, - delete(dataID: DataID): void, - get(dataID: DataID): RecordProxy | void, - getRoot(): RecordProxy, - getRootField(fieldName: string): RecordProxy | void, - getPluralRootField(fieldName: string): RecordProxy[] | void, - } - - export interface RecordProxy { - copyFieldsFrom(source: RecordProxy): void, - getDataID(): DataID, - getLinkedRecord(name: string, args?: Variables | void): RecordProxy | void, - getLinkedRecords(name: string, args?: Variables | void): (RecordProxy | void)[] | void, - getOrCreateLinkedRecord( - name: string, - typeName: string, - args?: Variables | void, - ): RecordProxy, - getType(): string, - getValue(name: string, args?: Variables | void): any, - setLinkedRecord( - record: RecordProxy, - name: string, - args?: Variables | void, - ): RecordProxy, - setLinkedRecords( - records: (RecordProxy | void)[] | void, - name: string, - args?: Variables | void, - ): RecordProxy, - setValue(value: any, name: string, args?: Variables | void): RecordProxy, - } - - export interface RecordSourceProxy { - create(dataID: DataID, typeName: string): RecordProxy, - delete(dataID: DataID): void, - get(dataID: DataID): (RecordProxy | void)[] | void, - getRoot(): RecordProxy, - } - - export type HandleFieldPayload = { - // The arguments that were fetched. - args: Variables, - // The __id of the record containing the source/handle field. - dataID: DataID, - // The (storage) key at which the original server data was written. - fieldKey: string, - // The name of the handle. - handle: string, - // The (storage) key at which the handle's data should be written by the - // handler. - handleKey: string, - }; - interface IHandler { - update: (store: RecordSourceProxy, fieldPayload: HandleFieldPayload) => void; - [functionName: string]: Function; - } - export const Handler: IHandler; - - - // ~~~~~~~~~~~~~~~~~~~~~ - // RelayCombinedEnvironmentTypes - // Version: Relay 1.3.0 - // File: https://github.com/facebook/relay/blob/b85a1d69bb72be4ace67179f55c2a54a8d761c8b/packages/react-relay/classic/environment/RelayCombinedEnvironmentTypes.js - // ~~~~~~~~~~~~~~~~~~~~~ - /** - * Settings for how a query response may be cached. - * - * - `force`: causes a query to be issued unconditionally, irrespective of the - * state of any configured response cache. - * - `poll`: causes a query to live update by polling at the specified interval - in milliseconds. (This value will be passed to setTimeout.) - */ - export type CacheConfig = { - force?: boolean | void, - poll?: number | void, - }; - - /** - * Represents any resource that must be explicitly disposed of. The most common - * use-case is as a return value for subscriptions, where calling `dispose()` - * would cancel the subscription. - */ - export type Disposable = { - dispose(): void, - }; - - - /** - * Arbitrary data e.g. received by a container as props. - */ - export type Props = {[key: string]: any}; - - /* - * An individual cached graph object. - */ - export type Record = {[key: string]: any}; - - /** - * A collection of records keyed by id. - */ - export type RecordMap = {[dataID: string]: Record | void}; - - /** - * A selector defines the starting point for a traversal into the graph for the - * purposes of targeting a subgraph. - */ - export type CSelector = { - dataID: DataID, - node: TNode, - variables: Variables, - }; - - /** - * A representation of a selector and its results at a particular point in time. - */ - export type CSnapshot = CSelector & { - data: SelectorData | void, - seenRecords: RecordMap, - }; - - /** - * The results of a selector given a store/RecordSource. - */ - export type SelectorData = {[key: string]: any}; - - /** - * The results of reading the results of a FragmentMap given some input - * `Props`. - */ - export type FragmentSpecResults = {[key: string]: any}; - - /** - * A utility for resolving and subscribing to the results of a fragment spec - * (key -> fragment mapping) given some "props" that determine the root ID - * and variables to use when reading each fragment. When props are changed via - * `setProps()`, the resolver will update its results and subscriptions - * accordingly. Internally, the resolver: - * - Converts the fragment map & props map into a map of `Selector`s. - * - Removes any resolvers for any props that became null. - * - Creates resolvers for any props that became non-null. - * - Updates resolvers with the latest props. - */ - export interface FragmentSpecResolver { - /** - * Stop watching for changes to the results of the fragments. - */ - dispose(): void, - - /** - * Get the current results. - */ - resolve(): FragmentSpecResults, - - /** - * Update the resolver with new inputs. Call `resolve()` to get the updated - * results. - */ - setProps(props: Props): void, - - /** - * Override the variables used to read the results of the fragments. Call - * `resolve()` to get the updated results. - */ - setVariables(variables: Variables): void, - } - - export type CFragmentMap = {[key: string]: TFragment}; - - /** - * An operation selector describes a specific instance of a GraphQL operation - * with variables applied. - * - * - `root`: a selector intended for processing server results or retaining - * response data in the store. - * - `fragment`: a selector intended for use in reading or subscribing to - * the results of the the operation. - */ - export type COperationSelector = { - fragment: CSelector, - node: TOperation, - root: CSelector, - variables: Variables, - }; - - /** - * The public API of Relay core. Represents an encapsulated environment with its - * own in-memory cache. - */ - export interface CEnvironment< - TEnvironment, - TFragment, - TGraphQLTaggedNode, - TNode, - TOperation, - TPayload, - > { - /** - * Read the results of a selector from in-memory records in the store. - */ - lookup(selector: CSelector): CSnapshot, - - /** - * Subscribe to changes to the results of a selector. The callback is called - * when data has been committed to the store that would cause the results of - * the snapshot's selector to change. - */ - subscribe( - snapshot: CSnapshot, - callback: (snapshot: CSnapshot) => void, - ): Disposable, - - /** - * Ensure that all the records necessary to fulfill the given selector are - * retained in-memory. The records will not be eligible for garbage collection - * until the returned reference is disposed. - * - * Note: This is a no-op in the classic core. - */ - retain(selector: CSelector): Disposable, - - /** - * Send a query to the server with request/response semantics: the query will - * either complete successfully (calling `onNext` and `onCompleted`) or fail - * (calling `onError`). - * - * Note: Most applications should use `streamQuery` in order to - * optionally receive updated information over time, should that feature be - * supported by the network/server. A good rule of thumb is to use this method - * if you would otherwise immediately dispose the `streamQuery()` - * after receving the first `onNext` result. - */ - sendQuery(config: { - cacheConfig?: CacheConfig | void, - onCompleted?: Maybe<() => void>, - onError?: Maybe<(error: Error) => void>, - onNext?: Maybe<(payload: TPayload) => void>, - operation: COperationSelector, - }): Disposable, - - /** - * Send a query to the server with request/subscription semantics: one or more - * responses may be returned (via `onNext`) over time followed by either - * the request completing (`onCompleted`) or an error (`onError`). - * - * Networks/servers that support subscriptions may choose to hold the - * subscription open indefinitely such that `onCompleted` is not called. - */ - streamQuery(config: { - cacheConfig?: Maybe, - onCompleted?: Maybe<() => void>, - onError?: Maybe<(error: Error) => void>, - onNext?: Maybe<(payload: TPayload) => void>, - operation: COperationSelector, - }): Disposable, - - unstable_internal: CUnstableEnvironmentCore< - TEnvironment, - TFragment, - TGraphQLTaggedNode, - TNode, - TOperation - >, - } - - export interface CUnstableEnvironmentCore< - TEnvironment, - TFragment, - TGraphQLTaggedNode, - TNode, - TOperation, - > { - /** - * Create an instance of a FragmentSpecResolver. - * - * TODO: The FragmentSpecResolver *can* be implemented via the other methods - * defined here, so this could be moved out of core. It's convenient to have - * separate implementations until the experimental core is in OSS. - */ - createFragmentSpecResolver: ( - context: CRelayContext, - containerName: string, - fragments: CFragmentMap, - props: Props, - callback: () => void, - ) => FragmentSpecResolver, - - /** - * Creates an instance of an OperationSelector given an operation definition - * (see `getOperation`) and the variables to apply. The input variables are - * filtered to exclude variables that do not matche defined arguments on the - * operation, and default values are populated for null values. - */ - createOperationSelector: ( - operation: TOperation, - variables: Variables, - ) => COperationSelector, - - /** - * Given a graphql`...` tagged template, extract a fragment definition usable - * by this version of Relay core. Throws if the value is not a fragment. - */ - getFragment: (node: TGraphQLTaggedNode) => TFragment, - - /** - * Given a graphql`...` tagged template, extract an operation definition - * usable by this version of Relay core. Throws if the value is not an - * operation. - */ - getOperation: (node: TGraphQLTaggedNode) => TOperation, - - /** - * Determine if two selectors are equal (represent the same selection). Note - * that this function returns `false` when the two queries/fragments are - * different objects, even if they select the same fields. - */ - areEqualSelectors: (a: CSelector, b: CSelector) => boolean, - - /** - * Given the result `item` from a parent that fetched `fragment`, creates a - * selector that can be used to read the results of that fragment for that item. - * - * Example: - * - * Given two fragments as follows: - * - * ``` - * fragment Parent on User { - * id - * ...Child - * } - * fragment Child on User { - * name - * } - * ``` - * - * And given some object `parent` that is the results of `Parent` for id "4", - * the results of `Child` can be accessed by first getting a selector and then - * using that selector to `lookup()` the results against the environment: - * - * ``` - * const childSelector = getSelector(queryVariables, Child, parent); - * const childData = environment.lookup(childSelector).data; - * ``` - */ - getSelector: ( - operationVariables: Variables, - fragment: TFragment, - prop: any, - ) => CSelector | void, - - /** - * Given the result `items` from a parent that fetched `fragment`, creates a - * selector that can be used to read the results of that fragment on those - * items. This is similar to `getSelector` but for "plural" fragments that - * expect an array of results and therefore return an array of selectors. - */ - getSelectorList: ( - operationVariables: Variables, - fragment: TFragment, - props: Array, - ) => Array> | void, - - /** - * Given a mapping of keys -> results and a mapping of keys -> fragments, - * extracts the selectors for those fragments from the results. - * - * The canonical use-case for this function are Relay Containers, which - * use this function to convert (props, fragments) into selectors so that they - * can read the results to pass to the inner component. - */ - getSelectorsFromObject: ( - operationVariables: Variables, - fragments: CFragmentMap, - props: Props, - ) => {[key: string]: Maybe<(CSelector | Array>)>}, - - /** - * Given a mapping of keys -> results and a mapping of keys -> fragments, - * extracts a mapping of keys -> id(s) of the results. - * - * Similar to `getSelectorsFromObject()`, this function can be useful in - * determining the "identity" of the props passed to a component. - */ - getDataIDsFromObject: ( - fragments: CFragmentMap, - props: Props, - ) => {[key: string]: Maybe<(DataID | Array)>}, - - /** - * Given a mapping of keys -> results and a mapping of keys -> fragments, - * extracts the merged variables that would be in scope for those - * fragments/results. - * - * This can be useful in determing what varaibles were used to fetch the data - * for a Relay container, for example. - */ - getVariablesFromObject: ( - operationVariables: Variables, - fragments: CFragmentMap, - props: Props, - ) => Variables, - } - - /** - * The type of the `relay` property set on React context by the React/Relay - * integration layer (e.g. QueryRenderer, FragmentContainer, etc). - */ - export type CRelayContext = { - environment: TEnvironment, - variables: Variables, - }; - - - // ~~~~~~~~~~~~~~~~~~~~~ - // RelayTypes - /** - * Version: Relay 1.3.0 - * File: - * https://github.com/facebook/relay/blob/fa9f48ea209ee2402d433b59a84d1cbc046574e2/packages/react-relay/classic/tools/RelayTypes.js - */ - // ~~~~~~~~~~~~~~~~~~~~~ - export type RerunParam = { - param: string, - import: string, - max_runs: number, - }; - interface FIELDS_CHANGE { - type: 'FIELDS_CHANGE', - fieldIDs: {[fieldName: string]: DataID | Array}, - } - interface RANGE_ADD { - type: 'RANGE_ADD', - parentName?: string, - parentID?: string, - connectionInfo?: Array<{ - key: string, - filters?: Variables, - rangeBehavior: string, - }>, - connectionName?: string, - edgeName: string, - rangeBehaviors?: RangeBehaviors, - } - interface NODE_DELETE { - type: 'NODE_DELETE', - parentName?: string, - parentID?: string, - connectionName?: string, - deletedIDFieldName: string, - } - interface RANGE_DELETE { - type: 'RANGE_DELETE', - parentName?: string, - parentID?: string, - connectionKeys?: Array<{ - key: string, - filters?: Variables, - }>, - connectionName?: string, - deletedIDFieldName: string | Array, - pathToConnection: Array, - } - interface REQUIRED_CHILDREN { - type: 'REQUIRED_CHILDREN', - children: Array, - } - export type RelayMutationConfig = - FIELDS_CHANGE | - RANGE_ADD | - NODE_DELETE | - RANGE_DELETE | - REQUIRED_CHILDREN; - - export type RelayMutationTransactionCommitCallbacks = { - onFailure?: RelayMutationTransactionCommitFailureCallback, - onSuccess?: RelayMutationTransactionCommitSuccessCallback, - }; - export type RelayMutationTransactionCommitFailureCallback = ( - transaction: RelayMutationTransaction, - preventAutoRollback: () => void, - ) => void; - export type RelayMutationTransactionCommitSuccessCallback = (response: { - [key: string]: any, - }) => void; - export type NetworkLayer = { - sendMutation(request: RelayMutationRequest): Promise | void, - sendQueries(requests: Array): Promise | void, - supports(...options: Array): boolean, - }; - export type QueryResult = { - error?: Error | void, - ref_params?: {[name: string]: any} | void, - response: QueryPayload, - }; - export type ReadyState = { - aborted: boolean, - done: boolean, - error: Error | void, - events: Array, - ready: boolean, - stale: boolean, - }; - type RelayContainerErrorEventType = - | 'CACHE_RESTORE_FAILED' - | 'NETWORK_QUERY_ERROR'; - type RelayContainerLoadingEventType = - | 'ABORT' - | 'CACHE_RESTORED_REQUIRED' - | 'CACHE_RESTORE_START' - | 'NETWORK_QUERY_RECEIVED_ALL' - | 'NETWORK_QUERY_RECEIVED_REQUIRED' - | 'NETWORK_QUERY_START' - | 'STORE_FOUND_ALL' - | 'STORE_FOUND_REQUIRED'; - export type ReadyStateChangeCallback = (readyState: ReadyState) => void; - export type ReadyStateEvent = { - type: RelayContainerLoadingEventType | RelayContainerErrorEventType, - error?: Error, - }; - export type Abortable = { - abort(): void, - }; - - - // ~~~~~~~~~~~~~~~~~~~~~ - // RelayInternalTypes - /** - * Version: Relay 1.3.0 - * File: - * https://github.com/facebook/relay/blob/master/packages/react-relay/classic/tools/RelayInternalTypes.js - */ - // ~~~~~~~~~~~~~~~~~~~~~ - export type QueryPayload = {[key: string]: any}; - export type RelayQuerySet = {[queryName: string]: any}; - type RangeBehaviorsFunction = (connectionArgs: { - [argName: string]: any, - }) => 'APPEND' | 'IGNORE' | 'PREPEND' | 'REFETCH' | 'REMOVE'; - type RangeBehaviorsObject = { - [key: string]: 'APPEND' | 'IGNORE' | 'PREPEND' | 'REFETCH' | 'REMOVE'; - }; - export type RangeBehaviors = RangeBehaviorsFunction | RangeBehaviorsObject; - } - - - - -declare namespace __Relay.Runtime { - // ~~~~~~~~~~~~~~~~~~~~~ - // Maybe Fix - // ~~~~~~~~~~~~~~~~~~~~~ - type RelayDebugger = any; - type OptimisticUpdate = any; - type OperationSelector = Common.COperationSelector; - type Selector = Common.CSelector; - type PayloadData = any; - type Snapshot = Common.CSnapshot; - type RelayResponsePayload = any; - type MutableRecordSource = RecordSource; - - /** - * A function that returns an Observable representing the response of executing - * a GraphQL operation. - */ - type ExecuteFunction = ( - operation: object, - variables: Common.Variables, - cacheConfig: Common.CacheConfig, - uploadables?: Common.UploadableMap | void, - ) => Promise; - type RelayNetwork = { - execute: ExecuteFunction, - }; - - // ~~~~~~~~~~~~~~~~~~~~~ - // RelayDefaultHandlerProvider - // ~~~~~~~~~~~~~~~~~~~~~ - export function HandlerProvider(name: string): typeof Common.Handler | void; - - // ~~~~~~~~~~~~~~~~~~~~~ - // RelayModernEnvironment - // ~~~~~~~~~~~~~~~~~~~~~ - type EnvironmentConfig = { - configName?: string, - handlerProvider?: typeof HandlerProvider, - network: Network, - store: Store, - }; - class Environment { - constructor (config: EnvironmentConfig); - getStore(): Store; - getDebugger(): RelayDebugger; - applyUpdate(optimisticUpdate: OptimisticUpdate): Common.Disposable; - revertUpdate(update: OptimisticUpdate): void; - replaceUpdate(update: OptimisticUpdate, newUpdate: OptimisticUpdate): void; - applyMutation(config: { - operation: OperationSelector, - optimisticUpdater?: Common.SelectorStoreUpdater, - optimisticResponse?: object, - }): Common.Disposable; - check(readSelector: Selector): boolean; - commitPayload( - operationSelector: OperationSelector, - payload: PayloadData, - ): void; - commitUpdate(updater: Common.StoreUpdater): void; - lookup(readSelector: Selector): Snapshot; - subscribe( - snapshot: Snapshot, - callback: (snapshot: Snapshot) => void, - ): Common.Disposable; - retain(selector: Selector): Common.Disposable; - execute(config: { - operation: OperationSelector, - cacheConfig?: Common.CacheConfig | void, - updater?: Common.SelectorStoreUpdater | void, - }): RelayObservable; - executeMutation(config: { - operation: OperationSelector, - optimisticUpdater?: Common.SelectorStoreUpdater | void, - optimisticResponse?: object | void, - updater?: Common.SelectorStoreUpdater | void, - uploadables?: Common.UploadableMap | void, - }): RelayObservable; - } - - // ~~~~~~~~~~~~~~~~~~~~~ - // RelayInMemoryRecordSource - // ~~~~~~~~~~~~~~~~~~~~~ - type Record = {[key: string]: any}; - type RecordMap = {[dataID: string]: Record | void}; - - // ~~~~~~~~~~~~~~~~~~~~~ - // Network - // ~~~~~~~~~~~~~~~~~~~~~ - class Network { /** - * Creates an implementation of the `Network` interface defined in - * `RelayNetworkTypes` given `fetch` and `subscribe` functions. + * SOURCE: + * Relay 1.3.0 + * https://github.com/facebook/relay/blob/b85a1d69bb72be4ace67179f55c2a54a8d761c8b/packages/react-relay/classic/environment/RelayCombinedEnvironmentTypes.js + */ + // ~~~~~~~~~~~~~~~~~~~~~ + // Util + // ~~~~~~~~~~~~~~~~~~~~~ + type Maybe = T | void; + + // ~~~~~~~~~~~~~~~~~~~~~ + // Maybe Fix + // ~~~~~~~~~~~~~~~~~~~~~ + type RelayConcreteNode = any; + type RelayMutationTransaction = any; + type RelayMutationRequest = any; + type RelayQueryRequest = any; + type ConcreteFragment = any; + type ConcreteBatch = any; + type ConcreteFragmentDefinition = object; + type ConcreteOperationDefinition = object; + + + /** + * FIXME: RelayContainer used to be typed with ReactClass, but + * ReactClass is broken and allows for access to any property. For example + * ReactClass.getFragment('foo') is valid even though ReactClass has no + * such getFragment() type definition. When ReactClass is fixed this causes a + * lot of errors in Relay code since methods like getFragment() are used often + * but have no definition in Relay's types. Suppressing for now. */ - static create(fetchFn: typeof Common.FetchFunction, subscribeFn?: Common.SubscribeFunction): RelayNetwork; + export type RelayContainer = any; + // ~~~~~~~~~~~~~~~~~~~~~ + // RelayQL + // ~~~~~~~~~~~~~~~~~~~~~ + type RelayQL = ( + strings: string[], + ...substitutions: any[] + ) => Common.RelayConcreteNode; + + // ~~~~~~~~~~~~~~~~~~~~~ + // RelayModernGraphQLTag + // ~~~~~~~~~~~~~~~~~~~~~ + type GeneratedNodeMap = { [key: string]: GraphQLTaggedNode }; + type GraphQLTaggedNode = + (() => ConcreteFragment | ConcreteBatch) | + { + modern: () => ConcreteFragment | ConcreteBatch, + classic: (relayQL: RelayQL) => + | ConcreteFragmentDefinition + | ConcreteOperationDefinition, + }; + // ~~~~~~~~~~~~~~~~~~~~~ + // General Usage + // ~~~~~~~~~~~~~~~~~~~~~ + export type DataID = string; + export type Variables = { [name: string]: any }; + export type Uploadable = File | Blob; + export type UploadableMap = { [key: string]: Uploadable }; + + + // ~~~~~~~~~~~~~~~~~~~~~ + // RelayNetworkTypes + // Version: Relay 1.3.0 + // File: https://github.com/facebook/relay/blob/master/packages/relay-runtime/network/RelayNetworkTypes.js + // ~~~~~~~~~~~~~~~~~~~~~ + + export type LegacyObserver = { + onCompleted?: (() => void) | void, + onError?: ((error: Error) => void) | void, + onNext?: ((data: T) => void) | void, + }; + export type PayloadError = { + message: string, + locations?: Array<{ + line: number, + column: number, + }>, + }; + /** + * A function that executes a GraphQL operation with request/response semantics. + * + * May return an Observable or Promise of a raw server response. + */ + export function FetchFunction( + operation: ConcreteBatch, + variables: Variables, + cacheConfig: CacheConfig, + uploadables?: Common.UploadableMap, + ): Runtime.ObservableFromValue; + + /** + * A function that executes a GraphQL subscription operation, returning one or + * more raw server responses over time. + * + * May return an Observable, otherwise must call the callbacks found in the + * fourth parameter. + */ + export type SubscribeFunction = ( + operation: ConcreteBatch, + variables: Variables, + cacheConfig: CacheConfig, + observer: LegacyObserver, + ) => Runtime.RelayObservable | Disposable; + + + // ~~~~~~~~~~~~~~~~~~~~~ + // RelayStoreTypes + // Version: Relay 1.3.0 + // File: https://github.com/facebook/relay/blob/master/packages/relay-runtime/store/RelayStoreTypes.js + // ~~~~~~~~~~~~~~~~~~~~~ + /** + * A function that receives a proxy over the store and may trigger side-effects + * (indirectly) by calling `set*` methods on the store or its record proxies. + */ + export type StoreUpdater = (store: RecordSourceProxy) => void; + + /** + * Similar to StoreUpdater, but accepts a proxy tied to a specific selector in + * order to easily access the root fields of a query/mutation as well as a + * second argument of the response object of the mutation. + */ + export type SelectorStoreUpdater = ( + store: RecordSourceSelectorProxy, + // Actually RelayCombinedEnvironmentTypes#SelectorData, but mixed is + // inconvenient to access deeply in product code. + data: any, // FLOW FIXME + ) => void; + + /** + * Extends the RecordSourceProxy interface with methods for accessing the root + * fields of a Selector. + */ + export interface RecordSourceSelectorProxy { + create(dataID: DataID, typeName: string): RecordProxy, + delete(dataID: DataID): void, + get(dataID: DataID): RecordProxy | void, + getRoot(): RecordProxy, + getRootField(fieldName: string): RecordProxy | void, + getPluralRootField(fieldName: string): RecordProxy[] | void, + } + + export interface RecordProxy { + copyFieldsFrom(source: RecordProxy): void, + getDataID(): DataID, + getLinkedRecord(name: string, args?: Variables | void): RecordProxy | void, + getLinkedRecords(name: string, args?: Variables | void): Array | void, + getOrCreateLinkedRecord( + name: string, + typeName: string, + args?: Variables | void, + ): RecordProxy, + getType(): string, + getValue(name: string, args?: Variables | void): any, + setLinkedRecord( + record: RecordProxy, + name: string, + args?: Variables | void, + ): RecordProxy, + setLinkedRecords( + records: (RecordProxy | void)[] | void, + name: string, + args?: Variables | void, + ): RecordProxy, + setValue(value: any, name: string, args?: Variables | void): RecordProxy, + } + + export interface RecordSourceProxy { + create(dataID: DataID, typeName: string): RecordProxy, + delete(dataID: DataID): void, + get(dataID: DataID): (RecordProxy | void)[] | void, + getRoot(): RecordProxy, + } + + export type HandleFieldPayload = { + // The arguments that were fetched. + args: Variables, + // The __id of the record containing the source/handle field. + dataID: DataID, + // The (storage) key at which the original server data was written. + fieldKey: string, + // The name of the handle. + handle: string, + // The (storage) key at which the handle's data should be written by the + // handler. + handleKey: string, + }; + interface IHandler { + update: (store: RecordSourceProxy, fieldPayload: HandleFieldPayload) => void; + [functionName: string]: (...args: any[]) => any; + } + export const Handler: IHandler; + + + // ~~~~~~~~~~~~~~~~~~~~~ + // RelayCombinedEnvironmentTypes + // Version: Relay 1.3.0 + // File: https://github.com/facebook/relay/blob/b85a1d69bb72be4ace67179f55c2a54a8d761c8b/packages/react-relay/classic/environment/RelayCombinedEnvironmentTypes.js + // ~~~~~~~~~~~~~~~~~~~~~ + /** + * Settings for how a query response may be cached. + * + * - `force`: causes a query to be issued unconditionally, irrespective of the + * state of any configured response cache. + * - `poll`: causes a query to live update by polling at the specified interval + in milliseconds. (This value will be passed to setTimeout.) + */ + export type CacheConfig = { + force?: boolean | void, + poll?: number | void, + }; + + /** + * Represents any resource that must be explicitly disposed of. The most common + * use-case is as a return value for subscriptions, where calling `dispose()` + * would cancel the subscription. + */ + export type Disposable = { + dispose(): void, + }; + + + /** + * Arbitrary data e.g. received by a container as props. + */ + export type Props = { [key: string]: any }; + + /* + * An individual cached graph object. + */ + export type Record = { [key: string]: any }; + + /** + * A collection of records keyed by id. + */ + export type RecordMap = { [dataID: string]: Record | void }; + + /** + * A selector defines the starting point for a traversal into the graph for the + * purposes of targeting a subgraph. + */ + export type CSelector = { + dataID: DataID, + node: TNode, + variables: Variables, + }; + + /** + * A representation of a selector and its results at a particular point in time. + */ + export type CSnapshot = CSelector & { + data: SelectorData | void, + seenRecords: RecordMap, + }; + + /** + * The results of a selector given a store/RecordSource. + */ + export type SelectorData = { [key: string]: any }; + + /** + * The results of reading the results of a FragmentMap given some input + * `Props`. + */ + export type FragmentSpecResults = { [key: string]: any }; + + /** + * A utility for resolving and subscribing to the results of a fragment spec + * (key -> fragment mapping) given some "props" that determine the root ID + * and variables to use when reading each fragment. When props are changed via + * `setProps()`, the resolver will update its results and subscriptions + * accordingly. Internally, the resolver: + * - Converts the fragment map & props map into a map of `Selector`s. + * - Removes any resolvers for any props that became null. + * - Creates resolvers for any props that became non-null. + * - Updates resolvers with the latest props. + */ + export interface FragmentSpecResolver { + /** + * Stop watching for changes to the results of the fragments. + */ + dispose(): void, + + /** + * Get the current results. + */ + resolve(): FragmentSpecResults, + + /** + * Update the resolver with new inputs. Call `resolve()` to get the updated + * results. + */ + setProps(props: Props): void, + + /** + * Override the variables used to read the results of the fragments. Call + * `resolve()` to get the updated results. + */ + setVariables(variables: Variables): void, + } + + export type CFragmentMap = { [key: string]: TFragment }; + + /** + * An operation selector describes a specific instance of a GraphQL operation + * with variables applied. + * + * - `root`: a selector intended for processing server results or retaining + * response data in the store. + * - `fragment`: a selector intended for use in reading or subscribing to + * the results of the the operation. + */ + export type COperationSelector = { + fragment: CSelector, + node: TOperation, + root: CSelector, + variables: Variables, + }; + + /** + * The public API of Relay core. Represents an encapsulated environment with its + * own in-memory cache. + */ + export interface CEnvironment< + TEnvironment, + TFragment, + TGraphQLTaggedNode, + TNode, + TOperation, + TPayload, + > { + /** + * Read the results of a selector from in-memory records in the store. + */ + lookup(selector: CSelector): CSnapshot, + + /** + * Subscribe to changes to the results of a selector. The callback is called + * when data has been committed to the store that would cause the results of + * the snapshot's selector to change. + */ + subscribe( + snapshot: CSnapshot, + callback: (snapshot: CSnapshot) => void, + ): Disposable, + + /** + * Ensure that all the records necessary to fulfill the given selector are + * retained in-memory. The records will not be eligible for garbage collection + * until the returned reference is disposed. + * + * Note: This is a no-op in the classic core. + */ + retain(selector: CSelector): Disposable, + + /** + * Send a query to the server with request/response semantics: the query will + * either complete successfully (calling `onNext` and `onCompleted`) or fail + * (calling `onError`). + * + * Note: Most applications should use `streamQuery` in order to + * optionally receive updated information over time, should that feature be + * supported by the network/server. A good rule of thumb is to use this method + * if you would otherwise immediately dispose the `streamQuery()` + * after receving the first `onNext` result. + */ + sendQuery(config: { + cacheConfig?: CacheConfig | void, + onCompleted?: Maybe<() => void>, + onError?: Maybe<(error: Error) => void>, + onNext?: Maybe<(payload: TPayload) => void>, + operation: COperationSelector, + }): Disposable, + + /** + * Send a query to the server with request/subscription semantics: one or more + * responses may be returned (via `onNext`) over time followed by either + * the request completing (`onCompleted`) or an error (`onError`). + * + * Networks/servers that support subscriptions may choose to hold the + * subscription open indefinitely such that `onCompleted` is not called. + */ + streamQuery(config: { + cacheConfig?: Maybe, + onCompleted?: Maybe<() => void>, + onError?: Maybe<(error: Error) => void>, + onNext?: Maybe<(payload: TPayload) => void>, + operation: COperationSelector, + }): Disposable, + + unstable_internal: CUnstableEnvironmentCore< + TEnvironment, + TFragment, + TGraphQLTaggedNode, + TNode, + TOperation + >, + } + + export interface CUnstableEnvironmentCore< + TEnvironment, + TFragment, + TGraphQLTaggedNode, + TNode, + TOperation, + > { + /** + * Create an instance of a FragmentSpecResolver. + * + * TODO: The FragmentSpecResolver *can* be implemented via the other methods + * defined here, so this could be moved out of core. It's convenient to have + * separate implementations until the experimental core is in OSS. + */ + createFragmentSpecResolver: ( + context: CRelayContext, + containerName: string, + fragments: CFragmentMap, + props: Props, + callback: () => void, + ) => FragmentSpecResolver, + + /** + * Creates an instance of an OperationSelector given an operation definition + * (see `getOperation`) and the variables to apply. The input variables are + * filtered to exclude variables that do not matche defined arguments on the + * operation, and default values are populated for null values. + */ + createOperationSelector: ( + operation: TOperation, + variables: Variables, + ) => COperationSelector, + + /** + * Given a graphql`...` tagged template, extract a fragment definition usable + * by this version of Relay core. Throws if the value is not a fragment. + */ + getFragment: (node: TGraphQLTaggedNode) => TFragment, + + /** + * Given a graphql`...` tagged template, extract an operation definition + * usable by this version of Relay core. Throws if the value is not an + * operation. + */ + getOperation: (node: TGraphQLTaggedNode) => TOperation, + + /** + * Determine if two selectors are equal (represent the same selection). Note + * that this function returns `false` when the two queries/fragments are + * different objects, even if they select the same fields. + */ + areEqualSelectors: (a: CSelector, b: CSelector) => boolean, + + /** + * Given the result `item` from a parent that fetched `fragment`, creates a + * selector that can be used to read the results of that fragment for that item. + * + * Example: + * + * Given two fragments as follows: + * + * ``` + * fragment Parent on User { + * id + * ...Child + * } + * fragment Child on User { + * name + * } + * ``` + * + * And given some object `parent` that is the results of `Parent` for id "4", + * the results of `Child` can be accessed by first getting a selector and then + * using that selector to `lookup()` the results against the environment: + * + * ``` + * const childSelector = getSelector(queryVariables, Child, parent); + * const childData = environment.lookup(childSelector).data; + * ``` + */ + getSelector: ( + operationVariables: Variables, + fragment: TFragment, + prop: any, + ) => CSelector | void, + + /** + * Given the result `items` from a parent that fetched `fragment`, creates a + * selector that can be used to read the results of that fragment on those + * items. This is similar to `getSelector` but for "plural" fragments that + * expect an array of results and therefore return an array of selectors. + */ + getSelectorList: ( + operationVariables: Variables, + fragment: TFragment, + props: any[], + ) => Array> | void, + + /** + * Given a mapping of keys -> results and a mapping of keys -> fragments, + * extracts the selectors for those fragments from the results. + * + * The canonical use-case for this function are Relay Containers, which + * use this function to convert (props, fragments) into selectors so that they + * can read the results to pass to the inner component. + */ + getSelectorsFromObject: ( + operationVariables: Variables, + fragments: CFragmentMap, + props: Props, + ) => { [key: string]: Maybe<(CSelector | Array>)> }, + + /** + * Given a mapping of keys -> results and a mapping of keys -> fragments, + * extracts a mapping of keys -> id(s) of the results. + * + * Similar to `getSelectorsFromObject()`, this function can be useful in + * determining the "identity" of the props passed to a component. + */ + getDataIDsFromObject: ( + fragments: CFragmentMap, + props: Props, + ) => { [key: string]: Maybe<(DataID | Array)> }, + + /** + * Given a mapping of keys -> results and a mapping of keys -> fragments, + * extracts the merged variables that would be in scope for those + * fragments/results. + * + * This can be useful in determing what varaibles were used to fetch the data + * for a Relay container, for example. + */ + getVariablesFromObject: ( + operationVariables: Variables, + fragments: CFragmentMap, + props: Props, + ) => Variables, + } + + /** + * The type of the `relay` property set on React context by the React/Relay + * integration layer (e.g. QueryRenderer, FragmentContainer, etc). + */ + export type CRelayContext = { + environment: TEnvironment, + variables: Variables, + }; + + + // ~~~~~~~~~~~~~~~~~~~~~ + // RelayTypes + /** + * Version: Relay 1.3.0 + * File: + * https://github.com/facebook/relay/blob/fa9f48ea209ee2402d433b59a84d1cbc046574e2/packages/react-relay/classic/tools/RelayTypes.js + */ + // ~~~~~~~~~~~~~~~~~~~~~ + export type RerunParam = { + param: string, + import: string, + max_runs: number, + }; + interface FIELDS_CHANGE { + type: 'FIELDS_CHANGE', + fieldIDs: { [fieldName: string]: DataID | Array }, + } + interface RANGE_ADD { + type: 'RANGE_ADD', + parentName?: string, + parentID?: string, + connectionInfo?: Array<{ + key: string, + filters?: Variables, + rangeBehavior: string, + }>, + connectionName?: string, + edgeName: string, + rangeBehaviors?: RangeBehaviors, + } + interface NODE_DELETE { + type: 'NODE_DELETE', + parentName?: string, + parentID?: string, + connectionName?: string, + deletedIDFieldName: string, + } + interface RANGE_DELETE { + type: 'RANGE_DELETE', + parentName?: string, + parentID?: string, + connectionKeys?: Array<{ + key: string, + filters?: Variables, + }>, + connectionName?: string, + deletedIDFieldName: string | string[], + pathToConnection: string[], + } + interface REQUIRED_CHILDREN { + type: 'REQUIRED_CHILDREN', + children: Array, + } + export type RelayMutationConfig = + FIELDS_CHANGE | + RANGE_ADD | + NODE_DELETE | + RANGE_DELETE | + REQUIRED_CHILDREN; + + export type RelayMutationTransactionCommitCallbacks = { + onFailure?: RelayMutationTransactionCommitFailureCallback, + onSuccess?: RelayMutationTransactionCommitSuccessCallback, + }; + export type RelayMutationTransactionCommitFailureCallback = ( + transaction: RelayMutationTransaction, + preventAutoRollback: () => void, + ) => void; + export type RelayMutationTransactionCommitSuccessCallback = (response: { + [key: string]: any, + }) => void; + export type NetworkLayer = { + sendMutation(request: RelayMutationRequest): Promise | void, + sendQueries(requests: Array): Promise | void, + supports(...options: string[]): boolean, + }; + export type QueryResult = { + error?: Error | void, + ref_params?: { [name: string]: any } | void, + response: QueryPayload, + }; + export type ReadyState = { + aborted: boolean, + done: boolean, + error: Error | void, + events: Array, + ready: boolean, + stale: boolean, + }; + type RelayContainerErrorEventType = + | 'CACHE_RESTORE_FAILED' + | 'NETWORK_QUERY_ERROR'; + type RelayContainerLoadingEventType = + | 'ABORT' + | 'CACHE_RESTORED_REQUIRED' + | 'CACHE_RESTORE_START' + | 'NETWORK_QUERY_RECEIVED_ALL' + | 'NETWORK_QUERY_RECEIVED_REQUIRED' + | 'NETWORK_QUERY_START' + | 'STORE_FOUND_ALL' + | 'STORE_FOUND_REQUIRED'; + export type ReadyStateChangeCallback = (readyState: ReadyState) => void; + export type ReadyStateEvent = { + type: RelayContainerLoadingEventType | RelayContainerErrorEventType, + error?: Error, + }; + export type Abortable = { + abort(): void, + }; + + + // ~~~~~~~~~~~~~~~~~~~~~ + // RelayInternalTypes + /** + * Version: Relay 1.3.0 + * File: + * https://github.com/facebook/relay/blob/master/packages/react-relay/classic/tools/RelayInternalTypes.js + */ + // ~~~~~~~~~~~~~~~~~~~~~ + export type QueryPayload = { [key: string]: any }; + export type RelayQuerySet = { [queryName: string]: any }; + type RangeBehaviorsFunction = (connectionArgs: { + [argName: string]: any, + }) => 'APPEND' | 'IGNORE' | 'PREPEND' | 'REFETCH' | 'REMOVE'; + type RangeBehaviorsObject = { + [key: string]: 'APPEND' | 'IGNORE' | 'PREPEND' | 'REFETCH' | 'REMOVE'; + }; + export type RangeBehaviors = RangeBehaviorsFunction | RangeBehaviorsObject; } - // ~~~~~~~~~~~~~~~~~~~~~ - // Network - // ~~~~~~~~~~~~~~~~~~~~~ - class RecordSource { - constructor(records?: RecordMap); - clear(): void; - delete(dataID: Common.DataID): void; - get(dataID: Common.DataID): Record | void; - getRecordIDs(): Common.DataID[]; - getStatus(dataID: Common.DataID): 'EXISTENT' | 'NONEXISTENT' | 'UNKNOWN'; - has(dataID: Common.DataID): boolean; - load( - dataID: Common.DataID, - callback: (error: Error | void, record: Record | void) => void, - ): void; - remove(dataID: Common.DataID): void; - set(dataID: Common.DataID, record: Record): void; - size(): number; - toJSON(): RecordMap; + namespace Runtime { + // ~~~~~~~~~~~~~~~~~~~~~ + // Maybe Fix + // ~~~~~~~~~~~~~~~~~~~~~ + type RelayDebugger = any; + type OptimisticUpdate = any; + type OperationSelector = Common.COperationSelector; + type Selector = Common.CSelector; + type PayloadData = any; + type Snapshot = Common.CSnapshot; + type RelayResponsePayload = any; + type MutableRecordSource = RecordSource; + + /** + * A function that returns an Observable representing the response of executing + * a GraphQL operation. + */ + type ExecuteFunction = ( + operation: object, + variables: Common.Variables, + cacheConfig: Common.CacheConfig, + uploadables?: Common.UploadableMap | void, + ) => Promise; + type RelayNetwork = { + execute: ExecuteFunction, + }; + + // ~~~~~~~~~~~~~~~~~~~~~ + // RelayDefaultHandlerProvider + // ~~~~~~~~~~~~~~~~~~~~~ + export function HandlerProvider(name: string): typeof Common.Handler | void; + + // ~~~~~~~~~~~~~~~~~~~~~ + // RelayModernEnvironment + // ~~~~~~~~~~~~~~~~~~~~~ + type EnvironmentConfig = { + configName?: string, + handlerProvider?: typeof HandlerProvider, + network: Network, + store: Store, + }; + class Environment { + constructor(config: EnvironmentConfig); + getStore(): Store; + getDebugger(): RelayDebugger; + applyUpdate(optimisticUpdate: OptimisticUpdate): Common.Disposable; + revertUpdate(update: OptimisticUpdate): void; + replaceUpdate(update: OptimisticUpdate, newUpdate: OptimisticUpdate): void; + applyMutation(config: { + operation: OperationSelector, + optimisticUpdater?: Common.SelectorStoreUpdater, + optimisticResponse?: object, + }): Common.Disposable; + check(readSelector: Selector): boolean; + commitPayload( + operationSelector: OperationSelector, + payload: PayloadData, + ): void; + commitUpdate(updater: Common.StoreUpdater): void; + lookup(readSelector: Selector): Snapshot; + subscribe( + snapshot: Snapshot, + callback: (snapshot: Snapshot) => void, + ): Common.Disposable; + retain(selector: Selector): Common.Disposable; + execute(config: { + operation: OperationSelector, + cacheConfig?: Common.CacheConfig | void, + updater?: Common.SelectorStoreUpdater | void, + }): RelayObservable; + executeMutation(config: { + operation: OperationSelector, + optimisticUpdater?: Common.SelectorStoreUpdater | void, + optimisticResponse?: object | void, + updater?: Common.SelectorStoreUpdater | void, + uploadables?: Common.UploadableMap | void, + }): RelayObservable; + } + + // ~~~~~~~~~~~~~~~~~~~~~ + // RelayInMemoryRecordSource + // ~~~~~~~~~~~~~~~~~~~~~ + type Record = { [key: string]: any }; + type RecordMap = { [dataID: string]: Record | void }; + + // ~~~~~~~~~~~~~~~~~~~~~ + // Network + // ~~~~~~~~~~~~~~~~~~~~~ + class Network { + /** + * Creates an implementation of the `Network` interface defined in + * `RelayNetworkTypes` given `fetch` and `subscribe` functions. + */ + static create(fetchFn: typeof Common.FetchFunction, subscribeFn?: Common.SubscribeFunction): RelayNetwork; + } + + // ~~~~~~~~~~~~~~~~~~~~~ + // Network + // ~~~~~~~~~~~~~~~~~~~~~ + class RecordSource { + constructor(records?: RecordMap); + clear(): void; + delete(dataID: Common.DataID): void; + get(dataID: Common.DataID): Record | void; + getRecordIDs(): Common.DataID[]; + getStatus(dataID: Common.DataID): 'EXISTENT' | 'NONEXISTENT' | 'UNKNOWN'; + has(dataID: Common.DataID): boolean; + load( + dataID: Common.DataID, + callback: (error: Error | void, record: Record | void) => void, + ): void; + remove(dataID: Common.DataID): void; + set(dataID: Common.DataID, record: Record): void; + size(): number; + toJSON(): RecordMap; + } + + // ~~~~~~~~~~~~~~~~~~~~~ + // ModernStore + // ~~~~~~~~~~~~~~~~~~~~~ + class Store { + constructor(source: RecordSource); + getSource(): MutableRecordSource; + check(selector: Selector): boolean; + retain(selector: Selector): Common.Disposable; + lookup(selector: Selector): Snapshot; + notify(): void; + publish(source: RecordSource): void; + subscribe( + snapshot: Snapshot, + callback: (snapshot: Snapshot) => void, + ): Common.Disposable; + } + + // ~~~~~~~~~~~~~~~~~~~~~ + // RelayRecordSourceInspector + // ~~~~~~~~~~~~~~~~~~~~~ + /** + * An internal class to provide a console-friendly string representation of a + * Record. + */ + class RecordSummary { + id: Common.DataID; + type: string | void; + static createFromRecord(id: Common.DataID, record: any): RecordSummary; + constructor(id: Common.DataID, type: string | void); + toString(): string; + } + /** + * Internal class for inspecting a single Record. + */ + class RecordInspector { + constructor(sourceInspector: RelayRecordSourceInspector, record: Record); + /** + * Get the cache id of the given record. For types that implement the `Node` + * interface (or that have an `id`) this will be `id`, for other types it will be + * a synthesized identifier based on the field path from the nearest ancestor + * record that does have an `id`. + */ + getDataID(): Common.DataID; + + /** + * Returns a list of the fields that have been fetched on the current record. + */ + getFields(): string[]; + + /** + * Returns the type of the record. + */ + getType(): string; + + /** + * Returns a copy of the internal representation of the record. + */ + inspect(): any; + + /** + * Returns the value of a scalar field. May throw if the given field is + * present but not actually scalar. + */ + getValue(name: string, args?: Common.Variables | void): any; + + /** + * Returns an inspector for the given scalar "linked" field (a field whose + * value is another Record instead of a scalar). May throw if the field is + * present but not a scalar linked record. + */ + getLinkedRecord(name: string, args?: Common.Variables | void): RecordInspector | void; + + /** + * Returns an array of inspectors for the given plural "linked" field (a field + * whose value is an array of Records instead of a scalar). May throw if the + * field is present but not a plural linked record. + */ + getLinkedRecords(name: string, args?: Common.Variables | void): RecordInspector[] | void; + } + + class RelayRecordSourceInspector { + constructor(source: RecordSource); + static getForEnvironment(environment: Environment): RelayRecordSourceInspector; + /** + * Returns an inspector for the record with the given id, or null/undefined if + * that record is deleted/unfetched. + */ + get(dataID: Common.DataID): RecordInspector | void; + /** + * Returns a list of ": " for each record in the store that has an + * `id`. + */ + getNodes(): Array; + /** + * Returns a list of ": " for all records in the store including + * those that do not have an `id`. + */ + getRecords(): Array; + + /** + * Returns an inspector for the synthesized "root" object, allowing access to + * e.g. the `viewer` object or the results of other fields on the "Query" + * type. + */ + getRoot(): RecordInspector; + } + + + // ~~~~~~~~~~~~~~~~~~~~~ + // RelayObservable + // ~~~~~~~~~~~~~~~~~~~~~ + type Subscription = { + unsubscribe: () => void, + readonly closed: boolean, + }; + type Observer = { + start?: ((subscription: Subscription) => any) | void, + next?: ((nextThing: T) => any) | void, + error?: ((error: Error) => any) | void, + complete?: (() => any) | void, + unsubscribe?: ((subscription: Subscription) => any) | void, + }; + type Source = () => any; + interface Subscribable { + subscribe(observer: Observer): Subscription, + } + type ObservableFromValue = RelayObservable | Promise | T; + class RelayObservable implements Subscribable { + _source: Source; + + constructor(source: Source); + + /** + * When an unhandled error is detected, it is reported to the host environment + * (the ESObservable spec refers to this method as "HostReportErrors()"). + * + * The default implementation in development builds re-throws errors in a + * separate frame, and from production builds does nothing (swallowing + * uncaught errors). + * + * Called during application initialization, this method allows + * application-specific handling of uncaught errors. Allowing, for example, + * integration with error logging or developer tools. + */ + static onUnhandledError(callback: (error: Error) => any): void; + + /** + * Accepts various kinds of data sources, and always returns a RelayObservable + * useful for accepting the result of a user-provided FetchFunction. + */ + static from(obj: ObservableFromValue): RelayObservable; + + /** + * Creates a RelayObservable, given a function which expects a legacy + * Relay Observer as the last argument and which returns a Disposable. + * + * To support migration to Observable, the function may ignore the + * legacy Relay observer and directly return an Observable instead. + */ + static fromLegacy( + callback: (legacyObserver: Common.LegacyObserver) => Common.Disposable | RelayObservable, + ): RelayObservable; + + /** + * Returns a new Observable which returns the same values as this one, but + * modified so that the provided Observer is called to perform a side-effects + * for all events emitted by the source. + * + * Any errors that are thrown in the side-effect Observer are unhandled, and + * do not affect the source Observable or its Observer. + * + * This is useful for when debugging your Observables or performing other + * side-effects such as logging or performance monitoring. + */ + do(observer: Observer): RelayObservable; + + /** + * Returns a new Observable which returns the same values as this one, but + * modified so that the finally callback is performed after completion, + * whether normal or due to error or unsubscription. + * + * This is useful for cleanup such as resource finalization. + */ + finally(fn: () => any): RelayObservable; + + /** + * Returns a new Observable which is identical to this one, unless this + * Observable completes before yielding any values, in which case the new + * Observable will yield the values from the alternate Observable. + * + * If this Observable does yield values, the alternate is never subscribed to. + * + * This is useful for scenarios where values may come from multiple sources + * which should be tried in order, i.e. from a cache before a network. + */ + ifEmpty(alternate: RelayObservable): RelayObservable; + + /** + * Observable's primary API: returns an unsubscribable Subscription to the + * source of this Observable. + */ + subscribe(observer: Observer): Subscription; + + /** + * Supports subscription of a legacy Relay Observer, returning a Disposable. + */ + subscribeLegacy(legacyObserver: Common.LegacyObserver): Common.Disposable; + + /** + * Returns a new Observerable where each value has been transformed by + * the mapping function. + */ + map(fn: (thing: T) => U): RelayObservable; + + /** + * Returns a new Observable where each value is replaced with a new Observable + * by the mapping function, the results of which returned as a single + * concattenated Observable. + */ + concatMap(fn: (thing: T) => ObservableFromValue): RelayObservable; + + /** + * Returns a new Observable which first mirrors this Observable, then when it + * completes, waits for `pollInterval` milliseconds before re-subscribing to + * this Observable again, looping in this manner until unsubscribed. + * + * The returned Observable never completes. + */ + poll(pollInterval: number): RelayObservable; + + /** + * Returns a Promise which resolves when this Observable yields a first value + * or when it completes with no value. + */ + toPromise(): Promise; + } + + + // ~~~~~~~~~~~~~~~~~~~~~ + // commitLocalUpdate + // ~~~~~~~~~~~~~~~~~~~~~ + // exposed through RelayModern, not Runtime directly + type commitLocalUpdate = ( + environment: Environment, + updater: Common.StoreUpdater, + ) => void; + + // ~~~~~~~~~~~~~~~~~~~~~ + // commitRelayModernMutation + // ~~~~~~~~~~~~~~~~~~~~~ + // exposed through RelayModern, not Runtime directly + type MutationConfig = { + configs?: Array, + mutation: Common.GraphQLTaggedNode, + variables: Common.Variables, + uploadables?: Common.UploadableMap, + onCompleted?: (response: T, errors: Array | void) => void, + onError?: (error?: Error) => void, + optimisticUpdater?: Common.SelectorStoreUpdater | void, + optimisticResponse?: object, + updater?: Common.SelectorStoreUpdater | void, + }; + function commitRelayModernMutation( + environment: Environment, + config: MutationConfig, + ): Common.Disposable; + + // ~~~~~~~~~~~~~~~~~~~~~ + // applyRelayModernOptimisticMutation + // ~~~~~~~~~~~~~~~~~~~~~ + // exposed through RelayModern, not Runtime directly + type OptimisticMutationConfig = { + configs?: Array, + mutation: Common.GraphQLTaggedNode, + variables: Common.Variables, + optimisticUpdater?: Common.SelectorStoreUpdater, + optimisticResponse?: object, + }; + + // ~~~~~~~~~~~~~~~~~~~~~ + // fetchRelayModernQuery + // ~~~~~~~~~~~~~~~~~~~~~ + // exposed through RelayModern, not Runtime directly + /** + * A helper function to fetch the results of a query. Note that results for + * fragment spreads are masked: fields must be explicitly listed in the query in + * order to be accessible in the result object. + * + * NOTE: This module is primarily intended for integrating with classic APIs. + * Most product code should use a Renderer or Container. + * + * TODO(t16875667): The return type should be `Promise`, but + * that's not really helpful as `SelectorData` is essentially just `mixed`. We + * can probably leverage generated flow types here to return the real expected + * shape. + */ + function fetchRelayModernQuery( + environment: any, // FIXME - $FlowFixMe in facebook source code + taggedNode: Common.GraphQLTaggedNode, + variables: Common.Variables, + cacheConfig?: Common.CacheConfig | void, + ): Promise; // FIXME - $FlowFixMe in facebook source code + + + // ~~~~~~~~~~~~~~~~~~~~~ + // requestRelaySubscription + // ~~~~~~~~~~~~~~~~~~~~~ + // exposed through RelayModern, not Runtime directly + export type GraphQLSubscriptionConfig = { + configs?: Array, + subscription: Common.GraphQLTaggedNode, + variables: Common.Variables, + onCompleted?: () => void, + onError?: (error: Error) => void, + onNext?: (response: object | void) => void, + updater?: (store: Common.RecordSourceSelectorProxy) => void, + }; + export function requestRelaySubscription( + environment: Environment, + config: GraphQLSubscriptionConfig, + ): Common.Disposable; } +} - // ~~~~~~~~~~~~~~~~~~~~~ - // ModernStore - // ~~~~~~~~~~~~~~~~~~~~~ - class Store { - constructor(source: RecordSource); - getSource(): MutableRecordSource; - check(selector: Selector): boolean; - retain(selector: Selector): Common.Disposable; - lookup(selector: Selector): Snapshot; - notify(): void; - publish(source: RecordSource): void; - subscribe( - snapshot: Snapshot, - callback: (snapshot: Snapshot) => void, - ): Common.Disposable; - } - - // ~~~~~~~~~~~~~~~~~~~~~ - // RelayRecordSourceInspector - // ~~~~~~~~~~~~~~~~~~~~~ - /** - * An internal class to provide a console-friendly string representation of a - * Record. - */ - class RecordSummary { - id: Common.DataID; - type: string | void; - static createFromRecord(id: Common.DataID, record: any): RecordSummary; - constructor(id: Common.DataID, type: string | void); - toString(): string; - } - /** - * Internal class for inspecting a single Record. - */ - class RecordInspector { - constructor(sourceInspector: RelayRecordSourceInspector, record: Record); - /** - * Get the cache id of the given record. For types that implement the `Node` - * interface (or that have an `id`) this will be `id`, for other types it will be - * a synthesized identifier based on the field path from the nearest ancestor - * record that does have an `id`. - */ - getDataID(): Common.DataID; - - /** - * Returns a list of the fields that have been fetched on the current record. - */ - getFields(): Array; - - /** - * Returns the type of the record. - */ - getType(): string; - - /** - * Returns a copy of the internal representation of the record. - */ - inspect(): any; - - /** - * Returns the value of a scalar field. May throw if the given field is - * present but not actually scalar. - */ - getValue(name: string, args?: Common.Variables | void): any; - - /** - * Returns an inspector for the given scalar "linked" field (a field whose - * value is another Record instead of a scalar). May throw if the field is - * present but not a scalar linked record. - */ - getLinkedRecord(name: string, args?: Common.Variables | void): RecordInspector | void; - - /** - * Returns an array of inspectors for the given plural "linked" field (a field - * whose value is an array of Records instead of a scalar). May throw if the - * field is present but not a plural linked record. - */ - getLinkedRecords(name: string, args?: Common.Variables | void): RecordInspector[] | void; - } - - class RelayRecordSourceInspector { - constructor(source: RecordSource); - static getForEnvironment(environment: Environment): RelayRecordSourceInspector; - /** - * Returns an inspector for the record with the given id, or null/undefined if - * that record is deleted/unfetched. - */ - get(dataID: Common.DataID): RecordInspector | void; - /** - * Returns a list of ": " for each record in the store that has an - * `id`. - */ - getNodes(): Array; - /** - * Returns a list of ": " for all records in the store including - * those that do not have an `id`. - */ - getRecords(): Array; - - /** - * Returns an inspector for the synthesized "root" object, allowing access to - * e.g. the `viewer` object or the results of other fields on the "Query" - * type. - */ - getRoot(): RecordInspector; - } - - - // ~~~~~~~~~~~~~~~~~~~~~ - // RelayObservable - // ~~~~~~~~~~~~~~~~~~~~~ - type Subscription = { - unsubscribe: () => void, - readonly closed: boolean, - }; - type Observer = { - start?: ((subscription: Subscription) => any) | void, - next?: ((nextThing: T) => any) | void, - error?: ((error: Error) => any) | void, - complete?: (() => any) | void, - unsubscribe?: ((subscription: Subscription) => any) | void, - }; - type Source = () => any; - interface Subscribable { - subscribe(observer: Observer): Subscription, - } - type ObservableFromValue = RelayObservable | Promise | T; - class RelayObservable implements Subscribable { - _source: Source; - - constructor(source: Source); - - /** - * When an unhandled error is detected, it is reported to the host environment - * (the ESObservable spec refers to this method as "HostReportErrors()"). - * - * The default implementation in development builds re-throws errors in a - * separate frame, and from production builds does nothing (swallowing - * uncaught errors). - * - * Called during application initialization, this method allows - * application-specific handling of uncaught errors. Allowing, for example, - * integration with error logging or developer tools. - */ - static onUnhandledError(callback: (error: Error) => any): void; - - /** - * Accepts various kinds of data sources, and always returns a RelayObservable - * useful for accepting the result of a user-provided FetchFunction. - */ - static from(obj: ObservableFromValue): RelayObservable; - - /** - * Creates a RelayObservable, given a function which expects a legacy - * Relay Observer as the last argument and which returns a Disposable. - * - * To support migration to Observable, the function may ignore the - * legacy Relay observer and directly return an Observable instead. - */ - static fromLegacy( - callback: (legacyObserver: Common.LegacyObserver) => Common.Disposable | RelayObservable, - ): RelayObservable; - - /** - * Returns a new Observable which returns the same values as this one, but - * modified so that the provided Observer is called to perform a side-effects - * for all events emitted by the source. - * - * Any errors that are thrown in the side-effect Observer are unhandled, and - * do not affect the source Observable or its Observer. - * - * This is useful for when debugging your Observables or performing other - * side-effects such as logging or performance monitoring. - */ - do(observer: Observer): RelayObservable; - - /** - * Returns a new Observable which returns the same values as this one, but - * modified so that the finally callback is performed after completion, - * whether normal or due to error or unsubscription. - * - * This is useful for cleanup such as resource finalization. - */ - finally(fn: () => any): RelayObservable; - - /** - * Returns a new Observable which is identical to this one, unless this - * Observable completes before yielding any values, in which case the new - * Observable will yield the values from the alternate Observable. - * - * If this Observable does yield values, the alternate is never subscribed to. - * - * This is useful for scenarios where values may come from multiple sources - * which should be tried in order, i.e. from a cache before a network. - */ - ifEmpty(alternate: RelayObservable): RelayObservable; - - /** - * Observable's primary API: returns an unsubscribable Subscription to the - * source of this Observable. - */ - subscribe(observer: Observer): Subscription; - - /** - * Supports subscription of a legacy Relay Observer, returning a Disposable. - */ - subscribeLegacy(legacyObserver: Common.LegacyObserver): Common.Disposable; - - /** - * Returns a new Observerable where each value has been transformed by - * the mapping function. - */ - map(fn: (thing: T) => U): RelayObservable; - - /** - * Returns a new Observable where each value is replaced with a new Observable - * by the mapping function, the results of which returned as a single - * concattenated Observable. - */ - concatMap(fn: (thing: T) => ObservableFromValue): RelayObservable; - - /** - * Returns a new Observable which first mirrors this Observable, then when it - * completes, waits for `pollInterval` milliseconds before re-subscribing to - * this Observable again, looping in this manner until unsubscribed. - * - * The returned Observable never completes. - */ - poll(pollInterval: number): RelayObservable; - - /** - * Returns a Promise which resolves when this Observable yields a first value - * or when it completes with no value. - */ - toPromise(): Promise; - } - - - // ~~~~~~~~~~~~~~~~~~~~~ - // commitLocalUpdate - // ~~~~~~~~~~~~~~~~~~~~~ - // exposed through RelayModern, not Runtime directly - type commitLocalUpdate = ( - environment: Environment, - updater: Common.StoreUpdater, - ) => void; - - // ~~~~~~~~~~~~~~~~~~~~~ - // commitRelayModernMutation - // ~~~~~~~~~~~~~~~~~~~~~ - // exposed through RelayModern, not Runtime directly - type MutationConfig = { - configs?: Array, - mutation: Common.GraphQLTaggedNode, - variables: Common.Variables, - uploadables?: Common.UploadableMap, - onCompleted?: (response: T, errors: Array | void) => void, - onError?: (error?: Error) => void, - optimisticUpdater?: Common.SelectorStoreUpdater | void, - optimisticResponse?: object, - updater?: Common.SelectorStoreUpdater | void, - }; - function commitRelayModernMutation( - environment: Environment, - config: MutationConfig, - ): Common.Disposable; - - // ~~~~~~~~~~~~~~~~~~~~~ - // applyRelayModernOptimisticMutation - // ~~~~~~~~~~~~~~~~~~~~~ - // exposed through RelayModern, not Runtime directly - type OptimisticMutationConfig = { - configs?: Array, - mutation: Common.GraphQLTaggedNode, - variables: Common.Variables, - optimisticUpdater?: Common.SelectorStoreUpdater, - optimisticResponse?: object, - }; - - // ~~~~~~~~~~~~~~~~~~~~~ - // fetchRelayModernQuery - // ~~~~~~~~~~~~~~~~~~~~~ - // exposed through RelayModern, not Runtime directly - /** - * A helper function to fetch the results of a query. Note that results for - * fragment spreads are masked: fields must be explicitly listed in the query in - * order to be accessible in the result object. - * - * NOTE: This module is primarily intended for integrating with classic APIs. - * Most product code should use a Renderer or Container. - * - * TODO(t16875667): The return type should be `Promise`, but - * that's not really helpful as `SelectorData` is essentially just `mixed`. We - * can probably leverage generated flow types here to return the real expected - * shape. - */ - function fetchRelayModernQuery( - environment: any, // FIXME - $FlowFixMe in facebook source code - taggedNode: Common.GraphQLTaggedNode, - variables: Common.Variables, - cacheConfig?: Common.CacheConfig | void, - ): Promise; // FIXME - $FlowFixMe in facebook source code - - - // ~~~~~~~~~~~~~~~~~~~~~ - // requestRelaySubscription - // ~~~~~~~~~~~~~~~~~~~~~ - // exposed through RelayModern, not Runtime directly - export type GraphQLSubscriptionConfig = { - configs?: Array, - subscription: Common.GraphQLTaggedNode, - variables: Common.Variables, - onCompleted?: () => void, - onError?: (error: Error) => void, - onNext?: (response: object | void) => void, - updater?: (store: Common.RecordSourceSelectorProxy) => void, - }; - export function requestRelaySubscription( - environment: Environment, - config: GraphQLSubscriptionConfig, - ): Common.Disposable; - } - - declare module 'relay-runtime' { +declare module 'relay-runtime' { export import Environment = __Relay.Runtime.Environment; export import Network = __Relay.Runtime.Network; export import RecordSource = __Relay.Runtime.RecordSource; @@ -1136,4 +1136,4 @@ declare namespace __Relay.Runtime { export import RecordSourceInspector = __Relay.Runtime.RelayRecordSourceInspector; export import ConnectionHandler = __Relay.Common.Handler; export import ViewerHandler = __Relay.Common.Handler; - } +} From 9d699082b64288589c646f6033bae0b724a78fd6 Mon Sep 17 00:00:00 2001 From: voxmatt Date: Sun, 10 Sep 2017 10:05:01 -1000 Subject: [PATCH 015/828] continuing to fix linting errors --- types/relay-runtime/index.d.ts | 177 ++++++++++++++++----------------- 1 file changed, 84 insertions(+), 93 deletions(-) diff --git a/types/relay-runtime/index.d.ts b/types/relay-runtime/index.d.ts index 80ea0dcdea..5904a6067c 100644 --- a/types/relay-runtime/index.d.ts +++ b/types/relay-runtime/index.d.ts @@ -11,7 +11,7 @@ declare namespace __Relay { * SOURCE: * Relay 1.3.0 * https://github.com/facebook/relay/blob/b85a1d69bb72be4ace67179f55c2a54a8d761c8b/packages/react-relay/classic/environment/RelayCombinedEnvironmentTypes.js - */ + */ // ~~~~~~~~~~~~~~~~~~~~~ // Util // ~~~~~~~~~~~~~~~~~~~~~ @@ -29,7 +29,6 @@ declare namespace __Relay { type ConcreteFragmentDefinition = object; type ConcreteOperationDefinition = object; - /** * FIXME: RelayContainer used to be typed with ReactClass, but * ReactClass is broken and allows for access to any property. For example @@ -39,18 +38,19 @@ declare namespace __Relay { * but have no definition in Relay's types. Suppressing for now. */ export type RelayContainer = any; + // ~~~~~~~~~~~~~~~~~~~~~ // RelayQL // ~~~~~~~~~~~~~~~~~~~~~ type RelayQL = ( strings: string[], ...substitutions: any[] - ) => Common.RelayConcreteNode; + ) => RelayConcreteNode; // ~~~~~~~~~~~~~~~~~~~~~ // RelayModernGraphQLTag // ~~~~~~~~~~~~~~~~~~~~~ - type GeneratedNodeMap = { [key: string]: GraphQLTaggedNode }; + interface GeneratedNodeMap { [key: string]: GraphQLTaggedNode } type GraphQLTaggedNode = (() => ConcreteFragment | ConcreteBatch) | { @@ -63,10 +63,9 @@ declare namespace __Relay { // General Usage // ~~~~~~~~~~~~~~~~~~~~~ export type DataID = string; - export type Variables = { [name: string]: any }; + export interface Variables { [name: string]: any } export type Uploadable = File | Blob; - export type UploadableMap = { [key: string]: Uploadable }; - + export interface UploadableMap { [key: string]: Uploadable } // ~~~~~~~~~~~~~~~~~~~~~ // RelayNetworkTypes @@ -74,18 +73,18 @@ declare namespace __Relay { // File: https://github.com/facebook/relay/blob/master/packages/relay-runtime/network/RelayNetworkTypes.js // ~~~~~~~~~~~~~~~~~~~~~ - export type LegacyObserver = { + export interface LegacyObserver { onCompleted?: (() => void) | void, onError?: ((error: Error) => void) | void, onNext?: ((data: T) => void) | void, - }; - export type PayloadError = { + } + export interface PayloadError { message: string, locations?: Array<{ line: number, column: number, }>, - }; + } /** * A function that executes a GraphQL operation with request/response semantics. * @@ -95,7 +94,7 @@ declare namespace __Relay { operation: ConcreteBatch, variables: Variables, cacheConfig: CacheConfig, - uploadables?: Common.UploadableMap, + uploadables?: UploadableMap, ): Runtime.ObservableFromValue; /** @@ -112,7 +111,6 @@ declare namespace __Relay { observer: LegacyObserver, ) => Runtime.RelayObservable | Disposable; - // ~~~~~~~~~~~~~~~~~~~~~ // RelayStoreTypes // Version: Relay 1.3.0 @@ -125,10 +123,10 @@ declare namespace __Relay { export type StoreUpdater = (store: RecordSourceProxy) => void; /** - * Similar to StoreUpdater, but accepts a proxy tied to a specific selector in - * order to easily access the root fields of a query/mutation as well as a - * second argument of the response object of the mutation. - */ + * Similar to StoreUpdater, but accepts a proxy tied to a specific selector in + * order to easily access the root fields of a query/mutation as well as a + * second argument of the response object of the mutation. + */ export type SelectorStoreUpdater = ( store: RecordSourceSelectorProxy, // Actually RelayCombinedEnvironmentTypes#SelectorData, but mixed is @@ -167,7 +165,7 @@ declare namespace __Relay { args?: Variables | void, ): RecordProxy, setLinkedRecords( - records: (RecordProxy | void)[] | void, + records: Array | void, name: string, args?: Variables | void, ): RecordProxy, @@ -177,11 +175,11 @@ declare namespace __Relay { export interface RecordSourceProxy { create(dataID: DataID, typeName: string): RecordProxy, delete(dataID: DataID): void, - get(dataID: DataID): (RecordProxy | void)[] | void, + get(dataID: DataID): Array | void, getRoot(): RecordProxy, } - export type HandleFieldPayload = { + export interface HandleFieldPayload { // The arguments that were fetched. args: Variables, // The __id of the record containing the source/handle field. @@ -193,13 +191,12 @@ declare namespace __Relay { // The (storage) key at which the handle's data should be written by the // handler. handleKey: string, - }; - interface IHandler { + } + interface HandlerInterface { update: (store: RecordSourceProxy, fieldPayload: HandleFieldPayload) => void; [functionName: string]: (...args: any[]) => any; } - export const Handler: IHandler; - + export const Handler: HandlerInterface; // ~~~~~~~~~~~~~~~~~~~~~ // RelayCombinedEnvironmentTypes @@ -212,47 +209,46 @@ declare namespace __Relay { * - `force`: causes a query to be issued unconditionally, irrespective of the * state of any configured response cache. * - `poll`: causes a query to live update by polling at the specified interval - in milliseconds. (This value will be passed to setTimeout.) + * in milliseconds. (This value will be passed to setTimeout.) */ - export type CacheConfig = { + export interface CacheConfig { force?: boolean | void, poll?: number | void, - }; + } /** * Represents any resource that must be explicitly disposed of. The most common * use-case is as a return value for subscriptions, where calling `dispose()` * would cancel the subscription. */ - export type Disposable = { + export interface Disposable { dispose(): void, - }; - + } /** * Arbitrary data e.g. received by a container as props. */ - export type Props = { [key: string]: any }; + export interface Props { [key: string]: any } /* * An individual cached graph object. */ - export type Record = { [key: string]: any }; + export interface Record { [key: string]: any } /** * A collection of records keyed by id. */ - export type RecordMap = { [dataID: string]: Record | void }; + export interface RecordMap { [dataID: string]: Record | void } /** * A selector defines the starting point for a traversal into the graph for the * purposes of targeting a subgraph. */ - export type CSelector = { + export interface CSelector { dataID: DataID, node: TNode, variables: Variables, - }; + } /** * A representation of a selector and its results at a particular point in time. @@ -265,13 +261,13 @@ declare namespace __Relay { /** * The results of a selector given a store/RecordSource. */ - export type SelectorData = { [key: string]: any }; + export interface SelectorData { [key: string]: any } /** * The results of reading the results of a FragmentMap given some input * `Props`. */ - export type FragmentSpecResults = { [key: string]: any }; + export interface FragmentSpecResults { [key: string]: any } /** * A utility for resolving and subscribing to the results of a fragment spec @@ -308,7 +304,7 @@ declare namespace __Relay { setVariables(variables: Variables): void, } - export type CFragmentMap = { [key: string]: TFragment }; + export interface CFragmentMap { [key: string]: TFragment } /** * An operation selector describes a specific instance of a GraphQL operation @@ -319,12 +315,12 @@ declare namespace __Relay { * - `fragment`: a selector intended for use in reading or subscribing to * the results of the the operation. */ - export type COperationSelector = { + export interface COperationSelector { fragment: CSelector, node: TOperation, root: CSelector, variables: Variables, - }; + } /** * The public API of Relay core. Represents an encapsulated environment with its @@ -528,7 +524,7 @@ declare namespace __Relay { getDataIDsFromObject: ( fragments: CFragmentMap, props: Props, - ) => { [key: string]: Maybe<(DataID | Array)> }, + ) => { [key: string]: Maybe<(DataID | DataID[])> }, /** * Given a mapping of keys -> results and a mapping of keys -> fragments, @@ -549,11 +545,10 @@ declare namespace __Relay { * The type of the `relay` property set on React context by the React/Relay * integration layer (e.g. QueryRenderer, FragmentContainer, etc). */ - export type CRelayContext = { + export interface CRelayContext { environment: TEnvironment, variables: Variables, - }; - + } // ~~~~~~~~~~~~~~~~~~~~~ // RelayTypes @@ -561,16 +556,16 @@ declare namespace __Relay { * Version: Relay 1.3.0 * File: * https://github.com/facebook/relay/blob/fa9f48ea209ee2402d433b59a84d1cbc046574e2/packages/react-relay/classic/tools/RelayTypes.js - */ + */ // ~~~~~~~~~~~~~~~~~~~~~ - export type RerunParam = { + export interface RerunParam { param: string, import: string, max_runs: number, - }; + } interface FIELDS_CHANGE { type: 'FIELDS_CHANGE', - fieldIDs: { [fieldName: string]: DataID | Array }, + fieldIDs: { [fieldName: string]: DataID | DataID[] }, } interface RANGE_ADD { type: 'RANGE_ADD', @@ -606,7 +601,7 @@ declare namespace __Relay { } interface REQUIRED_CHILDREN { type: 'REQUIRED_CHILDREN', - children: Array, + children: RelayConcreteNode[], } export type RelayMutationConfig = FIELDS_CHANGE | @@ -615,10 +610,10 @@ declare namespace __Relay { RANGE_DELETE | REQUIRED_CHILDREN; - export type RelayMutationTransactionCommitCallbacks = { + export interface RelayMutationTransactionCommitCallbacks { onFailure?: RelayMutationTransactionCommitFailureCallback, onSuccess?: RelayMutationTransactionCommitSuccessCallback, - }; + } export type RelayMutationTransactionCommitFailureCallback = ( transaction: RelayMutationTransaction, preventAutoRollback: () => void, @@ -626,24 +621,24 @@ declare namespace __Relay { export type RelayMutationTransactionCommitSuccessCallback = (response: { [key: string]: any, }) => void; - export type NetworkLayer = { + export interface NetworkLayer { sendMutation(request: RelayMutationRequest): Promise | void, - sendQueries(requests: Array): Promise | void, + sendQueries(requests: RelayQueryRequest[]): Promise | void, supports(...options: string[]): boolean, - }; - export type QueryResult = { + } + export interface QueryResult { error?: Error | void, ref_params?: { [name: string]: any } | void, response: QueryPayload, - }; - export type ReadyState = { + } + export interface ReadyState { aborted: boolean, done: boolean, error: Error | void, - events: Array, + events: ReadyStateEvent[], ready: boolean, stale: boolean, - }; + } type RelayContainerErrorEventType = | 'CACHE_RESTORE_FAILED' | 'NETWORK_QUERY_ERROR'; @@ -661,10 +656,9 @@ declare namespace __Relay { type: RelayContainerLoadingEventType | RelayContainerErrorEventType, error?: Error, }; - export type Abortable = { + export interface Abortable { abort(): void, - }; - + } // ~~~~~~~~~~~~~~~~~~~~~ // RelayInternalTypes @@ -672,16 +666,16 @@ declare namespace __Relay { * Version: Relay 1.3.0 * File: * https://github.com/facebook/relay/blob/master/packages/react-relay/classic/tools/RelayInternalTypes.js - */ + */ // ~~~~~~~~~~~~~~~~~~~~~ - export type QueryPayload = { [key: string]: any }; - export type RelayQuerySet = { [queryName: string]: any }; + export interface QueryPayload { [key: string]: any } + export interface RelayQuerySet { [queryName: string]: any } type RangeBehaviorsFunction = (connectionArgs: { [argName: string]: any, }) => 'APPEND' | 'IGNORE' | 'PREPEND' | 'REFETCH' | 'REMOVE'; - type RangeBehaviorsObject = { + interface RangeBehaviorsObject { [key: string]: 'APPEND' | 'IGNORE' | 'PREPEND' | 'REFETCH' | 'REMOVE'; - }; + } export type RangeBehaviors = RangeBehaviorsFunction | RangeBehaviorsObject; } @@ -708,9 +702,9 @@ declare namespace __Relay { cacheConfig: Common.CacheConfig, uploadables?: Common.UploadableMap | void, ) => Promise; - type RelayNetwork = { + interface RelayNetwork { execute: ExecuteFunction, - }; + } // ~~~~~~~~~~~~~~~~~~~~~ // RelayDefaultHandlerProvider @@ -720,12 +714,12 @@ declare namespace __Relay { // ~~~~~~~~~~~~~~~~~~~~~ // RelayModernEnvironment // ~~~~~~~~~~~~~~~~~~~~~ - type EnvironmentConfig = { + interface EnvironmentConfig { configName?: string, handlerProvider?: typeof HandlerProvider, network: Network, store: Store, - }; + } class Environment { constructor(config: EnvironmentConfig); getStore(): Store; @@ -767,8 +761,8 @@ declare namespace __Relay { // ~~~~~~~~~~~~~~~~~~~~~ // RelayInMemoryRecordSource // ~~~~~~~~~~~~~~~~~~~~~ - type Record = { [key: string]: any }; - type RecordMap = { [dataID: string]: Record | void }; + interface Record { [key: string]: any } + interface RecordMap { [dataID: string]: Record | void } // ~~~~~~~~~~~~~~~~~~~~~ // Network @@ -835,7 +829,7 @@ declare namespace __Relay { } /** * Internal class for inspecting a single Record. - */ + */ class RecordInspector { constructor(sourceInspector: RelayRecordSourceInspector, record: Record); /** @@ -894,12 +888,12 @@ declare namespace __Relay { * Returns a list of ": " for each record in the store that has an * `id`. */ - getNodes(): Array; + getNodes(): RecordSummary[]; /** * Returns a list of ": " for all records in the store including * those that do not have an `id`. */ - getRecords(): Array; + getRecords(): RecordSummary[]; /** * Returns an inspector for the synthesized "root" object, allowing access to @@ -909,21 +903,20 @@ declare namespace __Relay { getRoot(): RecordInspector; } - // ~~~~~~~~~~~~~~~~~~~~~ // RelayObservable // ~~~~~~~~~~~~~~~~~~~~~ - type Subscription = { + interface Subscription { unsubscribe: () => void, readonly closed: boolean, - }; - type Observer = { + } + interface Observer { start?: ((subscription: Subscription) => any) | void, next?: ((nextThing: T) => any) | void, error?: ((error: Error) => any) | void, complete?: (() => any) | void, unsubscribe?: ((subscription: Subscription) => any) | void, - }; + } type Source = () => any; interface Subscribable { subscribe(observer: Observer): Subscription, @@ -1039,7 +1032,6 @@ declare namespace __Relay { toPromise(): Promise; } - // ~~~~~~~~~~~~~~~~~~~~~ // commitLocalUpdate // ~~~~~~~~~~~~~~~~~~~~~ @@ -1053,17 +1045,17 @@ declare namespace __Relay { // commitRelayModernMutation // ~~~~~~~~~~~~~~~~~~~~~ // exposed through RelayModern, not Runtime directly - type MutationConfig = { - configs?: Array, + interface MutationConfig { + configs?: Common.RelayMutationConfig[], mutation: Common.GraphQLTaggedNode, variables: Common.Variables, uploadables?: Common.UploadableMap, - onCompleted?: (response: T, errors: Array | void) => void, + onCompleted?: (response: T, errors: Common.PayloadError[] | void) => void, onError?: (error?: Error) => void, optimisticUpdater?: Common.SelectorStoreUpdater | void, optimisticResponse?: object, updater?: Common.SelectorStoreUpdater | void, - }; + } function commitRelayModernMutation( environment: Environment, config: MutationConfig, @@ -1073,13 +1065,13 @@ declare namespace __Relay { // applyRelayModernOptimisticMutation // ~~~~~~~~~~~~~~~~~~~~~ // exposed through RelayModern, not Runtime directly - type OptimisticMutationConfig = { - configs?: Array, + interface OptimisticMutationConfig { + configs?: Common.RelayMutationConfig[], mutation: Common.GraphQLTaggedNode, variables: Common.Variables, optimisticUpdater?: Common.SelectorStoreUpdater, optimisticResponse?: object, - }; + } // ~~~~~~~~~~~~~~~~~~~~~ // fetchRelayModernQuery @@ -1105,20 +1097,19 @@ declare namespace __Relay { cacheConfig?: Common.CacheConfig | void, ): Promise; // FIXME - $FlowFixMe in facebook source code - // ~~~~~~~~~~~~~~~~~~~~~ // requestRelaySubscription // ~~~~~~~~~~~~~~~~~~~~~ // exposed through RelayModern, not Runtime directly - export type GraphQLSubscriptionConfig = { - configs?: Array, + export interface GraphQLSubscriptionConfig { + configs?: Common.RelayMutationConfig[], subscription: Common.GraphQLTaggedNode, variables: Common.Variables, onCompleted?: () => void, onError?: (error: Error) => void, onNext?: (response: object | void) => void, updater?: (store: Common.RecordSourceSelectorProxy) => void, - }; + } export function requestRelaySubscription( environment: Environment, config: GraphQLSubscriptionConfig, From e85628dc15f1c5f2c952b25b9e8033c869ccd4e9 Mon Sep 17 00:00:00 2001 From: voxmatt Date: Sun, 10 Sep 2017 16:21:13 -1000 Subject: [PATCH 016/828] fixing all linting errors for relay-runtime --- types/relay-runtime/index.d.ts | 354 ++++++++++---------- types/relay-runtime/relay-runtime-tests.tsx | 17 +- 2 files changed, 185 insertions(+), 186 deletions(-) diff --git a/types/relay-runtime/index.d.ts b/types/relay-runtime/index.d.ts index 5904a6067c..4acab12c5b 100644 --- a/types/relay-runtime/index.d.ts +++ b/types/relay-runtime/index.d.ts @@ -1,4 +1,4 @@ -// Type definitions for relay-runtime 1.3.0 +// Type definitions for relay-runtime 1.3 // Project: https://github.com/facebook/relay // Definitions by: Matt Martin // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped @@ -50,12 +50,14 @@ declare namespace __Relay { // ~~~~~~~~~~~~~~~~~~~~~ // RelayModernGraphQLTag // ~~~~~~~~~~~~~~~~~~~~~ - interface GeneratedNodeMap { [key: string]: GraphQLTaggedNode } + interface GeneratedNodeMap { + [key: string]: GraphQLTaggedNode; + } type GraphQLTaggedNode = (() => ConcreteFragment | ConcreteBatch) | { - modern: () => ConcreteFragment | ConcreteBatch, - classic: (relayQL: RelayQL) => + modern(): ConcreteFragment | ConcreteBatch, + classic(relayQL: RelayQL): | ConcreteFragmentDefinition | ConcreteOperationDefinition, }; @@ -63,9 +65,13 @@ declare namespace __Relay { // General Usage // ~~~~~~~~~~~~~~~~~~~~~ export type DataID = string; - export interface Variables { [name: string]: any } + export interface Variables { + [name: string]: any; + } export type Uploadable = File | Blob; - export interface UploadableMap { [key: string]: Uploadable } + export interface UploadableMap { + [key: string]: Uploadable; + } // ~~~~~~~~~~~~~~~~~~~~~ // RelayNetworkTypes @@ -74,16 +80,16 @@ declare namespace __Relay { // ~~~~~~~~~~~~~~~~~~~~~ export interface LegacyObserver { - onCompleted?: (() => void) | void, - onError?: ((error: Error) => void) | void, - onNext?: ((data: T) => void) | void, + onCompleted?: (() => void) | void; + onError?: ((error: Error) => void) | void; + onNext?: ((data: T) => void) | void; } export interface PayloadError { - message: string, + message: string; locations?: Array<{ line: number, column: number, - }>, + }>; } /** * A function that executes a GraphQL operation with request/response semantics. @@ -139,61 +145,61 @@ declare namespace __Relay { * fields of a Selector. */ export interface RecordSourceSelectorProxy { - create(dataID: DataID, typeName: string): RecordProxy, - delete(dataID: DataID): void, - get(dataID: DataID): RecordProxy | void, - getRoot(): RecordProxy, - getRootField(fieldName: string): RecordProxy | void, - getPluralRootField(fieldName: string): RecordProxy[] | void, + create(dataID: DataID, typeName: string): RecordProxy; + delete(dataID: DataID): void; + get(dataID: DataID): RecordProxy | void; + getRoot(): RecordProxy; + getRootField(fieldName: string): RecordProxy | void; + getPluralRootField(fieldName: string): RecordProxy[] | void; } export interface RecordProxy { - copyFieldsFrom(source: RecordProxy): void, - getDataID(): DataID, - getLinkedRecord(name: string, args?: Variables | void): RecordProxy | void, - getLinkedRecords(name: string, args?: Variables | void): Array | void, + copyFieldsFrom(source: RecordProxy): void; + getDataID(): DataID; + getLinkedRecord(name: string, args?: Variables | void): RecordProxy | void; + getLinkedRecords(name: string, args?: Variables | void): Array | void; getOrCreateLinkedRecord( name: string, typeName: string, args?: Variables | void, - ): RecordProxy, - getType(): string, - getValue(name: string, args?: Variables | void): any, + ): RecordProxy; + getType(): string; + getValue(name: string, args?: Variables | void): any; setLinkedRecord( record: RecordProxy, name: string, args?: Variables | void, - ): RecordProxy, + ): RecordProxy; setLinkedRecords( records: Array | void, name: string, args?: Variables | void, - ): RecordProxy, - setValue(value: any, name: string, args?: Variables | void): RecordProxy, + ): RecordProxy; + setValue(value: any, name: string, args?: Variables | void): RecordProxy; } export interface RecordSourceProxy { - create(dataID: DataID, typeName: string): RecordProxy, - delete(dataID: DataID): void, - get(dataID: DataID): Array | void, - getRoot(): RecordProxy, + create(dataID: DataID, typeName: string): RecordProxy; + delete(dataID: DataID): void; + get(dataID: DataID): Array | void; + getRoot(): RecordProxy; } export interface HandleFieldPayload { // The arguments that were fetched. - args: Variables, + args: Variables; // The __id of the record containing the source/handle field. - dataID: DataID, + dataID: DataID; // The (storage) key at which the original server data was written. - fieldKey: string, - // The name of the handle. - handle: string, + fieldKey: string; + // The name of the handle + handle: string; // The (storage) key at which the handle's data should be written by the - // handler. - handleKey: string, + // handler + handleKey: string; } interface HandlerInterface { - update: (store: RecordSourceProxy, fieldPayload: HandleFieldPayload) => void; + update(store: RecordSourceProxy, fieldPayload: HandleFieldPayload): void; [functionName: string]: (...args: any[]) => any; } export const Handler: HandlerInterface; @@ -212,8 +218,8 @@ declare namespace __Relay { * in milliseconds. (This value will be passed to setTimeout.) */ export interface CacheConfig { - force?: boolean | void, - poll?: number | void, + force?: boolean | void; + poll?: number | void; } /** @@ -222,32 +228,32 @@ declare namespace __Relay { * would cancel the subscription. */ export interface Disposable { - dispose(): void, + dispose(): void; } /** * Arbitrary data e.g. received by a container as props. */ - export interface Props { [key: string]: any } + export interface Props { [key: string]: any; } /* * An individual cached graph object. */ - export interface Record { [key: string]: any } + export interface Record { [key: string]: any; } /** * A collection of records keyed by id. */ - export interface RecordMap { [dataID: string]: Record | void } + export interface RecordMap { [dataID: string]: Record | void; } /** * A selector defines the starting point for a traversal into the graph for the * purposes of targeting a subgraph. */ export interface CSelector { - dataID: DataID, - node: TNode, - variables: Variables, + dataID: DataID; + node: TNode; + variables: Variables; } /** @@ -261,13 +267,13 @@ declare namespace __Relay { /** * The results of a selector given a store/RecordSource. */ - export interface SelectorData { [key: string]: any } + export interface SelectorData { [key: string]: any; } /** * The results of reading the results of a FragmentMap given some input * `Props`. */ - export interface FragmentSpecResults { [key: string]: any } + export interface FragmentSpecResults { [key: string]: any; } /** * A utility for resolving and subscribing to the results of a fragment spec @@ -284,27 +290,27 @@ declare namespace __Relay { /** * Stop watching for changes to the results of the fragments. */ - dispose(): void, + dispose(): void; /** * Get the current results. */ - resolve(): FragmentSpecResults, + resolve(): FragmentSpecResults; /** * Update the resolver with new inputs. Call `resolve()` to get the updated * results. */ - setProps(props: Props): void, + setProps(props: Props): void; /** * Override the variables used to read the results of the fragments. Call * `resolve()` to get the updated results. */ - setVariables(variables: Variables): void, + setVariables(variables: Variables): void; } - export interface CFragmentMap { [key: string]: TFragment } + export interface CFragmentMap { [key: string]: TFragment; } /** * An operation selector describes a specific instance of a GraphQL operation @@ -316,10 +322,10 @@ declare namespace __Relay { * the results of the the operation. */ export interface COperationSelector { - fragment: CSelector, - node: TOperation, - root: CSelector, - variables: Variables, + fragment: CSelector; + node: TOperation; + root: CSelector; + variables: Variables; } /** @@ -333,11 +339,11 @@ declare namespace __Relay { TNode, TOperation, TPayload, - > { + > { /** * Read the results of a selector from in-memory records in the store. */ - lookup(selector: CSelector): CSnapshot, + lookup(selector: CSelector): CSnapshot; /** * Subscribe to changes to the results of a selector. The callback is called @@ -347,7 +353,7 @@ declare namespace __Relay { subscribe( snapshot: CSnapshot, callback: (snapshot: CSnapshot) => void, - ): Disposable, + ): Disposable; /** * Ensure that all the records necessary to fulfill the given selector are @@ -356,7 +362,7 @@ declare namespace __Relay { * * Note: This is a no-op in the classic core. */ - retain(selector: CSelector): Disposable, + retain(selector: CSelector): Disposable; /** * Send a query to the server with request/response semantics: the query will @@ -375,7 +381,7 @@ declare namespace __Relay { onError?: Maybe<(error: Error) => void>, onNext?: Maybe<(payload: TPayload) => void>, operation: COperationSelector, - }): Disposable, + }): Disposable; /** * Send a query to the server with request/subscription semantics: one or more @@ -391,15 +397,15 @@ declare namespace __Relay { onError?: Maybe<(error: Error) => void>, onNext?: Maybe<(payload: TPayload) => void>, operation: COperationSelector, - }): Disposable, + }): Disposable; unstable_internal: CUnstableEnvironmentCore< - TEnvironment, - TFragment, - TGraphQLTaggedNode, - TNode, - TOperation - >, + TEnvironment, + TFragment, + TGraphQLTaggedNode, + TNode, + TOperation + >; } export interface CUnstableEnvironmentCore< @@ -408,7 +414,7 @@ declare namespace __Relay { TGraphQLTaggedNode, TNode, TOperation, - > { + > { /** * Create an instance of a FragmentSpecResolver. * @@ -416,13 +422,13 @@ declare namespace __Relay { * defined here, so this could be moved out of core. It's convenient to have * separate implementations until the experimental core is in OSS. */ - createFragmentSpecResolver: ( + createFragmentSpecResolver( context: CRelayContext, containerName: string, fragments: CFragmentMap, props: Props, callback: () => void, - ) => FragmentSpecResolver, + ): FragmentSpecResolver; /** * Creates an instance of an OperationSelector given an operation definition @@ -430,30 +436,30 @@ declare namespace __Relay { * filtered to exclude variables that do not matche defined arguments on the * operation, and default values are populated for null values. */ - createOperationSelector: ( + createOperationSelector( operation: TOperation, variables: Variables, - ) => COperationSelector, + ): COperationSelector; /** * Given a graphql`...` tagged template, extract a fragment definition usable * by this version of Relay core. Throws if the value is not a fragment. */ - getFragment: (node: TGraphQLTaggedNode) => TFragment, + getFragment(node: TGraphQLTaggedNode): TFragment; /** * Given a graphql`...` tagged template, extract an operation definition * usable by this version of Relay core. Throws if the value is not an * operation. */ - getOperation: (node: TGraphQLTaggedNode) => TOperation, + getOperation(node: TGraphQLTaggedNode): TOperation; /** * Determine if two selectors are equal (represent the same selection). Note * that this function returns `false` when the two queries/fragments are * different objects, even if they select the same fields. */ - areEqualSelectors: (a: CSelector, b: CSelector) => boolean, + areEqualSelectors(a: CSelector, b: CSelector): boolean; /** * Given the result `item` from a parent that fetched `fragment`, creates a @@ -482,11 +488,11 @@ declare namespace __Relay { * const childData = environment.lookup(childSelector).data; * ``` */ - getSelector: ( + getSelector( operationVariables: Variables, fragment: TFragment, prop: any, - ) => CSelector | void, + ): CSelector | void; /** * Given the result `items` from a parent that fetched `fragment`, creates a @@ -494,11 +500,11 @@ declare namespace __Relay { * items. This is similar to `getSelector` but for "plural" fragments that * expect an array of results and therefore return an array of selectors. */ - getSelectorList: ( + getSelectorList( operationVariables: Variables, fragment: TFragment, props: any[], - ) => Array> | void, + ): Array> | void; /** * Given a mapping of keys -> results and a mapping of keys -> fragments, @@ -508,11 +514,11 @@ declare namespace __Relay { * use this function to convert (props, fragments) into selectors so that they * can read the results to pass to the inner component. */ - getSelectorsFromObject: ( + getSelectorsFromObject( operationVariables: Variables, fragments: CFragmentMap, props: Props, - ) => { [key: string]: Maybe<(CSelector | Array>)> }, + ): { [key: string]: Maybe<(CSelector | Array>)> }; /** * Given a mapping of keys -> results and a mapping of keys -> fragments, @@ -521,10 +527,10 @@ declare namespace __Relay { * Similar to `getSelectorsFromObject()`, this function can be useful in * determining the "identity" of the props passed to a component. */ - getDataIDsFromObject: ( + getDataIDsFromObject( fragments: CFragmentMap, props: Props, - ) => { [key: string]: Maybe<(DataID | DataID[])> }, + ): { [key: string]: Maybe<(DataID | DataID[])> }; /** * Given a mapping of keys -> results and a mapping of keys -> fragments, @@ -534,11 +540,11 @@ declare namespace __Relay { * This can be useful in determing what varaibles were used to fetch the data * for a Relay container, for example. */ - getVariablesFromObject: ( + getVariablesFromObject( operationVariables: Variables, fragments: CFragmentMap, props: Props, - ) => Variables, + ): Variables; } /** @@ -546,8 +552,8 @@ declare namespace __Relay { * integration layer (e.g. QueryRenderer, FragmentContainer, etc). */ export interface CRelayContext { - environment: TEnvironment, - variables: Variables, + environment: TEnvironment; + variables: Variables; } // ~~~~~~~~~~~~~~~~~~~~~ @@ -559,49 +565,49 @@ declare namespace __Relay { */ // ~~~~~~~~~~~~~~~~~~~~~ export interface RerunParam { - param: string, - import: string, - max_runs: number, + param: string; + import: string; + max_runs: number; } interface FIELDS_CHANGE { - type: 'FIELDS_CHANGE', - fieldIDs: { [fieldName: string]: DataID | DataID[] }, + type: 'FIELDS_CHANGE'; + fieldIDs: { [fieldName: string]: DataID | DataID[]; }; } interface RANGE_ADD { - type: 'RANGE_ADD', - parentName?: string, - parentID?: string, + type: 'RANGE_ADD'; + parentName?: string; + parentID?: string; connectionInfo?: Array<{ key: string, filters?: Variables, rangeBehavior: string, - }>, - connectionName?: string, - edgeName: string, - rangeBehaviors?: RangeBehaviors, + }>; + connectionName?: string; + edgeName: string; + rangeBehaviors?: RangeBehaviors; } interface NODE_DELETE { - type: 'NODE_DELETE', - parentName?: string, - parentID?: string, - connectionName?: string, - deletedIDFieldName: string, + type: 'NODE_DELETE'; + parentName?: string; + parentID?: string; + connectionName?: string; + deletedIDFieldName: string; } interface RANGE_DELETE { - type: 'RANGE_DELETE', - parentName?: string, - parentID?: string, + type: 'RANGE_DELETE'; + parentName?: string; + parentID?: string; connectionKeys?: Array<{ key: string, filters?: Variables, - }>, - connectionName?: string, - deletedIDFieldName: string | string[], - pathToConnection: string[], + }>; + connectionName?: string; + deletedIDFieldName: string | string[]; + pathToConnection: string[]; } interface REQUIRED_CHILDREN { - type: 'REQUIRED_CHILDREN', - children: RelayConcreteNode[], + type: 'REQUIRED_CHILDREN'; + children: RelayConcreteNode[]; } export type RelayMutationConfig = FIELDS_CHANGE | @@ -611,8 +617,8 @@ declare namespace __Relay { REQUIRED_CHILDREN; export interface RelayMutationTransactionCommitCallbacks { - onFailure?: RelayMutationTransactionCommitFailureCallback, - onSuccess?: RelayMutationTransactionCommitSuccessCallback, + onFailure?: RelayMutationTransactionCommitFailureCallback; + onSuccess?: RelayMutationTransactionCommitSuccessCallback; } export type RelayMutationTransactionCommitFailureCallback = ( transaction: RelayMutationTransaction, @@ -622,22 +628,22 @@ declare namespace __Relay { [key: string]: any, }) => void; export interface NetworkLayer { - sendMutation(request: RelayMutationRequest): Promise | void, - sendQueries(requests: RelayQueryRequest[]): Promise | void, - supports(...options: string[]): boolean, + sendMutation(request: RelayMutationRequest): Promise | void; + sendQueries(requests: RelayQueryRequest[]): Promise | void; + supports(...options: string[]): boolean; } export interface QueryResult { - error?: Error | void, - ref_params?: { [name: string]: any } | void, - response: QueryPayload, + error?: Error | void; + ref_params?: { [name: string]: any } | void; + response: QueryPayload; } export interface ReadyState { - aborted: boolean, - done: boolean, - error: Error | void, - events: ReadyStateEvent[], - ready: boolean, - stale: boolean, + aborted: boolean; + done: boolean; + error: Error | void; + events: ReadyStateEvent[]; + ready: boolean; + stale: boolean; } type RelayContainerErrorEventType = | 'CACHE_RESTORE_FAILED' @@ -652,12 +658,12 @@ declare namespace __Relay { | 'STORE_FOUND_ALL' | 'STORE_FOUND_REQUIRED'; export type ReadyStateChangeCallback = (readyState: ReadyState) => void; - export type ReadyStateEvent = { - type: RelayContainerLoadingEventType | RelayContainerErrorEventType, - error?: Error, - }; + export interface ReadyStateEvent { + type: RelayContainerLoadingEventType | RelayContainerErrorEventType; + error?: Error; + } export interface Abortable { - abort(): void, + abort(): void; } // ~~~~~~~~~~~~~~~~~~~~~ @@ -668,8 +674,8 @@ declare namespace __Relay { * https://github.com/facebook/relay/blob/master/packages/react-relay/classic/tools/RelayInternalTypes.js */ // ~~~~~~~~~~~~~~~~~~~~~ - export interface QueryPayload { [key: string]: any } - export interface RelayQuerySet { [queryName: string]: any } + export interface QueryPayload { [key: string]: any; } + export interface RelayQuerySet { [queryName: string]: any; } type RangeBehaviorsFunction = (connectionArgs: { [argName: string]: any, }) => 'APPEND' | 'IGNORE' | 'PREPEND' | 'REFETCH' | 'REMOVE'; @@ -703,7 +709,7 @@ declare namespace __Relay { uploadables?: Common.UploadableMap | void, ) => Promise; interface RelayNetwork { - execute: ExecuteFunction, + execute: ExecuteFunction; } // ~~~~~~~~~~~~~~~~~~~~~ @@ -715,10 +721,10 @@ declare namespace __Relay { // RelayModernEnvironment // ~~~~~~~~~~~~~~~~~~~~~ interface EnvironmentConfig { - configName?: string, - handlerProvider?: typeof HandlerProvider, - network: Network, - store: Store, + configName?: string; + handlerProvider?: typeof HandlerProvider; + network: Network; + store: Store; } class Environment { constructor(config: EnvironmentConfig); @@ -761,8 +767,8 @@ declare namespace __Relay { // ~~~~~~~~~~~~~~~~~~~~~ // RelayInMemoryRecordSource // ~~~~~~~~~~~~~~~~~~~~~ - interface Record { [key: string]: any } - interface RecordMap { [dataID: string]: Record | void } + interface Record { [key: string]: any; } + interface RecordMap { [dataID: string]: Record | void; } // ~~~~~~~~~~~~~~~~~~~~~ // Network @@ -907,19 +913,19 @@ declare namespace __Relay { // RelayObservable // ~~~~~~~~~~~~~~~~~~~~~ interface Subscription { - unsubscribe: () => void, - readonly closed: boolean, + unsubscribe(): void; + readonly closed: boolean; } interface Observer { - start?: ((subscription: Subscription) => any) | void, - next?: ((nextThing: T) => any) | void, - error?: ((error: Error) => any) | void, - complete?: (() => any) | void, - unsubscribe?: ((subscription: Subscription) => any) | void, + start?: ((subscription: Subscription) => any) | void; + next?: ((nextThing: T) => any) | void; + error?: ((error: Error) => any) | void; + complete?: (() => any) | void; + unsubscribe?: ((subscription: Subscription) => any) | void; } type Source = () => any; interface Subscribable { - subscribe(observer: Observer): Subscription, + subscribe(observer: Observer): Subscription; } type ObservableFromValue = RelayObservable | Promise | T; class RelayObservable implements Subscribable { @@ -1046,15 +1052,15 @@ declare namespace __Relay { // ~~~~~~~~~~~~~~~~~~~~~ // exposed through RelayModern, not Runtime directly interface MutationConfig { - configs?: Common.RelayMutationConfig[], - mutation: Common.GraphQLTaggedNode, - variables: Common.Variables, - uploadables?: Common.UploadableMap, - onCompleted?: (response: T, errors: Common.PayloadError[] | void) => void, - onError?: (error?: Error) => void, - optimisticUpdater?: Common.SelectorStoreUpdater | void, - optimisticResponse?: object, - updater?: Common.SelectorStoreUpdater | void, + configs?: Common.RelayMutationConfig[]; + mutation: Common.GraphQLTaggedNode; + variables: Common.Variables; + uploadables?: Common.UploadableMap; + onCompleted?(response: T, errors: Common.PayloadError[] | void): void; + onError?(error?: Error): void; + optimisticUpdater?: Common.SelectorStoreUpdater | void; + optimisticResponse?: object; + updater?: Common.SelectorStoreUpdater | void; } function commitRelayModernMutation( environment: Environment, @@ -1066,11 +1072,11 @@ declare namespace __Relay { // ~~~~~~~~~~~~~~~~~~~~~ // exposed through RelayModern, not Runtime directly interface OptimisticMutationConfig { - configs?: Common.RelayMutationConfig[], - mutation: Common.GraphQLTaggedNode, - variables: Common.Variables, - optimisticUpdater?: Common.SelectorStoreUpdater, - optimisticResponse?: object, + configs?: Common.RelayMutationConfig[]; + mutation: Common.GraphQLTaggedNode; + variables: Common.Variables; + optimisticUpdater?: Common.SelectorStoreUpdater; + optimisticResponse?: object; } // ~~~~~~~~~~~~~~~~~~~~~ @@ -1102,13 +1108,13 @@ declare namespace __Relay { // ~~~~~~~~~~~~~~~~~~~~~ // exposed through RelayModern, not Runtime directly export interface GraphQLSubscriptionConfig { - configs?: Common.RelayMutationConfig[], - subscription: Common.GraphQLTaggedNode, - variables: Common.Variables, - onCompleted?: () => void, - onError?: (error: Error) => void, - onNext?: (response: object | void) => void, - updater?: (store: Common.RecordSourceSelectorProxy) => void, + configs?: Common.RelayMutationConfig[]; + subscription: Common.GraphQLTaggedNode; + variables: Common.Variables; + onCompleted?(): void; + onError?(error: Error): void; + onNext?(response: object | void): void; + updater?(store: Common.RecordSourceSelectorProxy): void; } export function requestRelaySubscription( environment: Environment, diff --git a/types/relay-runtime/relay-runtime-tests.tsx b/types/relay-runtime/relay-runtime-tests.tsx index 609399f079..c6dd9c15a2 100644 --- a/types/relay-runtime/relay-runtime-tests.tsx +++ b/types/relay-runtime/relay-runtime-tests.tsx @@ -3,6 +3,8 @@ import { Network, RecordSource, Store, + ConnectionHandler, + ViewerHandler, } from 'relay-runtime'; const source = new RecordSource(); @@ -20,15 +22,11 @@ function fetchQuery( ) { return fetch('/graphql', { method: 'POST', - headers: { - // Add authentication and other headers here - 'content-type': 'application/json' - }, body: JSON.stringify({ - query: operation.text, // GraphQL text from input - variables, + query: operation.text, // GraphQL text from input + variables, }), - }).then(response => { + }).then((response: any) => { return response.json(); }); } @@ -49,11 +47,6 @@ const environment = new Environment({ // Handler Provider // ~~~~~~~~~~~~~~~~~~~~~ -import { - ConnectionHandler, - ViewerHandler, -} from 'relay-runtime'; - function handlerProvider(handle: any) { switch (handle) { // Augment (or remove from) this list: From c2ea2eb7c4c5ba8505c54fd46b7864b53b7f9a84 Mon Sep 17 00:00:00 2001 From: voxmatt Date: Sun, 10 Sep 2017 16:36:14 -1000 Subject: [PATCH 017/828] starting in on the linting errors in react-relay --- types/react-relay/index.d.ts | 569 +++++++++++++++++------------------ 1 file changed, 280 insertions(+), 289 deletions(-) diff --git a/types/react-relay/index.d.ts b/types/react-relay/index.d.ts index a165229584..eb940d296d 100644 --- a/types/react-relay/index.d.ts +++ b/types/react-relay/index.d.ts @@ -1,281 +1,274 @@ -// Type definitions for react-relay 1.3.0 +// Type definitions for react-relay 1.3 // Project: https://github.com/facebook/relay // Definitions by: Johannes Schickling , Matt Martin // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped // TypeScript Version: 2.4 -/// /// -//////////////////////////// -// RELAY MODERN TYPES -/////////////////////////// +declare namespace __Relay { -declare namespace __Relay.Modern { - // ~~~~~~~~~~~~~~~~~~~~~ - // Maybe Fix - // ~~~~~~~~~~~~~~~~~~~~~ - type ConcreteFragment = any; - type ConcreteBatch = any; - type ConcreteFragmentDefinition = object; - type ConcreteOperationDefinition = object; - type ReactBaseComponent = React.ComponentClass | React.StatelessComponent; + //////////////////////////// + // RELAY MODERN TYPES + /////////////////////////// + namespace Modern { + // ~~~~~~~~~~~~~~~~~~~~~ + // Maybe Fix + // ~~~~~~~~~~~~~~~~~~~~~ + type ConcreteFragment = any; + type ConcreteBatch = any; + type ConcreteFragmentDefinition = object; + type ConcreteOperationDefinition = object; + type ReactBaseComponent = React.ComponentClass | React.StatelessComponent; - // ~~~~~~~~~~~~~~~~~~~~~ - // RelayProp - // ~~~~~~~~~~~~~~~~~~~~~ - // note: refetch and pagination containers augment this - export type RelayProp = { - environment: Runtime.Environment, - }; + // ~~~~~~~~~~~~~~~~~~~~~ + // RelayProp + // ~~~~~~~~~~~~~~~~~~~~~ + // note: refetch and pagination containers augment this + export interface RelayProp { + environment: Runtime.Environment; + } - // ~~~~~~~~~~~~~~~~~~~~~ - // RelayQL - // ~~~~~~~~~~~~~~~~~~~~~ - export function RelayQL( - strings: Array, - ...substitutions: Array - ): Common.RelayConcreteNode; + // ~~~~~~~~~~~~~~~~~~~~~ + // RelayQL + // ~~~~~~~~~~~~~~~~~~~~~ + export function RelayQL( + strings: string[], + ...substitutions: any[] + ): Common.RelayConcreteNode; - // ~~~~~~~~~~~~~~~~~~~~~ - // RelayModernGraphQLTag - // ~~~~~~~~~~~~~~~~~~~~~ - type GeneratedNodeMap = {[key: string]: GraphQLTaggedNode}; - type GraphQLTaggedNode = - | (() => ConcreteFragment | ConcreteBatch) - | { - modern: () => ConcreteFragment | ConcreteBatch, - classic: (relayQL: typeof RelayQL) => - | ConcreteFragmentDefinition - | ConcreteOperationDefinition, - }; - /** - * Runtime function to correspond to the `graphql` tagged template function. - * All calls to this function should be transformed by the plugin. - */ - interface IGraphql { - (strings: Array | TemplateStringsArray): GraphQLTaggedNode; - experimental: (strings: Array | TemplateStringsArray) => GraphQLTaggedNode; - } - export const graphql: IGraphql; + // ~~~~~~~~~~~~~~~~~~~~~ + // RelayModernGraphQLTag + // ~~~~~~~~~~~~~~~~~~~~~ + interface GeneratedNodeMap { [key: string]: GraphQLTaggedNode; } + type GraphQLTaggedNode = + (() => ConcreteFragment | ConcreteBatch) + | { + modern(): ConcreteFragment | ConcreteBatch, + classic(relayQL: typeof RelayQL): + | ConcreteFragmentDefinition + | ConcreteOperationDefinition, + }; + /** + * Runtime function to correspond to the `graphql` tagged template function. + * All calls to this function should be transformed by the plugin. + */ + interface GraphqlInterface { + (strings: string[] | TemplateStringsArray): GraphQLTaggedNode; + experimental(strings: string[] | TemplateStringsArray): GraphQLTaggedNode; + } + export const graphql: GraphqlInterface; - // ~~~~~~~~~~~~~~~~~~~~~ - // ReactRelayQueryRenderer - // ~~~~~~~~~~~~~~~~~~~~~ - type QueryRendererProps = { - cacheConfig?: __Relay.Common.CacheConfig | void, - environment: __Relay.Runtime.Environment, - query: GraphQLTaggedNode, - render: (readyState: ReadyState) => React.ReactElement | void, - variables: Common.Variables, - rerunParamExperimental?: Common.RerunParam, - }; - export type ReadyState = { - error: Error | void, - props: { [propName: string]: any } | void, - retry: (() => void) | void, - }; - type QueryRendererState = { - readyState: ReadyState, - }; - class ReactRelayQueryRenderer extends React.Component {} + // ~~~~~~~~~~~~~~~~~~~~~ + // ReactRelayQueryRenderer + // ~~~~~~~~~~~~~~~~~~~~~ + interface QueryRendererProps { + cacheConfig?: Common.CacheConfig | void; + environment: Runtime.Environment; + query: GraphQLTaggedNode; + render(readyState: ReadyState): React.ReactElement | void; + variables: Common.Variables; + rerunParamExperimental?: Common.RerunParam; + } + export interface ReadyState { + error: Error | void; + props: { [propName: string]: any } | void; + retry: (() => void) | void; + } + interface QueryRendererState { + readyState: ReadyState; + } + class ReactRelayQueryRenderer extends React.Component { } - // ~~~~~~~~~~~~~~~~~~~~~ - // createFragmentContainer - // ~~~~~~~~~~~~~~~~~~~~~ - export function createFragmentContainer( - Component: ReactBaseComponent, - fragmentSpec: GraphQLTaggedNode | GeneratedNodeMap, - ): ReactBaseComponent; + // ~~~~~~~~~~~~~~~~~~~~~ + // createFragmentContainer + // ~~~~~~~~~~~~~~~~~~~~~ + export function createFragmentContainer( + Component: ReactBaseComponent, + fragmentSpec: GraphQLTaggedNode | GeneratedNodeMap, + ): ReactBaseComponent; - // ~~~~~~~~~~~~~~~~~~~~~ - // createPaginationContainer - // ~~~~~~~~~~~~~~~~~~~~~ - type PageInfo = { - endCursor: string | void, - hasNextPage: boolean, - hasPreviousPage: boolean, - startCursor: string | void, - }; - type ConnectionData = { - edges?: any[], - pageInfo?: PageInfo | void, - }; - export type RelayPaginationProp = RelayProp & { - hasMore: () => boolean, - isLoading: () => boolean, - loadMore: ( - pageSize: number, - callback: (error?: Error) => void, - options?: RefetchOptions, - ) => Common.Disposable | void, - refetchConnection: ( + // ~~~~~~~~~~~~~~~~~~~~~ + // createPaginationContainer + // ~~~~~~~~~~~~~~~~~~~~~ + interface PageInfo { + endCursor: string | void; + hasNextPage: boolean; + hasPreviousPage: boolean; + startCursor: string | void; + } + interface ConnectionData { + edges?: any[]; + pageInfo?: PageInfo | void; + } + export type RelayPaginationProp = RelayProp & { + hasMore(): boolean, + isLoading(): boolean, + loadMore( + pageSize: number, + callback: (error?: Error) => void, + options?: RefetchOptions, + ): Common.Disposable | void, + refetchConnection( + totalCount: number, + callback: (error?: Error | void) => void, + refetchVariables?: Common.Variables | void, + ): Common.Disposable | void, + }; + export function FragmentVariablesGetter( + prevVars: Common.Variables, totalCount: number, - callback: (error?: Error | void) => void, - refetchVariables?: Common.Variables | void, - ) => Common.Disposable | void, - }; - export function FragmentVariablesGetter( - prevVars: Common.Variables, - totalCount: number, - ): Common.Variables; - type ConnectionConfig = { - direction?: 'backward' | 'forward', - getConnectionFromProps?: (props: object) => ConnectionData | void, - getFragmentVariables?: typeof FragmentVariablesGetter, - getVariables: ( - props: {[propName: string]: any }, - paginationInfo: {count: number, cursor: string | void}, - fragmentVariables: Common.Variables, - ) => Common.Variables, - query: GraphQLTaggedNode, - }; - export function createPaginationContainer( - Component: ReactBaseComponent, - fragmentSpec: GraphQLTaggedNode | GeneratedNodeMap, - connectionConfig: ConnectionConfig, - ): ReactBaseComponent; + ): Common.Variables; + interface ConnectionConfig { + direction?: 'backward' | 'forward'; + getConnectionFromProps?(props: object): ConnectionData | void; + getFragmentVariables?: typeof FragmentVariablesGetter; + getVariables( + props: { [propName: string]: any }, + paginationInfo: { count: number, cursor: string | void }, + fragmentVariables: Common.Variables, + ): Common.Variables; + query: GraphQLTaggedNode; + } + export function createPaginationContainer( + Component: ReactBaseComponent, + fragmentSpec: GraphQLTaggedNode | GeneratedNodeMap, + connectionConfig: ConnectionConfig, + ): ReactBaseComponent; - // ~~~~~~~~~~~~~~~~~~~~~ - // createFragmentContainer - // ~~~~~~~~~~~~~~~~~~~~~ - export type RefetchOptions = { - force?: boolean, - rerunParamExperimental?: Common.RerunParam, - }; - export type RelayRefetchProp = RelayProp & { - refetch: ( - refetchVariables: Common.Variables | ((fragmentVariables: Common.Variables) => Common.Variables), - renderVariables?: Common.Variables, - callback?: (error: Error | void) => void, - options?: RefetchOptions, - ) => Common.Disposable, - }; - export function createRefetchContainer( - Component: ReactBaseComponent, - fragmentSpec: GraphQLTaggedNode | GeneratedNodeMap, - taggedNode: GraphQLTaggedNode, - ): ReactBaseComponent; + // ~~~~~~~~~~~~~~~~~~~~~ + // createFragmentContainer + // ~~~~~~~~~~~~~~~~~~~~~ + export interface RefetchOptions { + force?: boolean; + rerunParamExperimental?: Common.RerunParam; + } + export type RelayRefetchProp = RelayProp & { + refetch( + refetchVariables: Common.Variables | ((fragmentVariables: Common.Variables) => Common.Variables), + renderVariables?: Common.Variables, + callback?: (error: Error | void) => void, + options?: RefetchOptions, + ): Common.Disposable, + }; + export function createRefetchContainer( + Component: ReactBaseComponent, + fragmentSpec: GraphQLTaggedNode | GeneratedNodeMap, + taggedNode: GraphQLTaggedNode, + ): ReactBaseComponent; + } + //////////////////////////// + // RELAY CLASSIC TYPES + /////////////////////////// + // note: the namespace here is really for use inside of + // relay-compat; the module declaration below + // uses the old, pre-existing types + namespace Classic { + // ~~~~~~~~~~~~~~~~~~~~~ + // Maybe Fix + // ~~~~~~~~~~~~~~~~~~~~~ + type StoreReaderData = any; + type StoreReaderOptions = any; + type RelayStoreData = any; + interface RelayQuery { Fragment: any; Node: any; Root: any; } + // ~~~~~~~~~~~~~~~~~~~~~ + // Environment + // ~~~~~~~~~~~~~~~~~~~~~ + interface FragmentResolver { + dispose(): void; + resolve( + fragment: RelayQuery["Fragment"], + dataIDs: Common.DataID | Common.DataID[], + ): (StoreReaderData | StoreReaderData[]) | void; + } + interface RelayEnvironmentInterface { + forceFetch( + querySet: Common.RelayQuerySet, + onReadyStateChange: Common.ReadyStateChangeCallback, + ): Common.Abortable; + getFragmentResolver( + fragment: RelayQuery["Fragment"], + onNext: () => void, + ): FragmentResolver; + getStoreData(): RelayStoreData; + primeCache( + querySet: Common.RelayQuerySet, + onReadyStateChange: Common.ReadyStateChangeCallback, + ): Common.Abortable; + read( + node: RelayQuery["Node"], + dataID: Common.DataID, + options?: StoreReaderOptions, + ): StoreReaderData | void; + readQuery( + root: RelayQuery["Root"], + options?: StoreReaderOptions, + ): StoreReaderData[] | void; + } + } + //////////////////////////// + // RELAY COMPAT TYPES + /////////////////////////// + namespace Compat { + // ~~~~~~~~~~~~~~~~~~~~~ + // Maybe Fix + // ~~~~~~~~~~~~~~~~~~~~~ + type ConcreteFragment = any; + type ConcreteBatch = any; + type ConcreteFragmentDefinition = object; + type ConcreteOperationDefinition = object; + + // ~~~~~~~~~~~~~~~~~~~~~ + // Util + // ~~~~~~~~~~~~~~~~~~~~~ + export function getFragment(q: string, v?: Common.Variables): string; + interface ComponentWithFragment extends React.ComponentClass { + getFragment: typeof getFragment; + } + interface StatelessWithFragment extends React.StatelessComponent { + getFragment: typeof getFragment; + } + type ReactFragmentComponent = ComponentWithFragment | StatelessWithFragment; + type ReactBaseComponent = React.ComponentClass | React.StatelessComponent; + export type RelayClassicEnvironment = Classic.RelayEnvironmentInterface; + + // ~~~~~~~~~~~~~~~~~~~~~ + // RelayCompatTypes + // ~~~~~~~~~~~~~~~~~~~~~ + export type CompatEnvironment = Runtime.Environment | RelayClassicEnvironment; + + // ~~~~~~~~~~~~~~~~~~~~~ + // RelayCompatMutations + // ~~~~~~~~~~~~~~~~~~~~~ + export function commitUpdate( + environment: CompatEnvironment, + config: Runtime.MutationConfig, + ): Common.Disposable; + export function applyUpdate( + environment: CompatEnvironment, + config: Runtime.OptimisticMutationConfig, + ): Common.Disposable; + + // ~~~~~~~~~~~~~~~~~~~~~ + // RelayCompatContainer + // ~~~~~~~~~~~~~~~~~~~~~ + export interface GeneratedNodeMap { [key: string]: Modern.GraphQLTaggedNode; } + export function createContainer( + Component: ReactBaseComponent, + fragmentSpec: Modern.GraphQLTaggedNode | GeneratedNodeMap, + ): ReactFragmentComponent; + + // ~~~~~~~~~~~~~~~~~~~~~ + // injectDefaultVariablesProvider + // ~~~~~~~~~~~~~~~~~~~~~ + type VariablesProvider = () => Common.Variables; + export function injectDefaultVariablesProvider(variablesProvider: VariablesProvider): void; + } } - - -//////////////////////////// -// RELAY CLASSIC TYPES -/////////////////////////// -// note: the namespace here is really for use inside of -// relay-compat; the module declaration below -// uses the old, pre-existing types -declare namespace __Relay.Classic { - // ~~~~~~~~~~~~~~~~~~~~~ - // Maybe Fix - // ~~~~~~~~~~~~~~~~~~~~~ - type StoreReaderData = any; - type StoreReaderOptions = any; - type RelayStoreData = any; - type RelayQuery = { Fragment: any; Node: any; Root: any;}; - - // ~~~~~~~~~~~~~~~~~~~~~ - // Environment - // ~~~~~~~~~~~~~~~~~~~~~ - type FragmentResolver = { - dispose(): void, - resolve( - fragment: RelayQuery["Fragment"], - dataIDs: Common.DataID | Array, - ): (StoreReaderData | Array) | void, - }; - interface RelayEnvironmentInterface { - forceFetch( - querySet: Common.RelayQuerySet, - onReadyStateChange: Common.ReadyStateChangeCallback, - ): Common.Abortable, - getFragmentResolver( - fragment: RelayQuery["Fragment"], - onNext: () => void, - ): FragmentResolver, - getStoreData(): RelayStoreData, - primeCache( - querySet: Common.RelayQuerySet, - onReadyStateChange: Common.ReadyStateChangeCallback, - ): Common.Abortable, - read( - node: RelayQuery["Node"], - dataID: Common.DataID, - options?: StoreReaderOptions, - ): StoreReaderData | void, - readQuery( - root: RelayQuery["Root"], - options?: StoreReaderOptions, - ): Array | void, - } - } - -//////////////////////////// -// RELAY COMPAT TYPES -/////////////////////////// - -declare namespace __Relay.Compat { - // ~~~~~~~~~~~~~~~~~~~~~ - // Maybe Fix - // ~~~~~~~~~~~~~~~~~~~~~ - type ConcreteFragment = any; - type ConcreteBatch = any; - type ConcreteFragmentDefinition = object; - type ConcreteOperationDefinition = object; - - - // ~~~~~~~~~~~~~~~~~~~~~ - // Util - // ~~~~~~~~~~~~~~~~~~~~~ - export function getFragment(q: string, v?: Common.Variables): string; - interface ComponentWithFragment extends React.ComponentClass { - getFragment: typeof getFragment; - } - interface StatelessWithFragment extends React.StatelessComponent { - getFragment: typeof getFragment; - } - type ReactFragmentComponent = ComponentWithFragment | StatelessWithFragment; - type ReactBaseComponent = React.ComponentClass | React.StatelessComponent; - export type RelayClassicEnvironment = Classic.RelayEnvironmentInterface; - - // ~~~~~~~~~~~~~~~~~~~~~ - // RelayCompatTypes - // ~~~~~~~~~~~~~~~~~~~~~ - export type CompatEnvironment = Runtime.Environment | RelayClassicEnvironment; - - // ~~~~~~~~~~~~~~~~~~~~~ - // RelayCompatMutations - // ~~~~~~~~~~~~~~~~~~~~~ - export function commitUpdate( - environment: CompatEnvironment, - config: Runtime.MutationConfig, - ): Common.Disposable; - export function applyUpdate( - environment: CompatEnvironment, - config: Runtime.OptimisticMutationConfig, - ): Common.Disposable; - - // ~~~~~~~~~~~~~~~~~~~~~ - // RelayCompatContainer - // ~~~~~~~~~~~~~~~~~~~~~ - export type GeneratedNodeMap = {[key: string]: Modern.GraphQLTaggedNode}; - export function createContainer( - Component: ReactBaseComponent, - fragmentSpec: Modern.GraphQLTaggedNode | GeneratedNodeMap, - ): ReactFragmentComponent; - - // ~~~~~~~~~~~~~~~~~~~~~ - // injectDefaultVariablesProvider - // ~~~~~~~~~~~~~~~~~~~~~ - type VariablesProvider = () => Common.Variables; - export function injectDefaultVariablesProvider(variablesProvider: VariablesProvider): void; -} - - //////////////////////////// // MODULES /////////////////////////// @@ -308,8 +301,7 @@ declare module 'react-relay/compat' { export import QueryRenderer = __Relay.Modern.ReactRelayQueryRenderer; export import graphql = __Relay.Modern.graphql; export import fetchQuery = __Relay.Runtime.fetchRelayModernQuery; - } - +} declare module "react-relay/classic" { import * as React from "react"; @@ -341,21 +333,22 @@ declare module "react-relay/classic" { } type RelayMutationStatus = - 'UNCOMMITTED' | // Transaction hasn't yet been sent to the server. Transaction can be committed or rolled back. - 'COMMIT_QUEUED' | // Transaction was committed but another transaction with the same collision key is pending, so the transaction has been queued to send to the server. - 'COLLISION_COMMIT_FAILED' | //Transaction was queued for commit but another transaction with the same collision key failed. All transactions in the collision queue, including this one, have been failed. Transaction can be recommitted or rolled back. - 'COMMITTING' | // Transaction is waiting for the server to respond. - 'COMMIT_FAILED'; + 'UNCOMMITTED' | // Transaction hasn't yet been sent to the server. Transaction can be committed or rolled back. + 'COMMIT_QUEUED' | // Transaction was committed but another transaction with the same collision key is pending, so the transaction has been queued to send to the server. + 'COLLISION_COMMIT_FAILED' | // Transaction was queued for commit but another transaction with the same collision key failed. All transactions in the collision queue, + // including this one, have been failed. Transaction can be recommitted or rolled back. + 'COMMITTING' | // Transaction is waiting for the server to respond. + 'COMMIT_FAILED'; class RelayMutationTransaction { - applyOptimistic(): RelayMutationTransaction; - commit(): RelayMutationTransaction | null; - recommit(): void; - rollback(): void; - getError(): Error; - getStatus(): RelayMutationStatus; - getHash(): string; - getID(): ClientMutationID; + applyOptimistic(): RelayMutationTransaction; + commit(): RelayMutationTransaction | null; + recommit(): void; + rollback(): void; + getError(): Error; + getStatus(): RelayMutationStatus; + getHash(): string; + getID(): ClientMutationID; } interface RelayMutationRequest { @@ -398,7 +391,7 @@ declare module "react-relay/classic" { * S is typically dynamic as it depends on the data the app is currently using, but it's possible to always * return some data in the payload using REQUIRED_CHILDREN which is where specifying S is the most useful. */ - class Mutation { + class Mutation { props: T constructor(props: T) @@ -416,19 +409,19 @@ declare module "react-relay/classic" { } interface Store { - commitUpdate(mutation: Mutation, callbacks?: StoreUpdateCallbacks): any + commitUpdate(mutation: Mutation, callbacks?: StoreUpdateCallbacks): any } - var Store: Store + const Store: Store - class RootContainer extends React.Component {} + class RootContainer extends React.Component { } - interface RootContainerProps extends React.Props{ + interface RootContainerProps extends React.Props { Component: RelayContainerClass route: Route renderLoading?(): JSX.Element renderFetched?(data: any): JSX.Element - renderFailure?(error: Error, retry: Function): JSX.Element + renderFailure?(error: Error, retry: (...args: any[]) => any): JSX.Element } type ReadyStateEvent = @@ -443,16 +436,14 @@ declare module "react-relay/classic" { 'STORE_FOUND_ALL' | 'STORE_FOUND_REQUIRED'; - interface OnReadyStateChange { - (readyState: { - ready: boolean, - done: boolean, - stale: boolean, - error?: Error, - events: Array, - aborted: boolean - }): void - } + type OnReadyStateChange = (readyState: { + ready: boolean, + done: boolean, + stale: boolean, + error?: Error, + events: ReadyStateEvent[], + aborted: boolean + }) => void interface RelayProp { readonly route: { name: string; }; // incomplete, also has params and queries @@ -462,6 +453,6 @@ declare module "react-relay/classic" { forceFetch(variables: any, onReadyStateChange?: OnReadyStateChange): void; hasOptimisticUpdate(record: any): boolean; getPendingTransactions(record: any): RelayMutationTransaction[]; - commitUpdate: (mutation: Mutation, callbacks?: StoreUpdateCallbacks) => any; + commitUpdate(mutation: Mutation, callbacks?: StoreUpdateCallbacks): any; } } From ea247c58854b918552c4f846d7280b9eac7f543e Mon Sep 17 00:00:00 2001 From: voxmatt Date: Sun, 10 Sep 2017 17:08:21 -1000 Subject: [PATCH 018/828] removing redundent exports from relay-runtime --- types/relay-runtime/index.d.ts | 103 ++++++++++++++++----------------- 1 file changed, 51 insertions(+), 52 deletions(-) diff --git a/types/relay-runtime/index.d.ts b/types/relay-runtime/index.d.ts index 4acab12c5b..382711209f 100644 --- a/types/relay-runtime/index.d.ts +++ b/types/relay-runtime/index.d.ts @@ -6,7 +6,6 @@ declare namespace __Relay { namespace Common { - /** * SOURCE: * Relay 1.3.0 @@ -37,7 +36,7 @@ declare namespace __Relay { * lot of errors in Relay code since methods like getFragment() are used often * but have no definition in Relay's types. Suppressing for now. */ - export type RelayContainer = any; + type RelayContainer = any; // ~~~~~~~~~~~~~~~~~~~~~ // RelayQL @@ -64,12 +63,12 @@ declare namespace __Relay { // ~~~~~~~~~~~~~~~~~~~~~ // General Usage // ~~~~~~~~~~~~~~~~~~~~~ - export type DataID = string; - export interface Variables { + type DataID = string; + interface Variables { [name: string]: any; } - export type Uploadable = File | Blob; - export interface UploadableMap { + type Uploadable = File | Blob; + interface UploadableMap { [key: string]: Uploadable; } @@ -79,12 +78,12 @@ declare namespace __Relay { // File: https://github.com/facebook/relay/blob/master/packages/relay-runtime/network/RelayNetworkTypes.js // ~~~~~~~~~~~~~~~~~~~~~ - export interface LegacyObserver { - onCompleted?: (() => void) | void; - onError?: ((error: Error) => void) | void; - onNext?: ((data: T) => void) | void; + interface LegacyObserver { + onCompleted?(): void; + onError?(error: Error): void; + onNext?(data: T): void; } - export interface PayloadError { + interface PayloadError { message: string; locations?: Array<{ line: number, @@ -96,7 +95,7 @@ declare namespace __Relay { * * May return an Observable or Promise of a raw server response. */ - export function FetchFunction( + function FetchFunction( operation: ConcreteBatch, variables: Variables, cacheConfig: CacheConfig, @@ -110,7 +109,7 @@ declare namespace __Relay { * May return an Observable, otherwise must call the callbacks found in the * fourth parameter. */ - export type SubscribeFunction = ( + type SubscribeFunction = ( operation: ConcreteBatch, variables: Variables, cacheConfig: CacheConfig, @@ -126,14 +125,14 @@ declare namespace __Relay { * A function that receives a proxy over the store and may trigger side-effects * (indirectly) by calling `set*` methods on the store or its record proxies. */ - export type StoreUpdater = (store: RecordSourceProxy) => void; + type StoreUpdater = (store: RecordSourceProxy) => void; /** * Similar to StoreUpdater, but accepts a proxy tied to a specific selector in * order to easily access the root fields of a query/mutation as well as a * second argument of the response object of the mutation. */ - export type SelectorStoreUpdater = ( + type SelectorStoreUpdater = ( store: RecordSourceSelectorProxy, // Actually RelayCombinedEnvironmentTypes#SelectorData, but mixed is // inconvenient to access deeply in product code. @@ -144,7 +143,7 @@ declare namespace __Relay { * Extends the RecordSourceProxy interface with methods for accessing the root * fields of a Selector. */ - export interface RecordSourceSelectorProxy { + interface RecordSourceSelectorProxy { create(dataID: DataID, typeName: string): RecordProxy; delete(dataID: DataID): void; get(dataID: DataID): RecordProxy | void; @@ -153,7 +152,7 @@ declare namespace __Relay { getPluralRootField(fieldName: string): RecordProxy[] | void; } - export interface RecordProxy { + interface RecordProxy { copyFieldsFrom(source: RecordProxy): void; getDataID(): DataID; getLinkedRecord(name: string, args?: Variables | void): RecordProxy | void; @@ -178,14 +177,14 @@ declare namespace __Relay { setValue(value: any, name: string, args?: Variables | void): RecordProxy; } - export interface RecordSourceProxy { + interface RecordSourceProxy { create(dataID: DataID, typeName: string): RecordProxy; delete(dataID: DataID): void; get(dataID: DataID): Array | void; getRoot(): RecordProxy; } - export interface HandleFieldPayload { + interface HandleFieldPayload { // The arguments that were fetched. args: Variables; // The __id of the record containing the source/handle field. @@ -202,7 +201,7 @@ declare namespace __Relay { update(store: RecordSourceProxy, fieldPayload: HandleFieldPayload): void; [functionName: string]: (...args: any[]) => any; } - export const Handler: HandlerInterface; + const Handler: HandlerInterface; // ~~~~~~~~~~~~~~~~~~~~~ // RelayCombinedEnvironmentTypes @@ -217,7 +216,7 @@ declare namespace __Relay { * - `poll`: causes a query to live update by polling at the specified interval * in milliseconds. (This value will be passed to setTimeout.) */ - export interface CacheConfig { + interface CacheConfig { force?: boolean | void; poll?: number | void; } @@ -227,30 +226,30 @@ declare namespace __Relay { * use-case is as a return value for subscriptions, where calling `dispose()` * would cancel the subscription. */ - export interface Disposable { + interface Disposable { dispose(): void; } /** * Arbitrary data e.g. received by a container as props. */ - export interface Props { [key: string]: any; } + interface Props { [key: string]: any; } /* * An individual cached graph object. */ - export interface Record { [key: string]: any; } + interface Record { [key: string]: any; } /** * A collection of records keyed by id. */ - export interface RecordMap { [dataID: string]: Record | void; } + interface RecordMap { [dataID: string]: Record | void; } /** * A selector defines the starting point for a traversal into the graph for the * purposes of targeting a subgraph. */ - export interface CSelector { + interface CSelector { dataID: DataID; node: TNode; variables: Variables; @@ -259,7 +258,7 @@ declare namespace __Relay { /** * A representation of a selector and its results at a particular point in time. */ - export type CSnapshot = CSelector & { + type CSnapshot = CSelector & { data: SelectorData | void, seenRecords: RecordMap, }; @@ -267,13 +266,13 @@ declare namespace __Relay { /** * The results of a selector given a store/RecordSource. */ - export interface SelectorData { [key: string]: any; } + interface SelectorData { [key: string]: any; } /** * The results of reading the results of a FragmentMap given some input * `Props`. */ - export interface FragmentSpecResults { [key: string]: any; } + interface FragmentSpecResults { [key: string]: any; } /** * A utility for resolving and subscribing to the results of a fragment spec @@ -286,7 +285,7 @@ declare namespace __Relay { * - Creates resolvers for any props that became non-null. * - Updates resolvers with the latest props. */ - export interface FragmentSpecResolver { + interface FragmentSpecResolver { /** * Stop watching for changes to the results of the fragments. */ @@ -310,7 +309,7 @@ declare namespace __Relay { setVariables(variables: Variables): void; } - export interface CFragmentMap { [key: string]: TFragment; } + interface CFragmentMap { [key: string]: TFragment; } /** * An operation selector describes a specific instance of a GraphQL operation @@ -321,7 +320,7 @@ declare namespace __Relay { * - `fragment`: a selector intended for use in reading or subscribing to * the results of the the operation. */ - export interface COperationSelector { + interface COperationSelector { fragment: CSelector; node: TOperation; root: CSelector; @@ -332,7 +331,7 @@ declare namespace __Relay { * The public API of Relay core. Represents an encapsulated environment with its * own in-memory cache. */ - export interface CEnvironment< + interface CEnvironment< TEnvironment, TFragment, TGraphQLTaggedNode, @@ -408,7 +407,7 @@ declare namespace __Relay { >; } - export interface CUnstableEnvironmentCore< + interface CUnstableEnvironmentCore< TEnvironment, TFragment, TGraphQLTaggedNode, @@ -551,7 +550,7 @@ declare namespace __Relay { * The type of the `relay` property set on React context by the React/Relay * integration layer (e.g. QueryRenderer, FragmentContainer, etc). */ - export interface CRelayContext { + interface CRelayContext { environment: TEnvironment; variables: Variables; } @@ -564,7 +563,7 @@ declare namespace __Relay { * https://github.com/facebook/relay/blob/fa9f48ea209ee2402d433b59a84d1cbc046574e2/packages/react-relay/classic/tools/RelayTypes.js */ // ~~~~~~~~~~~~~~~~~~~~~ - export interface RerunParam { + interface RerunParam { param: string; import: string; max_runs: number; @@ -609,35 +608,35 @@ declare namespace __Relay { type: 'REQUIRED_CHILDREN'; children: RelayConcreteNode[]; } - export type RelayMutationConfig = + type RelayMutationConfig = FIELDS_CHANGE | RANGE_ADD | NODE_DELETE | RANGE_DELETE | REQUIRED_CHILDREN; - export interface RelayMutationTransactionCommitCallbacks { + interface RelayMutationTransactionCommitCallbacks { onFailure?: RelayMutationTransactionCommitFailureCallback; onSuccess?: RelayMutationTransactionCommitSuccessCallback; } - export type RelayMutationTransactionCommitFailureCallback = ( + type RelayMutationTransactionCommitFailureCallback = ( transaction: RelayMutationTransaction, preventAutoRollback: () => void, ) => void; - export type RelayMutationTransactionCommitSuccessCallback = (response: { + type RelayMutationTransactionCommitSuccessCallback = (response: { [key: string]: any, }) => void; - export interface NetworkLayer { + interface NetworkLayer { sendMutation(request: RelayMutationRequest): Promise | void; sendQueries(requests: RelayQueryRequest[]): Promise | void; supports(...options: string[]): boolean; } - export interface QueryResult { + interface QueryResult { error?: Error | void; ref_params?: { [name: string]: any } | void; response: QueryPayload; } - export interface ReadyState { + interface ReadyState { aborted: boolean; done: boolean; error: Error | void; @@ -657,12 +656,12 @@ declare namespace __Relay { | 'NETWORK_QUERY_START' | 'STORE_FOUND_ALL' | 'STORE_FOUND_REQUIRED'; - export type ReadyStateChangeCallback = (readyState: ReadyState) => void; - export interface ReadyStateEvent { + type ReadyStateChangeCallback = (readyState: ReadyState) => void; + interface ReadyStateEvent { type: RelayContainerLoadingEventType | RelayContainerErrorEventType; error?: Error; } - export interface Abortable { + interface Abortable { abort(): void; } @@ -674,15 +673,15 @@ declare namespace __Relay { * https://github.com/facebook/relay/blob/master/packages/react-relay/classic/tools/RelayInternalTypes.js */ // ~~~~~~~~~~~~~~~~~~~~~ - export interface QueryPayload { [key: string]: any; } - export interface RelayQuerySet { [queryName: string]: any; } + interface QueryPayload { [key: string]: any; } + interface RelayQuerySet { [queryName: string]: any; } type RangeBehaviorsFunction = (connectionArgs: { [argName: string]: any, }) => 'APPEND' | 'IGNORE' | 'PREPEND' | 'REFETCH' | 'REMOVE'; interface RangeBehaviorsObject { [key: string]: 'APPEND' | 'IGNORE' | 'PREPEND' | 'REFETCH' | 'REMOVE'; } - export type RangeBehaviors = RangeBehaviorsFunction | RangeBehaviorsObject; + type RangeBehaviors = RangeBehaviorsFunction | RangeBehaviorsObject; } namespace Runtime { @@ -715,7 +714,7 @@ declare namespace __Relay { // ~~~~~~~~~~~~~~~~~~~~~ // RelayDefaultHandlerProvider // ~~~~~~~~~~~~~~~~~~~~~ - export function HandlerProvider(name: string): typeof Common.Handler | void; + function HandlerProvider(name: string): typeof Common.Handler | void; // ~~~~~~~~~~~~~~~~~~~~~ // RelayModernEnvironment @@ -1107,7 +1106,7 @@ declare namespace __Relay { // requestRelaySubscription // ~~~~~~~~~~~~~~~~~~~~~ // exposed through RelayModern, not Runtime directly - export interface GraphQLSubscriptionConfig { + interface GraphQLSubscriptionConfig { configs?: Common.RelayMutationConfig[]; subscription: Common.GraphQLTaggedNode; variables: Common.Variables; @@ -1116,7 +1115,7 @@ declare namespace __Relay { onNext?(response: object | void): void; updater?(store: Common.RecordSourceSelectorProxy): void; } - export function requestRelaySubscription( + function requestRelaySubscription( environment: Environment, config: GraphQLSubscriptionConfig, ): Common.Disposable; From ec92bbda49dd7175006dc2e3ce1b9d648bf4cf2c Mon Sep 17 00:00:00 2001 From: voxmatt Date: Sun, 10 Sep 2017 17:13:38 -1000 Subject: [PATCH 019/828] removing single module declare in relay-runtime --- types/relay-runtime/index.d.ts | 25 ++++++++++++------------- 1 file changed, 12 insertions(+), 13 deletions(-) diff --git a/types/relay-runtime/index.d.ts b/types/relay-runtime/index.d.ts index 382711209f..682a74882e 100644 --- a/types/relay-runtime/index.d.ts +++ b/types/relay-runtime/index.d.ts @@ -4,6 +4,7 @@ // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped // TypeScript Version: 2.4 +// note: __Relay namespace is used so react-relay can access and inter-op declare namespace __Relay { namespace Common { /** @@ -1061,9 +1062,9 @@ declare namespace __Relay { optimisticResponse?: object; updater?: Common.SelectorStoreUpdater | void; } - function commitRelayModernMutation( + function commitRelayModernMutation( environment: Environment, - config: MutationConfig, + config: MutationConfig, ): Common.Disposable; // ~~~~~~~~~~~~~~~~~~~~~ @@ -1122,14 +1123,12 @@ declare namespace __Relay { } } -declare module 'relay-runtime' { - export import Environment = __Relay.Runtime.Environment; - export import Network = __Relay.Runtime.Network; - export import RecordSource = __Relay.Runtime.RecordSource; - export import Store = __Relay.Runtime.Store; - export import Observable = __Relay.Runtime.RelayObservable; - // note RecordSourceInspector is only available in dev environment - export import RecordSourceInspector = __Relay.Runtime.RelayRecordSourceInspector; - export import ConnectionHandler = __Relay.Common.Handler; - export import ViewerHandler = __Relay.Common.Handler; -} +export import Environment = __Relay.Runtime.Environment; +export import Network = __Relay.Runtime.Network; +export import RecordSource = __Relay.Runtime.RecordSource; +export import Store = __Relay.Runtime.Store; +export import Observable = __Relay.Runtime.RelayObservable; +// note RecordSourceInspector is only available in dev environment +export import RecordSourceInspector = __Relay.Runtime.RelayRecordSourceInspector; +export import ConnectionHandler = __Relay.Common.Handler; +export import ViewerHandler = __Relay.Common.Handler; From 38dd00d25ea48d0191589fd66f6a6a1f671bc2f9 Mon Sep 17 00:00:00 2001 From: voxmatt Date: Sun, 10 Sep 2017 17:18:52 -1000 Subject: [PATCH 020/828] single declare module is needed to allow access from react-relay --- types/react-relay/index.d.ts | 2 +- types/relay-runtime/index.d.ts | 20 +++++++++++--------- types/relay-runtime/tslint.json | 5 ++++- 3 files changed, 16 insertions(+), 11 deletions(-) diff --git a/types/react-relay/index.d.ts b/types/react-relay/index.d.ts index eb940d296d..a089d020c5 100644 --- a/types/react-relay/index.d.ts +++ b/types/react-relay/index.d.ts @@ -26,7 +26,7 @@ declare namespace __Relay { // ~~~~~~~~~~~~~~~~~~~~~ // note: refetch and pagination containers augment this export interface RelayProp { - environment: Runtime.Environment; + environment: __Relay.Runtime.Environment; } // ~~~~~~~~~~~~~~~~~~~~~ diff --git a/types/relay-runtime/index.d.ts b/types/relay-runtime/index.d.ts index 682a74882e..b5c3b006f8 100644 --- a/types/relay-runtime/index.d.ts +++ b/types/relay-runtime/index.d.ts @@ -1123,12 +1123,14 @@ declare namespace __Relay { } } -export import Environment = __Relay.Runtime.Environment; -export import Network = __Relay.Runtime.Network; -export import RecordSource = __Relay.Runtime.RecordSource; -export import Store = __Relay.Runtime.Store; -export import Observable = __Relay.Runtime.RelayObservable; -// note RecordSourceInspector is only available in dev environment -export import RecordSourceInspector = __Relay.Runtime.RelayRecordSourceInspector; -export import ConnectionHandler = __Relay.Common.Handler; -export import ViewerHandler = __Relay.Common.Handler; +declare module 'relay-runtime' { + export import Environment = __Relay.Runtime.Environment; + export import Network = __Relay.Runtime.Network; + export import RecordSource = __Relay.Runtime.RecordSource; + export import Store = __Relay.Runtime.Store; + export import Observable = __Relay.Runtime.RelayObservable; + // note RecordSourceInspector is only available in dev environment + export import RecordSourceInspector = __Relay.Runtime.RelayRecordSourceInspector; + export import ConnectionHandler = __Relay.Common.Handler; + export import ViewerHandler = __Relay.Common.Handler; +} diff --git a/types/relay-runtime/tslint.json b/types/relay-runtime/tslint.json index 3db14f85ea..1fded7a528 100644 --- a/types/relay-runtime/tslint.json +++ b/types/relay-runtime/tslint.json @@ -1 +1,4 @@ -{ "extends": "dtslint/dt.json" } +{ + "extends": "dtslint/dt.json", + "no-single-declare-module": false +} From 66af1890896bdb0ca54ecad2b219411efe35a6c8 Mon Sep 17 00:00:00 2001 From: voxmatt Date: Sun, 10 Sep 2017 17:44:00 -1000 Subject: [PATCH 021/828] removing maybe util type --- types/relay-runtime/index.d.ts | 32 ++++++++++++++------------------ 1 file changed, 14 insertions(+), 18 deletions(-) diff --git a/types/relay-runtime/index.d.ts b/types/relay-runtime/index.d.ts index b5c3b006f8..bddbc60600 100644 --- a/types/relay-runtime/index.d.ts +++ b/types/relay-runtime/index.d.ts @@ -12,11 +12,6 @@ declare namespace __Relay { * Relay 1.3.0 * https://github.com/facebook/relay/blob/b85a1d69bb72be4ace67179f55c2a54a8d761c8b/packages/react-relay/classic/environment/RelayCombinedEnvironmentTypes.js */ - // ~~~~~~~~~~~~~~~~~~~~~ - // Util - // ~~~~~~~~~~~~~~~~~~~~~ - type Maybe = T | void; - // ~~~~~~~~~~~~~~~~~~~~~ // Maybe Fix // ~~~~~~~~~~~~~~~~~~~~~ @@ -164,18 +159,18 @@ declare namespace __Relay { args?: Variables | void, ): RecordProxy; getType(): string; - getValue(name: string, args?: Variables | void): any; + getValue(name: string, args?: Variables): any; setLinkedRecord( record: RecordProxy, name: string, args?: Variables | void, ): RecordProxy; setLinkedRecords( - records: Array | void, + records: Array | undefined | null, name: string, - args?: Variables | void, + args?: Variables, ): RecordProxy; - setValue(value: any, name: string, args?: Variables | void): RecordProxy; + setValue(value: any, name: string, args?: Variables): RecordProxy; } interface RecordSourceProxy { @@ -377,9 +372,9 @@ declare namespace __Relay { */ sendQuery(config: { cacheConfig?: CacheConfig | void, - onCompleted?: Maybe<() => void>, - onError?: Maybe<(error: Error) => void>, - onNext?: Maybe<(payload: TPayload) => void>, + onCompleted?: () => void, + onError?: (error: Error) => void, + onNext?: (payload: TPayload) => void, operation: COperationSelector, }): Disposable; @@ -392,10 +387,10 @@ declare namespace __Relay { * subscription open indefinitely such that `onCompleted` is not called. */ streamQuery(config: { - cacheConfig?: Maybe, - onCompleted?: Maybe<() => void>, - onError?: Maybe<(error: Error) => void>, - onNext?: Maybe<(payload: TPayload) => void>, + cacheConfig?: CacheConfig, + onCompleted?: () => void, + onError?: (error: Error) => void, + onNext?: (payload: TPayload) => void, operation: COperationSelector, }): Disposable; @@ -518,7 +513,7 @@ declare namespace __Relay { operationVariables: Variables, fragments: CFragmentMap, props: Props, - ): { [key: string]: Maybe<(CSelector | Array>)> }; + ): { [key: string]: CSelector | Array> | null | undefined }; /** * Given a mapping of keys -> results and a mapping of keys -> fragments, @@ -530,7 +525,7 @@ declare namespace __Relay { getDataIDsFromObject( fragments: CFragmentMap, props: Props, - ): { [key: string]: Maybe<(DataID | DataID[])> }; + ): { [key: string]: DataID | DataID[] | null | undefined }; /** * Given a mapping of keys -> results and a mapping of keys -> fragments, @@ -1124,6 +1119,7 @@ declare namespace __Relay { } declare module 'relay-runtime' { + // tslint:disable strict-export-declare-modifiers export import Environment = __Relay.Runtime.Environment; export import Network = __Relay.Runtime.Network; export import RecordSource = __Relay.Runtime.RecordSource; From 8ce8311cdfd044761d6084626f61fd38d913fae7 Mon Sep 17 00:00:00 2001 From: voxmatt Date: Mon, 11 Sep 2017 08:02:22 -1000 Subject: [PATCH 022/828] fixing a bunch of linting errors in relay-runtime --- types/relay-runtime/index.d.ts | 84 ++++++++++++++++----------------- types/relay-runtime/tslint.json | 3 +- 2 files changed, 43 insertions(+), 44 deletions(-) diff --git a/types/relay-runtime/index.d.ts b/types/relay-runtime/index.d.ts index bddbc60600..c107dca8e7 100644 --- a/types/relay-runtime/index.d.ts +++ b/types/relay-runtime/index.d.ts @@ -151,22 +151,22 @@ declare namespace __Relay { interface RecordProxy { copyFieldsFrom(source: RecordProxy): void; getDataID(): DataID; - getLinkedRecord(name: string, args?: Variables | void): RecordProxy | void; - getLinkedRecords(name: string, args?: Variables | void): Array | void; + getLinkedRecord(name: string, args?: Variables): RecordProxy | void; + getLinkedRecords(name: string, args?: Variables): Array | void; getOrCreateLinkedRecord( name: string, typeName: string, - args?: Variables | void, + args?: Variables, ): RecordProxy; getType(): string; getValue(name: string, args?: Variables): any; setLinkedRecord( record: RecordProxy, name: string, - args?: Variables | void, + args?: Variables, ): RecordProxy; setLinkedRecords( - records: Array | undefined | null, + records: Array | undefined | null, name: string, args?: Variables, ): RecordProxy; @@ -176,7 +176,7 @@ declare namespace __Relay { interface RecordSourceProxy { create(dataID: DataID, typeName: string): RecordProxy; delete(dataID: DataID): void; - get(dataID: DataID): Array | void; + get(dataID: DataID): Array | void; getRoot(): RecordProxy; } @@ -213,8 +213,8 @@ declare namespace __Relay { * in milliseconds. (This value will be passed to setTimeout.) */ interface CacheConfig { - force?: boolean | void; - poll?: number | void; + force?: boolean; + poll?: number; } /** @@ -239,7 +239,7 @@ declare namespace __Relay { /** * A collection of records keyed by id. */ - interface RecordMap { [dataID: string]: Record | void; } + interface RecordMap { [dataID: string]: Record | null | undefined; } /** * A selector defines the starting point for a traversal into the graph for the @@ -371,10 +371,10 @@ declare namespace __Relay { * after receving the first `onNext` result. */ sendQuery(config: { - cacheConfig?: CacheConfig | void, + cacheConfig?: CacheConfig, onCompleted?: () => void, - onError?: (error: Error) => void, - onNext?: (payload: TPayload) => void, + onError?(error: Error): void, + onNext?(payload: TPayload): void, operation: COperationSelector, }): Disposable; @@ -389,8 +389,8 @@ declare namespace __Relay { streamQuery(config: { cacheConfig?: CacheConfig, onCompleted?: () => void, - onError?: (error: Error) => void, - onNext?: (payload: TPayload) => void, + onError?(error: Error): void, + onNext?(payload: TPayload): void, operation: COperationSelector, }): Disposable; @@ -628,14 +628,14 @@ declare namespace __Relay { supports(...options: string[]): boolean; } interface QueryResult { - error?: Error | void; - ref_params?: { [name: string]: any } | void; + error?: Error; + ref_params?: { [name: string]: any }; response: QueryPayload; } interface ReadyState { aborted: boolean; done: boolean; - error: Error | void; + error: Error | null; events: ReadyStateEvent[]; ready: boolean; stale: boolean; @@ -701,7 +701,7 @@ declare namespace __Relay { operation: object, variables: Common.Variables, cacheConfig: Common.CacheConfig, - uploadables?: Common.UploadableMap | void, + uploadables?: Common.UploadableMap, ) => Promise; interface RelayNetwork { execute: ExecuteFunction; @@ -747,15 +747,15 @@ declare namespace __Relay { retain(selector: Selector): Common.Disposable; execute(config: { operation: OperationSelector, - cacheConfig?: Common.CacheConfig | void, - updater?: Common.SelectorStoreUpdater | void, + cacheConfig?: Common.CacheConfig, + updater?: Common.SelectorStoreUpdater, }): RelayObservable; executeMutation(config: { operation: OperationSelector, - optimisticUpdater?: Common.SelectorStoreUpdater | void, - optimisticResponse?: object | void, - updater?: Common.SelectorStoreUpdater | void, - uploadables?: Common.UploadableMap | void, + optimisticUpdater?: Common.SelectorStoreUpdater, + optimisticResponse?: object, + updater?: Common.SelectorStoreUpdater, + uploadables?: Common.UploadableMap, }): RelayObservable; } @@ -763,7 +763,7 @@ declare namespace __Relay { // RelayInMemoryRecordSource // ~~~~~~~~~~~~~~~~~~~~~ interface Record { [key: string]: any; } - interface RecordMap { [dataID: string]: Record | void; } + interface RecordMap { [dataID: string]: Record | null | undefined; } // ~~~~~~~~~~~~~~~~~~~~~ // Network @@ -789,7 +789,7 @@ declare namespace __Relay { has(dataID: Common.DataID): boolean; load( dataID: Common.DataID, - callback: (error: Error | void, record: Record | void) => void, + callback: (error: Error | null, record: Record | null) => void, ): void; remove(dataID: Common.DataID): void; set(dataID: Common.DataID, record: Record): void; @@ -823,9 +823,9 @@ declare namespace __Relay { */ class RecordSummary { id: Common.DataID; - type: string | void; + type: string | null | undefined; static createFromRecord(id: Common.DataID, record: any): RecordSummary; - constructor(id: Common.DataID, type: string | void); + constructor(id: Common.DataID, type: string | null | undefined); toString(): string; } /** @@ -860,21 +860,21 @@ declare namespace __Relay { * Returns the value of a scalar field. May throw if the given field is * present but not actually scalar. */ - getValue(name: string, args?: Common.Variables | void): any; + getValue(name: string, args?: Common.Variables): any; /** * Returns an inspector for the given scalar "linked" field (a field whose * value is another Record instead of a scalar). May throw if the field is * present but not a scalar linked record. */ - getLinkedRecord(name: string, args?: Common.Variables | void): RecordInspector | void; + getLinkedRecord(name: string, args?: Common.Variables): RecordInspector | void; /** * Returns an array of inspectors for the given plural "linked" field (a field * whose value is an array of Records instead of a scalar). May throw if the * field is present but not a plural linked record. */ - getLinkedRecords(name: string, args?: Common.Variables | void): RecordInspector[] | void; + getLinkedRecords(name: string, args?: Common.Variables): RecordInspector[] | void; } class RelayRecordSourceInspector { @@ -912,11 +912,11 @@ declare namespace __Relay { readonly closed: boolean; } interface Observer { - start?: ((subscription: Subscription) => any) | void; - next?: ((nextThing: T) => any) | void; - error?: ((error: Error) => any) | void; - complete?: (() => any) | void; - unsubscribe?: ((subscription: Subscription) => any) | void; + start?: (subscription: Subscription) => any; + next?: (nextThing: T) => any; + error?: (error: Error) => any; + complete?: () => any; + unsubscribe?: (subscription: Subscription) => any; } type Source = () => any; interface Subscribable { @@ -1030,7 +1030,7 @@ declare namespace __Relay { * Returns a Promise which resolves when this Observable yields a first value * or when it completes with no value. */ - toPromise(): Promise; + toPromise(): Promise; } // ~~~~~~~~~~~~~~~~~~~~~ @@ -1051,11 +1051,11 @@ declare namespace __Relay { mutation: Common.GraphQLTaggedNode; variables: Common.Variables; uploadables?: Common.UploadableMap; - onCompleted?(response: T, errors: Common.PayloadError[] | void): void; + onCompleted?(response: T, errors: Common.PayloadError[] | null | undefined): void; onError?(error?: Error): void; optimisticUpdater?: Common.SelectorStoreUpdater | void; optimisticResponse?: object; - updater?: Common.SelectorStoreUpdater | void; + updater?: Common.SelectorStoreUpdater; } function commitRelayModernMutation( environment: Environment, @@ -1095,7 +1095,7 @@ declare namespace __Relay { environment: any, // FIXME - $FlowFixMe in facebook source code taggedNode: Common.GraphQLTaggedNode, variables: Common.Variables, - cacheConfig?: Common.CacheConfig | void, + cacheConfig?: Common.CacheConfig, ): Promise; // FIXME - $FlowFixMe in facebook source code // ~~~~~~~~~~~~~~~~~~~~~ @@ -1108,7 +1108,7 @@ declare namespace __Relay { variables: Common.Variables; onCompleted?(): void; onError?(error: Error): void; - onNext?(response: object | void): void; + onNext?(response: object | null | undefined): void; updater?(store: Common.RecordSourceSelectorProxy): void; } function requestRelaySubscription( @@ -1118,8 +1118,8 @@ declare namespace __Relay { } } +// tslint:disable no-single-declare-module strict-export-declare-modifiers declare module 'relay-runtime' { - // tslint:disable strict-export-declare-modifiers export import Environment = __Relay.Runtime.Environment; export import Network = __Relay.Runtime.Network; export import RecordSource = __Relay.Runtime.RecordSource; diff --git a/types/relay-runtime/tslint.json b/types/relay-runtime/tslint.json index 1fded7a528..f93cf8562a 100644 --- a/types/relay-runtime/tslint.json +++ b/types/relay-runtime/tslint.json @@ -1,4 +1,3 @@ { - "extends": "dtslint/dt.json", - "no-single-declare-module": false + "extends": "dtslint/dt.json" } From 7101bd194bb7f37063d924a3e103bfffed566ff6 Mon Sep 17 00:00:00 2001 From: voxmatt Date: Mon, 11 Sep 2017 10:50:28 -1000 Subject: [PATCH 023/828] hopefully the last of relay-runtime linting errors --- types/relay-runtime/index.d.ts | 18 +++++++++--------- 1 file changed, 9 insertions(+), 9 deletions(-) diff --git a/types/relay-runtime/index.d.ts b/types/relay-runtime/index.d.ts index c107dca8e7..2bd9938b0c 100644 --- a/types/relay-runtime/index.d.ts +++ b/types/relay-runtime/index.d.ts @@ -255,7 +255,7 @@ declare namespace __Relay { * A representation of a selector and its results at a particular point in time. */ type CSnapshot = CSelector & { - data: SelectorData | void, + data: SelectorData | null | undefined, seenRecords: RecordMap, }; @@ -372,7 +372,7 @@ declare namespace __Relay { */ sendQuery(config: { cacheConfig?: CacheConfig, - onCompleted?: () => void, + onCompleted?(): void, onError?(error: Error): void, onNext?(payload: TPayload): void, operation: COperationSelector, @@ -388,7 +388,7 @@ declare namespace __Relay { */ streamQuery(config: { cacheConfig?: CacheConfig, - onCompleted?: () => void, + onCompleted?(): void, onError?(error: Error): void, onNext?(payload: TPayload): void, operation: COperationSelector, @@ -912,11 +912,11 @@ declare namespace __Relay { readonly closed: boolean; } interface Observer { - start?: (subscription: Subscription) => any; - next?: (nextThing: T) => any; - error?: (error: Error) => any; - complete?: () => any; - unsubscribe?: (subscription: Subscription) => any; + start?(subscription: Subscription): any; + next?(nextThing: T): any; + error?(error: Error): any; + complete?(): any; + unsubscribe?(subscription: Subscription): any; } type Source = () => any; interface Subscribable { @@ -1053,7 +1053,7 @@ declare namespace __Relay { uploadables?: Common.UploadableMap; onCompleted?(response: T, errors: Common.PayloadError[] | null | undefined): void; onError?(error?: Error): void; - optimisticUpdater?: Common.SelectorStoreUpdater | void; + optimisticUpdater?: Common.SelectorStoreUpdater; optimisticResponse?: object; updater?: Common.SelectorStoreUpdater; } From cafeccbaf51e72f8e23f51b1b01a12eb28675104 Mon Sep 17 00:00:00 2001 From: voxmatt Date: Mon, 11 Sep 2017 11:00:47 -1000 Subject: [PATCH 024/828] cleaning up some linting errors in react-relay and its tests --- types/react-relay/index.d.ts | 81 ++++++++++++------------- types/react-relay/react-relay-tests.tsx | 76 ++++++++++------------- 2 files changed, 71 insertions(+), 86 deletions(-) diff --git a/types/react-relay/index.d.ts b/types/react-relay/index.d.ts index a089d020c5..e41f39e4ae 100644 --- a/types/react-relay/index.d.ts +++ b/types/react-relay/index.d.ts @@ -26,7 +26,7 @@ declare namespace __Relay { // ~~~~~~~~~~~~~~~~~~~~~ // note: refetch and pagination containers augment this export interface RelayProp { - environment: __Relay.Runtime.Environment; + environment: Runtime.Environment; } // ~~~~~~~~~~~~~~~~~~~~~ @@ -310,26 +310,26 @@ declare module "react-relay/classic" { /** Fragments are a hash of functions */ interface Fragments { - [query: string]: ((variables?: RelayVariables) => string) + [query: string]: ((variables?: RelayVariables) => string); } interface CreateContainerOpts { - initialVariables?: any - fragments: Fragments - prepareVariables?(prevVariables: RelayVariables): RelayVariables + initialVariables?: any; + fragments: Fragments; + prepareVariables?(prevVariables: RelayVariables): RelayVariables; } interface RelayVariables { - [name: string]: any + [name: string]: any; } /** add static getFragment method to the component constructor */ interface RelayContainerClass extends React.ComponentClass { - getFragment: ((q: string, v?: RelayVariables) => string) + getFragment: ((q: string, v?: RelayVariables) => string); } interface RelayQueryRequestResolve { - response: any + response: any; } type RelayMutationStatus = @@ -352,35 +352,34 @@ declare module "react-relay/classic" { } interface RelayMutationRequest { - getQueryString(): string - getVariables(): RelayVariables - resolve(result: RelayQueryRequestResolve): any - reject(errors: any): any + getQueryString(): string; + getVariables(): RelayVariables; + resolve(result: RelayQueryRequestResolve): any; + reject(errors: any): any; } interface RelayQueryRequest { - resolve(result: RelayQueryRequestResolve): any - reject(errors: any): any - - getQueryString(): string - getVariables(): RelayVariables - getID(): string - getDebugName(): string + resolve(result: RelayQueryRequestResolve): any; + reject(errors: any): any; + getQueryString(): string; + getVariables(): RelayVariables; + getID(): string; + getDebugName(): string; } interface RelayNetworkLayer { - supports(...options: string[]): boolean + supports(...options: string[]): boolean; } class DefaultNetworkLayer implements RelayNetworkLayer { - constructor(host: string, options?: any) - supports(...options: string[]): boolean + constructor(host: string, options?: any); + supports(...options: string[]): boolean; } - export function createContainer(component: React.ComponentClass | React.StatelessComponent, params?: CreateContainerOpts): RelayContainerClass - export function injectNetworkLayer(networkLayer: RelayNetworkLayer): any - export function isContainer(component: React.ComponentClass): boolean - export function QL(...args: any[]): string + export function createContainer(component: React.ComponentClass | React.StatelessComponent, params?: CreateContainerOpts): RelayContainerClass; + export function injectNetworkLayer(networkLayer: RelayNetworkLayer): any; + export function isContainer(component: React.ComponentClass): boolean; + export function QL(...args: any[]): string; class Route { constructor(params?: RelayVariables) @@ -392,36 +391,36 @@ declare module "react-relay/classic" { * return some data in the payload using REQUIRED_CHILDREN which is where specifying S is the most useful. */ class Mutation { - props: T + props: T; - constructor(props: T) - static getFragment(q: string): string + constructor(props: T); + static getFragment(q: string): string; } interface Transaction { - getError(): Error - Status(): number + getError(): Error; + Status(): number; } interface StoreUpdateCallbacks { - onFailure?(transaction: Transaction): any - onSuccess?(response: T): any + onFailure?(transaction: Transaction): any; + onSuccess?(response: T): any; } interface Store { - commitUpdate(mutation: Mutation, callbacks?: StoreUpdateCallbacks): any + commitUpdate(mutation: Mutation, callbacks?: StoreUpdateCallbacks): any; } - const Store: Store + const Store: Store; class RootContainer extends React.Component { } interface RootContainerProps extends React.Props { - Component: RelayContainerClass - route: Route - renderLoading?(): JSX.Element - renderFetched?(data: any): JSX.Element - renderFailure?(error: Error, retry: (...args: any[]) => any): JSX.Element + Component: RelayContainerClass; + route: Route; + renderLoading?(): JSX.Element; + renderFetched?(data: any): JSX.Element; + renderFailure?(error: Error, retry: (...args: any[]) => any): JSX.Element; } type ReadyStateEvent = @@ -443,7 +442,7 @@ declare module "react-relay/classic" { error?: Error, events: ReadyStateEvent[], aborted: boolean - }) => void + }) => void; interface RelayProp { readonly route: { name: string; }; // incomplete, also has params and queries diff --git a/types/react-relay/react-relay-tests.tsx b/types/react-relay/react-relay-tests.tsx index 2b76bc7860..5bd7c6c964 100644 --- a/types/react-relay/react-relay-tests.tsx +++ b/types/react-relay/react-relay-tests.tsx @@ -7,9 +7,6 @@ import { ConnectionHandler, } from 'relay-runtime'; - - - //////////////////////////// // RELAY MODERN TESTS /////////////////////////// @@ -25,16 +22,17 @@ import { RelayRefetchProp } from "react-relay"; - // ~~~~~~~~~~~~~~~~~~~~~ // Modern Environment // ~~~~~~~~~~~~~~~~~~~~~ -const network = {} as __Relay.Runtime.RelayNetwork; +function fetchQuery(operation: any, variables: any, cacheConfig: {}) { + return fetch('/graphql'); +} +const network = Network.create(fetchQuery); const source = new RecordSource(); const store = new Store(source); const modernEnvironment = new Environment({ network, store }); - // ~~~~~~~~~~~~~~~~~~~~~ // Modern QueryRenderer // ~~~~~~~~~~~~~~~~~~~~~ @@ -81,19 +79,18 @@ const MyFragmentContainer = createFragmentContainer( } ); - // ~~~~~~~~~~~~~~~~~~~~~ // Modern RefetchContainer // ~~~~~~~~~~~~~~~~~~~~~ -interface IStory { id: string } -interface IFeedStoriesProps { +interface StoryInterface { id: string; } +interface FeedStoriesProps { relay: RelayRefetchProp; feed: { - stories: { edges: { node: IStory }[] } - } + stories: { edges: Array<{ node: StoryInterface }> } + }; } -class Story extends React.Component<{ story: IStory }, {}> {} -class FeedStories extends React.Component { +class Story extends React.Component<{ story: StoryInterface }, {}> {} +class FeedStories extends React.Component { render() { return (
@@ -145,16 +142,14 @@ const FeedRefetchContainer = createRefetchContainer( `, ); - - // ~~~~~~~~~~~~~~~~~~~~~ // Modern PaginationContainer // ~~~~~~~~~~~~~~~~~~~~~ -interface IFeedProps { - user: { feed: { edges: { node: IStory}[]}} +interface FeedProps { + user: { feed: { edges: Array<{ node: StoryInterface}>}}; relay: RelayPaginationProp; } -class Feed extends React.Component { +class Feed extends React.Component { render() { return (
{this.props.user.feed.edges.map( @@ -236,7 +231,6 @@ const FeedPaginationContainer = createPaginationContainer( } ); - // ~~~~~~~~~~~~~~~~~~~~~ // Modern Mutations // ~~~~~~~~~~~~~~~~~~~~~ @@ -298,14 +292,13 @@ function markNotificationAsRead(source: string, storyID: string) { optimisticResponse, variables, onCompleted: (response, errors) => { - console.log('Response received from server.') + console.log('Response received from server.'); }, onError: err => console.error(err), }, ); } - // ~~~~~~~~~~~~~~~~~~~~~ // Modern Subscriptions // ~~~~~~~~~~~~~~~~~~~~~ @@ -351,9 +344,6 @@ requestSubscription( } ); - - - //////////////////////////// // RELAY-CLASSIC TESTS /////////////////////////// @@ -361,29 +351,25 @@ requestSubscription( import * as Relay from "react-relay/classic"; interface Props { - text: string - userId: string + text: string; + userId: string; } -interface Response { -} - -export default class AddTweetMutation extends Relay.Mutation { - - getMutation () { - return Relay.QL`mutation{addTweet}` +export default class AddTweetMutation extends Relay.Mutation { + getMutation() { + return Relay.QL`mutation{addTweet}`; } - getFatQuery () { + getFatQuery() { return Relay.QL` fragment on AddTweetPayload { tweetEdge user } - ` + `; } - getConfigs () { + getConfigs() { return [{ type: "RANGE_ADD", parentName: "user", @@ -393,19 +379,19 @@ export default class AddTweetMutation extends Relay.Mutation { rangeBehaviors: { "": "append", }, - }] + }]; } - getVariables () { - return this.props + getVariables() { + return this.props; } } interface ArtworkProps { artwork: { title: string - }, - relay: Relay.RelayProp, + }; + relay: Relay.RelayProp; } class Artwork extends React.Component { @@ -414,7 +400,7 @@ class Artwork extends React.Component { {this.props.artwork.title} - ) + ); } } @@ -426,7 +412,7 @@ const ArtworkContainer = Relay.createContainer(Artwork, { } ` } -}) +}); class StubbedArtwork extends React.Component { render() { @@ -445,7 +431,7 @@ class StubbedArtwork extends React.Component { getPendingTransactions: (): any => undefined, commitUpdate: () => {}, } - } - return + }; + return ; } } From e1f651b9f3336dfc684459cd9a16ac749f6150fb Mon Sep 17 00:00:00 2001 From: voxmatt Date: Mon, 11 Sep 2017 11:11:36 -1000 Subject: [PATCH 025/828] more cleanup of lint errors --- types/react-relay/index.d.ts | 83 ++++++++++++------------- types/react-relay/react-relay-tests.tsx | 6 +- 2 files changed, 44 insertions(+), 45 deletions(-) diff --git a/types/react-relay/index.d.ts b/types/react-relay/index.d.ts index e41f39e4ae..cd43410727 100644 --- a/types/react-relay/index.d.ts +++ b/types/react-relay/index.d.ts @@ -7,7 +7,6 @@ /// declare namespace __Relay { - //////////////////////////// // RELAY MODERN TYPES /////////////////////////// @@ -25,14 +24,14 @@ declare namespace __Relay { // RelayProp // ~~~~~~~~~~~~~~~~~~~~~ // note: refetch and pagination containers augment this - export interface RelayProp { + interface RelayProp { environment: Runtime.Environment; } // ~~~~~~~~~~~~~~~~~~~~~ // RelayQL // ~~~~~~~~~~~~~~~~~~~~~ - export function RelayQL( + function RelayQL( strings: string[], ...substitutions: any[] ): Common.RelayConcreteNode; @@ -57,23 +56,23 @@ declare namespace __Relay { (strings: string[] | TemplateStringsArray): GraphQLTaggedNode; experimental(strings: string[] | TemplateStringsArray): GraphQLTaggedNode; } - export const graphql: GraphqlInterface; + const graphql: GraphqlInterface; // ~~~~~~~~~~~~~~~~~~~~~ // ReactRelayQueryRenderer // ~~~~~~~~~~~~~~~~~~~~~ interface QueryRendererProps { - cacheConfig?: Common.CacheConfig | void; + cacheConfig?: Common.CacheConfig; environment: Runtime.Environment; query: GraphQLTaggedNode; - render(readyState: ReadyState): React.ReactElement | void; + render(readyState: ReadyState): React.ReactElement | undefined | null; variables: Common.Variables; rerunParamExperimental?: Common.RerunParam; } - export interface ReadyState { - error: Error | void; - props: { [propName: string]: any } | void; - retry: (() => void) | void; + interface ReadyState { + error: Error | undefined | null; + props: { [propName: string]: any } | undefined | null; + retry?(): void; } interface QueryRendererState { readyState: ReadyState; @@ -83,7 +82,7 @@ declare namespace __Relay { // ~~~~~~~~~~~~~~~~~~~~~ // createFragmentContainer // ~~~~~~~~~~~~~~~~~~~~~ - export function createFragmentContainer( + function createFragmentContainer( Component: ReactBaseComponent, fragmentSpec: GraphQLTaggedNode | GeneratedNodeMap, ): ReactBaseComponent; @@ -92,45 +91,45 @@ declare namespace __Relay { // createPaginationContainer // ~~~~~~~~~~~~~~~~~~~~~ interface PageInfo { - endCursor: string | void; + endCursor: string | undefined | null; hasNextPage: boolean; hasPreviousPage: boolean; - startCursor: string | void; + startCursor: string | undefined | null; } interface ConnectionData { edges?: any[]; - pageInfo?: PageInfo | void; + pageInfo?: PageInfo; } - export type RelayPaginationProp = RelayProp & { + type RelayPaginationProp = RelayProp & { hasMore(): boolean, isLoading(): boolean, loadMore( pageSize: number, callback: (error?: Error) => void, options?: RefetchOptions, - ): Common.Disposable | void, + ): Common.Disposable | undefined | null, refetchConnection( totalCount: number, - callback: (error?: Error | void) => void, - refetchVariables?: Common.Variables | void, - ): Common.Disposable | void, + callback: (error?: Error) => void, + refetchVariables?: Common.Variables, + ): Common.Disposable | undefined | null, }; - export function FragmentVariablesGetter( + function FragmentVariablesGetter( prevVars: Common.Variables, totalCount: number, ): Common.Variables; interface ConnectionConfig { direction?: 'backward' | 'forward'; - getConnectionFromProps?(props: object): ConnectionData | void; + getConnectionFromProps?(props: object): ConnectionData | undefined | null; getFragmentVariables?: typeof FragmentVariablesGetter; getVariables( props: { [propName: string]: any }, - paginationInfo: { count: number, cursor: string | void }, + paginationInfo: { count: number, cursor?: string }, fragmentVariables: Common.Variables, ): Common.Variables; query: GraphQLTaggedNode; } - export function createPaginationContainer( + function createPaginationContainer( Component: ReactBaseComponent, fragmentSpec: GraphQLTaggedNode | GeneratedNodeMap, connectionConfig: ConnectionConfig, @@ -139,19 +138,19 @@ declare namespace __Relay { // ~~~~~~~~~~~~~~~~~~~~~ // createFragmentContainer // ~~~~~~~~~~~~~~~~~~~~~ - export interface RefetchOptions { + interface RefetchOptions { force?: boolean; rerunParamExperimental?: Common.RerunParam; } - export type RelayRefetchProp = RelayProp & { + type RelayRefetchProp = RelayProp & { refetch( refetchVariables: Common.Variables | ((fragmentVariables: Common.Variables) => Common.Variables), renderVariables?: Common.Variables, - callback?: (error: Error | void) => void, + callback?: (error?: Error) => void, options?: RefetchOptions, ): Common.Disposable, }; - export function createRefetchContainer( + function createRefetchContainer( Component: ReactBaseComponent, fragmentSpec: GraphQLTaggedNode | GeneratedNodeMap, taggedNode: GraphQLTaggedNode, @@ -181,7 +180,7 @@ declare namespace __Relay { resolve( fragment: RelayQuery["Fragment"], dataIDs: Common.DataID | Common.DataID[], - ): (StoreReaderData | StoreReaderData[]) | void; + ): StoreReaderData | StoreReaderData[] | undefined | null; } interface RelayEnvironmentInterface { forceFetch( @@ -224,7 +223,7 @@ declare namespace __Relay { // ~~~~~~~~~~~~~~~~~~~~~ // Util // ~~~~~~~~~~~~~~~~~~~~~ - export function getFragment(q: string, v?: Common.Variables): string; + function getFragment(q: string, v?: Common.Variables): string; interface ComponentWithFragment extends React.ComponentClass { getFragment: typeof getFragment; } @@ -233,21 +232,21 @@ declare namespace __Relay { } type ReactFragmentComponent = ComponentWithFragment | StatelessWithFragment; type ReactBaseComponent = React.ComponentClass | React.StatelessComponent; - export type RelayClassicEnvironment = Classic.RelayEnvironmentInterface; + type RelayClassicEnvironment = Classic.RelayEnvironmentInterface; // ~~~~~~~~~~~~~~~~~~~~~ // RelayCompatTypes // ~~~~~~~~~~~~~~~~~~~~~ - export type CompatEnvironment = Runtime.Environment | RelayClassicEnvironment; + type CompatEnvironment = Runtime.Environment | RelayClassicEnvironment; // ~~~~~~~~~~~~~~~~~~~~~ // RelayCompatMutations // ~~~~~~~~~~~~~~~~~~~~~ - export function commitUpdate( + function commitUpdate( environment: CompatEnvironment, - config: Runtime.MutationConfig, + config: Runtime.MutationConfig, ): Common.Disposable; - export function applyUpdate( + function applyUpdate( environment: CompatEnvironment, config: Runtime.OptimisticMutationConfig, ): Common.Disposable; @@ -255,8 +254,8 @@ declare namespace __Relay { // ~~~~~~~~~~~~~~~~~~~~~ // RelayCompatContainer // ~~~~~~~~~~~~~~~~~~~~~ - export interface GeneratedNodeMap { [key: string]: Modern.GraphQLTaggedNode; } - export function createContainer( + interface GeneratedNodeMap { [key: string]: Modern.GraphQLTaggedNode; } + function createContainer( Component: ReactBaseComponent, fragmentSpec: Modern.GraphQLTaggedNode | GeneratedNodeMap, ): ReactFragmentComponent; @@ -265,7 +264,7 @@ declare namespace __Relay { // injectDefaultVariablesProvider // ~~~~~~~~~~~~~~~~~~~~~ type VariablesProvider = () => Common.Variables; - export function injectDefaultVariablesProvider(variablesProvider: VariablesProvider): void; + function injectDefaultVariablesProvider(variablesProvider: VariablesProvider): void; } } @@ -376,10 +375,10 @@ declare module "react-relay/classic" { supports(...options: string[]): boolean; } - export function createContainer(component: React.ComponentClass | React.StatelessComponent, params?: CreateContainerOpts): RelayContainerClass; - export function injectNetworkLayer(networkLayer: RelayNetworkLayer): any; - export function isContainer(component: React.ComponentClass): boolean; - export function QL(...args: any[]): string; + function createContainer(component: React.ComponentClass | React.StatelessComponent, params?: CreateContainerOpts): RelayContainerClass; + function injectNetworkLayer(networkLayer: RelayNetworkLayer): any; + function isContainer(component: React.ComponentClass): boolean; + function QL(...args: any[]): string; class Route { constructor(params?: RelayVariables) @@ -447,7 +446,7 @@ declare module "react-relay/classic" { interface RelayProp { readonly route: { name: string; }; // incomplete, also has params and queries readonly variables: any; - readonly pendingVariables?: any | null; + readonly pendingVariables?: any; setVariables(variables: any, onReadyStateChange?: OnReadyStateChange): void; forceFetch(variables: any, onReadyStateChange?: OnReadyStateChange): void; hasOptimisticUpdate(record: any): boolean; diff --git a/types/react-relay/react-relay-tests.tsx b/types/react-relay/react-relay-tests.tsx index 5bd7c6c964..2b8e371ee2 100644 --- a/types/react-relay/react-relay-tests.tsx +++ b/types/react-relay/react-relay-tests.tsx @@ -89,8 +89,8 @@ interface FeedStoriesProps { stories: { edges: Array<{ node: StoryInterface }> } }; } -class Story extends React.Component<{ story: StoryInterface }, {}> {} -class FeedStories extends React.Component { +class Story extends React.Component<{ story: StoryInterface }> {} +class FeedStories extends React.Component { render() { return (
@@ -149,7 +149,7 @@ interface FeedProps { user: { feed: { edges: Array<{ node: StoryInterface}>}}; relay: RelayPaginationProp; } -class Feed extends React.Component { +class Feed extends React.Component { render() { return (
{this.props.user.feed.edges.map( From e90ca4bb3ec352283019eba8b6127abe7c091bd2 Mon Sep 17 00:00:00 2001 From: voxmatt Date: Mon, 11 Sep 2017 11:17:03 -1000 Subject: [PATCH 026/828] I need these exports; put in a ts-lint disable line around them --- types/react-relay/index.d.ts | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/types/react-relay/index.d.ts b/types/react-relay/index.d.ts index cd43410727..ebb7fe714e 100644 --- a/types/react-relay/index.d.ts +++ b/types/react-relay/index.d.ts @@ -271,7 +271,7 @@ declare namespace __Relay { //////////////////////////// // MODULES /////////////////////////// - +// tslint:disable strict-export-declare-modifiers declare module 'react-relay' { export import QueryRenderer = __Relay.Modern.ReactRelayQueryRenderer; export import createFragmentContainer = __Relay.Modern.createFragmentContainer; @@ -301,6 +301,7 @@ declare module 'react-relay/compat' { export import graphql = __Relay.Modern.graphql; export import fetchQuery = __Relay.Runtime.fetchRelayModernQuery; } +// tslint:enable strict-export-declare-modifiers declare module "react-relay/classic" { import * as React from "react"; From 1bae0838318dd5afcb288601747adcd1d64a490a Mon Sep 17 00:00:00 2001 From: voxmatt Date: Mon, 11 Sep 2017 16:00:29 -1000 Subject: [PATCH 027/828] adding back in Renderer --- types/react-relay/index.d.ts | 20 ++++++++++++++++++++ 1 file changed, 20 insertions(+) diff --git a/types/react-relay/index.d.ts b/types/react-relay/index.d.ts index ebb7fe714e..83b2890020 100644 --- a/types/react-relay/index.d.ts +++ b/types/react-relay/index.d.ts @@ -423,6 +423,26 @@ declare module "react-relay/classic" { renderFailure?(error: Error, retry: (...args: any[]) => any): JSX.Element; } + class Renderer extends React.Component { } + + interface RendererProps { + Container: RelayContainerClass; // Relay container that defines fragments and the view to render. + forceFetch?: boolean; // Whether to send a server request regardless of data available on the client. + queryConfig: Route; // `QueryConfig` or `Relay.Route` that defines the query roots. + environment: Store; // An instance of `Relay.Environment` or any object that implements the `RelayEnvironment` interface. + render?: RenderCallback; // Called to render when data requirements are being fulfilled. + onReadyStateChange?: OnReadyStateChange; + } + + interface RenderStateConfig { + props?: { [propName: string]: any }; + done: boolean; + error?: Error; + retry?(): void; + stale: boolean; + } + type RenderCallback = (renderState: RenderStateConfig) => any; + type ReadyStateEvent = 'ABORT' | 'CACHE_RESTORED_REQUIRED' | From d3a7b32ced5b099fbcfa9e78cf87c24ec347c520 Mon Sep 17 00:00:00 2001 From: Young Rok Kim Date: Sun, 24 Sep 2017 01:57:04 +0900 Subject: [PATCH 028/828] joi: add missing 'alt' method --- types/joi/index.d.ts | 10 ++++++++-- types/joi/joi-tests.ts | 7 +++++++ 2 files changed, 15 insertions(+), 2 deletions(-) diff --git a/types/joi/index.d.ts b/types/joi/index.d.ts index 1b4c3fcbaf..68eb27ca93 100644 --- a/types/joi/index.d.ts +++ b/types/joi/index.d.ts @@ -551,7 +551,7 @@ export interface StringSchema extends AnySchema { * Requires the string value to be a valid GUID. */ guid(options?: GuidOptions): this; - + /** * Alias for `guid` -- Requires the string value to be a valid GUID */ @@ -962,10 +962,15 @@ export function string(): StringSchema; /** * Generates a type that will match one of the provided alternative schemas */ -export function alternatives(): AlternativesSchema; export function alternatives(types: SchemaLike[]): AlternativesSchema; export function alternatives(...types: SchemaLike[]): AlternativesSchema; +/** + * Alias for `alternatives` + */ +export function alt(types: SchemaLike[]): AlternativesSchema; +export function alt(...types: SchemaLike[]): AlternativesSchema; + /** * Generates a placeholder schema for a schema that you would provide with the fn. * Supports the same methods of the any() type. @@ -1031,3 +1036,4 @@ export function extend(extention: Extension): any; * Returns a plain object representing the schema's rules and properties */ export function describe(schema: Schema): Description; + diff --git a/types/joi/joi-tests.ts b/types/joi/joi-tests.ts index 4f49a69b3f..5f44e6ad01 100644 --- a/types/joi/joi-tests.ts +++ b/types/joi/joi-tests.ts @@ -830,6 +830,13 @@ schema = Joi.alternatives().try(schema, schema); schema = Joi.alternatives(schemaArr); schema = Joi.alternatives(schema, anySchema, boolSchema); +schema = Joi.alt(); +schema = Joi.alt().try(schemaArr); +schema = Joi.alt().try(schema, schema); + +schema = Joi.alt(schemaArr); +schema = Joi.alt(schema, anySchema, boolSchema); + // --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- schema = Joi.lazy(() => schema) From d90627cfa9bd47a2f3dbbc5ccaf23472a4472909 Mon Sep 17 00:00:00 2001 From: Young Rok Kim Date: Sun, 24 Sep 2017 02:04:43 +0900 Subject: [PATCH 029/828] joi: revert f59617 --- types/joi/index.d.ts | 222 +++++++++++++++++++++++++++++++---------- types/joi/joi-tests.ts | 53 ++++++++++ 2 files changed, 222 insertions(+), 53 deletions(-) diff --git a/types/joi/index.d.ts b/types/joi/index.d.ts index 68eb27ca93..af07b0bb2a 100644 --- a/types/joi/index.d.ts +++ b/types/joi/index.d.ts @@ -37,10 +37,10 @@ export interface ValidationOptions { skipFunctions?: boolean; /** * remove unknown elements from objects and arrays. Defaults to false - * - when true, all unknown elements will be removed - * - when an object: - * - arrays - set to true to remove unknown items from arrays. - * - objects - set to true to remove unknown keys from objects + * when true, all unknown elements will be removed + * when an object: + * arrays set to true to remove unknown items from arrays. + * objects set to true to remove unknown keys from objects */ stripUnknown?: boolean | { arrays?: boolean; objects?: boolean }; /** @@ -291,7 +291,7 @@ export interface AnySchema extends JoiObject { /** * Sets a default value if the original value is undefined. - * @param value - the value. + * @param value the value. * value supports references. * value may also be a function which returns the default value. * If value is specified as a function that accepts a single parameter, that parameter will be a context @@ -333,22 +333,22 @@ export interface AnySchema extends JoiObject { /** * Considers anything that matches the schema to be empty (undefined). - * @param schema - any object or joi schema to match. An undefined schema unsets that rule. + * @param schema any object or joi schema to match. An undefined schema unsets that rule. */ empty(schema?: SchemaLike): this; /** * Overrides the default joi error with a custom error if the rule fails where: - * @param err - can be: - * an instance of `Error` - the override error. + * @param err can be: + * an instance of `Error` the override error. * a `function(errors)`, taking an array of errors as argument, where it must either: - * return a `string` - substitutes the error message with this text + * return a `string` substitutes the error message with this text * return a single `object` or an `Array` of it, where: - * `type` - optional parameter providing the type of the error (eg. `number.min`). - * `message` - optional parameter if `template` is provided, containing the text of the error. - * `template` - optional parameter if `message` is provided, containing a template string, using the same format as usual joi language errors. - * `context` - optional parameter, to provide context to your error if you are using the `template`. - * return an `Error` - same as when you directly provide an `Error`, but you can customize the error message based on the errors. + * `type` optional parameter providing the type of the error (eg. `number.min`). + * `message` optional parameter if `template` is provided, containing the text of the error. + * `template` optional parameter if `message` is provided, containing a template string, using the same format as usual joi language errors. + * `context` optional parameter, to provide context to your error if you are using the `template`. + * return an `Error` same as when you directly provide an `Error`, but you can customize the error message based on the errors. * * Note that if you provide an `Error`, it will be returned as-is, unmodified and undecorated with any of the * normal joi error properties. If validation fails and another error is found before the error @@ -396,7 +396,7 @@ export interface BooleanSchema extends AnySchema { * Allows for additional values to be considered valid booleans by converting them to true during validation. * Accepts a value or an array of values. String comparisons are by default case insensitive, * see boolean.insensitive() to change this behavior. - * @param values - strings, numbers or arrays of them + * @param values strings, numbers or arrays of them */ truthy(...values: Array): this; @@ -404,7 +404,7 @@ export interface BooleanSchema extends AnySchema { * Allows for additional values to be considered valid booleans by converting them to false during validation. * Accepts a value or an array of values. String comparisons are by default case insensitive, * see boolean.insensitive() to change this behavior. - * @param values - strings, numbers or arrays of them + * @param values strings, numbers or arrays of them */ falsy(...values: Array): this; @@ -452,7 +452,7 @@ export interface NumberSchema extends AnySchema { /** * Specifies the maximum number of decimal places where: - * limit - the maximum number of decimal places allowed. + * limit the maximum number of decimal places allowed. */ precision(limit: number): this; @@ -480,16 +480,16 @@ export interface StringSchema extends AnySchema { /** * Specifies the minimum number string characters. - * @param limit - the minimum number of string characters required. It can also be a reference to another field. - * @param encoding - if specified, the string length is calculated in bytes using the provided encoding. + * @param limit the minimum number of string characters required. It can also be a reference to another field. + * @param encoding if specified, the string length is calculated in bytes using the provided encoding. */ min(limit: number, encoding?: string): this; min(limit: Reference, encoding?: string): this; /** * Specifies the maximum number of string characters. - * @param limit - the maximum number of string characters allowed. It can also be a reference to another field. - * @param encoding - if specified, the string length is calculated in bytes using the provided encoding. + * @param limit the maximum number of string characters allowed. It can also be a reference to another field. + * @param encoding if specified, the string length is calculated in bytes using the provided encoding. */ max(limit: number, encoding?: string): this; max(limit: Reference, encoding?: string): this; @@ -501,23 +501,23 @@ export interface StringSchema extends AnySchema { /** * Specifies the exact string length required - * @param limit - the required string length. It can also be a reference to another field. - * @param encoding - if specified, the string length is calculated in bytes using the provided encoding. + * @param limit the required string length. It can also be a reference to another field. + * @param encoding if specified, the string length is calculated in bytes using the provided encoding. */ length(limit: number, encoding?: string): this; length(limit: Reference, encoding?: string): this; /** * Defines a regular expression rule. - * @param pattern - a regular expression object the string value must match against. - * @param name - optional name for patterns (useful with multiple patterns). Defaults to 'required'. + * @param pattern a regular expression object the string value must match against. + * @param name optional name for patterns (useful with multiple patterns). Defaults to 'required'. */ regex(pattern: RegExp, name?: string): this; /** * Replace characters matching the given pattern with the specified replacement string where: - * @param pattern - a regular expression object to match against, or a string of which all occurrences will be replaced. - * @param replacement - the string that will replace the pattern. + * @param pattern a regular expression object to match against, or a string of which all occurrences will be replaced. + * @param replacement the string that will replace the pattern. */ replace(pattern: RegExp, replacement: string): this; replace(pattern: string, replacement: string): this; @@ -553,7 +553,7 @@ export interface StringSchema extends AnySchema { guid(options?: GuidOptions): this; /** - * Alias for `guid` -- Requires the string value to be a valid GUID + * Alias for `guid`- Requires the string value to be a valid GUID */ uuid(options?: GuidOptions): this; @@ -610,14 +610,14 @@ export interface ArraySchema extends AnySchema { * Errors will contain the number of items that didn't match. * Any unmatched item having a label will be mentioned explicitly. * - * @param type - a joi schema object to validate each array item against. + * @param type a joi schema object to validate each array item against. */ items(...types: SchemaLike[]): this; items(types: SchemaLike[]): this; /** * Lists the types in sequence order for the array values where: - * @param type - a joi schema object to validate against each array item in sequence order. type can be an array of values, or multiple values can be passed as individual arguments. + * @param type a joi schema object to validate against each array item in sequence order. type can be an array of values, or multiple values can be passed as individual arguments. * If a given type is .required() then there must be a matching item with the same index position in the array. Errors will contain the number of items that didn't match. Any unmatched item having a label will be mentioned explicitly. */ ordered(...types: SchemaLike[]): this; @@ -675,7 +675,7 @@ export interface ObjectSchema extends AnySchema { /** * Defines an all-or-nothing relationship between keys where if one of the peers is present, all of them are required as well. - * @param peers - the key names of which if one present, all are required. peers can be a single string value, + * @param peers the key names of which if one present, all are required. peers can be a single string value, * an array of string values, or each peer provided as an argument. */ and(...peers: string[]): this; @@ -683,7 +683,7 @@ export interface ObjectSchema extends AnySchema { /** * Defines a relationship between keys where not all peers can be present at the same time. - * @param peers - the key names of which if one present, the others may not all be present. + * @param peers the key names of which if one present, the others may not all be present. * peers can be a single string value, an array of string values, or each peer provided as an argument. */ nand(...peers: string[]): this; @@ -732,15 +732,15 @@ export interface ObjectSchema extends AnySchema { /** * Requires the object to be an instance of a given constructor. * - * @param constructor - the constructor function that the object must be an instance of. - * @param name - an alternate name to use in validation errors. This is useful when the constructor function does not have a name. + * @param constructor the constructor function that the object must be an instance of. + * @param name an alternate name to use in validation errors. This is useful when the constructor function does not have a name. */ type(constructor: Function, name?: string): this; /** * Sets the specified children to required. * - * @param children - can be a single string value, an array of string values, or each child provided as an argument. + * @param children can be a single string value, an array of string values, or each child provided as an argument. * * var schema = Joi.object().keys({ a: { b: Joi.number() }, c: { d: Joi.string() } }); * var requiredSchema = schema.requiredKeys('', 'a.b', 'c', 'c.d'); @@ -753,7 +753,7 @@ export interface ObjectSchema extends AnySchema { /** * Sets the specified children to optional. * - * @param children - can be a single string value, an array of string values, or each child provided as an argument. + * @param children can be a single string value, an array of string values, or each child provided as an argument. * * The behavior is exactly the same as requiredKeys. */ @@ -809,7 +809,7 @@ export interface DateSchema extends AnySchema { /** * Specifies the allowed date format: - * @param format - string or array of strings that follow the moment.js format. + * @param format string or array of strings that follow the moment.js format. */ format(format: string): this; format(format: string[]): this; @@ -821,7 +821,7 @@ export interface DateSchema extends AnySchema { /** * Requires the value to be a timestamp interval from Unix Time. - * @param type - the type of timestamp (allowed values are unix or javascript [default]) + * @param type the type of timestamp (allowed values are unix or javascript [default]) */ timestamp(type?: 'javascript' | 'unix'): this; } @@ -830,19 +830,19 @@ export interface FunctionSchema extends AnySchema { /** * Specifies the arity of the function where: - * @param n - the arity expected. + * @param n the arity expected. */ arity(n: number): this; /** * Specifies the minimal arity of the function where: - * @param n - the minimal arity expected. + * @param n the minimal arity expected. */ minArity(n: number): this; /** * Specifies the minimal arity of the function where: - * @param n - the minimal arity expected. + * @param n the minimal arity expected. */ maxArity(n: number): this; @@ -875,17 +875,17 @@ export type ExtensionBoundSchema = Schema & { /** * Creates a joi error object. * Used in conjunction with custom rules. - * @param type - the type of rule to create the error for. - * @param context - provide properties that will be available in the `language` templates. - * @param state - should the context passed into the `validate` function in a custom rule - * @param options - should the context passed into the `validate` function in a custom rule + * @param type the type of rule to create the error for. + * @param context provide properties that will be available in the `language` templates. + * @param state should the context passed into the `validate` function in a custom rule + * @param options should the context passed into the `validate` function in a custom rule */ createError(type: string, context: Context, state: State, options: ValidationOptions): Err; } export interface Rules

{ name: string; - params?: ObjectSchema | { [key in keyof P]: SchemaLike; }; + params?: ObjectSchema | {[key in keyof P]: SchemaLike; }; setup?(this: ExtensionBoundSchema, params: P): Schema | void; validate?(this: ExtensionBoundSchema, params: P, value: any, state: State, options: ValidationOptions): Err | R; description?: string | ((params: P) => string); @@ -905,7 +905,7 @@ export interface Err extends JoiObject { toString(): string; } -// --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- +//-------------------------------------------------- /** * Current version of the joi package. @@ -996,18 +996,18 @@ export function compile(schema: SchemaLike): T; /** * Validates a value against a schema and throws if validation fails. * - * @param value - the value to validate. - * @param schema - the schema object. - * @param message - optional message string prefix added in front of the error message. may also be an Error object. + * @param value the value to validate. + * @param schema the schema object. + * @param message optional message string prefix added in front of the error message. may also be an Error object. */ export function assert(value: any, schema: SchemaLike, message?: string | Error): void; /** * Validates a value against a schema, returns valid object, and throws if validation fails where: * - * @param value - the value to validate. - * @param schema - the schema object. - * @param message - optional message string prefix added in front of the error message. may also be an Error object. + * @param value the value to validate. + * @param schema the schema object. + * @param message optional message string prefix added in front of the error message. may also be an Error object. */ export function attempt(value: T, schema: SchemaLike, message?: string | Error): T; @@ -1032,8 +1032,124 @@ export function reach(schema: ObjectSchema, path: string): T; */ export function extend(extention: Extension): any; +// Below are undocumented APIs. use them at your own risk + /** * Returns a plain object representing the schema's rules and properties */ export function describe(schema: Schema): Description; +/** +* Whitelists a value +*/ +export function allow(value: any, ...values: any[]): Schema; +export function allow(values: any[]): Schema; + +/** + * Adds the provided values into the allowed whitelist and marks them as the only valid values allowed. + */ +export function valid(value: any, ...values: any[]): Schema; +export function valid(values: any[]): Schema; +export function only(value: any, ...values: any[]): Schema; +export function only(values: any[]): Schema; +export function equal(value: any, ...values: any[]): Schema; +export function equal(values: any[]): Schema; + +/** + * Blacklists a value + */ +export function invalid(value: any, ...values: any[]): Schema; +export function invalid(values: any[]): Schema; +export function disallow(value: any, ...values: any[]): Schema; +export function disallow(values: any[]): Schema; +export function not(value: any, ...values: any[]): Schema; +export function not(values: any[]): Schema; + +/** + * Marks a key as required which will not allow undefined as value. All keys are optional by default. + */ +export function required(): Schema; + +/** + * Marks a key as optional which will allow undefined as values. Used to annotate the schema for readability as all keys are optional by default. + */ +export function optional(): Schema; + +/** + * Marks a key as forbidden which will not allow any value except undefined. Used to explicitly forbid keys. + */ +export function forbidden(): Schema; + +/** + * Marks a key to be removed from a resulting object or array after validation. Used to sanitize output. + */ +export function strip(): Schema; + +/** + * Annotates the key + */ +export function description(desc: string): Schema; + +/** + * Annotates the key + */ +export function notes(notes: string): Schema; +export function notes(notes: string[]): Schema; + +/** + * Annotates the key + */ +export function tags(notes: string): Schema; +export function tags(notes: string[]): Schema; + +/** + * Attaches metadata to the key. + */ +export function meta(meta: Object): Schema; + +/** + * Annotates the key with an example value, must be valid. + */ +export function example(value: any): Schema; + +/** + * Annotates the key with an unit name. + */ +export function unit(name: string): Schema; + +/** + * Overrides the global validate() options for the current key and any sub-key. + */ +export function options(options: ValidationOptions): Schema; + +/** + * Sets the options.convert options to false which prevent type casting for the current key and any child keys. + */ +export function strict(isStrict?: boolean): Schema; + +/** + * Returns a new type that is the result of adding the rules of one type to another. + */ +export function concat(schema: T): T; + +/** + * Converts the type into an alternatives type where the conditions are merged into the type definition where: + */ +export function when(ref: string, options: WhenOptions): AlternativesSchema; +export function when(ref: Reference, options: WhenOptions): AlternativesSchema; + +/** + * Overrides the key name in error messages. + */ +export function label(name: string): Schema; + +/** + * Outputs the original untouched value instead of the casted value. + */ +export function raw(isRaw?: boolean): Schema; + +/** + * Considers anything that matches the schema to be empty (undefined). + * @param schema any object or joi schema to match. An undefined schema unsets that rule. + */ +export function empty(schema?: any): Schema; diff --git a/types/joi/joi-tests.ts b/types/joi/joi-tests.ts index 5f44e6ad01..f83196a983 100644 --- a/types/joi/joi-tests.ts +++ b/types/joi/joi-tests.ts @@ -957,3 +957,56 @@ const Joi3 = Joi.extend({ }, ], }); + +// --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- + +schema = Joi.allow(x, x); +schema = Joi.allow([x, x, x]); +schema = Joi.valid(x); +schema = Joi.valid(x, x); +schema = Joi.valid([x, x, x]); +schema = Joi.only(x); +schema = Joi.only(x, x); +schema = Joi.only([x, x, x]); +schema = Joi.equal(x); +schema = Joi.equal(x, x); +schema = Joi.equal([x, x, x]); +schema = Joi.invalid(x); +schema = Joi.invalid(x, x); +schema = Joi.invalid([x, x, x]); +schema = Joi.disallow(x); +schema = Joi.disallow(x, x); +schema = Joi.disallow([x, x, x]); +schema = Joi.not(x); +schema = Joi.not(x, x); +schema = Joi.not([x, x, x]); + +schema = Joi.required(); +schema = Joi.optional(); +schema = Joi.forbidden(); +schema = Joi.strip(); + +schema = Joi.description(str); +schema = Joi.notes(str); +schema = Joi.notes(strArr); +schema = Joi.tags(str); +schema = Joi.tags(strArr); + +schema = Joi.meta(obj); +schema = Joi.example(obj); +schema = Joi.unit(str); + +schema = Joi.options(validOpts); +schema = Joi.strict(); +schema = Joi.strict(bool); +schema = Joi.concat(x); + +schema = Joi.when(str, whenOpts); +schema = Joi.when(ref, whenOpts); + +schema = Joi.label(str); +schema = Joi.raw(); +schema = Joi.raw(bool); +schema = Joi.empty(); +schema = Joi.empty(str); +schema = Joi.empty(anySchema); From 67356265a43372ed5b3364e74927d6199ba5c350 Mon Sep 17 00:00:00 2001 From: Young Rok Kim Date: Sun, 24 Sep 2017 02:32:41 +0900 Subject: [PATCH 030/828] joi: updated to v11.0.3 --- types/joi/index.d.ts | 142 ++++++++++++++++++++++++---------------- types/joi/joi-tests.ts | 72 ++++++++++++++++++-- types/joi/tsconfig.json | 2 +- 3 files changed, 153 insertions(+), 63 deletions(-) diff --git a/types/joi/index.d.ts b/types/joi/index.d.ts index af07b0bb2a..e71fa86a89 100644 --- a/types/joi/index.d.ts +++ b/types/joi/index.d.ts @@ -1,6 +1,13 @@ -// Type definitions for joi v10.4.2 +// Type definitions for joi v11.0.3 // Project: https://github.com/hapijs/joi -// Definitions by: Bart van der Schoor , Laurence Dougal Myers , Christopher Glantschnig , David Broder-Rodgers , Gael Magnan de Bornier , Rytis Alekna , Pavel Ivanov , Youngrok Kim +// Definitions by: Bart van der Schoor +// Laurence Dougal Myers +// Christopher Glantschnig +// David Broder-Rodgers +// Gael Magnan de Bornier +// Rytis Alekna +// Pavel Ivanov +// Youngrok Kim // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped // TypeScript Version: 2.4 @@ -37,10 +44,10 @@ export interface ValidationOptions { skipFunctions?: boolean; /** * remove unknown elements from objects and arrays. Defaults to false - * when true, all unknown elements will be removed - * when an object: - * arrays set to true to remove unknown items from arrays. - * objects set to true to remove unknown keys from objects + * - when true, all unknown elements will be removed + * - when an object: + * - arrays - set to true to remove unknown items from arrays. + * - objects - set to true to remove unknown keys from objects */ stripUnknown?: boolean | { arrays?: boolean; objects?: boolean }; /** @@ -158,7 +165,7 @@ export interface ValidationError extends Error, JoiObject { export interface ValidationErrorItem { message: string; type: string; - path: string; + path: string[]; options?: ValidationOptions; context?: Context; } @@ -192,6 +199,8 @@ export type Schema = AnySchema export interface AnySchema extends JoiObject { + schemaType?: Types | string; + /** * Validates a value using the schema and options. */ @@ -291,7 +300,7 @@ export interface AnySchema extends JoiObject { /** * Sets a default value if the original value is undefined. - * @param value the value. + * @param value - the value. * value supports references. * value may also be a function which returns the default value. * If value is specified as a function that accepts a single parameter, that parameter will be a context @@ -333,22 +342,22 @@ export interface AnySchema extends JoiObject { /** * Considers anything that matches the schema to be empty (undefined). - * @param schema any object or joi schema to match. An undefined schema unsets that rule. + * @param schema - any object or joi schema to match. An undefined schema unsets that rule. */ empty(schema?: SchemaLike): this; /** * Overrides the default joi error with a custom error if the rule fails where: - * @param err can be: - * an instance of `Error` the override error. + * @param err - can be: + * an instance of `Error` - the override error. * a `function(errors)`, taking an array of errors as argument, where it must either: - * return a `string` substitutes the error message with this text - * return a single `object` or an `Array` of it, where: - * `type` optional parameter providing the type of the error (eg. `number.min`). - * `message` optional parameter if `template` is provided, containing the text of the error. - * `template` optional parameter if `message` is provided, containing a template string, using the same format as usual joi language errors. - * `context` optional parameter, to provide context to your error if you are using the `template`. - * return an `Error` same as when you directly provide an `Error`, but you can customize the error message based on the errors. + * return a `string` - substitutes the error message with this text + * return a single ` object` or an `Array` of it, where: + * `type` - optional parameter providing the type of the error (eg. `number.min`). + * `message` - optional parameter if `template` is provided, containing the text of the error. + * `template` - optional parameter if `message` is provided, containing a template string, using the same format as usual joi language errors. + * `context` - optional parameter, to provide context to your error if you are using the `template`. + * return an `Error` - same as when you directly provide an `Error`, but you can customize the error message based on the errors. * * Note that if you provide an `Error`, it will be returned as-is, unmodified and undecorated with any of the * normal joi error properties. If validation fails and another error is found before the error @@ -396,7 +405,7 @@ export interface BooleanSchema extends AnySchema { * Allows for additional values to be considered valid booleans by converting them to true during validation. * Accepts a value or an array of values. String comparisons are by default case insensitive, * see boolean.insensitive() to change this behavior. - * @param values strings, numbers or arrays of them + * @param values - strings, numbers or arrays of them */ truthy(...values: Array): this; @@ -404,7 +413,7 @@ export interface BooleanSchema extends AnySchema { * Allows for additional values to be considered valid booleans by converting them to false during validation. * Accepts a value or an array of values. String comparisons are by default case insensitive, * see boolean.insensitive() to change this behavior. - * @param values strings, numbers or arrays of them + * @param values - strings, numbers or arrays of them */ falsy(...values: Array): this; @@ -452,7 +461,7 @@ export interface NumberSchema extends AnySchema { /** * Specifies the maximum number of decimal places where: - * limit the maximum number of decimal places allowed. + * @param limit - the maximum number of decimal places allowed. */ precision(limit: number): this; @@ -480,16 +489,16 @@ export interface StringSchema extends AnySchema { /** * Specifies the minimum number string characters. - * @param limit the minimum number of string characters required. It can also be a reference to another field. - * @param encoding if specified, the string length is calculated in bytes using the provided encoding. + * @param limit - the minimum number of string characters required. It can also be a reference to another field. + * @param encoding - if specified, the string length is calculated in bytes using the provided encoding. */ min(limit: number, encoding?: string): this; min(limit: Reference, encoding?: string): this; /** * Specifies the maximum number of string characters. - * @param limit the maximum number of string characters allowed. It can also be a reference to another field. - * @param encoding if specified, the string length is calculated in bytes using the provided encoding. + * @param limit - the maximum number of string characters allowed. It can also be a reference to another field. + * @param encoding - if specified, the string length is calculated in bytes using the provided encoding. */ max(limit: number, encoding?: string): this; max(limit: Reference, encoding?: string): this; @@ -501,23 +510,23 @@ export interface StringSchema extends AnySchema { /** * Specifies the exact string length required - * @param limit the required string length. It can also be a reference to another field. - * @param encoding if specified, the string length is calculated in bytes using the provided encoding. + * @param limit - the required string length. It can also be a reference to another field. + * @param encoding - if specified, the string length is calculated in bytes using the provided encoding. */ length(limit: number, encoding?: string): this; length(limit: Reference, encoding?: string): this; /** * Defines a regular expression rule. - * @param pattern a regular expression object the string value must match against. - * @param name optional name for patterns (useful with multiple patterns). Defaults to 'required'. + * @param pattern - a regular expression object the string value must match against. + * @param name - optional name for patterns (useful with multiple patterns). Defaults to 'required'. */ regex(pattern: RegExp, name?: string): this; /** * Replace characters matching the given pattern with the specified replacement string where: - * @param pattern a regular expression object to match against, or a string of which all occurrences will be replaced. - * @param replacement the string that will replace the pattern. + * @param pattern - a regular expression object to match against, or a string of which all occurrences will be replaced. + * @param replacement - the string that will replace the pattern. */ replace(pattern: RegExp, replacement: string): this; replace(pattern: string, replacement: string): this; @@ -553,7 +562,7 @@ export interface StringSchema extends AnySchema { guid(options?: GuidOptions): this; /** - * Alias for `guid`- Requires the string value to be a valid GUID + * Alias for `guid` -- Requires the string value to be a valid GUID */ uuid(options?: GuidOptions): this; @@ -610,14 +619,14 @@ export interface ArraySchema extends AnySchema { * Errors will contain the number of items that didn't match. * Any unmatched item having a label will be mentioned explicitly. * - * @param type a joi schema object to validate each array item against. + * @param type - a joi schema object to validate each array item against. */ items(...types: SchemaLike[]): this; items(types: SchemaLike[]): this; /** * Lists the types in sequence order for the array values where: - * @param type a joi schema object to validate against each array item in sequence order. type can be an array of values, or multiple values can be passed as individual arguments. + * @param type - a joi schema object to validate against each array item in sequence order. type can be an array of values, or multiple values can be passed as individual arguments. * If a given type is .required() then there must be a matching item with the same index position in the array. Errors will contain the number of items that didn't match. Any unmatched item having a label will be mentioned explicitly. */ ordered(...types: SchemaLike[]): this; @@ -648,6 +657,7 @@ export interface ArraySchema extends AnySchema { } export interface ObjectSchema extends AnySchema { + /** * Sets the allowed object keys. */ @@ -675,7 +685,7 @@ export interface ObjectSchema extends AnySchema { /** * Defines an all-or-nothing relationship between keys where if one of the peers is present, all of them are required as well. - * @param peers the key names of which if one present, all are required. peers can be a single string value, + * @param peers - the key names of which if one present, all are required. peers can be a single string value, * an array of string values, or each peer provided as an argument. */ and(...peers: string[]): this; @@ -683,7 +693,7 @@ export interface ObjectSchema extends AnySchema { /** * Defines a relationship between keys where not all peers can be present at the same time. - * @param peers the key names of which if one present, the others may not all be present. + * @param peers - the key names of which if one present, the others may not all be present. * peers can be a single string value, an array of string values, or each peer provided as an argument. */ nand(...peers: string[]): this; @@ -732,15 +742,15 @@ export interface ObjectSchema extends AnySchema { /** * Requires the object to be an instance of a given constructor. * - * @param constructor the constructor function that the object must be an instance of. - * @param name an alternate name to use in validation errors. This is useful when the constructor function does not have a name. + * @param constructor - the constructor function that the object must be an instance of. + * @param name - an alternate name to use in validation errors. This is useful when the constructor function does not have a name. */ type(constructor: Function, name?: string): this; /** * Sets the specified children to required. * - * @param children can be a single string value, an array of string values, or each child provided as an argument. + * @param children - can be a single string value, an array of string values, or each child provided as an argument. * * var schema = Joi.object().keys({ a: { b: Joi.number() }, c: { d: Joi.string() } }); * var requiredSchema = schema.requiredKeys('', 'a.b', 'c', 'c.d'); @@ -753,7 +763,7 @@ export interface ObjectSchema extends AnySchema { /** * Sets the specified children to optional. * - * @param children can be a single string value, an array of string values, or each child provided as an argument. + * @param children - can be a single string value, an array of string values, or each child provided as an argument. * * The behavior is exactly the same as requiredKeys. */ @@ -809,7 +819,7 @@ export interface DateSchema extends AnySchema { /** * Specifies the allowed date format: - * @param format string or array of strings that follow the moment.js format. + * @param format - string or array of strings that follow the moment.js format. */ format(format: string): this; format(format: string[]): this; @@ -821,7 +831,7 @@ export interface DateSchema extends AnySchema { /** * Requires the value to be a timestamp interval from Unix Time. - * @param type the type of timestamp (allowed values are unix or javascript [default]) + * @param type - the type of timestamp (allowed values are unix or javascript [default]) */ timestamp(type?: 'javascript' | 'unix'): this; } @@ -830,19 +840,19 @@ export interface FunctionSchema extends AnySchema { /** * Specifies the arity of the function where: - * @param n the arity expected. + * @param n - the arity expected. */ arity(n: number): this; /** * Specifies the minimal arity of the function where: - * @param n the minimal arity expected. + * @param n - the minimal arity expected. */ minArity(n: number): this; /** * Specifies the minimal arity of the function where: - * @param n the minimal arity expected. + * @param n - the minimal arity expected. */ maxArity(n: number): this; @@ -875,10 +885,10 @@ export type ExtensionBoundSchema = Schema & { /** * Creates a joi error object. * Used in conjunction with custom rules. - * @param type the type of rule to create the error for. - * @param context provide properties that will be available in the `language` templates. - * @param state should the context passed into the `validate` function in a custom rule - * @param options should the context passed into the `validate` function in a custom rule + * @param type - the type of rule to create the error for. + * @param context - provide properties that will be available in the `language` templates. + * @param state - should the context passed into the `validate` function in a custom rule + * @param options - should the context passed into the `validate` function in a custom rule */ createError(type: string, context: Context, state: State, options: ValidationOptions): Err; } @@ -905,7 +915,7 @@ export interface Err extends JoiObject { toString(): string; } -//-------------------------------------------------- +// --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- /** * Current version of the joi package. @@ -996,18 +1006,18 @@ export function compile(schema: SchemaLike): T; /** * Validates a value against a schema and throws if validation fails. * - * @param value the value to validate. - * @param schema the schema object. - * @param message optional message string prefix added in front of the error message. may also be an Error object. + * @param value - the value to validate. + * @param schema - the schema object. + * @param message - optional message string prefix added in front of the error message. may also be an Error object. */ export function assert(value: any, schema: SchemaLike, message?: string | Error): void; /** * Validates a value against a schema, returns valid object, and throws if validation fails where: * - * @param value the value to validate. - * @param schema the schema object. - * @param message optional message string prefix added in front of the error message. may also be an Error object. + * @param value - the value to validate. + * @param schema - the schema object. + * @param message - optional message string prefix added in front of the error message. may also be an Error object. */ export function attempt(value: T, schema: SchemaLike, message?: string | Error): T; @@ -1032,7 +1042,23 @@ export function reach(schema: ObjectSchema, path: string): T; */ export function extend(extention: Extension): any; -// Below are undocumented APIs. use them at your own risk +// --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- + +import * as Module from 'joi'; +export type Root = typeof Module; +export type DefaultsFunction = (root: Schema) => Schema; + +/** + * Creates a new Joi instance that will apply defaults onto newly created schemas + * through the use of the fn function that takes exactly one argument, the schema being created. + * + * @param fn - The function must always return a schema, even if untransformed. + */ +export function defaults(fn: DefaultsFunction): Root; + +// --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- +// Below are undocumented APIs. use at your own risk +// --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- /** * Returns a plain object representing the schema's rules and properties @@ -1150,6 +1176,6 @@ export function raw(isRaw?: boolean): Schema; /** * Considers anything that matches the schema to be empty (undefined). - * @param schema any object or joi schema to match. An undefined schema unsets that rule. + * @param schema - any object or joi schema to match. An undefined schema unsets that rule. */ export function empty(schema?: any): Schema; diff --git a/types/joi/joi-tests.ts b/types/joi/joi-tests.ts index f83196a983..939059bdd3 100644 --- a/types/joi/joi-tests.ts +++ b/types/joi/joi-tests.ts @@ -136,13 +136,13 @@ var validErrFunc: Joi.ValidationErrorFunction; validErrItem = { message: str, type: str, - path: str + path: [str] }; validErrItem = { message: str, type: str, - path: str, + path: [str], options: validOpts, context: obj }; @@ -851,14 +851,14 @@ namespace validate_tests { Joi.validate(value, schema, validOpts, (err, value) => { x = value; str = err.message; - str = err.details[0].path; + str = err.details[0].path[0]; str = err.details[0].message; str = err.details[0].type; }); Joi.validate(value, schema, (err, value) => { x = value; str = err.message; - str = err.details[0].path; + str = err.details[0].path.join('.'); str = err.details[0].message; str = err.details[0].type; }); @@ -960,6 +960,70 @@ const Joi3 = Joi.extend({ // --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- +const defaultsJoi = Joi.defaults((schema) => { + switch (schema.schemaType) { + case 'string': + return schema.allow(''); + case 'object': + return (schema as Joi.ObjectSchema).min(1); + default: + return schema; + } +}); + +schema = Joi.allow(x, x); +schema = Joi.allow([x, x, x]); +schema = Joi.valid(x); +schema = Joi.valid(x, x); +schema = Joi.valid([x, x, x]); +schema = Joi.only(x); +schema = Joi.only(x, x); +schema = Joi.only([x, x, x]); +schema = Joi.equal(x); +schema = Joi.equal(x, x); +schema = Joi.equal([x, x, x]); +schema = Joi.invalid(x); +schema = Joi.invalid(x, x); +schema = Joi.invalid([x, x, x]); +schema = Joi.disallow(x); +schema = Joi.disallow(x, x); +schema = Joi.disallow([x, x, x]); +schema = Joi.not(x); +schema = Joi.not(x, x); +schema = Joi.not([x, x, x]); + +schema = Joi.required(); +schema = Joi.optional(); +schema = Joi.forbidden(); +schema = Joi.strip(); + +schema = Joi.description(str); +schema = Joi.notes(str); +schema = Joi.notes(strArr); +schema = Joi.tags(str); +schema = Joi.tags(strArr); + +schema = Joi.meta(obj); +schema = Joi.example(obj); +schema = Joi.unit(str); + +schema = Joi.options(validOpts); +schema = Joi.strict(); +schema = Joi.strict(bool); +schema = Joi.concat(x); + +schema = Joi.when(str, whenOpts); +schema = Joi.when(ref, whenOpts); + +schema = Joi.label(str); +schema = Joi.raw(); +schema = Joi.raw(bool); +schema = Joi.empty(); +schema = Joi.empty(str); +schema = Joi.empty(anySchema); + +// --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- + schema = Joi.allow(x, x); schema = Joi.allow([x, x, x]); schema = Joi.valid(x); diff --git a/types/joi/tsconfig.json b/types/joi/tsconfig.json index 8d3ca40052..a45ccb7c63 100644 --- a/types/joi/tsconfig.json +++ b/types/joi/tsconfig.json @@ -19,4 +19,4 @@ "index.d.ts", "joi-tests.ts" ] -} \ No newline at end of file +} From dcc853211623616aabb57ce46912194e1bf7b2ce Mon Sep 17 00:00:00 2001 From: voxmatt Date: Sun, 1 Oct 2017 11:03:05 -0700 Subject: [PATCH 031/828] removing UMD style module structure from relay-runtime and moving new relay types to v1 folder --- types/react-relay/index.d.ts | 459 +--- types/react-relay/react-relay-tests.tsx | 393 +-- types/react-relay/tsconfig.json | 4 +- types/react-relay/v1/index.d.ts | 474 ++++ .../v1/lib/react-relay-classic.d.ts | 0 .../v1/lib/react-relay-compat.d.ts | 0 .../v1/lib/react-relay-modern.d.ts | 0 types/react-relay/v1/react-relay-tests.tsx | 437 ++++ types/react-relay/v1/tsconfig.json | 31 + types/react-relay/{ => v1}/tslint.json | 0 types/relay-runtime/index.d.ts | 2182 ++++++++--------- 11 files changed, 2129 insertions(+), 1851 deletions(-) create mode 100644 types/react-relay/v1/index.d.ts create mode 100644 types/react-relay/v1/lib/react-relay-classic.d.ts create mode 100644 types/react-relay/v1/lib/react-relay-compat.d.ts create mode 100644 types/react-relay/v1/lib/react-relay-modern.d.ts create mode 100644 types/react-relay/v1/react-relay-tests.tsx create mode 100644 types/react-relay/v1/tsconfig.json rename types/react-relay/{ => v1}/tslint.json (100%) diff --git a/types/react-relay/index.d.ts b/types/react-relay/index.d.ts index 83b2890020..4f9f49e5e7 100644 --- a/types/react-relay/index.d.ts +++ b/types/react-relay/index.d.ts @@ -1,385 +1,86 @@ -// Type definitions for react-relay 1.3 +// Type definitions for react-relay 0.9.2 // Project: https://github.com/facebook/relay -// Definitions by: Johannes Schickling , Matt Martin +// Definitions by: Johannes Schickling // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -// TypeScript Version: 2.4 +// TypeScript Version: 2.3 -/// - -declare namespace __Relay { - //////////////////////////// - // RELAY MODERN TYPES - /////////////////////////// - namespace Modern { - // ~~~~~~~~~~~~~~~~~~~~~ - // Maybe Fix - // ~~~~~~~~~~~~~~~~~~~~~ - type ConcreteFragment = any; - type ConcreteBatch = any; - type ConcreteFragmentDefinition = object; - type ConcreteOperationDefinition = object; - type ReactBaseComponent = React.ComponentClass | React.StatelessComponent; - - // ~~~~~~~~~~~~~~~~~~~~~ - // RelayProp - // ~~~~~~~~~~~~~~~~~~~~~ - // note: refetch and pagination containers augment this - interface RelayProp { - environment: Runtime.Environment; - } - - // ~~~~~~~~~~~~~~~~~~~~~ - // RelayQL - // ~~~~~~~~~~~~~~~~~~~~~ - function RelayQL( - strings: string[], - ...substitutions: any[] - ): Common.RelayConcreteNode; - - // ~~~~~~~~~~~~~~~~~~~~~ - // RelayModernGraphQLTag - // ~~~~~~~~~~~~~~~~~~~~~ - interface GeneratedNodeMap { [key: string]: GraphQLTaggedNode; } - type GraphQLTaggedNode = - (() => ConcreteFragment | ConcreteBatch) - | { - modern(): ConcreteFragment | ConcreteBatch, - classic(relayQL: typeof RelayQL): - | ConcreteFragmentDefinition - | ConcreteOperationDefinition, - }; - /** - * Runtime function to correspond to the `graphql` tagged template function. - * All calls to this function should be transformed by the plugin. - */ - interface GraphqlInterface { - (strings: string[] | TemplateStringsArray): GraphQLTaggedNode; - experimental(strings: string[] | TemplateStringsArray): GraphQLTaggedNode; - } - const graphql: GraphqlInterface; - - // ~~~~~~~~~~~~~~~~~~~~~ - // ReactRelayQueryRenderer - // ~~~~~~~~~~~~~~~~~~~~~ - interface QueryRendererProps { - cacheConfig?: Common.CacheConfig; - environment: Runtime.Environment; - query: GraphQLTaggedNode; - render(readyState: ReadyState): React.ReactElement | undefined | null; - variables: Common.Variables; - rerunParamExperimental?: Common.RerunParam; - } - interface ReadyState { - error: Error | undefined | null; - props: { [propName: string]: any } | undefined | null; - retry?(): void; - } - interface QueryRendererState { - readyState: ReadyState; - } - class ReactRelayQueryRenderer extends React.Component { } - - // ~~~~~~~~~~~~~~~~~~~~~ - // createFragmentContainer - // ~~~~~~~~~~~~~~~~~~~~~ - function createFragmentContainer( - Component: ReactBaseComponent, - fragmentSpec: GraphQLTaggedNode | GeneratedNodeMap, - ): ReactBaseComponent; - - // ~~~~~~~~~~~~~~~~~~~~~ - // createPaginationContainer - // ~~~~~~~~~~~~~~~~~~~~~ - interface PageInfo { - endCursor: string | undefined | null; - hasNextPage: boolean; - hasPreviousPage: boolean; - startCursor: string | undefined | null; - } - interface ConnectionData { - edges?: any[]; - pageInfo?: PageInfo; - } - type RelayPaginationProp = RelayProp & { - hasMore(): boolean, - isLoading(): boolean, - loadMore( - pageSize: number, - callback: (error?: Error) => void, - options?: RefetchOptions, - ): Common.Disposable | undefined | null, - refetchConnection( - totalCount: number, - callback: (error?: Error) => void, - refetchVariables?: Common.Variables, - ): Common.Disposable | undefined | null, - }; - function FragmentVariablesGetter( - prevVars: Common.Variables, - totalCount: number, - ): Common.Variables; - interface ConnectionConfig { - direction?: 'backward' | 'forward'; - getConnectionFromProps?(props: object): ConnectionData | undefined | null; - getFragmentVariables?: typeof FragmentVariablesGetter; - getVariables( - props: { [propName: string]: any }, - paginationInfo: { count: number, cursor?: string }, - fragmentVariables: Common.Variables, - ): Common.Variables; - query: GraphQLTaggedNode; - } - function createPaginationContainer( - Component: ReactBaseComponent, - fragmentSpec: GraphQLTaggedNode | GeneratedNodeMap, - connectionConfig: ConnectionConfig, - ): ReactBaseComponent; - - // ~~~~~~~~~~~~~~~~~~~~~ - // createFragmentContainer - // ~~~~~~~~~~~~~~~~~~~~~ - interface RefetchOptions { - force?: boolean; - rerunParamExperimental?: Common.RerunParam; - } - type RelayRefetchProp = RelayProp & { - refetch( - refetchVariables: Common.Variables | ((fragmentVariables: Common.Variables) => Common.Variables), - renderVariables?: Common.Variables, - callback?: (error?: Error) => void, - options?: RefetchOptions, - ): Common.Disposable, - }; - function createRefetchContainer( - Component: ReactBaseComponent, - fragmentSpec: GraphQLTaggedNode | GeneratedNodeMap, - taggedNode: GraphQLTaggedNode, - ): ReactBaseComponent; - } - - //////////////////////////// - // RELAY CLASSIC TYPES - /////////////////////////// - // note: the namespace here is really for use inside of - // relay-compat; the module declaration below - // uses the old, pre-existing types - namespace Classic { - // ~~~~~~~~~~~~~~~~~~~~~ - // Maybe Fix - // ~~~~~~~~~~~~~~~~~~~~~ - type StoreReaderData = any; - type StoreReaderOptions = any; - type RelayStoreData = any; - interface RelayQuery { Fragment: any; Node: any; Root: any; } - - // ~~~~~~~~~~~~~~~~~~~~~ - // Environment - // ~~~~~~~~~~~~~~~~~~~~~ - interface FragmentResolver { - dispose(): void; - resolve( - fragment: RelayQuery["Fragment"], - dataIDs: Common.DataID | Common.DataID[], - ): StoreReaderData | StoreReaderData[] | undefined | null; - } - interface RelayEnvironmentInterface { - forceFetch( - querySet: Common.RelayQuerySet, - onReadyStateChange: Common.ReadyStateChangeCallback, - ): Common.Abortable; - getFragmentResolver( - fragment: RelayQuery["Fragment"], - onNext: () => void, - ): FragmentResolver; - getStoreData(): RelayStoreData; - primeCache( - querySet: Common.RelayQuerySet, - onReadyStateChange: Common.ReadyStateChangeCallback, - ): Common.Abortable; - read( - node: RelayQuery["Node"], - dataID: Common.DataID, - options?: StoreReaderOptions, - ): StoreReaderData | void; - readQuery( - root: RelayQuery["Root"], - options?: StoreReaderOptions, - ): StoreReaderData[] | void; - } - } - - //////////////////////////// - // RELAY COMPAT TYPES - /////////////////////////// - namespace Compat { - // ~~~~~~~~~~~~~~~~~~~~~ - // Maybe Fix - // ~~~~~~~~~~~~~~~~~~~~~ - type ConcreteFragment = any; - type ConcreteBatch = any; - type ConcreteFragmentDefinition = object; - type ConcreteOperationDefinition = object; - - // ~~~~~~~~~~~~~~~~~~~~~ - // Util - // ~~~~~~~~~~~~~~~~~~~~~ - function getFragment(q: string, v?: Common.Variables): string; - interface ComponentWithFragment extends React.ComponentClass { - getFragment: typeof getFragment; - } - interface StatelessWithFragment extends React.StatelessComponent { - getFragment: typeof getFragment; - } - type ReactFragmentComponent = ComponentWithFragment | StatelessWithFragment; - type ReactBaseComponent = React.ComponentClass | React.StatelessComponent; - type RelayClassicEnvironment = Classic.RelayEnvironmentInterface; - - // ~~~~~~~~~~~~~~~~~~~~~ - // RelayCompatTypes - // ~~~~~~~~~~~~~~~~~~~~~ - type CompatEnvironment = Runtime.Environment | RelayClassicEnvironment; - - // ~~~~~~~~~~~~~~~~~~~~~ - // RelayCompatMutations - // ~~~~~~~~~~~~~~~~~~~~~ - function commitUpdate( - environment: CompatEnvironment, - config: Runtime.MutationConfig, - ): Common.Disposable; - function applyUpdate( - environment: CompatEnvironment, - config: Runtime.OptimisticMutationConfig, - ): Common.Disposable; - - // ~~~~~~~~~~~~~~~~~~~~~ - // RelayCompatContainer - // ~~~~~~~~~~~~~~~~~~~~~ - interface GeneratedNodeMap { [key: string]: Modern.GraphQLTaggedNode; } - function createContainer( - Component: ReactBaseComponent, - fragmentSpec: Modern.GraphQLTaggedNode | GeneratedNodeMap, - ): ReactFragmentComponent; - - // ~~~~~~~~~~~~~~~~~~~~~ - // injectDefaultVariablesProvider - // ~~~~~~~~~~~~~~~~~~~~~ - type VariablesProvider = () => Common.Variables; - function injectDefaultVariablesProvider(variablesProvider: VariablesProvider): void; - } -} - -//////////////////////////// -// MODULES -/////////////////////////// -// tslint:disable strict-export-declare-modifiers -declare module 'react-relay' { - export import QueryRenderer = __Relay.Modern.ReactRelayQueryRenderer; - export import createFragmentContainer = __Relay.Modern.createFragmentContainer; - export import createPaginationContainer = __Relay.Modern.createPaginationContainer; - export import createRefetchContainer = __Relay.Modern.createRefetchContainer; - export import graphql = __Relay.Modern.graphql; - - export import commitLocalUpdate = __Relay.Runtime.commitLocalUpdate; - export import commitMutation = __Relay.Runtime.commitRelayModernMutation; - export import fetchQuery = __Relay.Runtime.fetchRelayModernQuery; - export import requestSubscription = __Relay.Runtime.requestRelaySubscription; - - // exported for convenience — not exports in the original module - export import RelayProp = __Relay.Modern.RelayProp; - export import RelayPaginationProp = __Relay.Modern.RelayPaginationProp; - export import RelayRefetchProp = __Relay.Modern.RelayRefetchProp; -} - -declare module 'react-relay/compat' { - export import applyOptimisticMutation = __Relay.Compat.applyUpdate; - export import commitMutation = __Relay.Compat.commitUpdate; - export import createFragmentContainer = __Relay.Compat.createContainer; - export import createPaginationContainer = __Relay.Compat.createContainer; - export import createRefetchContainer = __Relay.Compat.createContainer; - export import injectDefaultVariablesProvider = __Relay.Compat.injectDefaultVariablesProvider; - export import QueryRenderer = __Relay.Modern.ReactRelayQueryRenderer; - export import graphql = __Relay.Modern.graphql; - export import fetchQuery = __Relay.Runtime.fetchRelayModernQuery; -} -// tslint:enable strict-export-declare-modifiers - -declare module "react-relay/classic" { +declare module "react-relay" { import * as React from "react"; type ClientMutationID = string; /** Fragments are a hash of functions */ interface Fragments { - [query: string]: ((variables?: RelayVariables) => string); + [query: string]: ((variables?: RelayVariables) => string) } interface CreateContainerOpts { - initialVariables?: any; - fragments: Fragments; - prepareVariables?(prevVariables: RelayVariables): RelayVariables; + initialVariables?: any + fragments: Fragments + prepareVariables?(prevVariables: RelayVariables): RelayVariables } interface RelayVariables { - [name: string]: any; + [name: string]: any } /** add static getFragment method to the component constructor */ interface RelayContainerClass extends React.ComponentClass { - getFragment: ((q: string, v?: RelayVariables) => string); + getFragment: ((q: string, v?: RelayVariables) => string) } interface RelayQueryRequestResolve { - response: any; + response: any } type RelayMutationStatus = - 'UNCOMMITTED' | // Transaction hasn't yet been sent to the server. Transaction can be committed or rolled back. - 'COMMIT_QUEUED' | // Transaction was committed but another transaction with the same collision key is pending, so the transaction has been queued to send to the server. - 'COLLISION_COMMIT_FAILED' | // Transaction was queued for commit but another transaction with the same collision key failed. All transactions in the collision queue, - // including this one, have been failed. Transaction can be recommitted or rolled back. - 'COMMITTING' | // Transaction is waiting for the server to respond. - 'COMMIT_FAILED'; + 'UNCOMMITTED' | // Transaction hasn't yet been sent to the server. Transaction can be committed or rolled back. + 'COMMIT_QUEUED' | // Transaction was committed but another transaction with the same collision key is pending, so the transaction has been queued to send to the server. + 'COLLISION_COMMIT_FAILED' | //Transaction was queued for commit but another transaction with the same collision key failed. All transactions in the collision queue, including this one, have been failed. Transaction can be recommitted or rolled back. + 'COMMITTING' | // Transaction is waiting for the server to respond. + 'COMMIT_FAILED'; class RelayMutationTransaction { - applyOptimistic(): RelayMutationTransaction; - commit(): RelayMutationTransaction | null; - recommit(): void; - rollback(): void; - getError(): Error; - getStatus(): RelayMutationStatus; - getHash(): string; - getID(): ClientMutationID; + applyOptimistic(): RelayMutationTransaction; + commit(): RelayMutationTransaction | null; + recommit(): void; + rollback(): void; + getError(): Error; + getStatus(): RelayMutationStatus; + getHash(): string; + getID(): ClientMutationID; } interface RelayMutationRequest { - getQueryString(): string; - getVariables(): RelayVariables; - resolve(result: RelayQueryRequestResolve): any; - reject(errors: any): any; + getQueryString(): string + getVariables(): RelayVariables + resolve(result: RelayQueryRequestResolve): any + reject(errors: any): any } interface RelayQueryRequest { - resolve(result: RelayQueryRequestResolve): any; - reject(errors: any): any; - getQueryString(): string; - getVariables(): RelayVariables; - getID(): string; - getDebugName(): string; + resolve(result: RelayQueryRequestResolve): any + reject(errors: any): any + + getQueryString(): string + getVariables(): RelayVariables + getID(): string + getDebugName(): string } interface RelayNetworkLayer { - supports(...options: string[]): boolean; + supports(...options: string[]): boolean } class DefaultNetworkLayer implements RelayNetworkLayer { - constructor(host: string, options?: any); - supports(...options: string[]): boolean; + constructor(host: string, options?: any) + supports(...options: string[]): boolean } - function createContainer(component: React.ComponentClass | React.StatelessComponent, params?: CreateContainerOpts): RelayContainerClass; - function injectNetworkLayer(networkLayer: RelayNetworkLayer): any; - function isContainer(component: React.ComponentClass): boolean; - function QL(...args: any[]): string; + function createContainer(component: React.ComponentClass | React.StatelessComponent, params?: CreateContainerOpts): RelayContainerClass + function injectNetworkLayer(networkLayer: RelayNetworkLayer): any + function isContainer(component: React.ComponentClass): boolean + function QL(...args: any[]): string class Route { constructor(params?: RelayVariables) @@ -390,59 +91,39 @@ declare module "react-relay/classic" { * S is typically dynamic as it depends on the data the app is currently using, but it's possible to always * return some data in the payload using REQUIRED_CHILDREN which is where specifying S is the most useful. */ - class Mutation { - props: T; + class Mutation { + props: T - constructor(props: T); - static getFragment(q: string): string; + constructor(props: T) + static getFragment(q: string): string } interface Transaction { - getError(): Error; - Status(): number; + getError(): Error + Status(): number } interface StoreUpdateCallbacks { - onFailure?(transaction: Transaction): any; - onSuccess?(response: T): any; + onFailure?(transaction: Transaction): any + onSuccess?(response: T): any } interface Store { - commitUpdate(mutation: Mutation, callbacks?: StoreUpdateCallbacks): any; + commitUpdate(mutation: Mutation, callbacks?: StoreUpdateCallbacks): any } - const Store: Store; + var Store: Store - class RootContainer extends React.Component { } + class RootContainer extends React.Component {} - interface RootContainerProps extends React.Props { - Component: RelayContainerClass; - route: Route; - renderLoading?(): JSX.Element; - renderFetched?(data: any): JSX.Element; - renderFailure?(error: Error, retry: (...args: any[]) => any): JSX.Element; + interface RootContainerProps extends React.Props{ + Component: RelayContainerClass + route: Route + renderLoading?(): JSX.Element + renderFetched?(data: any): JSX.Element + renderFailure?(error: Error, retry: Function): JSX.Element } - class Renderer extends React.Component { } - - interface RendererProps { - Container: RelayContainerClass; // Relay container that defines fragments and the view to render. - forceFetch?: boolean; // Whether to send a server request regardless of data available on the client. - queryConfig: Route; // `QueryConfig` or `Relay.Route` that defines the query roots. - environment: Store; // An instance of `Relay.Environment` or any object that implements the `RelayEnvironment` interface. - render?: RenderCallback; // Called to render when data requirements are being fulfilled. - onReadyStateChange?: OnReadyStateChange; - } - - interface RenderStateConfig { - props?: { [propName: string]: any }; - done: boolean; - error?: Error; - retry?(): void; - stale: boolean; - } - type RenderCallback = (renderState: RenderStateConfig) => any; - type ReadyStateEvent = 'ABORT' | 'CACHE_RESTORED_REQUIRED' | @@ -455,23 +136,25 @@ declare module "react-relay/classic" { 'STORE_FOUND_ALL' | 'STORE_FOUND_REQUIRED'; - type OnReadyStateChange = (readyState: { - ready: boolean, - done: boolean, - stale: boolean, - error?: Error, - events: ReadyStateEvent[], - aborted: boolean - }) => void; + interface OnReadyStateChange { + (readyState: { + ready: boolean, + done: boolean, + stale: boolean, + error?: Error, + events: Array, + aborted: boolean + }): void + } interface RelayProp { readonly route: { name: string; }; // incomplete, also has params and queries readonly variables: any; - readonly pendingVariables?: any; + readonly pendingVariables?: any | null; setVariables(variables: any, onReadyStateChange?: OnReadyStateChange): void; forceFetch(variables: any, onReadyStateChange?: OnReadyStateChange): void; hasOptimisticUpdate(record: any): boolean; getPendingTransactions(record: any): RelayMutationTransaction[]; - commitUpdate(mutation: Mutation, callbacks?: StoreUpdateCallbacks): any; + commitUpdate: (mutation: Mutation, callbacks?: StoreUpdateCallbacks) => any; } } diff --git a/types/react-relay/react-relay-tests.tsx b/types/react-relay/react-relay-tests.tsx index 2b8e371ee2..90425156cc 100644 --- a/types/react-relay/react-relay-tests.tsx +++ b/types/react-relay/react-relay-tests.tsx @@ -1,375 +1,30 @@ -import * as React from "react"; -import { - Environment, - Network, - RecordSource, - Store, - ConnectionHandler, -} from 'relay-runtime'; - -//////////////////////////// -// RELAY MODERN TESTS -/////////////////////////// -import { - graphql, - commitMutation, - createFragmentContainer, - createPaginationContainer, - createRefetchContainer, - requestSubscription, - QueryRenderer, - RelayPaginationProp, - RelayRefetchProp -} from "react-relay"; - -// ~~~~~~~~~~~~~~~~~~~~~ -// Modern Environment -// ~~~~~~~~~~~~~~~~~~~~~ -function fetchQuery(operation: any, variables: any, cacheConfig: {}) { - return fetch('/graphql'); -} -const network = Network.create(fetchQuery); -const source = new RecordSource(); -const store = new Store(source); -const modernEnvironment = new Environment({ network, store }); - -// ~~~~~~~~~~~~~~~~~~~~~ -// Modern QueryRenderer -// ~~~~~~~~~~~~~~~~~~~~~ -const MyQueryRenderer = (props: { name: string}) => ( - { - if (error) { - return

{error.message}
; - } else if (props) { - return
{props.name} is great!
; - } - return
Loading
; - }} - /> -); - -// ~~~~~~~~~~~~~~~~~~~~~ -// Modern FragmentContainer -// ~~~~~~~~~~~~~~~~~~~~~ -const MyFragmentContainer = createFragmentContainer( - class TodoListView extends React.Component { - render() { - return
; - } - }, - { - item: graphql` - fragment TodoItem_item on Todo { - text - isComplete - } - `, - } -); - -// ~~~~~~~~~~~~~~~~~~~~~ -// Modern RefetchContainer -// ~~~~~~~~~~~~~~~~~~~~~ -interface StoryInterface { id: string; } -interface FeedStoriesProps { - relay: RelayRefetchProp; - feed: { - stories: { edges: Array<{ node: StoryInterface }> } - }; -} -class Story extends React.Component<{ story: StoryInterface }> {} -class FeedStories extends React.Component { - render() { - return ( -
- {this.props.feed.stories.edges.map( - edge => - )} -
- ); - } - - _loadMore() { - // Increments the number of stories being rendered by 10. - const refetchVariables = (fragmentVariables: {count: number }) => ({ - count: fragmentVariables.count + 10, - }); - this.props.relay.refetch(refetchVariables); - } - } - -const FeedRefetchContainer = createRefetchContainer( - FeedStories, - { - feed: graphql.experimental` - fragment FeedStories_feed on Feed - @argumentDefinitions( - count: {type: "Int", defaultValue: 10} - ) { - stories(first: $count) { - edges { - node { - id - ...Story_story - } - } - } - } - ` - }, - graphql.experimental` - query FeedStoriesRefetchQuery($count: Int) { - feed { - ...FeedStories_feed @arguments(count: $count) - } - } - `, - ); - -// ~~~~~~~~~~~~~~~~~~~~~ -// Modern PaginationContainer -// ~~~~~~~~~~~~~~~~~~~~~ -interface FeedProps { - user: { feed: { edges: Array<{ node: StoryInterface}>}}; - relay: RelayPaginationProp; -} -class Feed extends React.Component { - render() { - return (
- {this.props.user.feed.edges.map( - edge => - )} -
); - } - - _loadMore() { - if (!this.props.relay.hasMore() || this.props.relay.isLoading()) { - return; - } - - this.props.relay.loadMore( - 10, // Fetch the next 10 feed items - e => { - console.log(e); - }, - ); - } -} - -const FeedPaginationContainer = createPaginationContainer( - Feed, - { - user: graphql` - fragment Feed_user on User { - feed( - first: $count - after: $cursor - orderby: $orderBy # other variables - ) @connection(key: "Feed_feed") { - edges { - node { - id - ...Story_story - } - } - } - } - `, - }, - { - direction: 'forward', - getConnectionFromProps(props: { user: {feed: any}}) { - return props.user && props.user.feed; - }, - getFragmentVariables(prevVars, totalCount) { - return { - ...prevVars, - count: totalCount, - }; - }, - getVariables(props, {count, cursor}, fragmentVariables) { - return { - count, - cursor, - // in most cases, for variables other than connection filters like - // `first`, `after`, etc. you may want to use the previous values. - orderBy: fragmentVariables.orderBy, - }; - }, - query: graphql` - query FeedPaginationQuery( - $count: Int! - $cursor: String - $orderby: String! - ) { - user { - # You could reference the fragment defined previously. - ...Feed_user - } - } - ` - } -); - -// ~~~~~~~~~~~~~~~~~~~~~ -// Modern Mutations -// ~~~~~~~~~~~~~~~~~~~~~ -const mutation = graphql` -mutation MarkReadNotificationMutation( - $input: MarkReadNotificationData! -) { - markReadNotification(data: $input) { - notification { - seenState - } - } -} -`; - -const optimisticResponse = { - markReadNotification: { - notification: { - seenState: 'SEEN', - }, - }, -}; - -const configs = [{ - type: 'NODE_DELETE' as 'NODE_DELETE', - deletedIDFieldName: 'destroyedShipId', -}, { - type: 'RANGE_ADD' as 'RANGE_ADD', - parentID: 'shipId', - connectionInfo: [{ - key: 'AddShip_ships', - rangeBehavior: 'append', - }], - edgeName: 'newShipEdge', -}, { - type: 'RANGE_DELETE' as 'RANGE_DELETE', - parentID: 'todoId', - connectionKeys: [{ - key: 'RemoveTags_tags', - rangeBehavior: 'append', - }], - pathToConnection: ['todo', 'tags'], - deletedIDFieldName: 'removedTagId' -}]; - -function markNotificationAsRead(source: string, storyID: string) { - const variables = { - input: { - source, - storyID, - }, - }; - - commitMutation( - modernEnvironment, - { - configs, - mutation, - optimisticResponse, - variables, - onCompleted: (response, errors) => { - console.log('Response received from server.'); - }, - onError: err => console.error(err), - }, - ); -} - -// ~~~~~~~~~~~~~~~~~~~~~ -// Modern Subscriptions -// ~~~~~~~~~~~~~~~~~~~~~ -const subscription = graphql` - subscription MarkReadNotificationSubscription( - $storyID: ID! - ) { - markReadNotification(storyID: $storyID) { - notification { - seenState - } - } - } -`; -const variables = { - storyID: '123', -}; -requestSubscription( - modernEnvironment, // see Environment docs - { - subscription, - variables, - // optional but recommended: - onCompleted: () => {}, - onError: error => console.error(error), - // example of a custom updater - updater: store => { - // Get the notification - const rootField = store.getRootField('markReadNotification'); - const notification = !!rootField && rootField.getLinkedRecord('notification'); - // Add it to a connection - const viewer = store.getRoot().getLinkedRecord('viewer'); - const notifications = - ConnectionHandler.getConnection(viewer, 'notifications'); - const edge = ConnectionHandler.createEdge( - store, - notifications, - notification, - '', - ); - ConnectionHandler.insertEdgeAfter(notifications, edge); - }, - } -); - -//////////////////////////// -// RELAY-CLASSIC TESTS -/////////////////////////// - -import * as Relay from "react-relay/classic"; +import * as React from "react" +import * as Relay from "react-relay" interface Props { - text: string; - userId: string; + text: string + userId: string } -export default class AddTweetMutation extends Relay.Mutation { - getMutation() { - return Relay.QL`mutation{addTweet}`; +interface Response { +} + +export default class AddTweetMutation extends Relay.Mutation { + + getMutation () { + return Relay.QL`mutation{addTweet}` } - getFatQuery() { + getFatQuery () { return Relay.QL` fragment on AddTweetPayload { tweetEdge user } - `; + ` } - getConfigs() { + getConfigs () { return [{ type: "RANGE_ADD", parentName: "user", @@ -379,19 +34,19 @@ export default class AddTweetMutation extends Relay.Mutation { rangeBehaviors: { "": "append", }, - }]; + }] } - getVariables() { - return this.props; + getVariables () { + return this.props } } interface ArtworkProps { artwork: { title: string - }; - relay: Relay.RelayProp; + }, + relay: Relay.RelayProp, } class Artwork extends React.Component { @@ -400,7 +55,7 @@ class Artwork extends React.Component { {this.props.artwork.title} - ); + ) } } @@ -412,7 +67,7 @@ const ArtworkContainer = Relay.createContainer(Artwork, { } ` } -}); +}) class StubbedArtwork extends React.Component { render() { @@ -428,10 +83,10 @@ class StubbedArtwork extends React.Component { setVariables: () => {}, forceFetch: () => {}, hasOptimisticUpdate: () => false, - getPendingTransactions: (): any => undefined, + getPendingTransactions: (): Relay.RelayMutationTransaction[] => undefined, commitUpdate: () => {}, } - }; - return ; + } + return } } diff --git a/types/react-relay/tsconfig.json b/types/react-relay/tsconfig.json index 9cabc08c4a..90680fbafc 100644 --- a/types/react-relay/tsconfig.json +++ b/types/react-relay/tsconfig.json @@ -7,7 +7,7 @@ ], "noImplicitAny": true, "noImplicitThis": true, - "strictNullChecks": true, + "strictNullChecks": false, "baseUrl": "../", "typeRoots": [ "../" @@ -21,4 +21,4 @@ "index.d.ts", "react-relay-tests.tsx" ] -} +} \ No newline at end of file diff --git a/types/react-relay/v1/index.d.ts b/types/react-relay/v1/index.d.ts new file mode 100644 index 0000000000..14c7bb756a --- /dev/null +++ b/types/react-relay/v1/index.d.ts @@ -0,0 +1,474 @@ +// Type definitions for react-relay 1.3 +// Project: https://github.com/facebook/relay +// Definitions by: Johannes Schickling , Matt Martin +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.4 + +import * as React from 'react'; +import { RelayCommonTypes, RelayRuntimeTypes } from 'relay-runtime'; + +//////////////////////////// +// RELAY MODERN TYPES +/////////////////////////// +export namespace RelayModernTypes { + // ~~~~~~~~~~~~~~~~~~~~~ + // Maybe Fix + // ~~~~~~~~~~~~~~~~~~~~~ + type ConcreteFragment = any; + type ConcreteBatch = any; + type ConcreteFragmentDefinition = object; + type ConcreteOperationDefinition = object; + type ReactBaseComponent = React.ComponentClass | React.StatelessComponent; + + // ~~~~~~~~~~~~~~~~~~~~~ + // RelayProp + // ~~~~~~~~~~~~~~~~~~~~~ + // note: refetch and pagination containers augment this + interface RelayProp { + environment: RelayRuntimeTypes.Environment; + } + + // ~~~~~~~~~~~~~~~~~~~~~ + // RelayQL + // ~~~~~~~~~~~~~~~~~~~~~ + function RelayQL( + strings: string[], + ...substitutions: any[] + ): RelayCommonTypes.RelayConcreteNode; + + // ~~~~~~~~~~~~~~~~~~~~~ + // RelayModernGraphQLTag + // ~~~~~~~~~~~~~~~~~~~~~ + interface GeneratedNodeMap { [key: string]: GraphQLTaggedNode; } + type GraphQLTaggedNode = + (() => ConcreteFragment | ConcreteBatch) + | { + modern(): ConcreteFragment | ConcreteBatch, + classic(relayQL: typeof RelayQL): + | ConcreteFragmentDefinition + | ConcreteOperationDefinition, + }; + /** + * Runtime function to correspond to the `graphql` tagged template function. + * All calls to this function should be transformed by the plugin. + */ + interface GraphqlInterface { + (strings: string[] | TemplateStringsArray): GraphQLTaggedNode; + experimental(strings: string[] | TemplateStringsArray): GraphQLTaggedNode; + } + const graphql: GraphqlInterface; + + // ~~~~~~~~~~~~~~~~~~~~~ + // ReactRelayQueryRenderer + // ~~~~~~~~~~~~~~~~~~~~~ + interface QueryRendererProps { + cacheConfig?: RelayCommonTypes.CacheConfig; + environment: RelayRuntimeTypes.Environment; + query: GraphQLTaggedNode; + render(readyState: ReadyState): React.ReactElement | undefined | null; + variables: RelayCommonTypes.Variables; + rerunParamExperimental?: RelayCommonTypes.RerunParam; + } + interface ReadyState { + error: Error | undefined | null; + props: { [propName: string]: any } | undefined | null; + retry?(): void; + } + interface QueryRendererState { + readyState: ReadyState; + } + class ReactRelayQueryRenderer extends React.Component { } + + // ~~~~~~~~~~~~~~~~~~~~~ + // createFragmentContainer + // ~~~~~~~~~~~~~~~~~~~~~ + function createFragmentContainer( + Component: ReactBaseComponent, + fragmentSpec: GraphQLTaggedNode | GeneratedNodeMap, + ): ReactBaseComponent; + + // ~~~~~~~~~~~~~~~~~~~~~ + // createPaginationContainer + // ~~~~~~~~~~~~~~~~~~~~~ + interface PageInfo { + endCursor: string | undefined | null; + hasNextPage: boolean; + hasPreviousPage: boolean; + startCursor: string | undefined | null; + } + interface ConnectionData { + edges?: any[]; + pageInfo?: PageInfo; + } + type RelayPaginationProp = RelayProp & { + hasMore(): boolean, + isLoading(): boolean, + loadMore( + pageSize: number, + callback: (error?: Error) => void, + options?: RefetchOptions, + ): RelayCommonTypes.Disposable | undefined | null, + refetchConnection( + totalCount: number, + callback: (error?: Error) => void, + refetchVariables?: RelayCommonTypes.Variables, + ): RelayCommonTypes.Disposable | undefined | null, + }; + function FragmentVariablesGetter( + prevVars: RelayCommonTypes.Variables, + totalCount: number, + ): RelayCommonTypes.Variables; + interface ConnectionConfig { + direction?: 'backward' | 'forward'; + getConnectionFromProps?(props: object): ConnectionData | undefined | null; + getFragmentVariables?: typeof FragmentVariablesGetter; + getVariables( + props: { [propName: string]: any }, + paginationInfo: { count: number, cursor?: string }, + fragmentVariables: RelayCommonTypes.Variables, + ): RelayCommonTypes.Variables; + query: GraphQLTaggedNode; + } + function createPaginationContainer( + Component: ReactBaseComponent, + fragmentSpec: GraphQLTaggedNode | GeneratedNodeMap, + connectionConfig: ConnectionConfig, + ): ReactBaseComponent; + + // ~~~~~~~~~~~~~~~~~~~~~ + // createFragmentContainer + // ~~~~~~~~~~~~~~~~~~~~~ + interface RefetchOptions { + force?: boolean; + rerunParamExperimental?: RelayCommonTypes.RerunParam; + } + type RelayRefetchProp = RelayProp & { + refetch( + refetchVariables: RelayCommonTypes.Variables | ((fragmentVariables: RelayCommonTypes.Variables) => RelayCommonTypes.Variables), + renderVariables?: RelayCommonTypes.Variables, + callback?: (error?: Error) => void, + options?: RefetchOptions, + ): RelayCommonTypes.Disposable, + }; + function createRefetchContainer( + Component: ReactBaseComponent, + fragmentSpec: GraphQLTaggedNode | GeneratedNodeMap, + taggedNode: GraphQLTaggedNode, + ): ReactBaseComponent; +} + +//////////////////////////// +// RELAY CLASSIC TYPES +/////////////////////////// +// note: the namespace here is really for use inside of +// relay-compat; the module declaration below +// uses the old, pre-existing types +export namespace RelayClassicTypes { + // ~~~~~~~~~~~~~~~~~~~~~ + // Maybe Fix + // ~~~~~~~~~~~~~~~~~~~~~ + type StoreReaderData = any; + type StoreReaderOptions = any; + type RelayStoreData = any; + interface RelayQuery { Fragment: any; Node: any; Root: any; } + + // ~~~~~~~~~~~~~~~~~~~~~ + // Environment + // ~~~~~~~~~~~~~~~~~~~~~ + interface FragmentResolver { + dispose(): void; + resolve( + fragment: RelayQuery["Fragment"], + dataIDs: RelayCommonTypes.DataID | RelayCommonTypes.DataID[], + ): StoreReaderData | StoreReaderData[] | undefined | null; + } + interface RelayEnvironmentInterface { + forceFetch( + querySet: RelayCommonTypes.RelayQuerySet, + onReadyStateChange: RelayCommonTypes.ReadyStateChangeCallback, + ): RelayCommonTypes.Abortable; + getFragmentResolver( + fragment: RelayQuery["Fragment"], + onNext: () => void, + ): FragmentResolver; + getStoreData(): RelayStoreData; + primeCache( + querySet: RelayCommonTypes.RelayQuerySet, + onReadyStateChange: RelayCommonTypes.ReadyStateChangeCallback, + ): RelayCommonTypes.Abortable; + read( + node: RelayQuery["Node"], + dataID: RelayCommonTypes.DataID, + options?: StoreReaderOptions, + ): StoreReaderData | void; + readQuery( + root: RelayQuery["Root"], + options?: StoreReaderOptions, + ): StoreReaderData[] | void; + } +} + +//////////////////////////// +// RELAY COMPAT TYPES +/////////////////////////// +export namespace RelayCompatTypes { + // ~~~~~~~~~~~~~~~~~~~~~ + // Maybe Fix + // ~~~~~~~~~~~~~~~~~~~~~ + type ConcreteFragment = any; + type ConcreteBatch = any; + type ConcreteFragmentDefinition = object; + type ConcreteOperationDefinition = object; + + // ~~~~~~~~~~~~~~~~~~~~~ + // Util + // ~~~~~~~~~~~~~~~~~~~~~ + function getFragment(q: string, v?: RelayCommonTypes.Variables): string; + interface ComponentWithFragment extends React.ComponentClass { + getFragment: typeof getFragment; + } + interface StatelessWithFragment extends React.StatelessComponent { + getFragment: typeof getFragment; + } + type ReactFragmentComponent = ComponentWithFragment | StatelessWithFragment; + type ReactBaseComponent = React.ComponentClass | React.StatelessComponent; + type RelayClassicEnvironment = RelayClassicTypes.RelayEnvironmentInterface; + + // ~~~~~~~~~~~~~~~~~~~~~ + // RelayCompatTypes + // ~~~~~~~~~~~~~~~~~~~~~ + type CompatEnvironment = RelayRuntimeTypes.Environment | RelayClassicEnvironment; + + // ~~~~~~~~~~~~~~~~~~~~~ + // RelayCompatMutations + // ~~~~~~~~~~~~~~~~~~~~~ + function commitUpdate( + environment: CompatEnvironment, + config: RelayRuntimeTypes.MutationConfig, + ): RelayCommonTypes.Disposable; + function applyUpdate( + environment: CompatEnvironment, + config: RelayRuntimeTypes.OptimisticMutationConfig, + ): RelayCommonTypes.Disposable; + + // ~~~~~~~~~~~~~~~~~~~~~ + // RelayCompatContainer + // ~~~~~~~~~~~~~~~~~~~~~ + interface GeneratedNodeMap { [key: string]: RelayModernTypes.GraphQLTaggedNode; } + function createContainer( + Component: ReactBaseComponent, + fragmentSpec: RelayModernTypes.GraphQLTaggedNode | GeneratedNodeMap, + ): ReactFragmentComponent; + + // ~~~~~~~~~~~~~~~~~~~~~ + // injectDefaultVariablesProvider + // ~~~~~~~~~~~~~~~~~~~~~ + type VariablesProvider = () => RelayCommonTypes.Variables; + function injectDefaultVariablesProvider(variablesProvider: VariablesProvider): void; +} + + +//////////////////////////// +// MODULES +/////////////////////////// +export import QueryRenderer = RelayModernTypes.ReactRelayQueryRenderer; +export import createFragmentContainer = RelayModernTypes.createFragmentContainer; +export import createPaginationContainer = RelayModernTypes.createPaginationContainer; +export import createRefetchContainer = RelayModernTypes.createRefetchContainer; +export import graphql = RelayModernTypes.graphql; + +export import commitLocalUpdate = RelayRuntimeTypes.commitLocalUpdate; +export import commitMutation = RelayRuntimeTypes.commitRelayModernMutation; +export import fetchQuery = RelayRuntimeTypes.fetchRelayModernQuery; +export import requestSubscription = RelayRuntimeTypes.requestRelaySubscription; + +// exported for convenience — not exports in the original module +export import RelayProp = RelayModernTypes.RelayProp; +export import RelayPaginationProp = RelayModernTypes.RelayPaginationProp; +export import RelayRefetchProp = RelayModernTypes.RelayRefetchProp; + +declare module 'react-relay/compat' { + export import applyOptimisticMutation = RelayCompatTypes.applyUpdate; + export import commitMutation = RelayCompatTypes.commitUpdate; + export import createFragmentContainer = RelayCompatTypes.createContainer; + export import createPaginationContainer = RelayCompatTypes.createContainer; + export import createRefetchContainer = RelayCompatTypes.createContainer; + export import injectDefaultVariablesProvider = RelayCompatTypes.injectDefaultVariablesProvider; + export import QueryRenderer = RelayModernTypes.ReactRelayQueryRenderer; + export import graphql = RelayModernTypes.graphql; + export import fetchQuery = RelayRuntimeTypes.fetchRelayModernQuery; +} +// tslint:enable strict-export-declare-modifiers + +declare module "react-relay/classic" { + import * as React from "react"; + + type ClientMutationID = string; + + /** Fragments are a hash of functions */ + interface Fragments { + [query: string]: ((variables?: RelayVariables) => string); + } + + interface CreateContainerOpts { + initialVariables?: any; + fragments: Fragments; + prepareVariables?(prevVariables: RelayVariables): RelayVariables; + } + + interface RelayVariables { + [name: string]: any; + } + + /** add static getFragment method to the component constructor */ + interface RelayContainerClass extends React.ComponentClass { + getFragment: ((q: string, v?: RelayVariables) => string); + } + + interface RelayQueryRequestResolve { + response: any; + } + + type RelayMutationStatus = + 'UNCOMMITTED' | // Transaction hasn't yet been sent to the server. Transaction can be committed or rolled back. + 'COMMIT_QUEUED' | // Transaction was committed but another transaction with the same collision key is pending, so the transaction has been queued to send to the server. + 'COLLISION_COMMIT_FAILED' | // Transaction was queued for commit but another transaction with the same collision key failed. All transactions in the collision queue, + // including this one, have been failed. Transaction can be recommitted or rolled back. + 'COMMITTING' | // Transaction is waiting for the server to respond. + 'COMMIT_FAILED'; + + class RelayMutationTransaction { + applyOptimistic(): RelayMutationTransaction; + commit(): RelayMutationTransaction | null; + recommit(): void; + rollback(): void; + getError(): Error; + getStatus(): RelayMutationStatus; + getHash(): string; + getID(): ClientMutationID; + } + + interface RelayMutationRequest { + getQueryString(): string; + getVariables(): RelayVariables; + resolve(result: RelayQueryRequestResolve): any; + reject(errors: any): any; + } + + interface RelayQueryRequest { + resolve(result: RelayQueryRequestResolve): any; + reject(errors: any): any; + getQueryString(): string; + getVariables(): RelayVariables; + getID(): string; + getDebugName(): string; + } + + interface RelayNetworkLayer { + supports(...options: string[]): boolean; + } + + class DefaultNetworkLayer implements RelayNetworkLayer { + constructor(host: string, options?: any); + supports(...options: string[]): boolean; + } + + function createContainer(component: React.ComponentClass | React.StatelessComponent, params?: CreateContainerOpts): RelayContainerClass; + function injectNetworkLayer(networkLayer: RelayNetworkLayer): any; + function isContainer(component: React.ComponentClass): boolean; + function QL(...args: any[]): string; + + class Route { + constructor(params?: RelayVariables) + } + + /** + * Relay Mutation class, where T are the props it takes and S is the returned payload from Relay.Store.update. + * S is typically dynamic as it depends on the data the app is currently using, but it's possible to always + * return some data in the payload using REQUIRED_CHILDREN which is where specifying S is the most useful. + */ + class Mutation { + props: T; + + constructor(props: T); + static getFragment(q: string): string; + } + + interface Transaction { + getError(): Error; + Status(): number; + } + + interface StoreUpdateCallbacks { + onFailure?(transaction: Transaction): any; + onSuccess?(response: T): any; + } + + interface Store { + commitUpdate(mutation: Mutation, callbacks?: StoreUpdateCallbacks): any; + } + + const Store: Store; + + class RootContainer extends React.Component { } + + interface RootContainerProps extends React.Props { + Component: RelayContainerClass; + route: Route; + renderLoading?(): JSX.Element; + renderFetched?(data: any): JSX.Element; + renderFailure?(error: Error, retry: (...args: any[]) => any): JSX.Element; + } + + class Renderer extends React.Component { } + + interface RendererProps { + Container: RelayContainerClass; // Relay container that defines fragments and the view to render. + forceFetch?: boolean; // Whether to send a server request regardless of data available on the client. + queryConfig: Route; // `QueryConfig` or `Relay.Route` that defines the query roots. + environment: Store; // An instance of `Relay.Environment` or any object that implements the `RelayEnvironment` interface. + render?: RenderCallback; // Called to render when data requirements are being fulfilled. + onReadyStateChange?: OnReadyStateChange; + } + + interface RenderStateConfig { + props?: { [propName: string]: any }; + done: boolean; + error?: Error; + retry?(): void; + stale: boolean; + } + type RenderCallback = (renderState: RenderStateConfig) => any; + + type ReadyStateEvent = + 'ABORT' | + 'CACHE_RESTORED_REQUIRED' | + 'CACHE_RESTORE_FAILED' | + 'CACHE_RESTORE_START' | + 'NETWORK_QUERY_ERROR' | + 'NETWORK_QUERY_RECEIVED_ALL' | + 'NETWORK_QUERY_RECEIVED_REQUIRED' | + 'NETWORK_QUERY_START' | + 'STORE_FOUND_ALL' | + 'STORE_FOUND_REQUIRED'; + + type OnReadyStateChange = (readyState: { + ready: boolean, + done: boolean, + stale: boolean, + error?: Error, + events: ReadyStateEvent[], + aborted: boolean + }) => void; + + interface RelayProp { + readonly route: { name: string; }; // incomplete, also has params and queries + readonly variables: any; + readonly pendingVariables?: any; + setVariables(variables: any, onReadyStateChange?: OnReadyStateChange): void; + forceFetch(variables: any, onReadyStateChange?: OnReadyStateChange): void; + hasOptimisticUpdate(record: any): boolean; + getPendingTransactions(record: any): RelayMutationTransaction[]; + commitUpdate(mutation: Mutation, callbacks?: StoreUpdateCallbacks): any; + } +} diff --git a/types/react-relay/v1/lib/react-relay-classic.d.ts b/types/react-relay/v1/lib/react-relay-classic.d.ts new file mode 100644 index 0000000000..e69de29bb2 diff --git a/types/react-relay/v1/lib/react-relay-compat.d.ts b/types/react-relay/v1/lib/react-relay-compat.d.ts new file mode 100644 index 0000000000..e69de29bb2 diff --git a/types/react-relay/v1/lib/react-relay-modern.d.ts b/types/react-relay/v1/lib/react-relay-modern.d.ts new file mode 100644 index 0000000000..e69de29bb2 diff --git a/types/react-relay/v1/react-relay-tests.tsx b/types/react-relay/v1/react-relay-tests.tsx new file mode 100644 index 0000000000..2b8e371ee2 --- /dev/null +++ b/types/react-relay/v1/react-relay-tests.tsx @@ -0,0 +1,437 @@ +import * as React from "react"; +import { + Environment, + Network, + RecordSource, + Store, + ConnectionHandler, +} from 'relay-runtime'; + +//////////////////////////// +// RELAY MODERN TESTS +/////////////////////////// +import { + graphql, + commitMutation, + createFragmentContainer, + createPaginationContainer, + createRefetchContainer, + requestSubscription, + QueryRenderer, + RelayPaginationProp, + RelayRefetchProp +} from "react-relay"; + +// ~~~~~~~~~~~~~~~~~~~~~ +// Modern Environment +// ~~~~~~~~~~~~~~~~~~~~~ +function fetchQuery(operation: any, variables: any, cacheConfig: {}) { + return fetch('/graphql'); +} +const network = Network.create(fetchQuery); +const source = new RecordSource(); +const store = new Store(source); +const modernEnvironment = new Environment({ network, store }); + +// ~~~~~~~~~~~~~~~~~~~~~ +// Modern QueryRenderer +// ~~~~~~~~~~~~~~~~~~~~~ +const MyQueryRenderer = (props: { name: string}) => ( + { + if (error) { + return
{error.message}
; + } else if (props) { + return
{props.name} is great!
; + } + return
Loading
; + }} + /> +); + +// ~~~~~~~~~~~~~~~~~~~~~ +// Modern FragmentContainer +// ~~~~~~~~~~~~~~~~~~~~~ +const MyFragmentContainer = createFragmentContainer( + class TodoListView extends React.Component { + render() { + return
; + } + }, + { + item: graphql` + fragment TodoItem_item on Todo { + text + isComplete + } + `, + } +); + +// ~~~~~~~~~~~~~~~~~~~~~ +// Modern RefetchContainer +// ~~~~~~~~~~~~~~~~~~~~~ +interface StoryInterface { id: string; } +interface FeedStoriesProps { + relay: RelayRefetchProp; + feed: { + stories: { edges: Array<{ node: StoryInterface }> } + }; +} +class Story extends React.Component<{ story: StoryInterface }> {} +class FeedStories extends React.Component { + render() { + return ( +
+ {this.props.feed.stories.edges.map( + edge => + )} +
+ ); + } + + _loadMore() { + // Increments the number of stories being rendered by 10. + const refetchVariables = (fragmentVariables: {count: number }) => ({ + count: fragmentVariables.count + 10, + }); + this.props.relay.refetch(refetchVariables); + } + } + +const FeedRefetchContainer = createRefetchContainer( + FeedStories, + { + feed: graphql.experimental` + fragment FeedStories_feed on Feed + @argumentDefinitions( + count: {type: "Int", defaultValue: 10} + ) { + stories(first: $count) { + edges { + node { + id + ...Story_story + } + } + } + } + ` + }, + graphql.experimental` + query FeedStoriesRefetchQuery($count: Int) { + feed { + ...FeedStories_feed @arguments(count: $count) + } + } + `, + ); + +// ~~~~~~~~~~~~~~~~~~~~~ +// Modern PaginationContainer +// ~~~~~~~~~~~~~~~~~~~~~ +interface FeedProps { + user: { feed: { edges: Array<{ node: StoryInterface}>}}; + relay: RelayPaginationProp; +} +class Feed extends React.Component { + render() { + return (
+ {this.props.user.feed.edges.map( + edge => + )} +
); + } + + _loadMore() { + if (!this.props.relay.hasMore() || this.props.relay.isLoading()) { + return; + } + + this.props.relay.loadMore( + 10, // Fetch the next 10 feed items + e => { + console.log(e); + }, + ); + } +} + +const FeedPaginationContainer = createPaginationContainer( + Feed, + { + user: graphql` + fragment Feed_user on User { + feed( + first: $count + after: $cursor + orderby: $orderBy # other variables + ) @connection(key: "Feed_feed") { + edges { + node { + id + ...Story_story + } + } + } + } + `, + }, + { + direction: 'forward', + getConnectionFromProps(props: { user: {feed: any}}) { + return props.user && props.user.feed; + }, + getFragmentVariables(prevVars, totalCount) { + return { + ...prevVars, + count: totalCount, + }; + }, + getVariables(props, {count, cursor}, fragmentVariables) { + return { + count, + cursor, + // in most cases, for variables other than connection filters like + // `first`, `after`, etc. you may want to use the previous values. + orderBy: fragmentVariables.orderBy, + }; + }, + query: graphql` + query FeedPaginationQuery( + $count: Int! + $cursor: String + $orderby: String! + ) { + user { + # You could reference the fragment defined previously. + ...Feed_user + } + } + ` + } +); + +// ~~~~~~~~~~~~~~~~~~~~~ +// Modern Mutations +// ~~~~~~~~~~~~~~~~~~~~~ +const mutation = graphql` +mutation MarkReadNotificationMutation( + $input: MarkReadNotificationData! +) { + markReadNotification(data: $input) { + notification { + seenState + } + } +} +`; + +const optimisticResponse = { + markReadNotification: { + notification: { + seenState: 'SEEN', + }, + }, +}; + +const configs = [{ + type: 'NODE_DELETE' as 'NODE_DELETE', + deletedIDFieldName: 'destroyedShipId', +}, { + type: 'RANGE_ADD' as 'RANGE_ADD', + parentID: 'shipId', + connectionInfo: [{ + key: 'AddShip_ships', + rangeBehavior: 'append', + }], + edgeName: 'newShipEdge', +}, { + type: 'RANGE_DELETE' as 'RANGE_DELETE', + parentID: 'todoId', + connectionKeys: [{ + key: 'RemoveTags_tags', + rangeBehavior: 'append', + }], + pathToConnection: ['todo', 'tags'], + deletedIDFieldName: 'removedTagId' +}]; + +function markNotificationAsRead(source: string, storyID: string) { + const variables = { + input: { + source, + storyID, + }, + }; + + commitMutation( + modernEnvironment, + { + configs, + mutation, + optimisticResponse, + variables, + onCompleted: (response, errors) => { + console.log('Response received from server.'); + }, + onError: err => console.error(err), + }, + ); +} + +// ~~~~~~~~~~~~~~~~~~~~~ +// Modern Subscriptions +// ~~~~~~~~~~~~~~~~~~~~~ +const subscription = graphql` + subscription MarkReadNotificationSubscription( + $storyID: ID! + ) { + markReadNotification(storyID: $storyID) { + notification { + seenState + } + } + } +`; +const variables = { + storyID: '123', +}; +requestSubscription( + modernEnvironment, // see Environment docs + { + subscription, + variables, + // optional but recommended: + onCompleted: () => {}, + onError: error => console.error(error), + // example of a custom updater + updater: store => { + // Get the notification + const rootField = store.getRootField('markReadNotification'); + const notification = !!rootField && rootField.getLinkedRecord('notification'); + // Add it to a connection + const viewer = store.getRoot().getLinkedRecord('viewer'); + const notifications = + ConnectionHandler.getConnection(viewer, 'notifications'); + const edge = ConnectionHandler.createEdge( + store, + notifications, + notification, + '', + ); + ConnectionHandler.insertEdgeAfter(notifications, edge); + }, + } +); + +//////////////////////////// +// RELAY-CLASSIC TESTS +/////////////////////////// + +import * as Relay from "react-relay/classic"; + +interface Props { + text: string; + userId: string; +} + +export default class AddTweetMutation extends Relay.Mutation { + getMutation() { + return Relay.QL`mutation{addTweet}`; + } + + getFatQuery() { + return Relay.QL` + fragment on AddTweetPayload { + tweetEdge + user + } + `; + } + + getConfigs() { + return [{ + type: "RANGE_ADD", + parentName: "user", + parentID: this.props.userId, + connectionName: "tweets", + edgeName: "tweetEdge", + rangeBehaviors: { + "": "append", + }, + }]; + } + + getVariables() { + return this.props; + } +} + +interface ArtworkProps { + artwork: { + title: string + }; + relay: Relay.RelayProp; +} + +class Artwork extends React.Component { + render() { + return ( + + {this.props.artwork.title} + + ); + } +} + +const ArtworkContainer = Relay.createContainer(Artwork, { + fragments: { + artwork: () => Relay.QL` + fragment on Artwork { + title + } + ` + } +}); + +class StubbedArtwork extends React.Component { + render() { + const props = { + artwork: { title: "CHAMPAGNE FORMICA FLAG" }, + relay: { + route: { + name: "champagne" + }, + variables: { + artworkID: "champagne-formica-flag", + }, + setVariables: () => {}, + forceFetch: () => {}, + hasOptimisticUpdate: () => false, + getPendingTransactions: (): any => undefined, + commitUpdate: () => {}, + } + }; + return ; + } +} diff --git a/types/react-relay/v1/tsconfig.json b/types/react-relay/v1/tsconfig.json new file mode 100644 index 0000000000..e6b06bf446 --- /dev/null +++ b/types/react-relay/v1/tsconfig.json @@ -0,0 +1,31 @@ +{ + "compilerOptions": { + "module": "commonjs", + "lib": [ + "es6", + "dom" + ], + "noImplicitAny": true, + "noImplicitThis": true, + "strictNullChecks": true, + "baseUrl": "../../", + "typeRoots": [ + "../../" + ], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true, + "jsx": "react", + "paths": { + "react-relay": ["react-relay/v1"], + "react-relay/*": ["react-relay/v2/*"] + } + }, + "files": [ + "index.d.ts", + "react-relay-tests.tsx", + "lib/react-relay-classic.d.ts", + "lib/react-relay-modern.d.ts", + "lib/react-relay-compat.d.ts" + ] +} diff --git a/types/react-relay/tslint.json b/types/react-relay/v1/tslint.json similarity index 100% rename from types/react-relay/tslint.json rename to types/react-relay/v1/tslint.json diff --git a/types/relay-runtime/index.d.ts b/types/relay-runtime/index.d.ts index 2bd9938b0c..152df90640 100644 --- a/types/relay-runtime/index.d.ts +++ b/types/relay-runtime/index.d.ts @@ -4,1129 +4,1127 @@ // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped // TypeScript Version: 2.4 -// note: __Relay namespace is used so react-relay can access and inter-op -declare namespace __Relay { - namespace Common { - /** - * SOURCE: - * Relay 1.3.0 - * https://github.com/facebook/relay/blob/b85a1d69bb72be4ace67179f55c2a54a8d761c8b/packages/react-relay/classic/environment/RelayCombinedEnvironmentTypes.js - */ - // ~~~~~~~~~~~~~~~~~~~~~ - // Maybe Fix - // ~~~~~~~~~~~~~~~~~~~~~ - type RelayConcreteNode = any; - type RelayMutationTransaction = any; - type RelayMutationRequest = any; - type RelayQueryRequest = any; - type ConcreteFragment = any; - type ConcreteBatch = any; - type ConcreteFragmentDefinition = object; - type ConcreteOperationDefinition = object; +// note: namespace is used so react-relay can access and inter-op +export namespace RelayCommonTypes { + /** + * SOURCE: + * Relay 1.3.0 + * https://github.com/facebook/relay/blob/b85a1d69bb72be4ace67179f55c2a54a8d761c8b/packages/react-relay/classic/environment/RelayCombinedEnvironmentTypes.js + */ + // ~~~~~~~~~~~~~~~~~~~~~ + // Maybe Fix + // ~~~~~~~~~~~~~~~~~~~~~ + type RelayConcreteNode = any; + type RelayMutationTransaction = any; + type RelayMutationRequest = any; + type RelayQueryRequest = any; + type ConcreteFragment = any; + type ConcreteBatch = any; + type ConcreteFragmentDefinition = object; + type ConcreteOperationDefinition = object; - /** - * FIXME: RelayContainer used to be typed with ReactClass, but - * ReactClass is broken and allows for access to any property. For example - * ReactClass.getFragment('foo') is valid even though ReactClass has no - * such getFragment() type definition. When ReactClass is fixed this causes a - * lot of errors in Relay code since methods like getFragment() are used often - * but have no definition in Relay's types. Suppressing for now. - */ - type RelayContainer = any; + /** + * FIXME: RelayContainer used to be typed with ReactClass, but + * ReactClass is broken and allows for access to any property. For example + * ReactClass.getFragment('foo') is valid even though ReactClass has no + * such getFragment() type definition. When ReactClass is fixed this causes a + * lot of errors in Relay code since methods like getFragment() are used often + * but have no definition in Relay's types. Suppressing for now. + */ + type RelayContainer = any; - // ~~~~~~~~~~~~~~~~~~~~~ - // RelayQL - // ~~~~~~~~~~~~~~~~~~~~~ - type RelayQL = ( - strings: string[], - ...substitutions: any[] - ) => RelayConcreteNode; + // ~~~~~~~~~~~~~~~~~~~~~ + // RelayQL + // ~~~~~~~~~~~~~~~~~~~~~ + type RelayQL = ( + strings: string[], + ...substitutions: any[] + ) => RelayConcreteNode; - // ~~~~~~~~~~~~~~~~~~~~~ - // RelayModernGraphQLTag - // ~~~~~~~~~~~~~~~~~~~~~ - interface GeneratedNodeMap { - [key: string]: GraphQLTaggedNode; - } - type GraphQLTaggedNode = - (() => ConcreteFragment | ConcreteBatch) | - { - modern(): ConcreteFragment | ConcreteBatch, - classic(relayQL: RelayQL): - | ConcreteFragmentDefinition - | ConcreteOperationDefinition, - }; - // ~~~~~~~~~~~~~~~~~~~~~ - // General Usage - // ~~~~~~~~~~~~~~~~~~~~~ - type DataID = string; - interface Variables { - [name: string]: any; - } - type Uploadable = File | Blob; - interface UploadableMap { - [key: string]: Uploadable; - } - - // ~~~~~~~~~~~~~~~~~~~~~ - // RelayNetworkTypes - // Version: Relay 1.3.0 - // File: https://github.com/facebook/relay/blob/master/packages/relay-runtime/network/RelayNetworkTypes.js - // ~~~~~~~~~~~~~~~~~~~~~ - - interface LegacyObserver { - onCompleted?(): void; - onError?(error: Error): void; - onNext?(data: T): void; - } - interface PayloadError { - message: string; - locations?: Array<{ - line: number, - column: number, - }>; - } - /** - * A function that executes a GraphQL operation with request/response semantics. - * - * May return an Observable or Promise of a raw server response. - */ - function FetchFunction( - operation: ConcreteBatch, - variables: Variables, - cacheConfig: CacheConfig, - uploadables?: UploadableMap, - ): Runtime.ObservableFromValue; - - /** - * A function that executes a GraphQL subscription operation, returning one or - * more raw server responses over time. - * - * May return an Observable, otherwise must call the callbacks found in the - * fourth parameter. - */ - type SubscribeFunction = ( - operation: ConcreteBatch, - variables: Variables, - cacheConfig: CacheConfig, - observer: LegacyObserver, - ) => Runtime.RelayObservable | Disposable; - - // ~~~~~~~~~~~~~~~~~~~~~ - // RelayStoreTypes - // Version: Relay 1.3.0 - // File: https://github.com/facebook/relay/blob/master/packages/relay-runtime/store/RelayStoreTypes.js - // ~~~~~~~~~~~~~~~~~~~~~ - /** - * A function that receives a proxy over the store and may trigger side-effects - * (indirectly) by calling `set*` methods on the store or its record proxies. - */ - type StoreUpdater = (store: RecordSourceProxy) => void; - - /** - * Similar to StoreUpdater, but accepts a proxy tied to a specific selector in - * order to easily access the root fields of a query/mutation as well as a - * second argument of the response object of the mutation. - */ - type SelectorStoreUpdater = ( - store: RecordSourceSelectorProxy, - // Actually RelayCombinedEnvironmentTypes#SelectorData, but mixed is - // inconvenient to access deeply in product code. - data: any, // FLOW FIXME - ) => void; - - /** - * Extends the RecordSourceProxy interface with methods for accessing the root - * fields of a Selector. - */ - interface RecordSourceSelectorProxy { - create(dataID: DataID, typeName: string): RecordProxy; - delete(dataID: DataID): void; - get(dataID: DataID): RecordProxy | void; - getRoot(): RecordProxy; - getRootField(fieldName: string): RecordProxy | void; - getPluralRootField(fieldName: string): RecordProxy[] | void; - } - - interface RecordProxy { - copyFieldsFrom(source: RecordProxy): void; - getDataID(): DataID; - getLinkedRecord(name: string, args?: Variables): RecordProxy | void; - getLinkedRecords(name: string, args?: Variables): Array | void; - getOrCreateLinkedRecord( - name: string, - typeName: string, - args?: Variables, - ): RecordProxy; - getType(): string; - getValue(name: string, args?: Variables): any; - setLinkedRecord( - record: RecordProxy, - name: string, - args?: Variables, - ): RecordProxy; - setLinkedRecords( - records: Array | undefined | null, - name: string, - args?: Variables, - ): RecordProxy; - setValue(value: any, name: string, args?: Variables): RecordProxy; - } - - interface RecordSourceProxy { - create(dataID: DataID, typeName: string): RecordProxy; - delete(dataID: DataID): void; - get(dataID: DataID): Array | void; - getRoot(): RecordProxy; - } - - interface HandleFieldPayload { - // The arguments that were fetched. - args: Variables; - // The __id of the record containing the source/handle field. - dataID: DataID; - // The (storage) key at which the original server data was written. - fieldKey: string; - // The name of the handle - handle: string; - // The (storage) key at which the handle's data should be written by the - // handler - handleKey: string; - } - interface HandlerInterface { - update(store: RecordSourceProxy, fieldPayload: HandleFieldPayload): void; - [functionName: string]: (...args: any[]) => any; - } - const Handler: HandlerInterface; - - // ~~~~~~~~~~~~~~~~~~~~~ - // RelayCombinedEnvironmentTypes - // Version: Relay 1.3.0 - // File: https://github.com/facebook/relay/blob/b85a1d69bb72be4ace67179f55c2a54a8d761c8b/packages/react-relay/classic/environment/RelayCombinedEnvironmentTypes.js - // ~~~~~~~~~~~~~~~~~~~~~ - /** - * Settings for how a query response may be cached. - * - * - `force`: causes a query to be issued unconditionally, irrespective of the - * state of any configured response cache. - * - `poll`: causes a query to live update by polling at the specified interval - * in milliseconds. (This value will be passed to setTimeout.) - */ - interface CacheConfig { - force?: boolean; - poll?: number; - } - - /** - * Represents any resource that must be explicitly disposed of. The most common - * use-case is as a return value for subscriptions, where calling `dispose()` - * would cancel the subscription. - */ - interface Disposable { - dispose(): void; - } - - /** - * Arbitrary data e.g. received by a container as props. - */ - interface Props { [key: string]: any; } - - /* - * An individual cached graph object. - */ - interface Record { [key: string]: any; } - - /** - * A collection of records keyed by id. - */ - interface RecordMap { [dataID: string]: Record | null | undefined; } - - /** - * A selector defines the starting point for a traversal into the graph for the - * purposes of targeting a subgraph. - */ - interface CSelector { - dataID: DataID; - node: TNode; - variables: Variables; - } - - /** - * A representation of a selector and its results at a particular point in time. - */ - type CSnapshot = CSelector & { - data: SelectorData | null | undefined, - seenRecords: RecordMap, + // ~~~~~~~~~~~~~~~~~~~~~ + // RelayModernGraphQLTag + // ~~~~~~~~~~~~~~~~~~~~~ + interface GeneratedNodeMap { + [key: string]: GraphQLTaggedNode; + } + type GraphQLTaggedNode = + (() => ConcreteFragment | ConcreteBatch) | + { + modern(): ConcreteFragment | ConcreteBatch, + classic(relayQL: RelayQL): + | ConcreteFragmentDefinition + | ConcreteOperationDefinition, }; + // ~~~~~~~~~~~~~~~~~~~~~ + // General Usage + // ~~~~~~~~~~~~~~~~~~~~~ + type DataID = string; + interface Variables { + [name: string]: any; + } + type Uploadable = File | Blob; + interface UploadableMap { + [key: string]: Uploadable; + } + // ~~~~~~~~~~~~~~~~~~~~~ + // RelayNetworkTypes + // Version: Relay 1.3.0 + // File: https://github.com/facebook/relay/blob/master/packages/relay-runtime/network/RelayNetworkTypes.js + // ~~~~~~~~~~~~~~~~~~~~~ + + interface LegacyObserver { + onCompleted?(): void; + onError?(error: Error): void; + onNext?(data: T): void; + } + interface PayloadError { + message: string; + locations?: Array<{ + line: number, + column: number, + }>; + } + /** + * A function that executes a GraphQL operation with request/response semantics. + * + * May return an Observable or Promise of a raw server response. + */ + function FetchFunction( + operation: ConcreteBatch, + variables: Variables, + cacheConfig: CacheConfig, + uploadables?: UploadableMap, + ): Runtime.ObservableFromValue; + + /** + * A function that executes a GraphQL subscription operation, returning one or + * more raw server responses over time. + * + * May return an Observable, otherwise must call the callbacks found in the + * fourth parameter. + */ + type SubscribeFunction = ( + operation: ConcreteBatch, + variables: Variables, + cacheConfig: CacheConfig, + observer: LegacyObserver, + ) => Runtime.RelayObservable | Disposable; + + // ~~~~~~~~~~~~~~~~~~~~~ + // RelayStoreTypes + // Version: Relay 1.3.0 + // File: https://github.com/facebook/relay/blob/master/packages/relay-runtime/store/RelayStoreTypes.js + // ~~~~~~~~~~~~~~~~~~~~~ + /** + * A function that receives a proxy over the store and may trigger side-effects + * (indirectly) by calling `set*` methods on the store or its record proxies. + */ + type StoreUpdater = (store: RecordSourceProxy) => void; + + /** + * Similar to StoreUpdater, but accepts a proxy tied to a specific selector in + * order to easily access the root fields of a query/mutation as well as a + * second argument of the response object of the mutation. + */ + type SelectorStoreUpdater = ( + store: RecordSourceSelectorProxy, + // Actually RelayCombinedEnvironmentTypes#SelectorData, but mixed is + // inconvenient to access deeply in product code. + data: any, // FLOW FIXME + ) => void; + + /** + * Extends the RecordSourceProxy interface with methods for accessing the root + * fields of a Selector. + */ + interface RecordSourceSelectorProxy { + create(dataID: DataID, typeName: string): RecordProxy; + delete(dataID: DataID): void; + get(dataID: DataID): RecordProxy | void; + getRoot(): RecordProxy; + getRootField(fieldName: string): RecordProxy | void; + getPluralRootField(fieldName: string): RecordProxy[] | void; + } + + interface RecordProxy { + copyFieldsFrom(source: RecordProxy): void; + getDataID(): DataID; + getLinkedRecord(name: string, args?: Variables): RecordProxy | void; + getLinkedRecords(name: string, args?: Variables): Array | void; + getOrCreateLinkedRecord( + name: string, + typeName: string, + args?: Variables, + ): RecordProxy; + getType(): string; + getValue(name: string, args?: Variables): any; + setLinkedRecord( + record: RecordProxy, + name: string, + args?: Variables, + ): RecordProxy; + setLinkedRecords( + records: Array | undefined | null, + name: string, + args?: Variables, + ): RecordProxy; + setValue(value: any, name: string, args?: Variables): RecordProxy; + } + + interface RecordSourceProxy { + create(dataID: DataID, typeName: string): RecordProxy; + delete(dataID: DataID): void; + get(dataID: DataID): Array | void; + getRoot(): RecordProxy; + } + + interface HandleFieldPayload { + // The arguments that were fetched. + args: Variables; + // The __id of the record containing the source/handle field. + dataID: DataID; + // The (storage) key at which the original server data was written. + fieldKey: string; + // The name of the handle + handle: string; + // The (storage) key at which the handle's data should be written by the + // handler + handleKey: string; + } + interface HandlerInterface { + update(store: RecordSourceProxy, fieldPayload: HandleFieldPayload): void; + [functionName: string]: (...args: any[]) => any; + } + const Handler: HandlerInterface; + + // ~~~~~~~~~~~~~~~~~~~~~ + // RelayCombinedEnvironmentTypes + // Version: Relay 1.3.0 + // File: https://github.com/facebook/relay/blob/b85a1d69bb72be4ace67179f55c2a54a8d761c8b/packages/react-relay/classic/environment/RelayCombinedEnvironmentTypes.js + // ~~~~~~~~~~~~~~~~~~~~~ + /** + * Settings for how a query response may be cached. + * + * - `force`: causes a query to be issued unconditionally, irrespective of the + * state of any configured response cache. + * - `poll`: causes a query to live update by polling at the specified interval + * in milliseconds. (This value will be passed to setTimeout.) + */ + interface CacheConfig { + force?: boolean; + poll?: number; + } + + /** + * Represents any resource that must be explicitly disposed of. The most common + * use-case is as a return value for subscriptions, where calling `dispose()` + * would cancel the subscription. + */ + interface Disposable { + dispose(): void; + } + + /** + * Arbitrary data e.g. received by a container as props. + */ + interface Props { [key: string]: any; } + + /* + * An individual cached graph object. + */ + interface Record { [key: string]: any; } + + /** + * A collection of records keyed by id. + */ + interface RecordMap { [dataID: string]: Record | null | undefined; } + + /** + * A selector defines the starting point for a traversal into the graph for the + * purposes of targeting a subgraph. + */ + interface CSelector { + dataID: DataID; + node: TNode; + variables: Variables; + } + + /** + * A representation of a selector and its results at a particular point in time. + */ + type CSnapshot = CSelector & { + data: SelectorData | null | undefined, + seenRecords: RecordMap, + }; + + /** + * The results of a selector given a store/RecordSource. + */ + interface SelectorData { [key: string]: any; } + + /** + * The results of reading the results of a FragmentMap given some input + * `Props`. + */ + interface FragmentSpecResults { [key: string]: any; } + + /** + * A utility for resolving and subscribing to the results of a fragment spec + * (key -> fragment mapping) given some "props" that determine the root ID + * and variables to use when reading each fragment. When props are changed via + * `setProps()`, the resolver will update its results and subscriptions + * accordingly. Internally, the resolver: + * - Converts the fragment map & props map into a map of `Selector`s. + * - Removes any resolvers for any props that became null. + * - Creates resolvers for any props that became non-null. + * - Updates resolvers with the latest props. + */ + interface FragmentSpecResolver { /** - * The results of a selector given a store/RecordSource. + * Stop watching for changes to the results of the fragments. */ - interface SelectorData { [key: string]: any; } + dispose(): void; /** - * The results of reading the results of a FragmentMap given some input - * `Props`. + * Get the current results. */ - interface FragmentSpecResults { [key: string]: any; } + resolve(): FragmentSpecResults; /** - * A utility for resolving and subscribing to the results of a fragment spec - * (key -> fragment mapping) given some "props" that determine the root ID - * and variables to use when reading each fragment. When props are changed via - * `setProps()`, the resolver will update its results and subscriptions - * accordingly. Internally, the resolver: - * - Converts the fragment map & props map into a map of `Selector`s. - * - Removes any resolvers for any props that became null. - * - Creates resolvers for any props that became non-null. - * - Updates resolvers with the latest props. + * Update the resolver with new inputs. Call `resolve()` to get the updated + * results. */ - interface FragmentSpecResolver { - /** - * Stop watching for changes to the results of the fragments. - */ - dispose(): void; - - /** - * Get the current results. - */ - resolve(): FragmentSpecResults; - - /** - * Update the resolver with new inputs. Call `resolve()` to get the updated - * results. - */ - setProps(props: Props): void; - - /** - * Override the variables used to read the results of the fragments. Call - * `resolve()` to get the updated results. - */ - setVariables(variables: Variables): void; - } - - interface CFragmentMap { [key: string]: TFragment; } + setProps(props: Props): void; /** - * An operation selector describes a specific instance of a GraphQL operation - * with variables applied. + * Override the variables used to read the results of the fragments. Call + * `resolve()` to get the updated results. + */ + setVariables(variables: Variables): void; + } + + interface CFragmentMap { [key: string]: TFragment; } + + /** + * An operation selector describes a specific instance of a GraphQL operation + * with variables applied. + * + * - `root`: a selector intended for processing server results or retaining + * response data in the store. + * - `fragment`: a selector intended for use in reading or subscribing to + * the results of the the operation. + */ + interface COperationSelector { + fragment: CSelector; + node: TOperation; + root: CSelector; + variables: Variables; + } + + /** + * The public API of Relay core. Represents an encapsulated environment with its + * own in-memory cache. + */ + interface CEnvironment< + TEnvironment, + TFragment, + TGraphQLTaggedNode, + TNode, + TOperation, + TPayload, + > { + /** + * Read the results of a selector from in-memory records in the store. + */ + lookup(selector: CSelector): CSnapshot; + + /** + * Subscribe to changes to the results of a selector. The callback is called + * when data has been committed to the store that would cause the results of + * the snapshot's selector to change. + */ + subscribe( + snapshot: CSnapshot, + callback: (snapshot: CSnapshot) => void, + ): Disposable; + + /** + * Ensure that all the records necessary to fulfill the given selector are + * retained in-memory. The records will not be eligible for garbage collection + * until the returned reference is disposed. * - * - `root`: a selector intended for processing server results or retaining - * response data in the store. - * - `fragment`: a selector intended for use in reading or subscribing to - * the results of the the operation. + * Note: This is a no-op in the classic core. */ - interface COperationSelector { - fragment: CSelector; - node: TOperation; - root: CSelector; - variables: Variables; - } + retain(selector: CSelector): Disposable; /** - * The public API of Relay core. Represents an encapsulated environment with its - * own in-memory cache. + * Send a query to the server with request/response semantics: the query will + * either complete successfully (calling `onNext` and `onCompleted`) or fail + * (calling `onError`). + * + * Note: Most applications should use `streamQuery` in order to + * optionally receive updated information over time, should that feature be + * supported by the network/server. A good rule of thumb is to use this method + * if you would otherwise immediately dispose the `streamQuery()` + * after receving the first `onNext` result. */ - interface CEnvironment< + sendQuery(config: { + cacheConfig?: CacheConfig, + onCompleted?(): void, + onError?(error: Error): void, + onNext?(payload: TPayload): void, + operation: COperationSelector, + }): Disposable; + + /** + * Send a query to the server with request/subscription semantics: one or more + * responses may be returned (via `onNext`) over time followed by either + * the request completing (`onCompleted`) or an error (`onError`). + * + * Networks/servers that support subscriptions may choose to hold the + * subscription open indefinitely such that `onCompleted` is not called. + */ + streamQuery(config: { + cacheConfig?: CacheConfig, + onCompleted?(): void, + onError?(error: Error): void, + onNext?(payload: TPayload): void, + operation: COperationSelector, + }): Disposable; + + unstable_internal: CUnstableEnvironmentCore< TEnvironment, TFragment, TGraphQLTaggedNode, TNode, - TOperation, - TPayload, - > { - /** - * Read the results of a selector from in-memory records in the store. - */ - lookup(selector: CSelector): CSnapshot; - - /** - * Subscribe to changes to the results of a selector. The callback is called - * when data has been committed to the store that would cause the results of - * the snapshot's selector to change. - */ - subscribe( - snapshot: CSnapshot, - callback: (snapshot: CSnapshot) => void, - ): Disposable; - - /** - * Ensure that all the records necessary to fulfill the given selector are - * retained in-memory. The records will not be eligible for garbage collection - * until the returned reference is disposed. - * - * Note: This is a no-op in the classic core. - */ - retain(selector: CSelector): Disposable; - - /** - * Send a query to the server with request/response semantics: the query will - * either complete successfully (calling `onNext` and `onCompleted`) or fail - * (calling `onError`). - * - * Note: Most applications should use `streamQuery` in order to - * optionally receive updated information over time, should that feature be - * supported by the network/server. A good rule of thumb is to use this method - * if you would otherwise immediately dispose the `streamQuery()` - * after receving the first `onNext` result. - */ - sendQuery(config: { - cacheConfig?: CacheConfig, - onCompleted?(): void, - onError?(error: Error): void, - onNext?(payload: TPayload): void, - operation: COperationSelector, - }): Disposable; - - /** - * Send a query to the server with request/subscription semantics: one or more - * responses may be returned (via `onNext`) over time followed by either - * the request completing (`onCompleted`) or an error (`onError`). - * - * Networks/servers that support subscriptions may choose to hold the - * subscription open indefinitely such that `onCompleted` is not called. - */ - streamQuery(config: { - cacheConfig?: CacheConfig, - onCompleted?(): void, - onError?(error: Error): void, - onNext?(payload: TPayload): void, - operation: COperationSelector, - }): Disposable; - - unstable_internal: CUnstableEnvironmentCore< - TEnvironment, - TFragment, - TGraphQLTaggedNode, - TNode, - TOperation - >; - } - - interface CUnstableEnvironmentCore< - TEnvironment, - TFragment, - TGraphQLTaggedNode, - TNode, - TOperation, - > { - /** - * Create an instance of a FragmentSpecResolver. - * - * TODO: The FragmentSpecResolver *can* be implemented via the other methods - * defined here, so this could be moved out of core. It's convenient to have - * separate implementations until the experimental core is in OSS. - */ - createFragmentSpecResolver( - context: CRelayContext, - containerName: string, - fragments: CFragmentMap, - props: Props, - callback: () => void, - ): FragmentSpecResolver; - - /** - * Creates an instance of an OperationSelector given an operation definition - * (see `getOperation`) and the variables to apply. The input variables are - * filtered to exclude variables that do not matche defined arguments on the - * operation, and default values are populated for null values. - */ - createOperationSelector( - operation: TOperation, - variables: Variables, - ): COperationSelector; - - /** - * Given a graphql`...` tagged template, extract a fragment definition usable - * by this version of Relay core. Throws if the value is not a fragment. - */ - getFragment(node: TGraphQLTaggedNode): TFragment; - - /** - * Given a graphql`...` tagged template, extract an operation definition - * usable by this version of Relay core. Throws if the value is not an - * operation. - */ - getOperation(node: TGraphQLTaggedNode): TOperation; - - /** - * Determine if two selectors are equal (represent the same selection). Note - * that this function returns `false` when the two queries/fragments are - * different objects, even if they select the same fields. - */ - areEqualSelectors(a: CSelector, b: CSelector): boolean; - - /** - * Given the result `item` from a parent that fetched `fragment`, creates a - * selector that can be used to read the results of that fragment for that item. - * - * Example: - * - * Given two fragments as follows: - * - * ``` - * fragment Parent on User { - * id - * ...Child - * } - * fragment Child on User { - * name - * } - * ``` - * - * And given some object `parent` that is the results of `Parent` for id "4", - * the results of `Child` can be accessed by first getting a selector and then - * using that selector to `lookup()` the results against the environment: - * - * ``` - * const childSelector = getSelector(queryVariables, Child, parent); - * const childData = environment.lookup(childSelector).data; - * ``` - */ - getSelector( - operationVariables: Variables, - fragment: TFragment, - prop: any, - ): CSelector | void; - - /** - * Given the result `items` from a parent that fetched `fragment`, creates a - * selector that can be used to read the results of that fragment on those - * items. This is similar to `getSelector` but for "plural" fragments that - * expect an array of results and therefore return an array of selectors. - */ - getSelectorList( - operationVariables: Variables, - fragment: TFragment, - props: any[], - ): Array> | void; - - /** - * Given a mapping of keys -> results and a mapping of keys -> fragments, - * extracts the selectors for those fragments from the results. - * - * The canonical use-case for this function are Relay Containers, which - * use this function to convert (props, fragments) into selectors so that they - * can read the results to pass to the inner component. - */ - getSelectorsFromObject( - operationVariables: Variables, - fragments: CFragmentMap, - props: Props, - ): { [key: string]: CSelector | Array> | null | undefined }; - - /** - * Given a mapping of keys -> results and a mapping of keys -> fragments, - * extracts a mapping of keys -> id(s) of the results. - * - * Similar to `getSelectorsFromObject()`, this function can be useful in - * determining the "identity" of the props passed to a component. - */ - getDataIDsFromObject( - fragments: CFragmentMap, - props: Props, - ): { [key: string]: DataID | DataID[] | null | undefined }; - - /** - * Given a mapping of keys -> results and a mapping of keys -> fragments, - * extracts the merged variables that would be in scope for those - * fragments/results. - * - * This can be useful in determing what varaibles were used to fetch the data - * for a Relay container, for example. - */ - getVariablesFromObject( - operationVariables: Variables, - fragments: CFragmentMap, - props: Props, - ): Variables; - } - - /** - * The type of the `relay` property set on React context by the React/Relay - * integration layer (e.g. QueryRenderer, FragmentContainer, etc). - */ - interface CRelayContext { - environment: TEnvironment; - variables: Variables; - } - - // ~~~~~~~~~~~~~~~~~~~~~ - // RelayTypes - /** - * Version: Relay 1.3.0 - * File: - * https://github.com/facebook/relay/blob/fa9f48ea209ee2402d433b59a84d1cbc046574e2/packages/react-relay/classic/tools/RelayTypes.js - */ - // ~~~~~~~~~~~~~~~~~~~~~ - interface RerunParam { - param: string; - import: string; - max_runs: number; - } - interface FIELDS_CHANGE { - type: 'FIELDS_CHANGE'; - fieldIDs: { [fieldName: string]: DataID | DataID[]; }; - } - interface RANGE_ADD { - type: 'RANGE_ADD'; - parentName?: string; - parentID?: string; - connectionInfo?: Array<{ - key: string, - filters?: Variables, - rangeBehavior: string, - }>; - connectionName?: string; - edgeName: string; - rangeBehaviors?: RangeBehaviors; - } - interface NODE_DELETE { - type: 'NODE_DELETE'; - parentName?: string; - parentID?: string; - connectionName?: string; - deletedIDFieldName: string; - } - interface RANGE_DELETE { - type: 'RANGE_DELETE'; - parentName?: string; - parentID?: string; - connectionKeys?: Array<{ - key: string, - filters?: Variables, - }>; - connectionName?: string; - deletedIDFieldName: string | string[]; - pathToConnection: string[]; - } - interface REQUIRED_CHILDREN { - type: 'REQUIRED_CHILDREN'; - children: RelayConcreteNode[]; - } - type RelayMutationConfig = - FIELDS_CHANGE | - RANGE_ADD | - NODE_DELETE | - RANGE_DELETE | - REQUIRED_CHILDREN; - - interface RelayMutationTransactionCommitCallbacks { - onFailure?: RelayMutationTransactionCommitFailureCallback; - onSuccess?: RelayMutationTransactionCommitSuccessCallback; - } - type RelayMutationTransactionCommitFailureCallback = ( - transaction: RelayMutationTransaction, - preventAutoRollback: () => void, - ) => void; - type RelayMutationTransactionCommitSuccessCallback = (response: { - [key: string]: any, - }) => void; - interface NetworkLayer { - sendMutation(request: RelayMutationRequest): Promise | void; - sendQueries(requests: RelayQueryRequest[]): Promise | void; - supports(...options: string[]): boolean; - } - interface QueryResult { - error?: Error; - ref_params?: { [name: string]: any }; - response: QueryPayload; - } - interface ReadyState { - aborted: boolean; - done: boolean; - error: Error | null; - events: ReadyStateEvent[]; - ready: boolean; - stale: boolean; - } - type RelayContainerErrorEventType = - | 'CACHE_RESTORE_FAILED' - | 'NETWORK_QUERY_ERROR'; - type RelayContainerLoadingEventType = - | 'ABORT' - | 'CACHE_RESTORED_REQUIRED' - | 'CACHE_RESTORE_START' - | 'NETWORK_QUERY_RECEIVED_ALL' - | 'NETWORK_QUERY_RECEIVED_REQUIRED' - | 'NETWORK_QUERY_START' - | 'STORE_FOUND_ALL' - | 'STORE_FOUND_REQUIRED'; - type ReadyStateChangeCallback = (readyState: ReadyState) => void; - interface ReadyStateEvent { - type: RelayContainerLoadingEventType | RelayContainerErrorEventType; - error?: Error; - } - interface Abortable { - abort(): void; - } - - // ~~~~~~~~~~~~~~~~~~~~~ - // RelayInternalTypes - /** - * Version: Relay 1.3.0 - * File: - * https://github.com/facebook/relay/blob/master/packages/react-relay/classic/tools/RelayInternalTypes.js - */ - // ~~~~~~~~~~~~~~~~~~~~~ - interface QueryPayload { [key: string]: any; } - interface RelayQuerySet { [queryName: string]: any; } - type RangeBehaviorsFunction = (connectionArgs: { - [argName: string]: any, - }) => 'APPEND' | 'IGNORE' | 'PREPEND' | 'REFETCH' | 'REMOVE'; - interface RangeBehaviorsObject { - [key: string]: 'APPEND' | 'IGNORE' | 'PREPEND' | 'REFETCH' | 'REMOVE'; - } - type RangeBehaviors = RangeBehaviorsFunction | RangeBehaviorsObject; + TOperation + >; } - namespace Runtime { - // ~~~~~~~~~~~~~~~~~~~~~ - // Maybe Fix - // ~~~~~~~~~~~~~~~~~~~~~ - type RelayDebugger = any; - type OptimisticUpdate = any; - type OperationSelector = Common.COperationSelector; - type Selector = Common.CSelector; - type PayloadData = any; - type Snapshot = Common.CSnapshot; - type RelayResponsePayload = any; - type MutableRecordSource = RecordSource; - + interface CUnstableEnvironmentCore< + TEnvironment, + TFragment, + TGraphQLTaggedNode, + TNode, + TOperation, + > { /** - * A function that returns an Observable representing the response of executing - * a GraphQL operation. - */ - type ExecuteFunction = ( - operation: object, - variables: Common.Variables, - cacheConfig: Common.CacheConfig, - uploadables?: Common.UploadableMap, - ) => Promise; - interface RelayNetwork { - execute: ExecuteFunction; - } - - // ~~~~~~~~~~~~~~~~~~~~~ - // RelayDefaultHandlerProvider - // ~~~~~~~~~~~~~~~~~~~~~ - function HandlerProvider(name: string): typeof Common.Handler | void; - - // ~~~~~~~~~~~~~~~~~~~~~ - // RelayModernEnvironment - // ~~~~~~~~~~~~~~~~~~~~~ - interface EnvironmentConfig { - configName?: string; - handlerProvider?: typeof HandlerProvider; - network: Network; - store: Store; - } - class Environment { - constructor(config: EnvironmentConfig); - getStore(): Store; - getDebugger(): RelayDebugger; - applyUpdate(optimisticUpdate: OptimisticUpdate): Common.Disposable; - revertUpdate(update: OptimisticUpdate): void; - replaceUpdate(update: OptimisticUpdate, newUpdate: OptimisticUpdate): void; - applyMutation(config: { - operation: OperationSelector, - optimisticUpdater?: Common.SelectorStoreUpdater, - optimisticResponse?: object, - }): Common.Disposable; - check(readSelector: Selector): boolean; - commitPayload( - operationSelector: OperationSelector, - payload: PayloadData, - ): void; - commitUpdate(updater: Common.StoreUpdater): void; - lookup(readSelector: Selector): Snapshot; - subscribe( - snapshot: Snapshot, - callback: (snapshot: Snapshot) => void, - ): Common.Disposable; - retain(selector: Selector): Common.Disposable; - execute(config: { - operation: OperationSelector, - cacheConfig?: Common.CacheConfig, - updater?: Common.SelectorStoreUpdater, - }): RelayObservable; - executeMutation(config: { - operation: OperationSelector, - optimisticUpdater?: Common.SelectorStoreUpdater, - optimisticResponse?: object, - updater?: Common.SelectorStoreUpdater, - uploadables?: Common.UploadableMap, - }): RelayObservable; - } - - // ~~~~~~~~~~~~~~~~~~~~~ - // RelayInMemoryRecordSource - // ~~~~~~~~~~~~~~~~~~~~~ - interface Record { [key: string]: any; } - interface RecordMap { [dataID: string]: Record | null | undefined; } - - // ~~~~~~~~~~~~~~~~~~~~~ - // Network - // ~~~~~~~~~~~~~~~~~~~~~ - class Network { - /** - * Creates an implementation of the `Network` interface defined in - * `RelayNetworkTypes` given `fetch` and `subscribe` functions. - */ - static create(fetchFn: typeof Common.FetchFunction, subscribeFn?: Common.SubscribeFunction): RelayNetwork; - } - - // ~~~~~~~~~~~~~~~~~~~~~ - // Network - // ~~~~~~~~~~~~~~~~~~~~~ - class RecordSource { - constructor(records?: RecordMap); - clear(): void; - delete(dataID: Common.DataID): void; - get(dataID: Common.DataID): Record | void; - getRecordIDs(): Common.DataID[]; - getStatus(dataID: Common.DataID): 'EXISTENT' | 'NONEXISTENT' | 'UNKNOWN'; - has(dataID: Common.DataID): boolean; - load( - dataID: Common.DataID, - callback: (error: Error | null, record: Record | null) => void, - ): void; - remove(dataID: Common.DataID): void; - set(dataID: Common.DataID, record: Record): void; - size(): number; - toJSON(): RecordMap; - } - - // ~~~~~~~~~~~~~~~~~~~~~ - // ModernStore - // ~~~~~~~~~~~~~~~~~~~~~ - class Store { - constructor(source: RecordSource); - getSource(): MutableRecordSource; - check(selector: Selector): boolean; - retain(selector: Selector): Common.Disposable; - lookup(selector: Selector): Snapshot; - notify(): void; - publish(source: RecordSource): void; - subscribe( - snapshot: Snapshot, - callback: (snapshot: Snapshot) => void, - ): Common.Disposable; - } - - // ~~~~~~~~~~~~~~~~~~~~~ - // RelayRecordSourceInspector - // ~~~~~~~~~~~~~~~~~~~~~ - /** - * An internal class to provide a console-friendly string representation of a - * Record. - */ - class RecordSummary { - id: Common.DataID; - type: string | null | undefined; - static createFromRecord(id: Common.DataID, record: any): RecordSummary; - constructor(id: Common.DataID, type: string | null | undefined); - toString(): string; - } - /** - * Internal class for inspecting a single Record. - */ - class RecordInspector { - constructor(sourceInspector: RelayRecordSourceInspector, record: Record); - /** - * Get the cache id of the given record. For types that implement the `Node` - * interface (or that have an `id`) this will be `id`, for other types it will be - * a synthesized identifier based on the field path from the nearest ancestor - * record that does have an `id`. - */ - getDataID(): Common.DataID; - - /** - * Returns a list of the fields that have been fetched on the current record. - */ - getFields(): string[]; - - /** - * Returns the type of the record. - */ - getType(): string; - - /** - * Returns a copy of the internal representation of the record. - */ - inspect(): any; - - /** - * Returns the value of a scalar field. May throw if the given field is - * present but not actually scalar. - */ - getValue(name: string, args?: Common.Variables): any; - - /** - * Returns an inspector for the given scalar "linked" field (a field whose - * value is another Record instead of a scalar). May throw if the field is - * present but not a scalar linked record. - */ - getLinkedRecord(name: string, args?: Common.Variables): RecordInspector | void; - - /** - * Returns an array of inspectors for the given plural "linked" field (a field - * whose value is an array of Records instead of a scalar). May throw if the - * field is present but not a plural linked record. - */ - getLinkedRecords(name: string, args?: Common.Variables): RecordInspector[] | void; - } - - class RelayRecordSourceInspector { - constructor(source: RecordSource); - static getForEnvironment(environment: Environment): RelayRecordSourceInspector; - /** - * Returns an inspector for the record with the given id, or null/undefined if - * that record is deleted/unfetched. - */ - get(dataID: Common.DataID): RecordInspector | void; - /** - * Returns a list of ": " for each record in the store that has an - * `id`. - */ - getNodes(): RecordSummary[]; - /** - * Returns a list of ": " for all records in the store including - * those that do not have an `id`. - */ - getRecords(): RecordSummary[]; - - /** - * Returns an inspector for the synthesized "root" object, allowing access to - * e.g. the `viewer` object or the results of other fields on the "Query" - * type. - */ - getRoot(): RecordInspector; - } - - // ~~~~~~~~~~~~~~~~~~~~~ - // RelayObservable - // ~~~~~~~~~~~~~~~~~~~~~ - interface Subscription { - unsubscribe(): void; - readonly closed: boolean; - } - interface Observer { - start?(subscription: Subscription): any; - next?(nextThing: T): any; - error?(error: Error): any; - complete?(): any; - unsubscribe?(subscription: Subscription): any; - } - type Source = () => any; - interface Subscribable { - subscribe(observer: Observer): Subscription; - } - type ObservableFromValue = RelayObservable | Promise | T; - class RelayObservable implements Subscribable { - _source: Source; - - constructor(source: Source); - - /** - * When an unhandled error is detected, it is reported to the host environment - * (the ESObservable spec refers to this method as "HostReportErrors()"). - * - * The default implementation in development builds re-throws errors in a - * separate frame, and from production builds does nothing (swallowing - * uncaught errors). - * - * Called during application initialization, this method allows - * application-specific handling of uncaught errors. Allowing, for example, - * integration with error logging or developer tools. - */ - static onUnhandledError(callback: (error: Error) => any): void; - - /** - * Accepts various kinds of data sources, and always returns a RelayObservable - * useful for accepting the result of a user-provided FetchFunction. - */ - static from(obj: ObservableFromValue): RelayObservable; - - /** - * Creates a RelayObservable, given a function which expects a legacy - * Relay Observer as the last argument and which returns a Disposable. - * - * To support migration to Observable, the function may ignore the - * legacy Relay observer and directly return an Observable instead. - */ - static fromLegacy( - callback: (legacyObserver: Common.LegacyObserver) => Common.Disposable | RelayObservable, - ): RelayObservable; - - /** - * Returns a new Observable which returns the same values as this one, but - * modified so that the provided Observer is called to perform a side-effects - * for all events emitted by the source. - * - * Any errors that are thrown in the side-effect Observer are unhandled, and - * do not affect the source Observable or its Observer. - * - * This is useful for when debugging your Observables or performing other - * side-effects such as logging or performance monitoring. - */ - do(observer: Observer): RelayObservable; - - /** - * Returns a new Observable which returns the same values as this one, but - * modified so that the finally callback is performed after completion, - * whether normal or due to error or unsubscription. - * - * This is useful for cleanup such as resource finalization. - */ - finally(fn: () => any): RelayObservable; - - /** - * Returns a new Observable which is identical to this one, unless this - * Observable completes before yielding any values, in which case the new - * Observable will yield the values from the alternate Observable. - * - * If this Observable does yield values, the alternate is never subscribed to. - * - * This is useful for scenarios where values may come from multiple sources - * which should be tried in order, i.e. from a cache before a network. - */ - ifEmpty(alternate: RelayObservable): RelayObservable; - - /** - * Observable's primary API: returns an unsubscribable Subscription to the - * source of this Observable. - */ - subscribe(observer: Observer): Subscription; - - /** - * Supports subscription of a legacy Relay Observer, returning a Disposable. - */ - subscribeLegacy(legacyObserver: Common.LegacyObserver): Common.Disposable; - - /** - * Returns a new Observerable where each value has been transformed by - * the mapping function. - */ - map(fn: (thing: T) => U): RelayObservable; - - /** - * Returns a new Observable where each value is replaced with a new Observable - * by the mapping function, the results of which returned as a single - * concattenated Observable. - */ - concatMap(fn: (thing: T) => ObservableFromValue): RelayObservable; - - /** - * Returns a new Observable which first mirrors this Observable, then when it - * completes, waits for `pollInterval` milliseconds before re-subscribing to - * this Observable again, looping in this manner until unsubscribed. - * - * The returned Observable never completes. - */ - poll(pollInterval: number): RelayObservable; - - /** - * Returns a Promise which resolves when this Observable yields a first value - * or when it completes with no value. - */ - toPromise(): Promise; - } - - // ~~~~~~~~~~~~~~~~~~~~~ - // commitLocalUpdate - // ~~~~~~~~~~~~~~~~~~~~~ - // exposed through RelayModern, not Runtime directly - type commitLocalUpdate = ( - environment: Environment, - updater: Common.StoreUpdater, - ) => void; - - // ~~~~~~~~~~~~~~~~~~~~~ - // commitRelayModernMutation - // ~~~~~~~~~~~~~~~~~~~~~ - // exposed through RelayModern, not Runtime directly - interface MutationConfig { - configs?: Common.RelayMutationConfig[]; - mutation: Common.GraphQLTaggedNode; - variables: Common.Variables; - uploadables?: Common.UploadableMap; - onCompleted?(response: T, errors: Common.PayloadError[] | null | undefined): void; - onError?(error?: Error): void; - optimisticUpdater?: Common.SelectorStoreUpdater; - optimisticResponse?: object; - updater?: Common.SelectorStoreUpdater; - } - function commitRelayModernMutation( - environment: Environment, - config: MutationConfig, - ): Common.Disposable; - - // ~~~~~~~~~~~~~~~~~~~~~ - // applyRelayModernOptimisticMutation - // ~~~~~~~~~~~~~~~~~~~~~ - // exposed through RelayModern, not Runtime directly - interface OptimisticMutationConfig { - configs?: Common.RelayMutationConfig[]; - mutation: Common.GraphQLTaggedNode; - variables: Common.Variables; - optimisticUpdater?: Common.SelectorStoreUpdater; - optimisticResponse?: object; - } - - // ~~~~~~~~~~~~~~~~~~~~~ - // fetchRelayModernQuery - // ~~~~~~~~~~~~~~~~~~~~~ - // exposed through RelayModern, not Runtime directly - /** - * A helper function to fetch the results of a query. Note that results for - * fragment spreads are masked: fields must be explicitly listed in the query in - * order to be accessible in the result object. + * Create an instance of a FragmentSpecResolver. * - * NOTE: This module is primarily intended for integrating with classic APIs. - * Most product code should use a Renderer or Container. - * - * TODO(t16875667): The return type should be `Promise`, but - * that's not really helpful as `SelectorData` is essentially just `mixed`. We - * can probably leverage generated flow types here to return the real expected - * shape. + * TODO: The FragmentSpecResolver *can* be implemented via the other methods + * defined here, so this could be moved out of core. It's convenient to have + * separate implementations until the experimental core is in OSS. */ - function fetchRelayModernQuery( - environment: any, // FIXME - $FlowFixMe in facebook source code - taggedNode: Common.GraphQLTaggedNode, - variables: Common.Variables, - cacheConfig?: Common.CacheConfig, - ): Promise; // FIXME - $FlowFixMe in facebook source code + createFragmentSpecResolver( + context: CRelayContext, + containerName: string, + fragments: CFragmentMap, + props: Props, + callback: () => void, + ): FragmentSpecResolver; - // ~~~~~~~~~~~~~~~~~~~~~ - // requestRelaySubscription - // ~~~~~~~~~~~~~~~~~~~~~ - // exposed through RelayModern, not Runtime directly - interface GraphQLSubscriptionConfig { - configs?: Common.RelayMutationConfig[]; - subscription: Common.GraphQLTaggedNode; - variables: Common.Variables; - onCompleted?(): void; - onError?(error: Error): void; - onNext?(response: object | null | undefined): void; - updater?(store: Common.RecordSourceSelectorProxy): void; - } - function requestRelaySubscription( - environment: Environment, - config: GraphQLSubscriptionConfig, - ): Common.Disposable; + /** + * Creates an instance of an OperationSelector given an operation definition + * (see `getOperation`) and the variables to apply. The input variables are + * filtered to exclude variables that do not matche defined arguments on the + * operation, and default values are populated for null values. + */ + createOperationSelector( + operation: TOperation, + variables: Variables, + ): COperationSelector; + + /** + * Given a graphql`...` tagged template, extract a fragment definition usable + * by this version of Relay core. Throws if the value is not a fragment. + */ + getFragment(node: TGraphQLTaggedNode): TFragment; + + /** + * Given a graphql`...` tagged template, extract an operation definition + * usable by this version of Relay core. Throws if the value is not an + * operation. + */ + getOperation(node: TGraphQLTaggedNode): TOperation; + + /** + * Determine if two selectors are equal (represent the same selection). Note + * that this function returns `false` when the two queries/fragments are + * different objects, even if they select the same fields. + */ + areEqualSelectors(a: CSelector, b: CSelector): boolean; + + /** + * Given the result `item` from a parent that fetched `fragment`, creates a + * selector that can be used to read the results of that fragment for that item. + * + * Example: + * + * Given two fragments as follows: + * + * ``` + * fragment Parent on User { + * id + * ...Child + * } + * fragment Child on User { + * name + * } + * ``` + * + * And given some object `parent` that is the results of `Parent` for id "4", + * the results of `Child` can be accessed by first getting a selector and then + * using that selector to `lookup()` the results against the environment: + * + * ``` + * const childSelector = getSelector(queryVariables, Child, parent); + * const childData = environment.lookup(childSelector).data; + * ``` + */ + getSelector( + operationVariables: Variables, + fragment: TFragment, + prop: any, + ): CSelector | void; + + /** + * Given the result `items` from a parent that fetched `fragment`, creates a + * selector that can be used to read the results of that fragment on those + * items. This is similar to `getSelector` but for "plural" fragments that + * expect an array of results and therefore return an array of selectors. + */ + getSelectorList( + operationVariables: Variables, + fragment: TFragment, + props: any[], + ): Array> | void; + + /** + * Given a mapping of keys -> results and a mapping of keys -> fragments, + * extracts the selectors for those fragments from the results. + * + * The canonical use-case for this function are Relay Containers, which + * use this function to convert (props, fragments) into selectors so that they + * can read the results to pass to the inner component. + */ + getSelectorsFromObject( + operationVariables: Variables, + fragments: CFragmentMap, + props: Props, + ): { [key: string]: CSelector | Array> | null | undefined }; + + /** + * Given a mapping of keys -> results and a mapping of keys -> fragments, + * extracts a mapping of keys -> id(s) of the results. + * + * Similar to `getSelectorsFromObject()`, this function can be useful in + * determining the "identity" of the props passed to a component. + */ + getDataIDsFromObject( + fragments: CFragmentMap, + props: Props, + ): { [key: string]: DataID | DataID[] | null | undefined }; + + /** + * Given a mapping of keys -> results and a mapping of keys -> fragments, + * extracts the merged variables that would be in scope for those + * fragments/results. + * + * This can be useful in determing what varaibles were used to fetch the data + * for a Relay container, for example. + */ + getVariablesFromObject( + operationVariables: Variables, + fragments: CFragmentMap, + props: Props, + ): Variables; } + + /** + * The type of the `relay` property set on React context by the React/Relay + * integration layer (e.g. QueryRenderer, FragmentContainer, etc). + */ + interface CRelayContext { + environment: TEnvironment; + variables: Variables; + } + + // ~~~~~~~~~~~~~~~~~~~~~ + // RelayTypes + /** + * Version: Relay 1.3.0 + * File: + * https://github.com/facebook/relay/blob/fa9f48ea209ee2402d433b59a84d1cbc046574e2/packages/react-relay/classic/tools/RelayTypes.js + */ + // ~~~~~~~~~~~~~~~~~~~~~ + interface RerunParam { + param: string; + import: string; + max_runs: number; + } + interface FIELDS_CHANGE { + type: 'FIELDS_CHANGE'; + fieldIDs: { [fieldName: string]: DataID | DataID[]; }; + } + interface RANGE_ADD { + type: 'RANGE_ADD'; + parentName?: string; + parentID?: string; + connectionInfo?: Array<{ + key: string, + filters?: Variables, + rangeBehavior: string, + }>; + connectionName?: string; + edgeName: string; + rangeBehaviors?: RangeBehaviors; + } + interface NODE_DELETE { + type: 'NODE_DELETE'; + parentName?: string; + parentID?: string; + connectionName?: string; + deletedIDFieldName: string; + } + interface RANGE_DELETE { + type: 'RANGE_DELETE'; + parentName?: string; + parentID?: string; + connectionKeys?: Array<{ + key: string, + filters?: Variables, + }>; + connectionName?: string; + deletedIDFieldName: string | string[]; + pathToConnection: string[]; + } + interface REQUIRED_CHILDREN { + type: 'REQUIRED_CHILDREN'; + children: RelayConcreteNode[]; + } + type RelayMutationConfig = + FIELDS_CHANGE | + RANGE_ADD | + NODE_DELETE | + RANGE_DELETE | + REQUIRED_CHILDREN; + + interface RelayMutationTransactionCommitCallbacks { + onFailure?: RelayMutationTransactionCommitFailureCallback; + onSuccess?: RelayMutationTransactionCommitSuccessCallback; + } + type RelayMutationTransactionCommitFailureCallback = ( + transaction: RelayMutationTransaction, + preventAutoRollback: () => void, + ) => void; + type RelayMutationTransactionCommitSuccessCallback = (response: { + [key: string]: any, + }) => void; + interface NetworkLayer { + sendMutation(request: RelayMutationRequest): Promise | void; + sendQueries(requests: RelayQueryRequest[]): Promise | void; + supports(...options: string[]): boolean; + } + interface QueryResult { + error?: Error; + ref_params?: { [name: string]: any }; + response: QueryPayload; + } + interface ReadyState { + aborted: boolean; + done: boolean; + error: Error | null; + events: ReadyStateEvent[]; + ready: boolean; + stale: boolean; + } + type RelayContainerErrorEventType = + | 'CACHE_RESTORE_FAILED' + | 'NETWORK_QUERY_ERROR'; + type RelayContainerLoadingEventType = + | 'ABORT' + | 'CACHE_RESTORED_REQUIRED' + | 'CACHE_RESTORE_START' + | 'NETWORK_QUERY_RECEIVED_ALL' + | 'NETWORK_QUERY_RECEIVED_REQUIRED' + | 'NETWORK_QUERY_START' + | 'STORE_FOUND_ALL' + | 'STORE_FOUND_REQUIRED'; + type ReadyStateChangeCallback = (readyState: ReadyState) => void; + interface ReadyStateEvent { + type: RelayContainerLoadingEventType | RelayContainerErrorEventType; + error?: Error; + } + interface Abortable { + abort(): void; + } + + // ~~~~~~~~~~~~~~~~~~~~~ + // RelayInternalTypes + /** + * Version: Relay 1.3.0 + * File: + * https://github.com/facebook/relay/blob/master/packages/react-relay/classic/tools/RelayInternalTypes.js + */ + // ~~~~~~~~~~~~~~~~~~~~~ + interface QueryPayload { [key: string]: any; } + interface RelayQuerySet { [queryName: string]: any; } + type RangeBehaviorsFunction = (connectionArgs: { + [argName: string]: any, + }) => 'APPEND' | 'IGNORE' | 'PREPEND' | 'REFETCH' | 'REMOVE'; + interface RangeBehaviorsObject { + [key: string]: 'APPEND' | 'IGNORE' | 'PREPEND' | 'REFETCH' | 'REMOVE'; + } + type RangeBehaviors = RangeBehaviorsFunction | RangeBehaviorsObject; } -// tslint:disable no-single-declare-module strict-export-declare-modifiers -declare module 'relay-runtime' { - export import Environment = __Relay.Runtime.Environment; - export import Network = __Relay.Runtime.Network; - export import RecordSource = __Relay.Runtime.RecordSource; - export import Store = __Relay.Runtime.Store; - export import Observable = __Relay.Runtime.RelayObservable; - // note RecordSourceInspector is only available in dev environment - export import RecordSourceInspector = __Relay.Runtime.RelayRecordSourceInspector; - export import ConnectionHandler = __Relay.Common.Handler; - export import ViewerHandler = __Relay.Common.Handler; +export namespace RelayRuntimeTypes { + // ~~~~~~~~~~~~~~~~~~~~~ + // Maybe Fix + // ~~~~~~~~~~~~~~~~~~~~~ + type RelayDebugger = any; + type OptimisticUpdate = any; + type OperationSelector = RelayCommonTypes.COperationSelector; + type Selector = RelayCommonTypes.CSelector; + type PayloadData = any; + type Snapshot = RelayCommonTypes.CSnapshot; + type RelayResponsePayload = any; + type MutableRecordSource = RecordSource; + + /** + * A function that returns an Observable representing the response of executing + * a GraphQL operation. + */ + type ExecuteFunction = ( + operation: object, + variables: RelayCommonTypes.Variables, + cacheConfig: RelayCommonTypes.CacheConfig, + uploadables?: RelayCommonTypes.UploadableMap, + ) => Promise; + interface RelayNetwork { + execute: ExecuteFunction; + } + + // ~~~~~~~~~~~~~~~~~~~~~ + // RelayDefaultHandlerProvider + // ~~~~~~~~~~~~~~~~~~~~~ + function HandlerProvider(name: string): typeof RelayCommonTypes.Handler | void; + + // ~~~~~~~~~~~~~~~~~~~~~ + // RelayModernEnvironment + // ~~~~~~~~~~~~~~~~~~~~~ + interface EnvironmentConfig { + configName?: string; + handlerProvider?: typeof HandlerProvider; + network: Network; + store: Store; + } + class Environment { + constructor(config: EnvironmentConfig); + getStore(): Store; + getDebugger(): RelayDebugger; + applyUpdate(optimisticUpdate: OptimisticUpdate): RelayCommonTypes.Disposable; + revertUpdate(update: OptimisticUpdate): void; + replaceUpdate(update: OptimisticUpdate, newUpdate: OptimisticUpdate): void; + applyMutation(config: { + operation: OperationSelector, + optimisticUpdater?: RelayCommonTypes.SelectorStoreUpdater, + optimisticResponse?: object, + }): RelayCommonTypes.Disposable; + check(readSelector: Selector): boolean; + commitPayload( + operationSelector: OperationSelector, + payload: PayloadData, + ): void; + commitUpdate(updater: RelayCommonTypes.StoreUpdater): void; + lookup(readSelector: Selector): Snapshot; + subscribe( + snapshot: Snapshot, + callback: (snapshot: Snapshot) => void, + ): RelayCommonTypes.Disposable; + retain(selector: Selector): RelayCommonTypes.Disposable; + execute(config: { + operation: OperationSelector, + cacheConfig?: RelayCommonTypes.CacheConfig, + updater?: RelayCommonTypes.SelectorStoreUpdater, + }): RelayObservable; + executeMutation(config: { + operation: OperationSelector, + optimisticUpdater?: RelayCommonTypes.SelectorStoreUpdater, + optimisticResponse?: object, + updater?: RelayCommonTypes.SelectorStoreUpdater, + uploadables?: RelayCommonTypes.UploadableMap, + }): RelayObservable; + } + + // ~~~~~~~~~~~~~~~~~~~~~ + // RelayInMemoryRecordSource + // ~~~~~~~~~~~~~~~~~~~~~ + interface Record { [key: string]: any; } + interface RecordMap { [dataID: string]: Record | null | undefined; } + + // ~~~~~~~~~~~~~~~~~~~~~ + // Network + // ~~~~~~~~~~~~~~~~~~~~~ + class Network { + /** + * Creates an implementation of the `Network` interface defined in + * `RelayNetworkTypes` given `fetch` and `subscribe` functions. + */ + static create(fetchFn: typeof RelayCommonTypes.FetchFunction, subscribeFn?: RelayCommonTypes.SubscribeFunction): RelayNetwork; + } + + // ~~~~~~~~~~~~~~~~~~~~~ + // Network + // ~~~~~~~~~~~~~~~~~~~~~ + class RecordSource { + constructor(records?: RecordMap); + clear(): void; + delete(dataID: RelayCommonTypes.DataID): void; + get(dataID: RelayCommonTypes.DataID): Record | void; + getRecordIDs(): RelayCommonTypes.DataID[]; + getStatus(dataID: RelayCommonTypes.DataID): 'EXISTENT' | 'NONEXISTENT' | 'UNKNOWN'; + has(dataID: RelayCommonTypes.DataID): boolean; + load( + dataID: RelayCommonTypes.DataID, + callback: (error: Error | null, record: Record | null) => void, + ): void; + remove(dataID: RelayCommonTypes.DataID): void; + set(dataID: RelayCommonTypes.DataID, record: Record): void; + size(): number; + toJSON(): RecordMap; + } + + // ~~~~~~~~~~~~~~~~~~~~~ + // ModernStore + // ~~~~~~~~~~~~~~~~~~~~~ + class Store { + constructor(source: RecordSource); + getSource(): MutableRecordSource; + check(selector: Selector): boolean; + retain(selector: Selector): RelayCommonTypes.Disposable; + lookup(selector: Selector): Snapshot; + notify(): void; + publish(source: RecordSource): void; + subscribe( + snapshot: Snapshot, + callback: (snapshot: Snapshot) => void, + ): RelayCommonTypes.Disposable; + } + + // ~~~~~~~~~~~~~~~~~~~~~ + // RelayRecordSourceInspector + // ~~~~~~~~~~~~~~~~~~~~~ + /** + * An internal class to provide a console-friendly string representation of a + * Record. + */ + class RecordSummary { + id: RelayCommonTypes.DataID; + type: string | null | undefined; + static createFromRecord(id: RelayCommonTypes.DataID, record: any): RecordSummary; + constructor(id: RelayCommonTypes.DataID, type: string | null | undefined); + toString(): string; + } + /** + * Internal class for inspecting a single Record. + */ + class RecordInspector { + constructor(sourceInspector: RelayRecordSourceInspector, record: Record); + /** + * Get the cache id of the given record. For types that implement the `Node` + * interface (or that have an `id`) this will be `id`, for other types it will be + * a synthesized identifier based on the field path from the nearest ancestor + * record that does have an `id`. + */ + getDataID(): RelayCommonTypes.DataID; + + /** + * Returns a list of the fields that have been fetched on the current record. + */ + getFields(): string[]; + + /** + * Returns the type of the record. + */ + getType(): string; + + /** + * Returns a copy of the internal representation of the record. + */ + inspect(): any; + + /** + * Returns the value of a scalar field. May throw if the given field is + * present but not actually scalar. + */ + getValue(name: string, args?: RelayCommonTypes.Variables): any; + + /** + * Returns an inspector for the given scalar "linked" field (a field whose + * value is another Record instead of a scalar). May throw if the field is + * present but not a scalar linked record. + */ + getLinkedRecord(name: string, args?: RelayCommonTypes.Variables): RecordInspector | void; + + /** + * Returns an array of inspectors for the given plural "linked" field (a field + * whose value is an array of Records instead of a scalar). May throw if the + * field is present but not a plural linked record. + */ + getLinkedRecords(name: string, args?: RelayCommonTypes.Variables): RecordInspector[] | void; + } + + class RelayRecordSourceInspector { + constructor(source: RecordSource); + static getForEnvironment(environment: Environment): RelayRecordSourceInspector; + /** + * Returns an inspector for the record with the given id, or null/undefined if + * that record is deleted/unfetched. + */ + get(dataID: RelayCommonTypes.DataID): RecordInspector | void; + /** + * Returns a list of ": " for each record in the store that has an + * `id`. + */ + getNodes(): RecordSummary[]; + /** + * Returns a list of ": " for all records in the store including + * those that do not have an `id`. + */ + getRecords(): RecordSummary[]; + + /** + * Returns an inspector for the synthesized "root" object, allowing access to + * e.g. the `viewer` object or the results of other fields on the "Query" + * type. + */ + getRoot(): RecordInspector; + } + + // ~~~~~~~~~~~~~~~~~~~~~ + // RelayObservable + // ~~~~~~~~~~~~~~~~~~~~~ + interface Subscription { + unsubscribe(): void; + readonly closed: boolean; + } + interface Observer { + start?(subscription: Subscription): any; + next?(nextThing: T): any; + error?(error: Error): any; + complete?(): any; + unsubscribe?(subscription: Subscription): any; + } + type Source = () => any; + interface Subscribable { + subscribe(observer: Observer): Subscription; + } + type ObservableFromValue = RelayObservable | Promise | T; + class RelayObservable implements Subscribable { + _source: Source; + + constructor(source: Source); + + /** + * When an unhandled error is detected, it is reported to the host environment + * (the ESObservable spec refers to this method as "HostReportErrors()"). + * + * The default implementation in development builds re-throws errors in a + * separate frame, and from production builds does nothing (swallowing + * uncaught errors). + * + * Called during application initialization, this method allows + * application-specific handling of uncaught errors. Allowing, for example, + * integration with error logging or developer tools. + */ + static onUnhandledError(callback: (error: Error) => any): void; + + /** + * Accepts various kinds of data sources, and always returns a RelayObservable + * useful for accepting the result of a user-provided FetchFunction. + */ + static from(obj: ObservableFromValue): RelayObservable; + + /** + * Creates a RelayObservable, given a function which expects a legacy + * Relay Observer as the last argument and which returns a Disposable. + * + * To support migration to Observable, the function may ignore the + * legacy Relay observer and directly return an Observable instead. + */ + static fromLegacy( + callback: (legacyObserver: RelayCommonTypes.LegacyObserver) => RelayCommonTypes.Disposable | RelayObservable, + ): RelayObservable; + + /** + * Returns a new Observable which returns the same values as this one, but + * modified so that the provided Observer is called to perform a side-effects + * for all events emitted by the source. + * + * Any errors that are thrown in the side-effect Observer are unhandled, and + * do not affect the source Observable or its Observer. + * + * This is useful for when debugging your Observables or performing other + * side-effects such as logging or performance monitoring. + */ + do(observer: Observer): RelayObservable; + + /** + * Returns a new Observable which returns the same values as this one, but + * modified so that the finally callback is performed after completion, + * whether normal or due to error or unsubscription. + * + * This is useful for cleanup such as resource finalization. + */ + finally(fn: () => any): RelayObservable; + + /** + * Returns a new Observable which is identical to this one, unless this + * Observable completes before yielding any values, in which case the new + * Observable will yield the values from the alternate Observable. + * + * If this Observable does yield values, the alternate is never subscribed to. + * + * This is useful for scenarios where values may come from multiple sources + * which should be tried in order, i.e. from a cache before a network. + */ + ifEmpty(alternate: RelayObservable): RelayObservable; + + /** + * Observable's primary API: returns an unsubscribable Subscription to the + * source of this Observable. + */ + subscribe(observer: Observer): Subscription; + + /** + * Supports subscription of a legacy Relay Observer, returning a Disposable. + */ + subscribeLegacy(legacyObserver: RelayCommonTypes.LegacyObserver): RelayCommonTypes.Disposable; + + /** + * Returns a new Observerable where each value has been transformed by + * the mapping function. + */ + map(fn: (thing: T) => U): RelayObservable; + + /** + * Returns a new Observable where each value is replaced with a new Observable + * by the mapping function, the results of which returned as a single + * concattenated Observable. + */ + concatMap(fn: (thing: T) => ObservableFromValue): RelayObservable; + + /** + * Returns a new Observable which first mirrors this Observable, then when it + * completes, waits for `pollInterval` milliseconds before re-subscribing to + * this Observable again, looping in this manner until unsubscribed. + * + * The returned Observable never completes. + */ + poll(pollInterval: number): RelayObservable; + + /** + * Returns a Promise which resolves when this Observable yields a first value + * or when it completes with no value. + */ + toPromise(): Promise; + } + + // ~~~~~~~~~~~~~~~~~~~~~ + // commitLocalUpdate + // ~~~~~~~~~~~~~~~~~~~~~ + // exposed through RelayModern, not Runtime directly + type commitLocalUpdate = ( + environment: Environment, + updater: RelayCommonTypes.StoreUpdater, + ) => void; + + // ~~~~~~~~~~~~~~~~~~~~~ + // commitRelayModernMutation + // ~~~~~~~~~~~~~~~~~~~~~ + // exposed through RelayModern, not Runtime directly + interface MutationConfig { + configs?: RelayCommonTypes.RelayMutationConfig[]; + mutation: RelayCommonTypes.GraphQLTaggedNode; + variables: RelayCommonTypes.Variables; + uploadables?: RelayCommonTypes.UploadableMap; + onCompleted?(response: T, errors: RelayCommonTypes.PayloadError[] | null | undefined): void; + onError?(error?: Error): void; + optimisticUpdater?: RelayCommonTypes.SelectorStoreUpdater; + optimisticResponse?: object; + updater?: RelayCommonTypes.SelectorStoreUpdater; + } + function commitRelayModernMutation( + environment: Environment, + config: MutationConfig, + ): RelayCommonTypes.Disposable; + + // ~~~~~~~~~~~~~~~~~~~~~ + // applyRelayModernOptimisticMutation + // ~~~~~~~~~~~~~~~~~~~~~ + // exposed through RelayModern, not Runtime directly + interface OptimisticMutationConfig { + configs?: RelayCommonTypes.RelayMutationConfig[]; + mutation: RelayCommonTypes.GraphQLTaggedNode; + variables: RelayCommonTypes.Variables; + optimisticUpdater?: RelayCommonTypes.SelectorStoreUpdater; + optimisticResponse?: object; + } + + // ~~~~~~~~~~~~~~~~~~~~~ + // fetchRelayModernQuery + // ~~~~~~~~~~~~~~~~~~~~~ + // exposed through RelayModern, not Runtime directly + /** + * A helper function to fetch the results of a query. Note that results for + * fragment spreads are masked: fields must be explicitly listed in the query in + * order to be accessible in the result object. + * + * NOTE: This module is primarily intended for integrating with classic APIs. + * Most product code should use a Renderer or Container. + * + * TODO(t16875667): The return type should be `Promise`, but + * that's not really helpful as `SelectorData` is essentially just `mixed`. We + * can probably leverage generated flow types here to return the real expected + * shape. + */ + function fetchRelayModernQuery( + environment: any, // FIXME - $FlowFixMe in facebook source code + taggedNode: RelayCommonTypes.GraphQLTaggedNode, + variables: RelayCommonTypes.Variables, + cacheConfig?: RelayCommonTypes.CacheConfig, + ): Promise; // FIXME - $FlowFixMe in facebook source code + + // ~~~~~~~~~~~~~~~~~~~~~ + // requestRelaySubscription + // ~~~~~~~~~~~~~~~~~~~~~ + // exposed through RelayModern, not Runtime directly + interface GraphQLSubscriptionConfig { + configs?: RelayCommonTypes.RelayMutationConfig[]; + subscription: RelayCommonTypes.GraphQLTaggedNode; + variables: RelayCommonTypes.Variables; + onCompleted?(): void; + onError?(error: Error): void; + onNext?(response: object | null | undefined): void; + updater?(store: RelayCommonTypes.RecordSourceSelectorProxy): void; + } + function requestRelaySubscription( + environment: Environment, + config: GraphQLSubscriptionConfig, + ): RelayCommonTypes.Disposable; } + +// ~~~~~~~~~~~~~~~~~~~~~ +// Package Exports +// ~~~~~~~~~~~~~~~~~~~~~ +export import Environment = RelayRuntimeTypes.Environment; +export import Network = RelayRuntimeTypes.Network; +export import RecordSource = RelayRuntimeTypes.RecordSource; +export import Store = RelayRuntimeTypes.Store; +export import Observable = RelayRuntimeTypes.RelayObservable; +// note RecordSourceInspector is only available in dev environment +export import RecordSourceInspector = RelayRuntimeTypes.RelayRecordSourceInspector; +export import ConnectionHandler = RelayCommonTypes.Handler; +export import ViewerHandler = RelayCommonTypes.Handler; From 9d1970bce092c5859a39b9a698938255c732eec9 Mon Sep 17 00:00:00 2001 From: voxmatt Date: Sun, 1 Oct 2017 19:47:49 -0700 Subject: [PATCH 032/828] trying to clean things up and fix some errors --- types/react-relay/v1/index.d.ts | 475 +----------------- .../v1/lib/react-relay-classic.d.ts | 218 ++++++++ .../v1/lib/react-relay-compat.d.ts | 57 +++ .../v1/lib/react-relay-modern.d.ts | 147 ++++++ types/react-relay/v1/react-relay-tests.tsx | 18 +- types/react-relay/v1/tsconfig.json | 4 +- 6 files changed, 450 insertions(+), 469 deletions(-) diff --git a/types/react-relay/v1/index.d.ts b/types/react-relay/v1/index.d.ts index 14c7bb756a..e214a9a441 100644 --- a/types/react-relay/v1/index.d.ts +++ b/types/react-relay/v1/index.d.ts @@ -4,471 +4,20 @@ // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped // TypeScript Version: 2.4 -import * as React from 'react'; -import { RelayCommonTypes, RelayRuntimeTypes } from 'relay-runtime'; - -//////////////////////////// -// RELAY MODERN TYPES -/////////////////////////// -export namespace RelayModernTypes { - // ~~~~~~~~~~~~~~~~~~~~~ - // Maybe Fix - // ~~~~~~~~~~~~~~~~~~~~~ - type ConcreteFragment = any; - type ConcreteBatch = any; - type ConcreteFragmentDefinition = object; - type ConcreteOperationDefinition = object; - type ReactBaseComponent = React.ComponentClass | React.StatelessComponent; - - // ~~~~~~~~~~~~~~~~~~~~~ - // RelayProp - // ~~~~~~~~~~~~~~~~~~~~~ - // note: refetch and pagination containers augment this - interface RelayProp { - environment: RelayRuntimeTypes.Environment; - } - - // ~~~~~~~~~~~~~~~~~~~~~ - // RelayQL - // ~~~~~~~~~~~~~~~~~~~~~ - function RelayQL( - strings: string[], - ...substitutions: any[] - ): RelayCommonTypes.RelayConcreteNode; - - // ~~~~~~~~~~~~~~~~~~~~~ - // RelayModernGraphQLTag - // ~~~~~~~~~~~~~~~~~~~~~ - interface GeneratedNodeMap { [key: string]: GraphQLTaggedNode; } - type GraphQLTaggedNode = - (() => ConcreteFragment | ConcreteBatch) - | { - modern(): ConcreteFragment | ConcreteBatch, - classic(relayQL: typeof RelayQL): - | ConcreteFragmentDefinition - | ConcreteOperationDefinition, - }; - /** - * Runtime function to correspond to the `graphql` tagged template function. - * All calls to this function should be transformed by the plugin. - */ - interface GraphqlInterface { - (strings: string[] | TemplateStringsArray): GraphQLTaggedNode; - experimental(strings: string[] | TemplateStringsArray): GraphQLTaggedNode; - } - const graphql: GraphqlInterface; - - // ~~~~~~~~~~~~~~~~~~~~~ - // ReactRelayQueryRenderer - // ~~~~~~~~~~~~~~~~~~~~~ - interface QueryRendererProps { - cacheConfig?: RelayCommonTypes.CacheConfig; - environment: RelayRuntimeTypes.Environment; - query: GraphQLTaggedNode; - render(readyState: ReadyState): React.ReactElement | undefined | null; - variables: RelayCommonTypes.Variables; - rerunParamExperimental?: RelayCommonTypes.RerunParam; - } - interface ReadyState { - error: Error | undefined | null; - props: { [propName: string]: any } | undefined | null; - retry?(): void; - } - interface QueryRendererState { - readyState: ReadyState; - } - class ReactRelayQueryRenderer extends React.Component { } - - // ~~~~~~~~~~~~~~~~~~~~~ - // createFragmentContainer - // ~~~~~~~~~~~~~~~~~~~~~ - function createFragmentContainer( - Component: ReactBaseComponent, - fragmentSpec: GraphQLTaggedNode | GeneratedNodeMap, - ): ReactBaseComponent; - - // ~~~~~~~~~~~~~~~~~~~~~ - // createPaginationContainer - // ~~~~~~~~~~~~~~~~~~~~~ - interface PageInfo { - endCursor: string | undefined | null; - hasNextPage: boolean; - hasPreviousPage: boolean; - startCursor: string | undefined | null; - } - interface ConnectionData { - edges?: any[]; - pageInfo?: PageInfo; - } - type RelayPaginationProp = RelayProp & { - hasMore(): boolean, - isLoading(): boolean, - loadMore( - pageSize: number, - callback: (error?: Error) => void, - options?: RefetchOptions, - ): RelayCommonTypes.Disposable | undefined | null, - refetchConnection( - totalCount: number, - callback: (error?: Error) => void, - refetchVariables?: RelayCommonTypes.Variables, - ): RelayCommonTypes.Disposable | undefined | null, - }; - function FragmentVariablesGetter( - prevVars: RelayCommonTypes.Variables, - totalCount: number, - ): RelayCommonTypes.Variables; - interface ConnectionConfig { - direction?: 'backward' | 'forward'; - getConnectionFromProps?(props: object): ConnectionData | undefined | null; - getFragmentVariables?: typeof FragmentVariablesGetter; - getVariables( - props: { [propName: string]: any }, - paginationInfo: { count: number, cursor?: string }, - fragmentVariables: RelayCommonTypes.Variables, - ): RelayCommonTypes.Variables; - query: GraphQLTaggedNode; - } - function createPaginationContainer( - Component: ReactBaseComponent, - fragmentSpec: GraphQLTaggedNode | GeneratedNodeMap, - connectionConfig: ConnectionConfig, - ): ReactBaseComponent; - - // ~~~~~~~~~~~~~~~~~~~~~ - // createFragmentContainer - // ~~~~~~~~~~~~~~~~~~~~~ - interface RefetchOptions { - force?: boolean; - rerunParamExperimental?: RelayCommonTypes.RerunParam; - } - type RelayRefetchProp = RelayProp & { - refetch( - refetchVariables: RelayCommonTypes.Variables | ((fragmentVariables: RelayCommonTypes.Variables) => RelayCommonTypes.Variables), - renderVariables?: RelayCommonTypes.Variables, - callback?: (error?: Error) => void, - options?: RefetchOptions, - ): RelayCommonTypes.Disposable, - }; - function createRefetchContainer( - Component: ReactBaseComponent, - fragmentSpec: GraphQLTaggedNode | GeneratedNodeMap, - taggedNode: GraphQLTaggedNode, - ): ReactBaseComponent; -} - -//////////////////////////// -// RELAY CLASSIC TYPES -/////////////////////////// -// note: the namespace here is really for use inside of -// relay-compat; the module declaration below -// uses the old, pre-existing types -export namespace RelayClassicTypes { - // ~~~~~~~~~~~~~~~~~~~~~ - // Maybe Fix - // ~~~~~~~~~~~~~~~~~~~~~ - type StoreReaderData = any; - type StoreReaderOptions = any; - type RelayStoreData = any; - interface RelayQuery { Fragment: any; Node: any; Root: any; } - - // ~~~~~~~~~~~~~~~~~~~~~ - // Environment - // ~~~~~~~~~~~~~~~~~~~~~ - interface FragmentResolver { - dispose(): void; - resolve( - fragment: RelayQuery["Fragment"], - dataIDs: RelayCommonTypes.DataID | RelayCommonTypes.DataID[], - ): StoreReaderData | StoreReaderData[] | undefined | null; - } - interface RelayEnvironmentInterface { - forceFetch( - querySet: RelayCommonTypes.RelayQuerySet, - onReadyStateChange: RelayCommonTypes.ReadyStateChangeCallback, - ): RelayCommonTypes.Abortable; - getFragmentResolver( - fragment: RelayQuery["Fragment"], - onNext: () => void, - ): FragmentResolver; - getStoreData(): RelayStoreData; - primeCache( - querySet: RelayCommonTypes.RelayQuerySet, - onReadyStateChange: RelayCommonTypes.ReadyStateChangeCallback, - ): RelayCommonTypes.Abortable; - read( - node: RelayQuery["Node"], - dataID: RelayCommonTypes.DataID, - options?: StoreReaderOptions, - ): StoreReaderData | void; - readQuery( - root: RelayQuery["Root"], - options?: StoreReaderOptions, - ): StoreReaderData[] | void; - } -} - -//////////////////////////// -// RELAY COMPAT TYPES -/////////////////////////// -export namespace RelayCompatTypes { - // ~~~~~~~~~~~~~~~~~~~~~ - // Maybe Fix - // ~~~~~~~~~~~~~~~~~~~~~ - type ConcreteFragment = any; - type ConcreteBatch = any; - type ConcreteFragmentDefinition = object; - type ConcreteOperationDefinition = object; - - // ~~~~~~~~~~~~~~~~~~~~~ - // Util - // ~~~~~~~~~~~~~~~~~~~~~ - function getFragment(q: string, v?: RelayCommonTypes.Variables): string; - interface ComponentWithFragment extends React.ComponentClass { - getFragment: typeof getFragment; - } - interface StatelessWithFragment extends React.StatelessComponent { - getFragment: typeof getFragment; - } - type ReactFragmentComponent = ComponentWithFragment | StatelessWithFragment; - type ReactBaseComponent = React.ComponentClass | React.StatelessComponent; - type RelayClassicEnvironment = RelayClassicTypes.RelayEnvironmentInterface; - - // ~~~~~~~~~~~~~~~~~~~~~ - // RelayCompatTypes - // ~~~~~~~~~~~~~~~~~~~~~ - type CompatEnvironment = RelayRuntimeTypes.Environment | RelayClassicEnvironment; - - // ~~~~~~~~~~~~~~~~~~~~~ - // RelayCompatMutations - // ~~~~~~~~~~~~~~~~~~~~~ - function commitUpdate( - environment: CompatEnvironment, - config: RelayRuntimeTypes.MutationConfig, - ): RelayCommonTypes.Disposable; - function applyUpdate( - environment: CompatEnvironment, - config: RelayRuntimeTypes.OptimisticMutationConfig, - ): RelayCommonTypes.Disposable; - - // ~~~~~~~~~~~~~~~~~~~~~ - // RelayCompatContainer - // ~~~~~~~~~~~~~~~~~~~~~ - interface GeneratedNodeMap { [key: string]: RelayModernTypes.GraphQLTaggedNode; } - function createContainer( - Component: ReactBaseComponent, - fragmentSpec: RelayModernTypes.GraphQLTaggedNode | GeneratedNodeMap, - ): ReactFragmentComponent; - - // ~~~~~~~~~~~~~~~~~~~~~ - // injectDefaultVariablesProvider - // ~~~~~~~~~~~~~~~~~~~~~ - type VariablesProvider = () => RelayCommonTypes.Variables; - function injectDefaultVariablesProvider(variablesProvider: VariablesProvider): void; -} - - -//////////////////////////// -// MODULES -/////////////////////////// -export import QueryRenderer = RelayModernTypes.ReactRelayQueryRenderer; -export import createFragmentContainer = RelayModernTypes.createFragmentContainer; -export import createPaginationContainer = RelayModernTypes.createPaginationContainer; -export import createRefetchContainer = RelayModernTypes.createRefetchContainer; -export import graphql = RelayModernTypes.graphql; +import { RelayRuntimeTypes } from 'relay-runtime'; +import * as ReactRelayModernTypes from './lib/react-relay-modern'; +// ~~~~~~~~~~~~~~~~~~~~~ +// React-Relay Modern +// ~~~~~~~~~~~~~~~~~~~~~ +export import QueryRenderer = ReactRelayModernTypes.ReactRelayQueryRenderer; +export import createFragmentContainer = ReactRelayModernTypes.createFragmentContainer; +export import createPaginationContainer = ReactRelayModernTypes.createPaginationContainer; +export import createRefetchContainer = ReactRelayModernTypes.createRefetchContainer; +export import graphql = ReactRelayModernTypes.graphql; export import commitLocalUpdate = RelayRuntimeTypes.commitLocalUpdate; export import commitMutation = RelayRuntimeTypes.commitRelayModernMutation; export import fetchQuery = RelayRuntimeTypes.fetchRelayModernQuery; export import requestSubscription = RelayRuntimeTypes.requestRelaySubscription; - -// exported for convenience — not exports in the original module -export import RelayProp = RelayModernTypes.RelayProp; -export import RelayPaginationProp = RelayModernTypes.RelayPaginationProp; -export import RelayRefetchProp = RelayModernTypes.RelayRefetchProp; - -declare module 'react-relay/compat' { - export import applyOptimisticMutation = RelayCompatTypes.applyUpdate; - export import commitMutation = RelayCompatTypes.commitUpdate; - export import createFragmentContainer = RelayCompatTypes.createContainer; - export import createPaginationContainer = RelayCompatTypes.createContainer; - export import createRefetchContainer = RelayCompatTypes.createContainer; - export import injectDefaultVariablesProvider = RelayCompatTypes.injectDefaultVariablesProvider; - export import QueryRenderer = RelayModernTypes.ReactRelayQueryRenderer; - export import graphql = RelayModernTypes.graphql; - export import fetchQuery = RelayRuntimeTypes.fetchRelayModernQuery; -} -// tslint:enable strict-export-declare-modifiers - -declare module "react-relay/classic" { - import * as React from "react"; - - type ClientMutationID = string; - - /** Fragments are a hash of functions */ - interface Fragments { - [query: string]: ((variables?: RelayVariables) => string); - } - - interface CreateContainerOpts { - initialVariables?: any; - fragments: Fragments; - prepareVariables?(prevVariables: RelayVariables): RelayVariables; - } - - interface RelayVariables { - [name: string]: any; - } - - /** add static getFragment method to the component constructor */ - interface RelayContainerClass extends React.ComponentClass { - getFragment: ((q: string, v?: RelayVariables) => string); - } - - interface RelayQueryRequestResolve { - response: any; - } - - type RelayMutationStatus = - 'UNCOMMITTED' | // Transaction hasn't yet been sent to the server. Transaction can be committed or rolled back. - 'COMMIT_QUEUED' | // Transaction was committed but another transaction with the same collision key is pending, so the transaction has been queued to send to the server. - 'COLLISION_COMMIT_FAILED' | // Transaction was queued for commit but another transaction with the same collision key failed. All transactions in the collision queue, - // including this one, have been failed. Transaction can be recommitted or rolled back. - 'COMMITTING' | // Transaction is waiting for the server to respond. - 'COMMIT_FAILED'; - - class RelayMutationTransaction { - applyOptimistic(): RelayMutationTransaction; - commit(): RelayMutationTransaction | null; - recommit(): void; - rollback(): void; - getError(): Error; - getStatus(): RelayMutationStatus; - getHash(): string; - getID(): ClientMutationID; - } - - interface RelayMutationRequest { - getQueryString(): string; - getVariables(): RelayVariables; - resolve(result: RelayQueryRequestResolve): any; - reject(errors: any): any; - } - - interface RelayQueryRequest { - resolve(result: RelayQueryRequestResolve): any; - reject(errors: any): any; - getQueryString(): string; - getVariables(): RelayVariables; - getID(): string; - getDebugName(): string; - } - - interface RelayNetworkLayer { - supports(...options: string[]): boolean; - } - - class DefaultNetworkLayer implements RelayNetworkLayer { - constructor(host: string, options?: any); - supports(...options: string[]): boolean; - } - - function createContainer(component: React.ComponentClass | React.StatelessComponent, params?: CreateContainerOpts): RelayContainerClass; - function injectNetworkLayer(networkLayer: RelayNetworkLayer): any; - function isContainer(component: React.ComponentClass): boolean; - function QL(...args: any[]): string; - - class Route { - constructor(params?: RelayVariables) - } - - /** - * Relay Mutation class, where T are the props it takes and S is the returned payload from Relay.Store.update. - * S is typically dynamic as it depends on the data the app is currently using, but it's possible to always - * return some data in the payload using REQUIRED_CHILDREN which is where specifying S is the most useful. - */ - class Mutation { - props: T; - - constructor(props: T); - static getFragment(q: string): string; - } - - interface Transaction { - getError(): Error; - Status(): number; - } - - interface StoreUpdateCallbacks { - onFailure?(transaction: Transaction): any; - onSuccess?(response: T): any; - } - - interface Store { - commitUpdate(mutation: Mutation, callbacks?: StoreUpdateCallbacks): any; - } - - const Store: Store; - - class RootContainer extends React.Component { } - - interface RootContainerProps extends React.Props { - Component: RelayContainerClass; - route: Route; - renderLoading?(): JSX.Element; - renderFetched?(data: any): JSX.Element; - renderFailure?(error: Error, retry: (...args: any[]) => any): JSX.Element; - } - - class Renderer extends React.Component { } - - interface RendererProps { - Container: RelayContainerClass; // Relay container that defines fragments and the view to render. - forceFetch?: boolean; // Whether to send a server request regardless of data available on the client. - queryConfig: Route; // `QueryConfig` or `Relay.Route` that defines the query roots. - environment: Store; // An instance of `Relay.Environment` or any object that implements the `RelayEnvironment` interface. - render?: RenderCallback; // Called to render when data requirements are being fulfilled. - onReadyStateChange?: OnReadyStateChange; - } - - interface RenderStateConfig { - props?: { [propName: string]: any }; - done: boolean; - error?: Error; - retry?(): void; - stale: boolean; - } - type RenderCallback = (renderState: RenderStateConfig) => any; - - type ReadyStateEvent = - 'ABORT' | - 'CACHE_RESTORED_REQUIRED' | - 'CACHE_RESTORE_FAILED' | - 'CACHE_RESTORE_START' | - 'NETWORK_QUERY_ERROR' | - 'NETWORK_QUERY_RECEIVED_ALL' | - 'NETWORK_QUERY_RECEIVED_REQUIRED' | - 'NETWORK_QUERY_START' | - 'STORE_FOUND_ALL' | - 'STORE_FOUND_REQUIRED'; - - type OnReadyStateChange = (readyState: { - ready: boolean, - done: boolean, - stale: boolean, - error?: Error, - events: ReadyStateEvent[], - aborted: boolean - }) => void; - - interface RelayProp { - readonly route: { name: string; }; // incomplete, also has params and queries - readonly variables: any; - readonly pendingVariables?: any; - setVariables(variables: any, onReadyStateChange?: OnReadyStateChange): void; - forceFetch(variables: any, onReadyStateChange?: OnReadyStateChange): void; - hasOptimisticUpdate(record: any): boolean; - getPendingTransactions(record: any): RelayMutationTransaction[]; - commitUpdate(mutation: Mutation, callbacks?: StoreUpdateCallbacks): any; - } -} +// exported for convenience +export import ModernTypes = ReactRelayModernTypes; diff --git a/types/react-relay/v1/lib/react-relay-classic.d.ts b/types/react-relay/v1/lib/react-relay-classic.d.ts index e69de29bb2..02517b7e80 100644 --- a/types/react-relay/v1/lib/react-relay-classic.d.ts +++ b/types/react-relay/v1/lib/react-relay-classic.d.ts @@ -0,0 +1,218 @@ +import * as React from 'react'; +import { RelayCommonTypes } from 'relay-runtime'; + +// ~~~~~~~~~~~~~~~~~~~~~ +// Maybe Fix +// ~~~~~~~~~~~~~~~~~~~~~ +export type StoreReaderData = any; +export type StoreReaderOptions = any; +export type RelayStoreData = any; +export interface RelayQuery { Fragment: any; Node: any; Root: any; } + +// ~~~~~~~~~~~~~~~~~~~~~ +// Environment +// ~~~~~~~~~~~~~~~~~~~~~ +export interface FragmentResolver { + dispose(): void; + resolve( + fragment: RelayQuery["Fragment"], + dataIDs: RelayCommonTypes.DataID | RelayCommonTypes.DataID[], + ): StoreReaderData | StoreReaderData[] | undefined | null; +} + +export interface RelayEnvironmentInterface { + forceFetch( + querySet: RelayCommonTypes.RelayQuerySet, + onReadyStateChange: RelayCommonTypes.ReadyStateChangeCallback, + ): RelayCommonTypes.Abortable; + getFragmentResolver( + fragment: RelayQuery["Fragment"], + onNext: () => void, + ): FragmentResolver; + getStoreData(): RelayStoreData; + primeCache( + querySet: RelayCommonTypes.RelayQuerySet, + onReadyStateChange: RelayCommonTypes.ReadyStateChangeCallback, + ): RelayCommonTypes.Abortable; + read( + node: RelayQuery["Node"], + dataID: RelayCommonTypes.DataID, + options?: StoreReaderOptions, + ): StoreReaderData | void; + readQuery( + root: RelayQuery["Root"], + options?: StoreReaderOptions, + ): StoreReaderData[] | void; +} + +// ~~~~~~~~~~~~~~~~~~~~~ +// the rest is to match pre-existing types from before v1 +// ~~~~~~~~~~~~~~~~~~~~~ +export type ClientMutationID = string; + +/** Fragments are a hash of functions */ +export interface Fragments { + [query: string]: ((variables?: RelayVariables) => string); +} + +export interface CreateContainerOpts { + initialVariables?: any; + fragments: Fragments; + prepareVariables?(prevVariables: RelayVariables): RelayVariables; +} + +export interface RelayVariables { + [name: string]: any; +} + +/** add static getFragment method to the component constructor */ +export interface RelayContainerClass extends React.ComponentClass { + getFragment: ((q: string, v?: RelayVariables) => string); +} + +export interface RelayQueryRequestResolve { + response: any; +} + +export type RelayMutationStatus = + 'UNCOMMITTED' | // Transaction hasn't yet been sent to the server. Transaction can be committed or rolled back. + 'COMMIT_QUEUED' | // Transaction was committed but another transaction with the same collision key is pending, so the transaction has been queued to send to the server. + 'COLLISION_COMMIT_FAILED' | // Transaction was queued for commit but another transaction with the same collision key failed. All transactions in the collision queue, + // including this one, have been failed. Transaction can be recommitted or rolled back. + 'COMMITTING' | // Transaction is waiting for the server to respond. + 'COMMIT_FAILED'; + +export class RelayMutationTransaction { + applyOptimistic(): RelayMutationTransaction; + commit(): RelayMutationTransaction | null; + recommit(): void; + rollback(): void; + getError(): Error; + getStatus(): RelayMutationStatus; + getHash(): string; + getID(): ClientMutationID; +} + +export interface RelayMutationRequest { + getQueryString(): string; + getVariables(): RelayVariables; + resolve(result: RelayQueryRequestResolve): any; + reject(errors: any): any; +} + +export interface RelayQueryRequest { + resolve(result: RelayQueryRequestResolve): any; + reject(errors: any): any; + getQueryString(): string; + getVariables(): RelayVariables; + getID(): string; + getDebugName(): string; +} + +export interface RelayNetworkLayer { + supports(...options: string[]): boolean; +} + +export class DefaultNetworkLayer implements RelayNetworkLayer { + constructor(host: string, options?: any); + supports(...options: string[]): boolean; +} + +export function createContainer(component: React.ComponentClass | React.StatelessComponent, params?: CreateContainerOpts): RelayContainerClass; +export function injectNetworkLayer(networkLayer: RelayNetworkLayer): any; +export function isContainer(component: React.ComponentClass): boolean; +export function QL(...args: any[]): string; + +export class Route { + constructor(params?: RelayVariables) +} + +/** + * Relay Mutation class, where T are the props it takes and S is the returned payload from Relay.Store.update. + * S is typically dynamic as it depends on the data the app is currently using, but it's possible to always + * return some data in the payload using REQUIRED_CHILDREN which is where specifying S is the most useful. + */ +export class Mutation { + props: T; + + constructor(props: T); + static getFragment(q: string): string; +} + +export interface Transaction { + getError(): Error; + Status(): number; +} + +export interface StoreUpdateCallbacks { + onFailure?(transaction: Transaction): any; + onSuccess?(response: T): any; +} + +export interface Store { + commitUpdate(mutation: Mutation, callbacks?: StoreUpdateCallbacks): any; +} + +export const Store: Store; + +export class RootContainer extends React.Component { } + +export interface RootContainerProps extends React.Props { + Component: RelayContainerClass; + route: Route; + renderLoading?(): JSX.Element; + renderFetched?(data: any): JSX.Element; + renderFailure?(error: Error, retry: (...args: any[]) => any): JSX.Element; +} + +export class Renderer extends React.Component { } + +export interface RendererProps { + Container: RelayContainerClass; // Relay container that defines fragments and the view to render. + forceFetch?: boolean; // Whether to send a server request regardless of data available on the client. + queryConfig: Route; // `QueryConfig` or `Relay.Route` that defines the query roots. + environment: Store; // An instance of `Relay.Environment` or any object that implements the `RelayEnvironment` interface. + render?: RenderCallback; // Called to render when data requirements are being fulfilled. + onReadyStateChange?: OnReadyStateChange; +} + +export interface RenderStateConfig { + props?: { [propName: string]: any }; + done: boolean; + error?: Error; + retry?(): void; + stale: boolean; +} +export type RenderCallback = (renderState: RenderStateConfig) => any; + +export type ReadyStateEvent = + 'ABORT' | + 'CACHE_RESTORED_REQUIRED' | + 'CACHE_RESTORE_FAILED' | + 'CACHE_RESTORE_START' | + 'NETWORK_QUERY_ERROR' | + 'NETWORK_QUERY_RECEIVED_ALL' | + 'NETWORK_QUERY_RECEIVED_REQUIRED' | + 'NETWORK_QUERY_START' | + 'STORE_FOUND_ALL' | + 'STORE_FOUND_REQUIRED'; + +export type OnReadyStateChange = (readyState: { + ready: boolean, + done: boolean, + stale: boolean, + error?: Error, + events: ReadyStateEvent[], + aborted: boolean +}) => void; + +export interface RelayProp { + readonly route: { name: string; }; // incomplete, also has params and queries + readonly variables: any; + readonly pendingVariables?: any; + setVariables(variables: any, onReadyStateChange?: OnReadyStateChange): void; + forceFetch(variables: any, onReadyStateChange?: OnReadyStateChange): void; + hasOptimisticUpdate(record: any): boolean; + getPendingTransactions(record: any): RelayMutationTransaction[]; + commitUpdate(mutation: Mutation, callbacks?: StoreUpdateCallbacks): any; +} diff --git a/types/react-relay/v1/lib/react-relay-compat.d.ts b/types/react-relay/v1/lib/react-relay-compat.d.ts index e69de29bb2..0d6197d2eb 100644 --- a/types/react-relay/v1/lib/react-relay-compat.d.ts +++ b/types/react-relay/v1/lib/react-relay-compat.d.ts @@ -0,0 +1,57 @@ +import { RelayRuntimeTypes, RelayCommonTypes } from 'relay-runtime'; +import { RelayEnvironmentInterface } from './react-relay-classic'; +import {} from './react-relay-modern'; + +// ~~~~~~~~~~~~~~~~~~~~~ +// Maybe Fix +// ~~~~~~~~~~~~~~~~~~~~~ +type ConcreteFragment = any; +type ConcreteBatch = any; +type ConcreteFragmentDefinition = object; +type ConcreteOperationDefinition = object; + +// ~~~~~~~~~~~~~~~~~~~~~ +// Util +// ~~~~~~~~~~~~~~~~~~~~~ +export function getFragment(q: string, v?: RelayCommonTypes.Variables): string; +export interface ComponentWithFragment extends React.ComponentClass { + getFragment: typeof getFragment; +} +export interface StatelessWithFragment extends React.StatelessComponent { + getFragment: typeof getFragment; +} +export type ReactFragmentComponent = ComponentWithFragment | StatelessWithFragment; +export type ReactBaseComponent = React.ComponentClass | React.StatelessComponent; +export type RelayClassicEnvironment = RelayEnvironmentInterface; + +// ~~~~~~~~~~~~~~~~~~~~~ +// RelayCompatTypes +// ~~~~~~~~~~~~~~~~~~~~~ +export type CompatEnvironment = RelayRuntimeTypes.Environment | RelayClassicEnvironment; + +// ~~~~~~~~~~~~~~~~~~~~~ +// RelayCompatMutations +// ~~~~~~~~~~~~~~~~~~~~~ +export function commitUpdate( + environment: CompatEnvironment, + config: RelayRuntimeTypes.MutationConfig, +): RelayCommonTypes.Disposable; +export function applyUpdate( + environment: CompatEnvironment, + config: RelayRuntimeTypes.OptimisticMutationConfig, +): RelayCommonTypes.Disposable; + +// ~~~~~~~~~~~~~~~~~~~~~ +// RelayCompatContainer +// ~~~~~~~~~~~~~~~~~~~~~ +export interface GeneratedNodeMap { [key: string]: RelayCommonTypes.GraphQLTaggedNode; } +export function createContainer( + Component: ReactBaseComponent, + fragmentSpec: RelayCommonTypes.GraphQLTaggedNode | GeneratedNodeMap, +): ReactFragmentComponent; + +// ~~~~~~~~~~~~~~~~~~~~~ +// injectDefaultVariablesProvider +// ~~~~~~~~~~~~~~~~~~~~~ +export type VariablesProvider = () => RelayCommonTypes.Variables; +export function injectDefaultVariablesProvider(variablesProvider: VariablesProvider): void; diff --git a/types/react-relay/v1/lib/react-relay-modern.d.ts b/types/react-relay/v1/lib/react-relay-modern.d.ts index e69de29bb2..f6d1eb0381 100644 --- a/types/react-relay/v1/lib/react-relay-modern.d.ts +++ b/types/react-relay/v1/lib/react-relay-modern.d.ts @@ -0,0 +1,147 @@ +import * as React from 'react'; +import { RelayCommonTypes, RelayRuntimeTypes } from 'relay-runtime'; + +// ~~~~~~~~~~~~~~~~~~~~~ +// Maybe Fix +// ~~~~~~~~~~~~~~~~~~~~~ +type ConcreteFragment = any; +type ConcreteBatch = any; +type ConcreteFragmentDefinition = object; +type ConcreteOperationDefinition = object; +type ReactBaseComponent = React.ComponentClass | React.StatelessComponent; + +// ~~~~~~~~~~~~~~~~~~~~~ +// RelayProp +// ~~~~~~~~~~~~~~~~~~~~~ +// note: refetch and pagination containers augment this +export interface RelayProp { + environment: RelayRuntimeTypes.Environment; +} + +// ~~~~~~~~~~~~~~~~~~~~~ +// RelayQL +// ~~~~~~~~~~~~~~~~~~~~~ +export function RelayQL( + strings: string[], + ...substitutions: any[] +): RelayCommonTypes.RelayConcreteNode; + +// ~~~~~~~~~~~~~~~~~~~~~ +// RelayModernGraphQLTag +// ~~~~~~~~~~~~~~~~~~~~~ +export interface GeneratedNodeMap { [key: string]: GraphQLTaggedNode; } +export type GraphQLTaggedNode = + (() => ConcreteFragment | ConcreteBatch) + | { + modern(): ConcreteFragment | ConcreteBatch, + classic(relayQL: typeof RelayQL): + | ConcreteFragmentDefinition + | ConcreteOperationDefinition, + }; +/** + * Runtime function to correspond to the `graphql` tagged template function. + * All calls to this function should be transformed by the plugin. + */ +export interface GraphqlInterface { + (strings: string[] | TemplateStringsArray): GraphQLTaggedNode; + experimental(strings: string[] | TemplateStringsArray): GraphQLTaggedNode; +} +export const graphql: GraphqlInterface; + +// ~~~~~~~~~~~~~~~~~~~~~ +// ReactRelayQueryRenderer +// ~~~~~~~~~~~~~~~~~~~~~ +export interface QueryRendererProps { + cacheConfig?: RelayCommonTypes.CacheConfig; + environment: RelayRuntimeTypes.Environment; + query: GraphQLTaggedNode; + render(readyState: ReadyState): React.ReactElement | undefined | null; + variables: RelayCommonTypes.Variables; + rerunParamExperimental?: RelayCommonTypes.RerunParam; +} +export interface ReadyState { + error: Error | undefined | null; + props: { [propName: string]: any } | undefined | null; + retry?(): void; +} +export interface QueryRendererState { + readyState: ReadyState; +} +export class ReactRelayQueryRenderer extends React.Component { } + +// ~~~~~~~~~~~~~~~~~~~~~ +// createFragmentContainer +// ~~~~~~~~~~~~~~~~~~~~~ +export function createFragmentContainer( + Component: ReactBaseComponent, + fragmentSpec: GraphQLTaggedNode | GeneratedNodeMap, +): ReactBaseComponent; + +// ~~~~~~~~~~~~~~~~~~~~~ +// createPaginationContainer +// ~~~~~~~~~~~~~~~~~~~~~ +export interface PageInfo { + endCursor: string | undefined | null; + hasNextPage: boolean; + hasPreviousPage: boolean; + startCursor: string | undefined | null; +} +export interface ConnectionData { + edges?: any[]; + pageInfo?: PageInfo; +} +export type RelayPaginationProp = RelayProp & { + hasMore(): boolean, + isLoading(): boolean, + loadMore( + pageSize: number, + callback: (error?: Error) => void, + options?: RefetchOptions, + ): RelayCommonTypes.Disposable | undefined | null, + refetchConnection( + totalCount: number, + callback: (error?: Error) => void, + refetchVariables?: RelayCommonTypes.Variables, + ): RelayCommonTypes.Disposable | undefined | null, +}; +export function FragmentVariablesGetter( + prevVars: RelayCommonTypes.Variables, + totalCount: number, +): RelayCommonTypes.Variables; +export interface ConnectionConfig { + direction?: 'backward' | 'forward'; + getConnectionFromProps?(props: object): ConnectionData | undefined | null; + getFragmentVariables?: typeof FragmentVariablesGetter; + getVariables( + props: { [propName: string]: any }, + paginationInfo: { count: number, cursor?: string }, + fragmentVariables: RelayCommonTypes.Variables, + ): RelayCommonTypes.Variables; + query: GraphQLTaggedNode; +} +export function createPaginationContainer( + Component: ReactBaseComponent, + fragmentSpec: GraphQLTaggedNode | GeneratedNodeMap, + connectionConfig: ConnectionConfig, +): ReactBaseComponent; + +// ~~~~~~~~~~~~~~~~~~~~~ +// createFragmentContainer +// ~~~~~~~~~~~~~~~~~~~~~ +export interface RefetchOptions { + force?: boolean; + rerunParamExperimental?: RelayCommonTypes.RerunParam; +} +export type RelayRefetchProp = RelayProp & { + refetch( + refetchVariables: RelayCommonTypes.Variables | ((fragmentVariables: RelayCommonTypes.Variables) => RelayCommonTypes.Variables), + renderVariables?: RelayCommonTypes.Variables, + callback?: (error?: Error) => void, + options?: RefetchOptions, + ): RelayCommonTypes.Disposable, +}; +export function createRefetchContainer( + Component: ReactBaseComponent, + fragmentSpec: GraphQLTaggedNode | GeneratedNodeMap, + taggedNode: GraphQLTaggedNode, +): ReactBaseComponent; diff --git a/types/react-relay/v1/react-relay-tests.tsx b/types/react-relay/v1/react-relay-tests.tsx index 2b8e371ee2..50506ac111 100644 --- a/types/react-relay/v1/react-relay-tests.tsx +++ b/types/react-relay/v1/react-relay-tests.tsx @@ -18,8 +18,7 @@ import { createRefetchContainer, requestSubscription, QueryRenderer, - RelayPaginationProp, - RelayRefetchProp + ModernTypes, } from "react-relay"; // ~~~~~~~~~~~~~~~~~~~~~ @@ -84,7 +83,7 @@ const MyFragmentContainer = createFragmentContainer( // ~~~~~~~~~~~~~~~~~~~~~ interface StoryInterface { id: string; } interface FeedStoriesProps { - relay: RelayRefetchProp; + relay: ModernTypes.RelayRefetchProp; feed: { stories: { edges: Array<{ node: StoryInterface }> } }; @@ -147,7 +146,7 @@ const FeedRefetchContainer = createRefetchContainer( // ~~~~~~~~~~~~~~~~~~~~~ interface FeedProps { user: { feed: { edges: Array<{ node: StoryInterface}>}}; - relay: RelayPaginationProp; + relay: ModernTypes.RelayPaginationProp; } class Feed extends React.Component { render() { @@ -344,10 +343,19 @@ requestSubscription( } ); +//////////////////////////// +// RELAY COMPAT TESTS +/////////////////////////// +import { + QueryRenderer as CompatQueryRenderer, + createFragmentContainer as createFragmentContainerCompat +} from "react-relay/compat"; + +// TODO? This is all more or less identical to modern... + //////////////////////////// // RELAY-CLASSIC TESTS /////////////////////////// - import * as Relay from "react-relay/classic"; interface Props { diff --git a/types/react-relay/v1/tsconfig.json b/types/react-relay/v1/tsconfig.json index e6b06bf446..37049aa13e 100644 --- a/types/react-relay/v1/tsconfig.json +++ b/types/react-relay/v1/tsconfig.json @@ -18,7 +18,9 @@ "jsx": "react", "paths": { "react-relay": ["react-relay/v1"], - "react-relay/*": ["react-relay/v2/*"] + "react-relay/*": ["react-relay/v1/*"], + "react-relay/classic": ["react-relay/v1/classic.d"], + "react-relay/compat": ["react-relay/v1/compat.d"] } }, "files": [ From aafbcfd90bb6ff374842b5e370e3c08790fa0b46 Mon Sep 17 00:00:00 2001 From: Daniel Lebrecht Date: Tue, 3 Oct 2017 13:57:11 +0200 Subject: [PATCH 033/828] verify should return boolean, fixed inputs --- types/bitcoinjs-lib/bitcoinjs-lib-tests.ts | 2 +- types/bitcoinjs-lib/index.d.ts | 19 ++++++++++--------- 2 files changed, 11 insertions(+), 10 deletions(-) diff --git a/types/bitcoinjs-lib/bitcoinjs-lib-tests.ts b/types/bitcoinjs-lib/bitcoinjs-lib-tests.ts index 549de76507..868659e6b6 100644 --- a/types/bitcoinjs-lib/bitcoinjs-lib-tests.ts +++ b/types/bitcoinjs-lib/bitcoinjs-lib-tests.ts @@ -53,7 +53,7 @@ describe('bitcoinjs-lib (basic)', () => { const tx = new bitcoin.TransactionBuilder(); tx.addInput('aa94ab02c182214f090e99a0d57021caffd0f195a81c24602b1028b130b63e31', 0); - tx.addOutput(Buffer.from('1Gokm82v6DmtwKEB8AiVhm82hyFSsEvBDK'), 15000); + tx.addOutput(Buffer.from('1Gokm82v6DmtwKEB8AiVhm82hyFSsEvBDK', 'utf8'), 15000); tx.sign(0, keyPair); // tslint:disable-next-line:max-line-length diff --git a/types/bitcoinjs-lib/index.d.ts b/types/bitcoinjs-lib/index.d.ts index 20e7162ecf..796758715d 100644 --- a/types/bitcoinjs-lib/index.d.ts +++ b/types/bitcoinjs-lib/index.d.ts @@ -132,7 +132,7 @@ export class HDNode { toBase58(): string; - verify(hash: Buffer, signature: ECSignature): Buffer; + verify(hash: Buffer, signature: ECSignature): boolean; static HIGHEST_BIT: number; @@ -204,15 +204,16 @@ export class Transaction { } export class TransactionBuilder { - constructor(network?: Network, maximumFeeRate?: number); - + tx: Transaction; inputs: Array<{ pubKeys: Buffer[], - signatures: ECSignature[], - prevOutScript: Buffer, - prevOutType: string, - signType: string, - signScript: Buffer, - witness: boolean} >; + signatures: Buffer[], + prevOutScript: Buffer, + prevOutType: string, + signType: string, + signScript: Buffer, + witness: boolean} >; + + constructor(network?: Network, maximumFeeRate?: number); addInput(txhash: Buffer | string | Transaction, vout: number, sequence?: number, prevOutScript?: Buffer): number; From 694fb9b2286ba5d37d3c8a4d85e05dd9a6c855b5 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Eloy=20Dur=C3=A1n?= Date: Wed, 11 Oct 2017 15:08:00 +0200 Subject: [PATCH 034/828] [Relay] Change imports to work as per normal usage. --- .../react-relay-classic.d.ts => classic.d.ts} | 0 .../react-relay-compat.d.ts => compat.d.ts} | 4 +- types/react-relay/index.d.ts | 175 +------ .../react-relay-modern.d.ts => modern.d.ts} | 0 .../react-relay/react-relay-classic-tests.tsx | 92 ++++ types/react-relay/react-relay-tests.tsx | 401 +++++++++++++++- types/react-relay/tsconfig.json | 10 +- types/react-relay/{v1 => }/tslint.json | 0 types/react-relay/v1/index.d.ts | 23 - types/react-relay/v1/react-relay-tests.tsx | 445 ------------------ types/react-relay/v1/tsconfig.json | 33 -- 11 files changed, 497 insertions(+), 686 deletions(-) rename types/react-relay/{v1/lib/react-relay-classic.d.ts => classic.d.ts} (100%) rename types/react-relay/{v1/lib/react-relay-compat.d.ts => compat.d.ts} (95%) rename types/react-relay/{v1/lib/react-relay-modern.d.ts => modern.d.ts} (100%) create mode 100644 types/react-relay/react-relay-classic-tests.tsx rename types/react-relay/{v1 => }/tslint.json (100%) delete mode 100644 types/react-relay/v1/index.d.ts delete mode 100644 types/react-relay/v1/react-relay-tests.tsx delete mode 100644 types/react-relay/v1/tsconfig.json diff --git a/types/react-relay/v1/lib/react-relay-classic.d.ts b/types/react-relay/classic.d.ts similarity index 100% rename from types/react-relay/v1/lib/react-relay-classic.d.ts rename to types/react-relay/classic.d.ts diff --git a/types/react-relay/v1/lib/react-relay-compat.d.ts b/types/react-relay/compat.d.ts similarity index 95% rename from types/react-relay/v1/lib/react-relay-compat.d.ts rename to types/react-relay/compat.d.ts index 0d6197d2eb..e16bbb01f9 100644 --- a/types/react-relay/v1/lib/react-relay-compat.d.ts +++ b/types/react-relay/compat.d.ts @@ -1,6 +1,6 @@ import { RelayRuntimeTypes, RelayCommonTypes } from 'relay-runtime'; -import { RelayEnvironmentInterface } from './react-relay-classic'; -import {} from './react-relay-modern'; +import { RelayEnvironmentInterface } from 'react-relay/classic'; +import {} from 'react-relay/modern'; // ~~~~~~~~~~~~~~~~~~~~~ // Maybe Fix diff --git a/types/react-relay/index.d.ts b/types/react-relay/index.d.ts index 4f9f49e5e7..72a661e6b7 100644 --- a/types/react-relay/index.d.ts +++ b/types/react-relay/index.d.ts @@ -1,160 +1,23 @@ -// Type definitions for react-relay 0.9.2 +// Type definitions for react-relay 1.3 // Project: https://github.com/facebook/relay -// Definitions by: Johannes Schickling +// Definitions by: Johannes Schickling , Matt Martin // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -// TypeScript Version: 2.3 +// TypeScript Version: 2.4 -declare module "react-relay" { - import * as React from "react"; +import { RelayRuntimeTypes } from 'relay-runtime'; +import * as ReactRelayModernTypes from 'react-relay/modern'; - type ClientMutationID = string; - - /** Fragments are a hash of functions */ - interface Fragments { - [query: string]: ((variables?: RelayVariables) => string) - } - - interface CreateContainerOpts { - initialVariables?: any - fragments: Fragments - prepareVariables?(prevVariables: RelayVariables): RelayVariables - } - - interface RelayVariables { - [name: string]: any - } - - /** add static getFragment method to the component constructor */ - interface RelayContainerClass extends React.ComponentClass { - getFragment: ((q: string, v?: RelayVariables) => string) - } - - interface RelayQueryRequestResolve { - response: any - } - - type RelayMutationStatus = - 'UNCOMMITTED' | // Transaction hasn't yet been sent to the server. Transaction can be committed or rolled back. - 'COMMIT_QUEUED' | // Transaction was committed but another transaction with the same collision key is pending, so the transaction has been queued to send to the server. - 'COLLISION_COMMIT_FAILED' | //Transaction was queued for commit but another transaction with the same collision key failed. All transactions in the collision queue, including this one, have been failed. Transaction can be recommitted or rolled back. - 'COMMITTING' | // Transaction is waiting for the server to respond. - 'COMMIT_FAILED'; - - class RelayMutationTransaction { - applyOptimistic(): RelayMutationTransaction; - commit(): RelayMutationTransaction | null; - recommit(): void; - rollback(): void; - getError(): Error; - getStatus(): RelayMutationStatus; - getHash(): string; - getID(): ClientMutationID; - } - - interface RelayMutationRequest { - getQueryString(): string - getVariables(): RelayVariables - resolve(result: RelayQueryRequestResolve): any - reject(errors: any): any - } - - interface RelayQueryRequest { - resolve(result: RelayQueryRequestResolve): any - reject(errors: any): any - - getQueryString(): string - getVariables(): RelayVariables - getID(): string - getDebugName(): string - } - - interface RelayNetworkLayer { - supports(...options: string[]): boolean - } - - class DefaultNetworkLayer implements RelayNetworkLayer { - constructor(host: string, options?: any) - supports(...options: string[]): boolean - } - - function createContainer(component: React.ComponentClass | React.StatelessComponent, params?: CreateContainerOpts): RelayContainerClass - function injectNetworkLayer(networkLayer: RelayNetworkLayer): any - function isContainer(component: React.ComponentClass): boolean - function QL(...args: any[]): string - - class Route { - constructor(params?: RelayVariables) - } - - /** - * Relay Mutation class, where T are the props it takes and S is the returned payload from Relay.Store.update. - * S is typically dynamic as it depends on the data the app is currently using, but it's possible to always - * return some data in the payload using REQUIRED_CHILDREN which is where specifying S is the most useful. - */ - class Mutation { - props: T - - constructor(props: T) - static getFragment(q: string): string - } - - interface Transaction { - getError(): Error - Status(): number - } - - interface StoreUpdateCallbacks { - onFailure?(transaction: Transaction): any - onSuccess?(response: T): any - } - - interface Store { - commitUpdate(mutation: Mutation, callbacks?: StoreUpdateCallbacks): any - } - - var Store: Store - - class RootContainer extends React.Component {} - - interface RootContainerProps extends React.Props{ - Component: RelayContainerClass - route: Route - renderLoading?(): JSX.Element - renderFetched?(data: any): JSX.Element - renderFailure?(error: Error, retry: Function): JSX.Element - } - - type ReadyStateEvent = - 'ABORT' | - 'CACHE_RESTORED_REQUIRED' | - 'CACHE_RESTORE_FAILED' | - 'CACHE_RESTORE_START' | - 'NETWORK_QUERY_ERROR' | - 'NETWORK_QUERY_RECEIVED_ALL' | - 'NETWORK_QUERY_RECEIVED_REQUIRED' | - 'NETWORK_QUERY_START' | - 'STORE_FOUND_ALL' | - 'STORE_FOUND_REQUIRED'; - - interface OnReadyStateChange { - (readyState: { - ready: boolean, - done: boolean, - stale: boolean, - error?: Error, - events: Array, - aborted: boolean - }): void - } - - interface RelayProp { - readonly route: { name: string; }; // incomplete, also has params and queries - readonly variables: any; - readonly pendingVariables?: any | null; - setVariables(variables: any, onReadyStateChange?: OnReadyStateChange): void; - forceFetch(variables: any, onReadyStateChange?: OnReadyStateChange): void; - hasOptimisticUpdate(record: any): boolean; - getPendingTransactions(record: any): RelayMutationTransaction[]; - commitUpdate: (mutation: Mutation, callbacks?: StoreUpdateCallbacks) => any; - } -} +// ~~~~~~~~~~~~~~~~~~~~~ +// React-Relay Modern +// ~~~~~~~~~~~~~~~~~~~~~ +export import QueryRenderer = ReactRelayModernTypes.ReactRelayQueryRenderer; +export import createFragmentContainer = ReactRelayModernTypes.createFragmentContainer; +export import createPaginationContainer = ReactRelayModernTypes.createPaginationContainer; +export import createRefetchContainer = ReactRelayModernTypes.createRefetchContainer; +export import graphql = ReactRelayModernTypes.graphql; +export import commitLocalUpdate = RelayRuntimeTypes.commitLocalUpdate; +export import commitMutation = RelayRuntimeTypes.commitRelayModernMutation; +export import fetchQuery = RelayRuntimeTypes.fetchRelayModernQuery; +export import requestSubscription = RelayRuntimeTypes.requestRelaySubscription; +// exported for convenience +export import ModernTypes = ReactRelayModernTypes; diff --git a/types/react-relay/v1/lib/react-relay-modern.d.ts b/types/react-relay/modern.d.ts similarity index 100% rename from types/react-relay/v1/lib/react-relay-modern.d.ts rename to types/react-relay/modern.d.ts diff --git a/types/react-relay/react-relay-classic-tests.tsx b/types/react-relay/react-relay-classic-tests.tsx new file mode 100644 index 0000000000..b7531598eb --- /dev/null +++ b/types/react-relay/react-relay-classic-tests.tsx @@ -0,0 +1,92 @@ +import * as React from "react" +import * as Relay from "react-relay/classic" + +interface Props { + text: string + userId: string +} + +interface Response { +} + +export default class AddTweetMutation extends Relay.Mutation { + + getMutation () { + return Relay.QL`mutation{addTweet}` + } + + getFatQuery () { + return Relay.QL` + fragment on AddTweetPayload { + tweetEdge + user + } + ` + } + + getConfigs () { + return [{ + type: "RANGE_ADD", + parentName: "user", + parentID: this.props.userId, + connectionName: "tweets", + edgeName: "tweetEdge", + rangeBehaviors: { + "": "append", + }, + }] + } + + getVariables () { + return this.props + } +} + +interface ArtworkProps { + artwork: { + title: string + }, + relay: Relay.RelayProp, +} + +class Artwork extends React.Component { + render() { + return ( + + {this.props.artwork.title} + + ) + } +} + +const ArtworkContainer = Relay.createContainer(Artwork, { + fragments: { + artwork: () => Relay.QL` + fragment on Artwork { + title + } + ` + } +}) + +class StubbedArtwork extends React.Component { + render() { + const props = { + artwork: { title: "CHAMPAGNE FORMICA FLAG" }, + relay: { + route: { + name: "champagne" + }, + variables: { + artworkID: "champagne-formica-flag", + }, + setVariables: () => {}, + forceFetch: () => {}, + hasOptimisticUpdate: () => false, + getPendingTransactions: (): Relay.RelayMutationTransaction[] => undefined, + commitUpdate: () => {}, + } + } + return + } +} diff --git a/types/react-relay/react-relay-tests.tsx b/types/react-relay/react-relay-tests.tsx index 90425156cc..50506ac111 100644 --- a/types/react-relay/react-relay-tests.tsx +++ b/types/react-relay/react-relay-tests.tsx @@ -1,30 +1,383 @@ -import * as React from "react" -import * as Relay from "react-relay" +import * as React from "react"; +import { + Environment, + Network, + RecordSource, + Store, + ConnectionHandler, +} from 'relay-runtime'; -interface Props { - text: string - userId: string +//////////////////////////// +// RELAY MODERN TESTS +/////////////////////////// +import { + graphql, + commitMutation, + createFragmentContainer, + createPaginationContainer, + createRefetchContainer, + requestSubscription, + QueryRenderer, + ModernTypes, +} from "react-relay"; + +// ~~~~~~~~~~~~~~~~~~~~~ +// Modern Environment +// ~~~~~~~~~~~~~~~~~~~~~ +function fetchQuery(operation: any, variables: any, cacheConfig: {}) { + return fetch('/graphql'); } +const network = Network.create(fetchQuery); +const source = new RecordSource(); +const store = new Store(source); +const modernEnvironment = new Environment({ network, store }); -interface Response { +// ~~~~~~~~~~~~~~~~~~~~~ +// Modern QueryRenderer +// ~~~~~~~~~~~~~~~~~~~~~ +const MyQueryRenderer = (props: { name: string}) => ( + { + if (error) { + return
{error.message}
; + } else if (props) { + return
{props.name} is great!
; + } + return
Loading
; + }} + /> +); + +// ~~~~~~~~~~~~~~~~~~~~~ +// Modern FragmentContainer +// ~~~~~~~~~~~~~~~~~~~~~ +const MyFragmentContainer = createFragmentContainer( + class TodoListView extends React.Component { + render() { + return
; + } + }, + { + item: graphql` + fragment TodoItem_item on Todo { + text + isComplete + } + `, + } +); + +// ~~~~~~~~~~~~~~~~~~~~~ +// Modern RefetchContainer +// ~~~~~~~~~~~~~~~~~~~~~ +interface StoryInterface { id: string; } +interface FeedStoriesProps { + relay: ModernTypes.RelayRefetchProp; + feed: { + stories: { edges: Array<{ node: StoryInterface }> } + }; } - -export default class AddTweetMutation extends Relay.Mutation { - - getMutation () { - return Relay.QL`mutation{addTweet}` +class Story extends React.Component<{ story: StoryInterface }> {} +class FeedStories extends React.Component { + render() { + return ( +
+ {this.props.feed.stories.edges.map( + edge => + )} +
+ ); } - getFatQuery () { + _loadMore() { + // Increments the number of stories being rendered by 10. + const refetchVariables = (fragmentVariables: {count: number }) => ({ + count: fragmentVariables.count + 10, + }); + this.props.relay.refetch(refetchVariables); + } + } + +const FeedRefetchContainer = createRefetchContainer( + FeedStories, + { + feed: graphql.experimental` + fragment FeedStories_feed on Feed + @argumentDefinitions( + count: {type: "Int", defaultValue: 10} + ) { + stories(first: $count) { + edges { + node { + id + ...Story_story + } + } + } + } + ` + }, + graphql.experimental` + query FeedStoriesRefetchQuery($count: Int) { + feed { + ...FeedStories_feed @arguments(count: $count) + } + } + `, + ); + +// ~~~~~~~~~~~~~~~~~~~~~ +// Modern PaginationContainer +// ~~~~~~~~~~~~~~~~~~~~~ +interface FeedProps { + user: { feed: { edges: Array<{ node: StoryInterface}>}}; + relay: ModernTypes.RelayPaginationProp; +} +class Feed extends React.Component { + render() { + return (
+ {this.props.user.feed.edges.map( + edge => + )} +
); + } + + _loadMore() { + if (!this.props.relay.hasMore() || this.props.relay.isLoading()) { + return; + } + + this.props.relay.loadMore( + 10, // Fetch the next 10 feed items + e => { + console.log(e); + }, + ); + } +} + +const FeedPaginationContainer = createPaginationContainer( + Feed, + { + user: graphql` + fragment Feed_user on User { + feed( + first: $count + after: $cursor + orderby: $orderBy # other variables + ) @connection(key: "Feed_feed") { + edges { + node { + id + ...Story_story + } + } + } + } + `, + }, + { + direction: 'forward', + getConnectionFromProps(props: { user: {feed: any}}) { + return props.user && props.user.feed; + }, + getFragmentVariables(prevVars, totalCount) { + return { + ...prevVars, + count: totalCount, + }; + }, + getVariables(props, {count, cursor}, fragmentVariables) { + return { + count, + cursor, + // in most cases, for variables other than connection filters like + // `first`, `after`, etc. you may want to use the previous values. + orderBy: fragmentVariables.orderBy, + }; + }, + query: graphql` + query FeedPaginationQuery( + $count: Int! + $cursor: String + $orderby: String! + ) { + user { + # You could reference the fragment defined previously. + ...Feed_user + } + } + ` + } +); + +// ~~~~~~~~~~~~~~~~~~~~~ +// Modern Mutations +// ~~~~~~~~~~~~~~~~~~~~~ +const mutation = graphql` +mutation MarkReadNotificationMutation( + $input: MarkReadNotificationData! +) { + markReadNotification(data: $input) { + notification { + seenState + } + } +} +`; + +const optimisticResponse = { + markReadNotification: { + notification: { + seenState: 'SEEN', + }, + }, +}; + +const configs = [{ + type: 'NODE_DELETE' as 'NODE_DELETE', + deletedIDFieldName: 'destroyedShipId', +}, { + type: 'RANGE_ADD' as 'RANGE_ADD', + parentID: 'shipId', + connectionInfo: [{ + key: 'AddShip_ships', + rangeBehavior: 'append', + }], + edgeName: 'newShipEdge', +}, { + type: 'RANGE_DELETE' as 'RANGE_DELETE', + parentID: 'todoId', + connectionKeys: [{ + key: 'RemoveTags_tags', + rangeBehavior: 'append', + }], + pathToConnection: ['todo', 'tags'], + deletedIDFieldName: 'removedTagId' +}]; + +function markNotificationAsRead(source: string, storyID: string) { + const variables = { + input: { + source, + storyID, + }, + }; + + commitMutation( + modernEnvironment, + { + configs, + mutation, + optimisticResponse, + variables, + onCompleted: (response, errors) => { + console.log('Response received from server.'); + }, + onError: err => console.error(err), + }, + ); +} + +// ~~~~~~~~~~~~~~~~~~~~~ +// Modern Subscriptions +// ~~~~~~~~~~~~~~~~~~~~~ +const subscription = graphql` + subscription MarkReadNotificationSubscription( + $storyID: ID! + ) { + markReadNotification(storyID: $storyID) { + notification { + seenState + } + } + } +`; +const variables = { + storyID: '123', +}; +requestSubscription( + modernEnvironment, // see Environment docs + { + subscription, + variables, + // optional but recommended: + onCompleted: () => {}, + onError: error => console.error(error), + // example of a custom updater + updater: store => { + // Get the notification + const rootField = store.getRootField('markReadNotification'); + const notification = !!rootField && rootField.getLinkedRecord('notification'); + // Add it to a connection + const viewer = store.getRoot().getLinkedRecord('viewer'); + const notifications = + ConnectionHandler.getConnection(viewer, 'notifications'); + const edge = ConnectionHandler.createEdge( + store, + notifications, + notification, + '', + ); + ConnectionHandler.insertEdgeAfter(notifications, edge); + }, + } +); + +//////////////////////////// +// RELAY COMPAT TESTS +/////////////////////////// +import { + QueryRenderer as CompatQueryRenderer, + createFragmentContainer as createFragmentContainerCompat +} from "react-relay/compat"; + +// TODO? This is all more or less identical to modern... + +//////////////////////////// +// RELAY-CLASSIC TESTS +/////////////////////////// +import * as Relay from "react-relay/classic"; + +interface Props { + text: string; + userId: string; +} + +export default class AddTweetMutation extends Relay.Mutation { + getMutation() { + return Relay.QL`mutation{addTweet}`; + } + + getFatQuery() { return Relay.QL` fragment on AddTweetPayload { tweetEdge user } - ` + `; } - getConfigs () { + getConfigs() { return [{ type: "RANGE_ADD", parentName: "user", @@ -34,19 +387,19 @@ export default class AddTweetMutation extends Relay.Mutation { rangeBehaviors: { "": "append", }, - }] + }]; } - getVariables () { - return this.props + getVariables() { + return this.props; } } interface ArtworkProps { artwork: { title: string - }, - relay: Relay.RelayProp, + }; + relay: Relay.RelayProp; } class Artwork extends React.Component { @@ -55,7 +408,7 @@ class Artwork extends React.Component { {this.props.artwork.title} - ) + ); } } @@ -67,7 +420,7 @@ const ArtworkContainer = Relay.createContainer(Artwork, { } ` } -}) +}); class StubbedArtwork extends React.Component { render() { @@ -83,10 +436,10 @@ class StubbedArtwork extends React.Component { setVariables: () => {}, forceFetch: () => {}, hasOptimisticUpdate: () => false, - getPendingTransactions: (): Relay.RelayMutationTransaction[] => undefined, + getPendingTransactions: (): any => undefined, commitUpdate: () => {}, } - } - return + }; + return ; } } diff --git a/types/react-relay/tsconfig.json b/types/react-relay/tsconfig.json index 90680fbafc..5447ff74ca 100644 --- a/types/react-relay/tsconfig.json +++ b/types/react-relay/tsconfig.json @@ -7,7 +7,7 @@ ], "noImplicitAny": true, "noImplicitThis": true, - "strictNullChecks": false, + "strictNullChecks": true, "baseUrl": "../", "typeRoots": [ "../" @@ -19,6 +19,10 @@ }, "files": [ "index.d.ts", - "react-relay-tests.tsx" + "react-relay-tests.tsx", + "react-relay-classic-tests.tsx", + "classic.d.ts", + "modern.d.ts", + "compat.d.ts" ] -} \ No newline at end of file +} diff --git a/types/react-relay/v1/tslint.json b/types/react-relay/tslint.json similarity index 100% rename from types/react-relay/v1/tslint.json rename to types/react-relay/tslint.json diff --git a/types/react-relay/v1/index.d.ts b/types/react-relay/v1/index.d.ts deleted file mode 100644 index e214a9a441..0000000000 --- a/types/react-relay/v1/index.d.ts +++ /dev/null @@ -1,23 +0,0 @@ -// Type definitions for react-relay 1.3 -// Project: https://github.com/facebook/relay -// Definitions by: Johannes Schickling , Matt Martin -// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -// TypeScript Version: 2.4 - -import { RelayRuntimeTypes } from 'relay-runtime'; -import * as ReactRelayModernTypes from './lib/react-relay-modern'; - -// ~~~~~~~~~~~~~~~~~~~~~ -// React-Relay Modern -// ~~~~~~~~~~~~~~~~~~~~~ -export import QueryRenderer = ReactRelayModernTypes.ReactRelayQueryRenderer; -export import createFragmentContainer = ReactRelayModernTypes.createFragmentContainer; -export import createPaginationContainer = ReactRelayModernTypes.createPaginationContainer; -export import createRefetchContainer = ReactRelayModernTypes.createRefetchContainer; -export import graphql = ReactRelayModernTypes.graphql; -export import commitLocalUpdate = RelayRuntimeTypes.commitLocalUpdate; -export import commitMutation = RelayRuntimeTypes.commitRelayModernMutation; -export import fetchQuery = RelayRuntimeTypes.fetchRelayModernQuery; -export import requestSubscription = RelayRuntimeTypes.requestRelaySubscription; -// exported for convenience -export import ModernTypes = ReactRelayModernTypes; diff --git a/types/react-relay/v1/react-relay-tests.tsx b/types/react-relay/v1/react-relay-tests.tsx deleted file mode 100644 index 50506ac111..0000000000 --- a/types/react-relay/v1/react-relay-tests.tsx +++ /dev/null @@ -1,445 +0,0 @@ -import * as React from "react"; -import { - Environment, - Network, - RecordSource, - Store, - ConnectionHandler, -} from 'relay-runtime'; - -//////////////////////////// -// RELAY MODERN TESTS -/////////////////////////// -import { - graphql, - commitMutation, - createFragmentContainer, - createPaginationContainer, - createRefetchContainer, - requestSubscription, - QueryRenderer, - ModernTypes, -} from "react-relay"; - -// ~~~~~~~~~~~~~~~~~~~~~ -// Modern Environment -// ~~~~~~~~~~~~~~~~~~~~~ -function fetchQuery(operation: any, variables: any, cacheConfig: {}) { - return fetch('/graphql'); -} -const network = Network.create(fetchQuery); -const source = new RecordSource(); -const store = new Store(source); -const modernEnvironment = new Environment({ network, store }); - -// ~~~~~~~~~~~~~~~~~~~~~ -// Modern QueryRenderer -// ~~~~~~~~~~~~~~~~~~~~~ -const MyQueryRenderer = (props: { name: string}) => ( - { - if (error) { - return
{error.message}
; - } else if (props) { - return
{props.name} is great!
; - } - return
Loading
; - }} - /> -); - -// ~~~~~~~~~~~~~~~~~~~~~ -// Modern FragmentContainer -// ~~~~~~~~~~~~~~~~~~~~~ -const MyFragmentContainer = createFragmentContainer( - class TodoListView extends React.Component { - render() { - return
; - } - }, - { - item: graphql` - fragment TodoItem_item on Todo { - text - isComplete - } - `, - } -); - -// ~~~~~~~~~~~~~~~~~~~~~ -// Modern RefetchContainer -// ~~~~~~~~~~~~~~~~~~~~~ -interface StoryInterface { id: string; } -interface FeedStoriesProps { - relay: ModernTypes.RelayRefetchProp; - feed: { - stories: { edges: Array<{ node: StoryInterface }> } - }; -} -class Story extends React.Component<{ story: StoryInterface }> {} -class FeedStories extends React.Component { - render() { - return ( -
- {this.props.feed.stories.edges.map( - edge => - )} -
- ); - } - - _loadMore() { - // Increments the number of stories being rendered by 10. - const refetchVariables = (fragmentVariables: {count: number }) => ({ - count: fragmentVariables.count + 10, - }); - this.props.relay.refetch(refetchVariables); - } - } - -const FeedRefetchContainer = createRefetchContainer( - FeedStories, - { - feed: graphql.experimental` - fragment FeedStories_feed on Feed - @argumentDefinitions( - count: {type: "Int", defaultValue: 10} - ) { - stories(first: $count) { - edges { - node { - id - ...Story_story - } - } - } - } - ` - }, - graphql.experimental` - query FeedStoriesRefetchQuery($count: Int) { - feed { - ...FeedStories_feed @arguments(count: $count) - } - } - `, - ); - -// ~~~~~~~~~~~~~~~~~~~~~ -// Modern PaginationContainer -// ~~~~~~~~~~~~~~~~~~~~~ -interface FeedProps { - user: { feed: { edges: Array<{ node: StoryInterface}>}}; - relay: ModernTypes.RelayPaginationProp; -} -class Feed extends React.Component { - render() { - return (
- {this.props.user.feed.edges.map( - edge => - )} -
); - } - - _loadMore() { - if (!this.props.relay.hasMore() || this.props.relay.isLoading()) { - return; - } - - this.props.relay.loadMore( - 10, // Fetch the next 10 feed items - e => { - console.log(e); - }, - ); - } -} - -const FeedPaginationContainer = createPaginationContainer( - Feed, - { - user: graphql` - fragment Feed_user on User { - feed( - first: $count - after: $cursor - orderby: $orderBy # other variables - ) @connection(key: "Feed_feed") { - edges { - node { - id - ...Story_story - } - } - } - } - `, - }, - { - direction: 'forward', - getConnectionFromProps(props: { user: {feed: any}}) { - return props.user && props.user.feed; - }, - getFragmentVariables(prevVars, totalCount) { - return { - ...prevVars, - count: totalCount, - }; - }, - getVariables(props, {count, cursor}, fragmentVariables) { - return { - count, - cursor, - // in most cases, for variables other than connection filters like - // `first`, `after`, etc. you may want to use the previous values. - orderBy: fragmentVariables.orderBy, - }; - }, - query: graphql` - query FeedPaginationQuery( - $count: Int! - $cursor: String - $orderby: String! - ) { - user { - # You could reference the fragment defined previously. - ...Feed_user - } - } - ` - } -); - -// ~~~~~~~~~~~~~~~~~~~~~ -// Modern Mutations -// ~~~~~~~~~~~~~~~~~~~~~ -const mutation = graphql` -mutation MarkReadNotificationMutation( - $input: MarkReadNotificationData! -) { - markReadNotification(data: $input) { - notification { - seenState - } - } -} -`; - -const optimisticResponse = { - markReadNotification: { - notification: { - seenState: 'SEEN', - }, - }, -}; - -const configs = [{ - type: 'NODE_DELETE' as 'NODE_DELETE', - deletedIDFieldName: 'destroyedShipId', -}, { - type: 'RANGE_ADD' as 'RANGE_ADD', - parentID: 'shipId', - connectionInfo: [{ - key: 'AddShip_ships', - rangeBehavior: 'append', - }], - edgeName: 'newShipEdge', -}, { - type: 'RANGE_DELETE' as 'RANGE_DELETE', - parentID: 'todoId', - connectionKeys: [{ - key: 'RemoveTags_tags', - rangeBehavior: 'append', - }], - pathToConnection: ['todo', 'tags'], - deletedIDFieldName: 'removedTagId' -}]; - -function markNotificationAsRead(source: string, storyID: string) { - const variables = { - input: { - source, - storyID, - }, - }; - - commitMutation( - modernEnvironment, - { - configs, - mutation, - optimisticResponse, - variables, - onCompleted: (response, errors) => { - console.log('Response received from server.'); - }, - onError: err => console.error(err), - }, - ); -} - -// ~~~~~~~~~~~~~~~~~~~~~ -// Modern Subscriptions -// ~~~~~~~~~~~~~~~~~~~~~ -const subscription = graphql` - subscription MarkReadNotificationSubscription( - $storyID: ID! - ) { - markReadNotification(storyID: $storyID) { - notification { - seenState - } - } - } -`; -const variables = { - storyID: '123', -}; -requestSubscription( - modernEnvironment, // see Environment docs - { - subscription, - variables, - // optional but recommended: - onCompleted: () => {}, - onError: error => console.error(error), - // example of a custom updater - updater: store => { - // Get the notification - const rootField = store.getRootField('markReadNotification'); - const notification = !!rootField && rootField.getLinkedRecord('notification'); - // Add it to a connection - const viewer = store.getRoot().getLinkedRecord('viewer'); - const notifications = - ConnectionHandler.getConnection(viewer, 'notifications'); - const edge = ConnectionHandler.createEdge( - store, - notifications, - notification, - '', - ); - ConnectionHandler.insertEdgeAfter(notifications, edge); - }, - } -); - -//////////////////////////// -// RELAY COMPAT TESTS -/////////////////////////// -import { - QueryRenderer as CompatQueryRenderer, - createFragmentContainer as createFragmentContainerCompat -} from "react-relay/compat"; - -// TODO? This is all more or less identical to modern... - -//////////////////////////// -// RELAY-CLASSIC TESTS -/////////////////////////// -import * as Relay from "react-relay/classic"; - -interface Props { - text: string; - userId: string; -} - -export default class AddTweetMutation extends Relay.Mutation { - getMutation() { - return Relay.QL`mutation{addTweet}`; - } - - getFatQuery() { - return Relay.QL` - fragment on AddTweetPayload { - tweetEdge - user - } - `; - } - - getConfigs() { - return [{ - type: "RANGE_ADD", - parentName: "user", - parentID: this.props.userId, - connectionName: "tweets", - edgeName: "tweetEdge", - rangeBehaviors: { - "": "append", - }, - }]; - } - - getVariables() { - return this.props; - } -} - -interface ArtworkProps { - artwork: { - title: string - }; - relay: Relay.RelayProp; -} - -class Artwork extends React.Component { - render() { - return ( - - {this.props.artwork.title} - - ); - } -} - -const ArtworkContainer = Relay.createContainer(Artwork, { - fragments: { - artwork: () => Relay.QL` - fragment on Artwork { - title - } - ` - } -}); - -class StubbedArtwork extends React.Component { - render() { - const props = { - artwork: { title: "CHAMPAGNE FORMICA FLAG" }, - relay: { - route: { - name: "champagne" - }, - variables: { - artworkID: "champagne-formica-flag", - }, - setVariables: () => {}, - forceFetch: () => {}, - hasOptimisticUpdate: () => false, - getPendingTransactions: (): any => undefined, - commitUpdate: () => {}, - } - }; - return ; - } -} diff --git a/types/react-relay/v1/tsconfig.json b/types/react-relay/v1/tsconfig.json deleted file mode 100644 index 37049aa13e..0000000000 --- a/types/react-relay/v1/tsconfig.json +++ /dev/null @@ -1,33 +0,0 @@ -{ - "compilerOptions": { - "module": "commonjs", - "lib": [ - "es6", - "dom" - ], - "noImplicitAny": true, - "noImplicitThis": true, - "strictNullChecks": true, - "baseUrl": "../../", - "typeRoots": [ - "../../" - ], - "types": [], - "noEmit": true, - "forceConsistentCasingInFileNames": true, - "jsx": "react", - "paths": { - "react-relay": ["react-relay/v1"], - "react-relay/*": ["react-relay/v1/*"], - "react-relay/classic": ["react-relay/v1/classic.d"], - "react-relay/compat": ["react-relay/v1/compat.d"] - } - }, - "files": [ - "index.d.ts", - "react-relay-tests.tsx", - "lib/react-relay-classic.d.ts", - "lib/react-relay-modern.d.ts", - "lib/react-relay-compat.d.ts" - ] -} From b438270ef30cba0eba981947fdbfdd0d579076a5 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Eloy=20Dur=C3=A1n?= Date: Wed, 11 Oct 2017 15:15:43 +0200 Subject: [PATCH 035/828] [Relay] Reformat all files using prettier. prettier --parser typescript --tab-width 4 --semi --trailing-comma es5 \ --write --print-width 120 \ types/{react-relay,relay-runtime}/*.ts* --- types/react-relay/classic.d.ts | 91 ++--- types/react-relay/compat.d.ts | 16 +- types/react-relay/index.d.ts | 4 +- types/react-relay/modern.d.ts | 59 ++- .../react-relay/react-relay-classic-tests.tsx | 75 ++-- types/react-relay/react-relay-tests.tsx | 350 ++++++++---------- types/relay-runtime/index.d.ts | 291 +++++++-------- types/relay-runtime/relay-runtime-tests.tsx | 29 +- 8 files changed, 422 insertions(+), 493 deletions(-) diff --git a/types/react-relay/classic.d.ts b/types/react-relay/classic.d.ts index 02517b7e80..9345199d27 100644 --- a/types/react-relay/classic.d.ts +++ b/types/react-relay/classic.d.ts @@ -1,5 +1,5 @@ -import * as React from 'react'; -import { RelayCommonTypes } from 'relay-runtime'; +import * as React from "react"; +import { RelayCommonTypes } from "relay-runtime"; // ~~~~~~~~~~~~~~~~~~~~~ // Maybe Fix @@ -7,7 +7,11 @@ import { RelayCommonTypes } from 'relay-runtime'; export type StoreReaderData = any; export type StoreReaderOptions = any; export type RelayStoreData = any; -export interface RelayQuery { Fragment: any; Node: any; Root: any; } +export interface RelayQuery { + Fragment: any; + Node: any; + Root: any; +} // ~~~~~~~~~~~~~~~~~~~~~ // Environment @@ -16,33 +20,27 @@ export interface FragmentResolver { dispose(): void; resolve( fragment: RelayQuery["Fragment"], - dataIDs: RelayCommonTypes.DataID | RelayCommonTypes.DataID[], + dataIDs: RelayCommonTypes.DataID | RelayCommonTypes.DataID[] ): StoreReaderData | StoreReaderData[] | undefined | null; } export interface RelayEnvironmentInterface { forceFetch( querySet: RelayCommonTypes.RelayQuerySet, - onReadyStateChange: RelayCommonTypes.ReadyStateChangeCallback, + onReadyStateChange: RelayCommonTypes.ReadyStateChangeCallback ): RelayCommonTypes.Abortable; - getFragmentResolver( - fragment: RelayQuery["Fragment"], - onNext: () => void, - ): FragmentResolver; + getFragmentResolver(fragment: RelayQuery["Fragment"], onNext: () => void): FragmentResolver; getStoreData(): RelayStoreData; primeCache( querySet: RelayCommonTypes.RelayQuerySet, - onReadyStateChange: RelayCommonTypes.ReadyStateChangeCallback, + onReadyStateChange: RelayCommonTypes.ReadyStateChangeCallback ): RelayCommonTypes.Abortable; read( node: RelayQuery["Node"], dataID: RelayCommonTypes.DataID, - options?: StoreReaderOptions, + options?: StoreReaderOptions ): StoreReaderData | void; - readQuery( - root: RelayQuery["Root"], - options?: StoreReaderOptions, - ): StoreReaderData[] | void; + readQuery(root: RelayQuery["Root"], options?: StoreReaderOptions): StoreReaderData[] | void; } // ~~~~~~~~~~~~~~~~~~~~~ @@ -75,12 +73,12 @@ export interface RelayQueryRequestResolve { } export type RelayMutationStatus = - 'UNCOMMITTED' | // Transaction hasn't yet been sent to the server. Transaction can be committed or rolled back. - 'COMMIT_QUEUED' | // Transaction was committed but another transaction with the same collision key is pending, so the transaction has been queued to send to the server. - 'COLLISION_COMMIT_FAILED' | // Transaction was queued for commit but another transaction with the same collision key failed. All transactions in the collision queue, + | "UNCOMMITTED" // Transaction hasn't yet been sent to the server. Transaction can be committed or rolled back. + | "COMMIT_QUEUED" // Transaction was committed but another transaction with the same collision key is pending, so the transaction has been queued to send to the server. + | "COLLISION_COMMIT_FAILED" // Transaction was queued for commit but another transaction with the same collision key failed. All transactions in the collision queue, // including this one, have been failed. Transaction can be recommitted or rolled back. - 'COMMITTING' | // Transaction is waiting for the server to respond. - 'COMMIT_FAILED'; + | "COMMITTING" // Transaction is waiting for the server to respond. + | "COMMIT_FAILED"; export class RelayMutationTransaction { applyOptimistic(): RelayMutationTransaction; @@ -118,13 +116,16 @@ export class DefaultNetworkLayer implements RelayNetworkLayer { supports(...options: string[]): boolean; } -export function createContainer(component: React.ComponentClass | React.StatelessComponent, params?: CreateContainerOpts): RelayContainerClass; +export function createContainer( + component: React.ComponentClass | React.StatelessComponent, + params?: CreateContainerOpts +): RelayContainerClass; export function injectNetworkLayer(networkLayer: RelayNetworkLayer): any; export function isContainer(component: React.ComponentClass): boolean; export function QL(...args: any[]): string; export class Route { - constructor(params?: RelayVariables) + constructor(params?: RelayVariables); } /** @@ -155,7 +156,7 @@ export interface Store { export const Store: Store; -export class RootContainer extends React.Component { } +export class RootContainer extends React.Component {} export interface RootContainerProps extends React.Props { Component: RelayContainerClass; @@ -165,13 +166,13 @@ export interface RootContainerProps extends React.Props { renderFailure?(error: Error, retry: (...args: any[]) => any): JSX.Element; } -export class Renderer extends React.Component { } +export class Renderer extends React.Component {} export interface RendererProps { Container: RelayContainerClass; // Relay container that defines fragments and the view to render. forceFetch?: boolean; // Whether to send a server request regardless of data available on the client. queryConfig: Route; // `QueryConfig` or `Relay.Route` that defines the query roots. - environment: Store; // An instance of `Relay.Environment` or any object that implements the `RelayEnvironment` interface. + environment: Store; // An instance of `Relay.Environment` or any object that implements the `RelayEnvironment` interface. render?: RenderCallback; // Called to render when data requirements are being fulfilled. onReadyStateChange?: OnReadyStateChange; } @@ -186,28 +187,30 @@ export interface RenderStateConfig { export type RenderCallback = (renderState: RenderStateConfig) => any; export type ReadyStateEvent = - 'ABORT' | - 'CACHE_RESTORED_REQUIRED' | - 'CACHE_RESTORE_FAILED' | - 'CACHE_RESTORE_START' | - 'NETWORK_QUERY_ERROR' | - 'NETWORK_QUERY_RECEIVED_ALL' | - 'NETWORK_QUERY_RECEIVED_REQUIRED' | - 'NETWORK_QUERY_START' | - 'STORE_FOUND_ALL' | - 'STORE_FOUND_REQUIRED'; + | "ABORT" + | "CACHE_RESTORED_REQUIRED" + | "CACHE_RESTORE_FAILED" + | "CACHE_RESTORE_START" + | "NETWORK_QUERY_ERROR" + | "NETWORK_QUERY_RECEIVED_ALL" + | "NETWORK_QUERY_RECEIVED_REQUIRED" + | "NETWORK_QUERY_START" + | "STORE_FOUND_ALL" + | "STORE_FOUND_REQUIRED"; -export type OnReadyStateChange = (readyState: { - ready: boolean, - done: boolean, - stale: boolean, - error?: Error, - events: ReadyStateEvent[], - aborted: boolean -}) => void; +export type OnReadyStateChange = ( + readyState: { + ready: boolean; + done: boolean; + stale: boolean; + error?: Error; + events: ReadyStateEvent[]; + aborted: boolean; + } +) => void; export interface RelayProp { - readonly route: { name: string; }; // incomplete, also has params and queries + readonly route: { name: string }; // incomplete, also has params and queries readonly variables: any; readonly pendingVariables?: any; setVariables(variables: any, onReadyStateChange?: OnReadyStateChange): void; diff --git a/types/react-relay/compat.d.ts b/types/react-relay/compat.d.ts index e16bbb01f9..74f7f55a03 100644 --- a/types/react-relay/compat.d.ts +++ b/types/react-relay/compat.d.ts @@ -1,6 +1,6 @@ -import { RelayRuntimeTypes, RelayCommonTypes } from 'relay-runtime'; -import { RelayEnvironmentInterface } from 'react-relay/classic'; -import {} from 'react-relay/modern'; +import { RelayRuntimeTypes, RelayCommonTypes } from "relay-runtime"; +import { RelayEnvironmentInterface } from "react-relay/classic"; +import {} from "react-relay/modern"; // ~~~~~~~~~~~~~~~~~~~~~ // Maybe Fix @@ -34,20 +34,22 @@ export type CompatEnvironment = RelayRuntimeTypes.Environment | RelayClassicEnvi // ~~~~~~~~~~~~~~~~~~~~~ export function commitUpdate( environment: CompatEnvironment, - config: RelayRuntimeTypes.MutationConfig, + config: RelayRuntimeTypes.MutationConfig ): RelayCommonTypes.Disposable; export function applyUpdate( environment: CompatEnvironment, - config: RelayRuntimeTypes.OptimisticMutationConfig, + config: RelayRuntimeTypes.OptimisticMutationConfig ): RelayCommonTypes.Disposable; // ~~~~~~~~~~~~~~~~~~~~~ // RelayCompatContainer // ~~~~~~~~~~~~~~~~~~~~~ -export interface GeneratedNodeMap { [key: string]: RelayCommonTypes.GraphQLTaggedNode; } +export interface GeneratedNodeMap { + [key: string]: RelayCommonTypes.GraphQLTaggedNode; +} export function createContainer( Component: ReactBaseComponent, - fragmentSpec: RelayCommonTypes.GraphQLTaggedNode | GeneratedNodeMap, + fragmentSpec: RelayCommonTypes.GraphQLTaggedNode | GeneratedNodeMap ): ReactFragmentComponent; // ~~~~~~~~~~~~~~~~~~~~~ diff --git a/types/react-relay/index.d.ts b/types/react-relay/index.d.ts index 72a661e6b7..30cb29b3e3 100644 --- a/types/react-relay/index.d.ts +++ b/types/react-relay/index.d.ts @@ -4,8 +4,8 @@ // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped // TypeScript Version: 2.4 -import { RelayRuntimeTypes } from 'relay-runtime'; -import * as ReactRelayModernTypes from 'react-relay/modern'; +import { RelayRuntimeTypes } from "relay-runtime"; +import * as ReactRelayModernTypes from "react-relay/modern"; // ~~~~~~~~~~~~~~~~~~~~~ // React-Relay Modern diff --git a/types/react-relay/modern.d.ts b/types/react-relay/modern.d.ts index f6d1eb0381..13b43bf449 100644 --- a/types/react-relay/modern.d.ts +++ b/types/react-relay/modern.d.ts @@ -1,5 +1,5 @@ -import * as React from 'react'; -import { RelayCommonTypes, RelayRuntimeTypes } from 'relay-runtime'; +import * as React from "react"; +import { RelayCommonTypes, RelayRuntimeTypes } from "relay-runtime"; // ~~~~~~~~~~~~~~~~~~~~~ // Maybe Fix @@ -21,23 +21,20 @@ export interface RelayProp { // ~~~~~~~~~~~~~~~~~~~~~ // RelayQL // ~~~~~~~~~~~~~~~~~~~~~ -export function RelayQL( - strings: string[], - ...substitutions: any[] -): RelayCommonTypes.RelayConcreteNode; +export function RelayQL(strings: string[], ...substitutions: any[]): RelayCommonTypes.RelayConcreteNode; // ~~~~~~~~~~~~~~~~~~~~~ // RelayModernGraphQLTag // ~~~~~~~~~~~~~~~~~~~~~ -export interface GeneratedNodeMap { [key: string]: GraphQLTaggedNode; } +export interface GeneratedNodeMap { + [key: string]: GraphQLTaggedNode; +} export type GraphQLTaggedNode = - (() => ConcreteFragment | ConcreteBatch) + | (() => ConcreteFragment | ConcreteBatch) | { - modern(): ConcreteFragment | ConcreteBatch, - classic(relayQL: typeof RelayQL): - | ConcreteFragmentDefinition - | ConcreteOperationDefinition, - }; + modern(): ConcreteFragment | ConcreteBatch; + classic(relayQL: typeof RelayQL): ConcreteFragmentDefinition | ConcreteOperationDefinition; + }; /** * Runtime function to correspond to the `graphql` tagged template function. * All calls to this function should be transformed by the plugin. @@ -67,14 +64,14 @@ export interface ReadyState { export interface QueryRendererState { readyState: ReadyState; } -export class ReactRelayQueryRenderer extends React.Component { } +export class ReactRelayQueryRenderer extends React.Component {} // ~~~~~~~~~~~~~~~~~~~~~ // createFragmentContainer // ~~~~~~~~~~~~~~~~~~~~~ export function createFragmentContainer( Component: ReactBaseComponent, - fragmentSpec: GraphQLTaggedNode | GeneratedNodeMap, + fragmentSpec: GraphQLTaggedNode | GeneratedNodeMap ): ReactBaseComponent; // ~~~~~~~~~~~~~~~~~~~~~ @@ -91,38 +88,38 @@ export interface ConnectionData { pageInfo?: PageInfo; } export type RelayPaginationProp = RelayProp & { - hasMore(): boolean, - isLoading(): boolean, + hasMore(): boolean; + isLoading(): boolean; loadMore( pageSize: number, callback: (error?: Error) => void, - options?: RefetchOptions, - ): RelayCommonTypes.Disposable | undefined | null, + options?: RefetchOptions + ): RelayCommonTypes.Disposable | undefined | null; refetchConnection( totalCount: number, callback: (error?: Error) => void, - refetchVariables?: RelayCommonTypes.Variables, - ): RelayCommonTypes.Disposable | undefined | null, + refetchVariables?: RelayCommonTypes.Variables + ): RelayCommonTypes.Disposable | undefined | null; }; export function FragmentVariablesGetter( prevVars: RelayCommonTypes.Variables, - totalCount: number, + totalCount: number ): RelayCommonTypes.Variables; export interface ConnectionConfig { - direction?: 'backward' | 'forward'; + direction?: "backward" | "forward"; getConnectionFromProps?(props: object): ConnectionData | undefined | null; getFragmentVariables?: typeof FragmentVariablesGetter; getVariables( props: { [propName: string]: any }, - paginationInfo: { count: number, cursor?: string }, - fragmentVariables: RelayCommonTypes.Variables, + paginationInfo: { count: number; cursor?: string }, + fragmentVariables: RelayCommonTypes.Variables ): RelayCommonTypes.Variables; query: GraphQLTaggedNode; } export function createPaginationContainer( Component: ReactBaseComponent, fragmentSpec: GraphQLTaggedNode | GeneratedNodeMap, - connectionConfig: ConnectionConfig, + connectionConfig: ConnectionConfig ): ReactBaseComponent; // ~~~~~~~~~~~~~~~~~~~~~ @@ -134,14 +131,16 @@ export interface RefetchOptions { } export type RelayRefetchProp = RelayProp & { refetch( - refetchVariables: RelayCommonTypes.Variables | ((fragmentVariables: RelayCommonTypes.Variables) => RelayCommonTypes.Variables), + refetchVariables: + | RelayCommonTypes.Variables + | ((fragmentVariables: RelayCommonTypes.Variables) => RelayCommonTypes.Variables), renderVariables?: RelayCommonTypes.Variables, callback?: (error?: Error) => void, - options?: RefetchOptions, - ): RelayCommonTypes.Disposable, + options?: RefetchOptions + ): RelayCommonTypes.Disposable; }; export function createRefetchContainer( Component: ReactBaseComponent, fragmentSpec: GraphQLTaggedNode | GeneratedNodeMap, - taggedNode: GraphQLTaggedNode, + taggedNode: GraphQLTaggedNode ): ReactBaseComponent; diff --git a/types/react-relay/react-relay-classic-tests.tsx b/types/react-relay/react-relay-classic-tests.tsx index b7531598eb..7aae267dfc 100644 --- a/types/react-relay/react-relay-classic-tests.tsx +++ b/types/react-relay/react-relay-classic-tests.tsx @@ -1,61 +1,58 @@ -import * as React from "react" -import * as Relay from "react-relay/classic" +import * as React from "react"; +import * as Relay from "react-relay/classic"; interface Props { - text: string - userId: string + text: string; + userId: string; } -interface Response { -} +// tslint:disable-next-line no-empty-interface +interface Response {} export default class AddTweetMutation extends Relay.Mutation { - - getMutation () { - return Relay.QL`mutation{addTweet}` + getMutation() { + return Relay.QL`mutation{addTweet}`; } - getFatQuery () { + getFatQuery() { return Relay.QL` fragment on AddTweetPayload { tweetEdge user } - ` + `; } - getConfigs () { - return [{ - type: "RANGE_ADD", - parentName: "user", - parentID: this.props.userId, - connectionName: "tweets", - edgeName: "tweetEdge", - rangeBehaviors: { - "": "append", + getConfigs() { + return [ + { + type: "RANGE_ADD", + parentName: "user", + parentID: this.props.userId, + connectionName: "tweets", + edgeName: "tweetEdge", + rangeBehaviors: { + "": "append", + }, }, - }] + ]; } - getVariables () { - return this.props + getVariables() { + return this.props; } } interface ArtworkProps { artwork: { - title: string - }, - relay: Relay.RelayProp, + title: string; + }; + relay: Relay.RelayProp; } class Artwork extends React.Component { render() { - return ( - - {this.props.artwork.title} - - ) + return {this.props.artwork.title}; } } @@ -65,9 +62,9 @@ const ArtworkContainer = Relay.createContainer(Artwork, { fragment on Artwork { title } - ` - } -}) + `, + }, +}); class StubbedArtwork extends React.Component { render() { @@ -75,7 +72,7 @@ class StubbedArtwork extends React.Component { artwork: { title: "CHAMPAGNE FORMICA FLAG" }, relay: { route: { - name: "champagne" + name: "champagne", }, variables: { artworkID: "champagne-formica-flag", @@ -83,10 +80,10 @@ class StubbedArtwork extends React.Component { setVariables: () => {}, forceFetch: () => {}, hasOptimisticUpdate: () => false, - getPendingTransactions: (): Relay.RelayMutationTransaction[] => undefined, + getPendingTransactions: (): Relay.RelayMutationTransaction[] => [], commitUpdate: () => {}, - } - } - return + }, + }; + return ; } } diff --git a/types/react-relay/react-relay-tests.tsx b/types/react-relay/react-relay-tests.tsx index 50506ac111..97cc5d47d9 100644 --- a/types/react-relay/react-relay-tests.tsx +++ b/types/react-relay/react-relay-tests.tsx @@ -1,11 +1,5 @@ import * as React from "react"; -import { - Environment, - Network, - RecordSource, - Store, - ConnectionHandler, -} from 'relay-runtime'; +import { Environment, Network, RecordSource, Store, ConnectionHandler } from "relay-runtime"; //////////////////////////// // RELAY MODERN TESTS @@ -25,7 +19,7 @@ import { // Modern Environment // ~~~~~~~~~~~~~~~~~~~~~ function fetchQuery(operation: any, variables: any, cacheConfig: {}) { - return fetch('/graphql'); + return fetch("/graphql"); } const network = Network.create(fetchQuery); const source = new RecordSource(); @@ -35,28 +29,28 @@ const modernEnvironment = new Environment({ network, store }); // ~~~~~~~~~~~~~~~~~~~~~ // Modern QueryRenderer // ~~~~~~~~~~~~~~~~~~~~~ -const MyQueryRenderer = (props: { name: string}) => ( - { - if (error) { - return
{error.message}
; - } else if (props) { - return
{props.name} is great!
; - } - return
Loading
; - }} - /> +const MyQueryRenderer = (props: { name: string }) => ( + { + if (error) { + return
{error.message}
; + } else if (props) { + return
{props.name} is great!
; + } + return
Loading
; + }} + /> ); // ~~~~~~~~~~~~~~~~~~~~~ @@ -65,14 +59,14 @@ const MyQueryRenderer = (props: { name: string}) => ( const MyFragmentContainer = createFragmentContainer( class TodoListView extends React.Component { render() { - return
; + return
; } }, { item: graphql` fragment TodoItem_item on Todo { - text - isComplete + text + isComplete } `, } @@ -81,84 +75,75 @@ const MyFragmentContainer = createFragmentContainer( // ~~~~~~~~~~~~~~~~~~~~~ // Modern RefetchContainer // ~~~~~~~~~~~~~~~~~~~~~ -interface StoryInterface { id: string; } +interface StoryInterface { + id: string; +} interface FeedStoriesProps { relay: ModernTypes.RelayRefetchProp; feed: { - stories: { edges: Array<{ node: StoryInterface }> } + stories: { edges: Array<{ node: StoryInterface }> }; }; } class Story extends React.Component<{ story: StoryInterface }> {} class FeedStories extends React.Component { render() { - return ( -
- {this.props.feed.stories.edges.map( - edge => - )} -
- ); + return ( +
+ {this.props.feed.stories.edges.map(edge => )} +
+ ); } _loadMore() { - // Increments the number of stories being rendered by 10. - const refetchVariables = (fragmentVariables: {count: number }) => ({ - count: fragmentVariables.count + 10, - }); - this.props.relay.refetch(refetchVariables); + // Increments the number of stories being rendered by 10. + const refetchVariables = (fragmentVariables: { count: number }) => ({ + count: fragmentVariables.count + 10, + }); + this.props.relay.refetch(refetchVariables); } - } +} const FeedRefetchContainer = createRefetchContainer( FeedStories, { - feed: graphql.experimental` - fragment FeedStories_feed on Feed - @argumentDefinitions( - count: {type: "Int", defaultValue: 10} - ) { - stories(first: $count) { - edges { - node { - id - ...Story_story - } + feed: graphql.experimental` + fragment FeedStories_feed on Feed @argumentDefinitions(count: { type: "Int", defaultValue: 10 }) { + stories(first: $count) { + edges { + node { + id + ...Story_story + } + } + } } - } - } - ` + `, }, graphql.experimental` - query FeedStoriesRefetchQuery($count: Int) { - feed { - ...FeedStories_feed @arguments(count: $count) + query FeedStoriesRefetchQuery($count: Int) { + feed { + ...FeedStories_feed @arguments(count: $count) + } } - } - `, - ); + ` +); // ~~~~~~~~~~~~~~~~~~~~~ // Modern PaginationContainer // ~~~~~~~~~~~~~~~~~~~~~ interface FeedProps { - user: { feed: { edges: Array<{ node: StoryInterface}>}}; + user: { feed: { edges: Array<{ node: StoryInterface }> } }; relay: ModernTypes.RelayPaginationProp; } class Feed extends React.Component { render() { - return (
- {this.props.user.feed.edges.map( - edge => - )} -
); + return ( +
+ {this.props.user.feed.edges.map(edge => )} +
+ ); } _loadMore() { @@ -170,7 +155,7 @@ class Feed extends React.Component { 10, // Fetch the next 10 feed items e => { console.log(e); - }, + } ); } } @@ -179,25 +164,25 @@ const FeedPaginationContainer = createPaginationContainer( Feed, { user: graphql` - fragment Feed_user on User { - feed( - first: $count - after: $cursor - orderby: $orderBy # other variables - ) @connection(key: "Feed_feed") { - edges { - node { - id - ...Story_story + fragment Feed_user on User { + feed( + first: $count + after: $cursor + orderby: $orderBy # other variables + ) @connection(key: "Feed_feed") { + edges { + node { + id + ...Story_story + } + } } } - } - } `, }, { - direction: 'forward', - getConnectionFromProps(props: { user: {feed: any}}) { + direction: "forward", + getConnectionFromProps(props: { user: { feed: any } }) { return props.user && props.user.feed; }, getFragmentVariables(prevVars, totalCount) { @@ -206,7 +191,7 @@ const FeedPaginationContainer = createPaginationContainer( count: totalCount, }; }, - getVariables(props, {count, cursor}, fragmentVariables) { + getVariables(props, { count, cursor }, fragmentVariables) { return { count, cursor, @@ -216,17 +201,13 @@ const FeedPaginationContainer = createPaginationContainer( }; }, query: graphql` - query FeedPaginationQuery( - $count: Int! - $cursor: String - $orderby: String! - ) { - user { - # You could reference the fragment defined previously. - ...Feed_user + query FeedPaginationQuery($count: Int!, $cursor: String, $orderby: String!) { + user { + # You could reference the fragment defined previously. + ...Feed_user + } } - } - ` + `, } ); @@ -234,46 +215,52 @@ const FeedPaginationContainer = createPaginationContainer( // Modern Mutations // ~~~~~~~~~~~~~~~~~~~~~ const mutation = graphql` -mutation MarkReadNotificationMutation( - $input: MarkReadNotificationData! -) { - markReadNotification(data: $input) { - notification { - seenState + mutation MarkReadNotificationMutation($input: MarkReadNotificationData!) { + markReadNotification(data: $input) { + notification { + seenState + } } } -} `; const optimisticResponse = { markReadNotification: { notification: { - seenState: 'SEEN', + seenState: "SEEN", }, }, }; -const configs = [{ - type: 'NODE_DELETE' as 'NODE_DELETE', - deletedIDFieldName: 'destroyedShipId', -}, { - type: 'RANGE_ADD' as 'RANGE_ADD', - parentID: 'shipId', - connectionInfo: [{ - key: 'AddShip_ships', - rangeBehavior: 'append', - }], - edgeName: 'newShipEdge', -}, { - type: 'RANGE_DELETE' as 'RANGE_DELETE', - parentID: 'todoId', - connectionKeys: [{ - key: 'RemoveTags_tags', - rangeBehavior: 'append', - }], - pathToConnection: ['todo', 'tags'], - deletedIDFieldName: 'removedTagId' -}]; +const configs = [ + { + type: "NODE_DELETE" as "NODE_DELETE", + deletedIDFieldName: "destroyedShipId", + }, + { + type: "RANGE_ADD" as "RANGE_ADD", + parentID: "shipId", + connectionInfo: [ + { + key: "AddShip_ships", + rangeBehavior: "append", + }, + ], + edgeName: "newShipEdge", + }, + { + type: "RANGE_DELETE" as "RANGE_DELETE", + parentID: "todoId", + connectionKeys: [ + { + key: "RemoveTags_tags", + rangeBehavior: "append", + }, + ], + pathToConnection: ["todo", "tags"], + deletedIDFieldName: "removedTagId", + }, +]; function markNotificationAsRead(source: string, storyID: string) { const variables = { @@ -283,37 +270,32 @@ function markNotificationAsRead(source: string, storyID: string) { }, }; - commitMutation( - modernEnvironment, - { - configs, - mutation, - optimisticResponse, - variables, - onCompleted: (response, errors) => { - console.log('Response received from server.'); - }, - onError: err => console.error(err), + commitMutation(modernEnvironment, { + configs, + mutation, + optimisticResponse, + variables, + onCompleted: (response, errors) => { + console.log("Response received from server."); }, - ); + onError: err => console.error(err), + }); } // ~~~~~~~~~~~~~~~~~~~~~ // Modern Subscriptions // ~~~~~~~~~~~~~~~~~~~~~ const subscription = graphql` - subscription MarkReadNotificationSubscription( - $storyID: ID! - ) { - markReadNotification(storyID: $storyID) { - notification { - seenState + subscription MarkReadNotificationSubscription($storyID: ID!) { + markReadNotification(storyID: $storyID) { + notification { + seenState + } } } - } `; const variables = { - storyID: '123', + storyID: "123", }; requestSubscription( modernEnvironment, // see Environment docs @@ -326,18 +308,12 @@ requestSubscription( // example of a custom updater updater: store => { // Get the notification - const rootField = store.getRootField('markReadNotification'); - const notification = !!rootField && rootField.getLinkedRecord('notification'); + const rootField = store.getRootField("markReadNotification"); + const notification = !!rootField && rootField.getLinkedRecord("notification"); // Add it to a connection - const viewer = store.getRoot().getLinkedRecord('viewer'); - const notifications = - ConnectionHandler.getConnection(viewer, 'notifications'); - const edge = ConnectionHandler.createEdge( - store, - notifications, - notification, - '', - ); + const viewer = store.getRoot().getLinkedRecord("viewer"); + const notifications = ConnectionHandler.getConnection(viewer, "notifications"); + const edge = ConnectionHandler.createEdge(store, notifications, notification, ""); ConnectionHandler.insertEdgeAfter(notifications, edge); }, } @@ -348,7 +324,7 @@ requestSubscription( /////////////////////////// import { QueryRenderer as CompatQueryRenderer, - createFragmentContainer as createFragmentContainerCompat + createFragmentContainer as createFragmentContainerCompat, } from "react-relay/compat"; // TODO? This is all more or less identical to modern... @@ -378,16 +354,18 @@ export default class AddTweetMutation extends Relay.Mutation { } getConfigs() { - return [{ - type: "RANGE_ADD", - parentName: "user", - parentID: this.props.userId, - connectionName: "tweets", - edgeName: "tweetEdge", - rangeBehaviors: { - "": "append", + return [ + { + type: "RANGE_ADD", + parentName: "user", + parentID: this.props.userId, + connectionName: "tweets", + edgeName: "tweetEdge", + rangeBehaviors: { + "": "append", + }, }, - }]; + ]; } getVariables() { @@ -397,18 +375,14 @@ export default class AddTweetMutation extends Relay.Mutation { interface ArtworkProps { artwork: { - title: string + title: string; }; relay: Relay.RelayProp; } class Artwork extends React.Component { render() { - return ( - - {this.props.artwork.title} - - ); + return {this.props.artwork.title}; } } @@ -418,8 +392,8 @@ const ArtworkContainer = Relay.createContainer(Artwork, { fragment on Artwork { title } - ` - } + `, + }, }); class StubbedArtwork extends React.Component { @@ -428,7 +402,7 @@ class StubbedArtwork extends React.Component { artwork: { title: "CHAMPAGNE FORMICA FLAG" }, relay: { route: { - name: "champagne" + name: "champagne", }, variables: { artworkID: "champagne-formica-flag", @@ -438,7 +412,7 @@ class StubbedArtwork extends React.Component { hasOptimisticUpdate: () => false, getPendingTransactions: (): any => undefined, commitUpdate: () => {}, - } + }, }; return ; } diff --git a/types/relay-runtime/index.d.ts b/types/relay-runtime/index.d.ts index 152df90640..88abec0a9b 100644 --- a/types/relay-runtime/index.d.ts +++ b/types/relay-runtime/index.d.ts @@ -36,10 +36,7 @@ export namespace RelayCommonTypes { // ~~~~~~~~~~~~~~~~~~~~~ // RelayQL // ~~~~~~~~~~~~~~~~~~~~~ - type RelayQL = ( - strings: string[], - ...substitutions: any[] - ) => RelayConcreteNode; + type RelayQL = (strings: string[], ...substitutions: any[]) => RelayConcreteNode; // ~~~~~~~~~~~~~~~~~~~~~ // RelayModernGraphQLTag @@ -48,13 +45,11 @@ export namespace RelayCommonTypes { [key: string]: GraphQLTaggedNode; } type GraphQLTaggedNode = - (() => ConcreteFragment | ConcreteBatch) | - { - modern(): ConcreteFragment | ConcreteBatch, - classic(relayQL: RelayQL): - | ConcreteFragmentDefinition - | ConcreteOperationDefinition, - }; + | (() => ConcreteFragment | ConcreteBatch) + | { + modern(): ConcreteFragment | ConcreteBatch; + classic(relayQL: RelayQL): ConcreteFragmentDefinition | ConcreteOperationDefinition; + }; // ~~~~~~~~~~~~~~~~~~~~~ // General Usage // ~~~~~~~~~~~~~~~~~~~~~ @@ -81,8 +76,8 @@ export namespace RelayCommonTypes { interface PayloadError { message: string; locations?: Array<{ - line: number, - column: number, + line: number; + column: number; }>; } /** @@ -94,7 +89,7 @@ export namespace RelayCommonTypes { operation: ConcreteBatch, variables: Variables, cacheConfig: CacheConfig, - uploadables?: UploadableMap, + uploadables?: UploadableMap ): Runtime.ObservableFromValue; /** @@ -108,7 +103,7 @@ export namespace RelayCommonTypes { operation: ConcreteBatch, variables: Variables, cacheConfig: CacheConfig, - observer: LegacyObserver, + observer: LegacyObserver ) => Runtime.RelayObservable | Disposable; // ~~~~~~~~~~~~~~~~~~~~~ @@ -131,7 +126,7 @@ export namespace RelayCommonTypes { store: RecordSourceSelectorProxy, // Actually RelayCombinedEnvironmentTypes#SelectorData, but mixed is // inconvenient to access deeply in product code. - data: any, // FLOW FIXME + data: any // FLOW FIXME ) => void; /** @@ -152,22 +147,14 @@ export namespace RelayCommonTypes { getDataID(): DataID; getLinkedRecord(name: string, args?: Variables): RecordProxy | void; getLinkedRecords(name: string, args?: Variables): Array | void; - getOrCreateLinkedRecord( - name: string, - typeName: string, - args?: Variables, - ): RecordProxy; + getOrCreateLinkedRecord(name: string, typeName: string, args?: Variables): RecordProxy; getType(): string; getValue(name: string, args?: Variables): any; - setLinkedRecord( - record: RecordProxy, - name: string, - args?: Variables, - ): RecordProxy; + setLinkedRecord(record: RecordProxy, name: string, args?: Variables): RecordProxy; setLinkedRecords( records: Array | undefined | null, name: string, - args?: Variables, + args?: Variables ): RecordProxy; setValue(value: any, name: string, args?: Variables): RecordProxy; } @@ -228,17 +215,23 @@ export namespace RelayCommonTypes { /** * Arbitrary data e.g. received by a container as props. */ - interface Props { [key: string]: any; } + interface Props { + [key: string]: any; + } /* * An individual cached graph object. */ - interface Record { [key: string]: any; } + interface Record { + [key: string]: any; + } /** * A collection of records keyed by id. */ - interface RecordMap { [dataID: string]: Record | null | undefined; } + interface RecordMap { + [dataID: string]: Record | null | undefined; + } /** * A selector defines the starting point for a traversal into the graph for the @@ -254,20 +247,24 @@ export namespace RelayCommonTypes { * A representation of a selector and its results at a particular point in time. */ type CSnapshot = CSelector & { - data: SelectorData | null | undefined, - seenRecords: RecordMap, + data: SelectorData | null | undefined; + seenRecords: RecordMap; }; /** * The results of a selector given a store/RecordSource. */ - interface SelectorData { [key: string]: any; } + interface SelectorData { + [key: string]: any; + } /** * The results of reading the results of a FragmentMap given some input * `Props`. */ - interface FragmentSpecResults { [key: string]: any; } + interface FragmentSpecResults { + [key: string]: any; + } /** * A utility for resolving and subscribing to the results of a fragment spec @@ -304,7 +301,9 @@ export namespace RelayCommonTypes { setVariables(variables: Variables): void; } - interface CFragmentMap { [key: string]: TFragment; } + interface CFragmentMap { + [key: string]: TFragment; + } /** * An operation selector describes a specific instance of a GraphQL operation @@ -326,14 +325,7 @@ export namespace RelayCommonTypes { * The public API of Relay core. Represents an encapsulated environment with its * own in-memory cache. */ - interface CEnvironment< - TEnvironment, - TFragment, - TGraphQLTaggedNode, - TNode, - TOperation, - TPayload, - > { + interface CEnvironment { /** * Read the results of a selector from in-memory records in the store. */ @@ -344,10 +336,7 @@ export namespace RelayCommonTypes { * when data has been committed to the store that would cause the results of * the snapshot's selector to change. */ - subscribe( - snapshot: CSnapshot, - callback: (snapshot: CSnapshot) => void, - ): Disposable; + subscribe(snapshot: CSnapshot, callback: (snapshot: CSnapshot) => void): Disposable; /** * Ensure that all the records necessary to fulfill the given selector are @@ -370,11 +359,11 @@ export namespace RelayCommonTypes { * after receving the first `onNext` result. */ sendQuery(config: { - cacheConfig?: CacheConfig, - onCompleted?(): void, - onError?(error: Error): void, - onNext?(payload: TPayload): void, - operation: COperationSelector, + cacheConfig?: CacheConfig; + onCompleted?(): void; + onError?(error: Error): void; + onNext?(payload: TPayload): void; + operation: COperationSelector; }): Disposable; /** @@ -386,29 +375,17 @@ export namespace RelayCommonTypes { * subscription open indefinitely such that `onCompleted` is not called. */ streamQuery(config: { - cacheConfig?: CacheConfig, - onCompleted?(): void, - onError?(error: Error): void, - onNext?(payload: TPayload): void, - operation: COperationSelector, + cacheConfig?: CacheConfig; + onCompleted?(): void; + onError?(error: Error): void; + onNext?(payload: TPayload): void; + operation: COperationSelector; }): Disposable; - unstable_internal: CUnstableEnvironmentCore< - TEnvironment, - TFragment, - TGraphQLTaggedNode, - TNode, - TOperation - >; + unstable_internal: CUnstableEnvironmentCore; } - interface CUnstableEnvironmentCore< - TEnvironment, - TFragment, - TGraphQLTaggedNode, - TNode, - TOperation, - > { + interface CUnstableEnvironmentCore { /** * Create an instance of a FragmentSpecResolver. * @@ -421,7 +398,7 @@ export namespace RelayCommonTypes { containerName: string, fragments: CFragmentMap, props: Props, - callback: () => void, + callback: () => void ): FragmentSpecResolver; /** @@ -430,10 +407,7 @@ export namespace RelayCommonTypes { * filtered to exclude variables that do not matche defined arguments on the * operation, and default values are populated for null values. */ - createOperationSelector( - operation: TOperation, - variables: Variables, - ): COperationSelector; + createOperationSelector(operation: TOperation, variables: Variables): COperationSelector; /** * Given a graphql`...` tagged template, extract a fragment definition usable @@ -482,11 +456,7 @@ export namespace RelayCommonTypes { * const childData = environment.lookup(childSelector).data; * ``` */ - getSelector( - operationVariables: Variables, - fragment: TFragment, - prop: any, - ): CSelector | void; + getSelector(operationVariables: Variables, fragment: TFragment, prop: any): CSelector | void; /** * Given the result `items` from a parent that fetched `fragment`, creates a @@ -497,7 +467,7 @@ export namespace RelayCommonTypes { getSelectorList( operationVariables: Variables, fragment: TFragment, - props: any[], + props: any[] ): Array> | void; /** @@ -511,7 +481,7 @@ export namespace RelayCommonTypes { getSelectorsFromObject( operationVariables: Variables, fragments: CFragmentMap, - props: Props, + props: Props ): { [key: string]: CSelector | Array> | null | undefined }; /** @@ -523,7 +493,7 @@ export namespace RelayCommonTypes { */ getDataIDsFromObject( fragments: CFragmentMap, - props: Props, + props: Props ): { [key: string]: DataID | DataID[] | null | undefined }; /** @@ -537,7 +507,7 @@ export namespace RelayCommonTypes { getVariablesFromObject( operationVariables: Variables, fragments: CFragmentMap, - props: Props, + props: Props ): Variables; } @@ -564,51 +534,46 @@ export namespace RelayCommonTypes { max_runs: number; } interface FIELDS_CHANGE { - type: 'FIELDS_CHANGE'; - fieldIDs: { [fieldName: string]: DataID | DataID[]; }; + type: "FIELDS_CHANGE"; + fieldIDs: { [fieldName: string]: DataID | DataID[] }; } interface RANGE_ADD { - type: 'RANGE_ADD'; + type: "RANGE_ADD"; parentName?: string; parentID?: string; connectionInfo?: Array<{ - key: string, - filters?: Variables, - rangeBehavior: string, + key: string; + filters?: Variables; + rangeBehavior: string; }>; connectionName?: string; edgeName: string; rangeBehaviors?: RangeBehaviors; } interface NODE_DELETE { - type: 'NODE_DELETE'; + type: "NODE_DELETE"; parentName?: string; parentID?: string; connectionName?: string; deletedIDFieldName: string; } interface RANGE_DELETE { - type: 'RANGE_DELETE'; + type: "RANGE_DELETE"; parentName?: string; parentID?: string; connectionKeys?: Array<{ - key: string, - filters?: Variables, + key: string; + filters?: Variables; }>; connectionName?: string; deletedIDFieldName: string | string[]; pathToConnection: string[]; } interface REQUIRED_CHILDREN { - type: 'REQUIRED_CHILDREN'; + type: "REQUIRED_CHILDREN"; children: RelayConcreteNode[]; } - type RelayMutationConfig = - FIELDS_CHANGE | - RANGE_ADD | - NODE_DELETE | - RANGE_DELETE | - REQUIRED_CHILDREN; + type RelayMutationConfig = FIELDS_CHANGE | RANGE_ADD | NODE_DELETE | RANGE_DELETE | REQUIRED_CHILDREN; interface RelayMutationTransactionCommitCallbacks { onFailure?: RelayMutationTransactionCommitFailureCallback; @@ -616,11 +581,13 @@ export namespace RelayCommonTypes { } type RelayMutationTransactionCommitFailureCallback = ( transaction: RelayMutationTransaction, - preventAutoRollback: () => void, + preventAutoRollback: () => void + ) => void; + type RelayMutationTransactionCommitSuccessCallback = ( + response: { + [key: string]: any; + } ) => void; - type RelayMutationTransactionCommitSuccessCallback = (response: { - [key: string]: any, - }) => void; interface NetworkLayer { sendMutation(request: RelayMutationRequest): Promise | void; sendQueries(requests: RelayQueryRequest[]): Promise | void; @@ -639,18 +606,16 @@ export namespace RelayCommonTypes { ready: boolean; stale: boolean; } - type RelayContainerErrorEventType = - | 'CACHE_RESTORE_FAILED' - | 'NETWORK_QUERY_ERROR'; + type RelayContainerErrorEventType = "CACHE_RESTORE_FAILED" | "NETWORK_QUERY_ERROR"; type RelayContainerLoadingEventType = - | 'ABORT' - | 'CACHE_RESTORED_REQUIRED' - | 'CACHE_RESTORE_START' - | 'NETWORK_QUERY_RECEIVED_ALL' - | 'NETWORK_QUERY_RECEIVED_REQUIRED' - | 'NETWORK_QUERY_START' - | 'STORE_FOUND_ALL' - | 'STORE_FOUND_REQUIRED'; + | "ABORT" + | "CACHE_RESTORED_REQUIRED" + | "CACHE_RESTORE_START" + | "NETWORK_QUERY_RECEIVED_ALL" + | "NETWORK_QUERY_RECEIVED_REQUIRED" + | "NETWORK_QUERY_START" + | "STORE_FOUND_ALL" + | "STORE_FOUND_REQUIRED"; type ReadyStateChangeCallback = (readyState: ReadyState) => void; interface ReadyStateEvent { type: RelayContainerLoadingEventType | RelayContainerErrorEventType; @@ -668,13 +633,19 @@ export namespace RelayCommonTypes { * https://github.com/facebook/relay/blob/master/packages/react-relay/classic/tools/RelayInternalTypes.js */ // ~~~~~~~~~~~~~~~~~~~~~ - interface QueryPayload { [key: string]: any; } - interface RelayQuerySet { [queryName: string]: any; } - type RangeBehaviorsFunction = (connectionArgs: { - [argName: string]: any, - }) => 'APPEND' | 'IGNORE' | 'PREPEND' | 'REFETCH' | 'REMOVE'; + interface QueryPayload { + [key: string]: any; + } + interface RelayQuerySet { + [queryName: string]: any; + } + type RangeBehaviorsFunction = ( + connectionArgs: { + [argName: string]: any; + } + ) => "APPEND" | "IGNORE" | "PREPEND" | "REFETCH" | "REMOVE"; interface RangeBehaviorsObject { - [key: string]: 'APPEND' | 'IGNORE' | 'PREPEND' | 'REFETCH' | 'REMOVE'; + [key: string]: "APPEND" | "IGNORE" | "PREPEND" | "REFETCH" | "REMOVE"; } type RangeBehaviors = RangeBehaviorsFunction | RangeBehaviorsObject; } @@ -700,7 +671,7 @@ export namespace RelayRuntimeTypes { operation: object, variables: RelayCommonTypes.Variables, cacheConfig: RelayCommonTypes.CacheConfig, - uploadables?: RelayCommonTypes.UploadableMap, + uploadables?: RelayCommonTypes.UploadableMap ) => Promise; interface RelayNetwork { execute: ExecuteFunction; @@ -728,41 +699,39 @@ export namespace RelayRuntimeTypes { revertUpdate(update: OptimisticUpdate): void; replaceUpdate(update: OptimisticUpdate, newUpdate: OptimisticUpdate): void; applyMutation(config: { - operation: OperationSelector, - optimisticUpdater?: RelayCommonTypes.SelectorStoreUpdater, - optimisticResponse?: object, + operation: OperationSelector; + optimisticUpdater?: RelayCommonTypes.SelectorStoreUpdater; + optimisticResponse?: object; }): RelayCommonTypes.Disposable; check(readSelector: Selector): boolean; - commitPayload( - operationSelector: OperationSelector, - payload: PayloadData, - ): void; + commitPayload(operationSelector: OperationSelector, payload: PayloadData): void; commitUpdate(updater: RelayCommonTypes.StoreUpdater): void; lookup(readSelector: Selector): Snapshot; - subscribe( - snapshot: Snapshot, - callback: (snapshot: Snapshot) => void, - ): RelayCommonTypes.Disposable; + subscribe(snapshot: Snapshot, callback: (snapshot: Snapshot) => void): RelayCommonTypes.Disposable; retain(selector: Selector): RelayCommonTypes.Disposable; execute(config: { - operation: OperationSelector, - cacheConfig?: RelayCommonTypes.CacheConfig, - updater?: RelayCommonTypes.SelectorStoreUpdater, + operation: OperationSelector; + cacheConfig?: RelayCommonTypes.CacheConfig; + updater?: RelayCommonTypes.SelectorStoreUpdater; }): RelayObservable; executeMutation(config: { - operation: OperationSelector, - optimisticUpdater?: RelayCommonTypes.SelectorStoreUpdater, - optimisticResponse?: object, - updater?: RelayCommonTypes.SelectorStoreUpdater, - uploadables?: RelayCommonTypes.UploadableMap, + operation: OperationSelector; + optimisticUpdater?: RelayCommonTypes.SelectorStoreUpdater; + optimisticResponse?: object; + updater?: RelayCommonTypes.SelectorStoreUpdater; + uploadables?: RelayCommonTypes.UploadableMap; }): RelayObservable; } // ~~~~~~~~~~~~~~~~~~~~~ // RelayInMemoryRecordSource // ~~~~~~~~~~~~~~~~~~~~~ - interface Record { [key: string]: any; } - interface RecordMap { [dataID: string]: Record | null | undefined; } + interface Record { + [key: string]: any; + } + interface RecordMap { + [dataID: string]: Record | null | undefined; + } // ~~~~~~~~~~~~~~~~~~~~~ // Network @@ -772,7 +741,10 @@ export namespace RelayRuntimeTypes { * Creates an implementation of the `Network` interface defined in * `RelayNetworkTypes` given `fetch` and `subscribe` functions. */ - static create(fetchFn: typeof RelayCommonTypes.FetchFunction, subscribeFn?: RelayCommonTypes.SubscribeFunction): RelayNetwork; + static create( + fetchFn: typeof RelayCommonTypes.FetchFunction, + subscribeFn?: RelayCommonTypes.SubscribeFunction + ): RelayNetwork; } // ~~~~~~~~~~~~~~~~~~~~~ @@ -784,12 +756,9 @@ export namespace RelayRuntimeTypes { delete(dataID: RelayCommonTypes.DataID): void; get(dataID: RelayCommonTypes.DataID): Record | void; getRecordIDs(): RelayCommonTypes.DataID[]; - getStatus(dataID: RelayCommonTypes.DataID): 'EXISTENT' | 'NONEXISTENT' | 'UNKNOWN'; + getStatus(dataID: RelayCommonTypes.DataID): "EXISTENT" | "NONEXISTENT" | "UNKNOWN"; has(dataID: RelayCommonTypes.DataID): boolean; - load( - dataID: RelayCommonTypes.DataID, - callback: (error: Error | null, record: Record | null) => void, - ): void; + load(dataID: RelayCommonTypes.DataID, callback: (error: Error | null, record: Record | null) => void): void; remove(dataID: RelayCommonTypes.DataID): void; set(dataID: RelayCommonTypes.DataID, record: Record): void; size(): number; @@ -807,10 +776,7 @@ export namespace RelayRuntimeTypes { lookup(selector: Selector): Snapshot; notify(): void; publish(source: RecordSource): void; - subscribe( - snapshot: Snapshot, - callback: (snapshot: Snapshot) => void, - ): RelayCommonTypes.Disposable; + subscribe(snapshot: Snapshot, callback: (snapshot: Snapshot) => void): RelayCommonTypes.Disposable; } // ~~~~~~~~~~~~~~~~~~~~~ @@ -955,7 +921,9 @@ export namespace RelayRuntimeTypes { * legacy Relay observer and directly return an Observable instead. */ static fromLegacy( - callback: (legacyObserver: RelayCommonTypes.LegacyObserver) => RelayCommonTypes.Disposable | RelayObservable, + callback: ( + legacyObserver: RelayCommonTypes.LegacyObserver + ) => RelayCommonTypes.Disposable | RelayObservable ): RelayObservable; /** @@ -1036,10 +1004,7 @@ export namespace RelayRuntimeTypes { // commitLocalUpdate // ~~~~~~~~~~~~~~~~~~~~~ // exposed through RelayModern, not Runtime directly - type commitLocalUpdate = ( - environment: Environment, - updater: RelayCommonTypes.StoreUpdater, - ) => void; + type commitLocalUpdate = (environment: Environment, updater: RelayCommonTypes.StoreUpdater) => void; // ~~~~~~~~~~~~~~~~~~~~~ // commitRelayModernMutation @@ -1058,7 +1023,7 @@ export namespace RelayRuntimeTypes { } function commitRelayModernMutation( environment: Environment, - config: MutationConfig, + config: MutationConfig ): RelayCommonTypes.Disposable; // ~~~~~~~~~~~~~~~~~~~~~ @@ -1094,7 +1059,7 @@ export namespace RelayRuntimeTypes { environment: any, // FIXME - $FlowFixMe in facebook source code taggedNode: RelayCommonTypes.GraphQLTaggedNode, variables: RelayCommonTypes.Variables, - cacheConfig?: RelayCommonTypes.CacheConfig, + cacheConfig?: RelayCommonTypes.CacheConfig ): Promise; // FIXME - $FlowFixMe in facebook source code // ~~~~~~~~~~~~~~~~~~~~~ @@ -1112,7 +1077,7 @@ export namespace RelayRuntimeTypes { } function requestRelaySubscription( environment: Environment, - config: GraphQLSubscriptionConfig, + config: GraphQLSubscriptionConfig ): RelayCommonTypes.Disposable; } diff --git a/types/relay-runtime/relay-runtime-tests.tsx b/types/relay-runtime/relay-runtime-tests.tsx index c6dd9c15a2..f786e4d5fa 100644 --- a/types/relay-runtime/relay-runtime-tests.tsx +++ b/types/relay-runtime/relay-runtime-tests.tsx @@ -1,11 +1,4 @@ -import { - Environment, - Network, - RecordSource, - Store, - ConnectionHandler, - ViewerHandler, -} from 'relay-runtime'; +import { Environment, Network, RecordSource, Store, ConnectionHandler, ViewerHandler } from "relay-runtime"; const source = new RecordSource(); const store = new Store(source); @@ -15,13 +8,9 @@ const store = new Store(source); // ~~~~~~~~~~~~~~~~~~~~~ // Define a function that fetches the results of an operation (query/mutation/etc) // and returns its results as a Promise: -function fetchQuery( - operation: any, - variables: { [key: string]: string }, - cacheConfig: {}, -) { - return fetch('/graphql', { - method: 'POST', +function fetchQuery(operation: any, variables: { [key: string]: string }, cacheConfig: {}) { + return fetch("/graphql", { + method: "POST", body: JSON.stringify({ query: operation.text, // GraphQL text from input variables, @@ -50,10 +39,10 @@ const environment = new Environment({ function handlerProvider(handle: any) { switch (handle) { // Augment (or remove from) this list: - case 'connection': return ConnectionHandler; - case 'viewer': return ViewerHandler; + case "connection": + return ConnectionHandler; + case "viewer": + return ViewerHandler; } - throw new Error( - `handlerProvider: No handler provided for ${handle}` - ); + throw new Error(`handlerProvider: No handler provided for ${handle}`); } From bafb5407cb8d37c6c8d34af91a0e546545726dd8 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Eloy=20Dur=C3=A1n?= Date: Wed, 11 Oct 2017 15:56:18 +0200 Subject: [PATCH 036/828] [Relay] Fix dtslint issues with test files. --- types/react-relay/{ => test}/react-relay-classic-tests.tsx | 0 types/react-relay/{ => test}/react-relay-tests.tsx | 0 types/react-relay/tsconfig.json | 6 +++--- 3 files changed, 3 insertions(+), 3 deletions(-) rename types/react-relay/{ => test}/react-relay-classic-tests.tsx (100%) rename types/react-relay/{ => test}/react-relay-tests.tsx (100%) diff --git a/types/react-relay/react-relay-classic-tests.tsx b/types/react-relay/test/react-relay-classic-tests.tsx similarity index 100% rename from types/react-relay/react-relay-classic-tests.tsx rename to types/react-relay/test/react-relay-classic-tests.tsx diff --git a/types/react-relay/react-relay-tests.tsx b/types/react-relay/test/react-relay-tests.tsx similarity index 100% rename from types/react-relay/react-relay-tests.tsx rename to types/react-relay/test/react-relay-tests.tsx diff --git a/types/react-relay/tsconfig.json b/types/react-relay/tsconfig.json index 5447ff74ca..2b992f91c8 100644 --- a/types/react-relay/tsconfig.json +++ b/types/react-relay/tsconfig.json @@ -19,10 +19,10 @@ }, "files": [ "index.d.ts", - "react-relay-tests.tsx", - "react-relay-classic-tests.tsx", "classic.d.ts", "modern.d.ts", - "compat.d.ts" + "compat.d.ts", + "test/react-relay-tests.tsx", + "test/react-relay-classic-tests.tsx" ] } From 339eadd3e10e9f6b40461c573cc2e32572ed863e Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Eloy=20Dur=C3=A1n?= Date: Wed, 11 Oct 2017 15:56:44 +0200 Subject: [PATCH 037/828] [Relay] Fix namespace reference. --- types/relay-runtime/index.d.ts | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/types/relay-runtime/index.d.ts b/types/relay-runtime/index.d.ts index 88abec0a9b..5b1554e929 100644 --- a/types/relay-runtime/index.d.ts +++ b/types/relay-runtime/index.d.ts @@ -90,7 +90,7 @@ export namespace RelayCommonTypes { variables: Variables, cacheConfig: CacheConfig, uploadables?: UploadableMap - ): Runtime.ObservableFromValue; + ): RelayRuntimeTypes.ObservableFromValue; /** * A function that executes a GraphQL subscription operation, returning one or @@ -104,7 +104,7 @@ export namespace RelayCommonTypes { variables: Variables, cacheConfig: CacheConfig, observer: LegacyObserver - ) => Runtime.RelayObservable | Disposable; + ) => RelayRuntimeTypes.RelayObservable | Disposable; // ~~~~~~~~~~~~~~~~~~~~~ // RelayStoreTypes From 3439a2d7a179616f834cc5bcf6d377a7f998358d Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Eloy=20Dur=C3=A1n?= Date: Wed, 11 Oct 2017 15:59:12 +0200 Subject: [PATCH 038/828] [Relay] Add myself to list of maintainers. --- types/react-relay/index.d.ts | 4 +++- types/relay-runtime/index.d.ts | 1 + 2 files changed, 4 insertions(+), 1 deletion(-) diff --git a/types/react-relay/index.d.ts b/types/react-relay/index.d.ts index 30cb29b3e3..cdb38afae6 100644 --- a/types/react-relay/index.d.ts +++ b/types/react-relay/index.d.ts @@ -1,6 +1,8 @@ // Type definitions for react-relay 1.3 // Project: https://github.com/facebook/relay -// Definitions by: Johannes Schickling , Matt Martin +// Definitions by: Johannes Schickling +// Matt Martin +// Eloy Durán // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped // TypeScript Version: 2.4 diff --git a/types/relay-runtime/index.d.ts b/types/relay-runtime/index.d.ts index 5b1554e929..a4867b4091 100644 --- a/types/relay-runtime/index.d.ts +++ b/types/relay-runtime/index.d.ts @@ -1,6 +1,7 @@ // Type definitions for relay-runtime 1.3 // Project: https://github.com/facebook/relay // Definitions by: Matt Martin +// Eloy Durán // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped // TypeScript Version: 2.4 From 091c46291e8635c31ed0e26ac24accd1d9697e65 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Eloy=20Dur=C3=A1n?= Date: Wed, 11 Oct 2017 16:23:14 +0200 Subject: [PATCH 039/828] [Relay] Add generics for `getConnectionFromProps`. --- types/react-relay/modern.d.ts | 6 +++--- types/react-relay/test/react-relay-tests.tsx | 2 +- 2 files changed, 4 insertions(+), 4 deletions(-) diff --git a/types/react-relay/modern.d.ts b/types/react-relay/modern.d.ts index 13b43bf449..d4c422b823 100644 --- a/types/react-relay/modern.d.ts +++ b/types/react-relay/modern.d.ts @@ -105,9 +105,9 @@ export function FragmentVariablesGetter( prevVars: RelayCommonTypes.Variables, totalCount: number ): RelayCommonTypes.Variables; -export interface ConnectionConfig { +export interface ConnectionConfig { direction?: "backward" | "forward"; - getConnectionFromProps?(props: object): ConnectionData | undefined | null; + getConnectionFromProps?(props: T): ConnectionData | undefined | null; getFragmentVariables?: typeof FragmentVariablesGetter; getVariables( props: { [propName: string]: any }, @@ -119,7 +119,7 @@ export interface ConnectionConfig { export function createPaginationContainer( Component: ReactBaseComponent, fragmentSpec: GraphQLTaggedNode | GeneratedNodeMap, - connectionConfig: ConnectionConfig + connectionConfig: ConnectionConfig ): ReactBaseComponent; // ~~~~~~~~~~~~~~~~~~~~~ diff --git a/types/react-relay/test/react-relay-tests.tsx b/types/react-relay/test/react-relay-tests.tsx index 97cc5d47d9..c7d144122b 100644 --- a/types/react-relay/test/react-relay-tests.tsx +++ b/types/react-relay/test/react-relay-tests.tsx @@ -182,7 +182,7 @@ const FeedPaginationContainer = createPaginationContainer( }, { direction: "forward", - getConnectionFromProps(props: { user: { feed: any } }) { + getConnectionFromProps(props) { return props.user && props.user.feed; }, getFragmentVariables(prevVars, totalCount) { From 08f193a6941ad3b3fbf701a63f0425930e6f9e86 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Eloy=20Dur=C3=A1n?= Date: Thu, 12 Oct 2017 00:46:10 +0200 Subject: [PATCH 040/828] [Relay] Return `null` instead of `void` for Flow Maybe types. --- types/react-relay/test/react-relay-tests.tsx | 6 ++++ types/relay-runtime/index.d.ts | 30 ++++++++++---------- 2 files changed, 21 insertions(+), 15 deletions(-) diff --git a/types/react-relay/test/react-relay-tests.tsx b/types/react-relay/test/react-relay-tests.tsx index c7d144122b..80380122f7 100644 --- a/types/react-relay/test/react-relay-tests.tsx +++ b/types/react-relay/test/react-relay-tests.tsx @@ -279,6 +279,12 @@ function markNotificationAsRead(source: string, storyID: string) { console.log("Response received from server."); }, onError: err => console.error(err), + updater: (store, data) => { + const field = store.get(storyID); + if (field) { + field.setValue(data.story, "story"); + } + } }); } diff --git a/types/relay-runtime/index.d.ts b/types/relay-runtime/index.d.ts index a4867b4091..69f5088ab4 100644 --- a/types/relay-runtime/index.d.ts +++ b/types/relay-runtime/index.d.ts @@ -137,17 +137,17 @@ export namespace RelayCommonTypes { interface RecordSourceSelectorProxy { create(dataID: DataID, typeName: string): RecordProxy; delete(dataID: DataID): void; - get(dataID: DataID): RecordProxy | void; + get(dataID: DataID): RecordProxy | null; getRoot(): RecordProxy; - getRootField(fieldName: string): RecordProxy | void; - getPluralRootField(fieldName: string): RecordProxy[] | void; + getRootField(fieldName: string): RecordProxy | null; + getPluralRootField(fieldName: string): RecordProxy[] | null; } interface RecordProxy { copyFieldsFrom(source: RecordProxy): void; getDataID(): DataID; - getLinkedRecord(name: string, args?: Variables): RecordProxy | void; - getLinkedRecords(name: string, args?: Variables): Array | void; + getLinkedRecord(name: string, args?: Variables): RecordProxy | null; + getLinkedRecords(name: string, args?: Variables): Array | null; getOrCreateLinkedRecord(name: string, typeName: string, args?: Variables): RecordProxy; getType(): string; getValue(name: string, args?: Variables): any; @@ -163,7 +163,7 @@ export namespace RelayCommonTypes { interface RecordSourceProxy { create(dataID: DataID, typeName: string): RecordProxy; delete(dataID: DataID): void; - get(dataID: DataID): Array | void; + get(dataID: DataID): Array | null; getRoot(): RecordProxy; } @@ -457,7 +457,7 @@ export namespace RelayCommonTypes { * const childData = environment.lookup(childSelector).data; * ``` */ - getSelector(operationVariables: Variables, fragment: TFragment, prop: any): CSelector | void; + getSelector(operationVariables: Variables, fragment: TFragment, prop: any): CSelector | null; /** * Given the result `items` from a parent that fetched `fragment`, creates a @@ -469,7 +469,7 @@ export namespace RelayCommonTypes { operationVariables: Variables, fragment: TFragment, props: any[] - ): Array> | void; + ): Array> | null; /** * Given a mapping of keys -> results and a mapping of keys -> fragments, @@ -590,8 +590,8 @@ export namespace RelayCommonTypes { } ) => void; interface NetworkLayer { - sendMutation(request: RelayMutationRequest): Promise | void; - sendQueries(requests: RelayQueryRequest[]): Promise | void; + sendMutation(request: RelayMutationRequest): Promise | null; + sendQueries(requests: RelayQueryRequest[]): Promise | null; supports(...options: string[]): boolean; } interface QueryResult { @@ -681,7 +681,7 @@ export namespace RelayRuntimeTypes { // ~~~~~~~~~~~~~~~~~~~~~ // RelayDefaultHandlerProvider // ~~~~~~~~~~~~~~~~~~~~~ - function HandlerProvider(name: string): typeof RelayCommonTypes.Handler | void; + function HandlerProvider(name: string): typeof RelayCommonTypes.Handler | null; // ~~~~~~~~~~~~~~~~~~~~~ // RelayModernEnvironment @@ -755,7 +755,7 @@ export namespace RelayRuntimeTypes { constructor(records?: RecordMap); clear(): void; delete(dataID: RelayCommonTypes.DataID): void; - get(dataID: RelayCommonTypes.DataID): Record | void; + get(dataID: RelayCommonTypes.DataID): Record | null; getRecordIDs(): RelayCommonTypes.DataID[]; getStatus(dataID: RelayCommonTypes.DataID): "EXISTENT" | "NONEXISTENT" | "UNKNOWN"; has(dataID: RelayCommonTypes.DataID): boolean; @@ -833,14 +833,14 @@ export namespace RelayRuntimeTypes { * value is another Record instead of a scalar). May throw if the field is * present but not a scalar linked record. */ - getLinkedRecord(name: string, args?: RelayCommonTypes.Variables): RecordInspector | void; + getLinkedRecord(name: string, args?: RelayCommonTypes.Variables): RecordInspector | null; /** * Returns an array of inspectors for the given plural "linked" field (a field * whose value is an array of Records instead of a scalar). May throw if the * field is present but not a plural linked record. */ - getLinkedRecords(name: string, args?: RelayCommonTypes.Variables): RecordInspector[] | void; + getLinkedRecords(name: string, args?: RelayCommonTypes.Variables): RecordInspector[] | null; } class RelayRecordSourceInspector { @@ -850,7 +850,7 @@ export namespace RelayRuntimeTypes { * Returns an inspector for the record with the given id, or null/undefined if * that record is deleted/unfetched. */ - get(dataID: RelayCommonTypes.DataID): RecordInspector | void; + get(dataID: RelayCommonTypes.DataID): RecordInspector | null; /** * Returns a list of ": " for each record in the store that has an * `id`. From c31e5f331684e95f53b29f4586378cb4e5680256 Mon Sep 17 00:00:00 2001 From: Gregor Yushinov Date: Fri, 13 Oct 2017 03:13:21 +0200 Subject: [PATCH 041/828] Added eachAsync options for concurrency --- types/mongoose/index.d.ts | 7 ++++++- 1 file changed, 6 insertions(+), 1 deletion(-) diff --git a/types/mongoose/index.d.ts b/types/mongoose/index.d.ts index cd7bb438d4..602b700958 100644 --- a/types/mongoose/index.d.ts +++ b/types/mongoose/index.d.ts @@ -469,6 +469,11 @@ declare module "mongoose" { static Messages: Object; } + interface EachAsyncOptions { + /** defaults to 1 */ + parallel?: number; + } + /* * section querycursor.js * http://mongoosejs.com/docs/api.html#querycursor-js @@ -502,7 +507,7 @@ declare module "mongoose" { * Returns a promise that resolves when done. * @param callback executed when all docs have been processed */ - eachAsync(fn: (doc: T) => any, callback?: (err: any) => void): Promise; + eachAsync(fn: (doc: T) => any, options: EachAsyncOptions, callback?: (err: any) => void): Promise; /** * Registers a transform function which subsequently maps documents retrieved From 5f30e1c83d41fbe04f2d8ed2b9c3f25cdfef5e65 Mon Sep 17 00:00:00 2001 From: Daniel Lebrecht Date: Fri, 13 Oct 2017 17:11:27 +0200 Subject: [PATCH 042/828] added property private key (d) in ECPair class --- types/bitcoinjs-lib/index.d.ts | 2 ++ 1 file changed, 2 insertions(+) diff --git a/types/bitcoinjs-lib/index.d.ts b/types/bitcoinjs-lib/index.d.ts index 796758715d..d33bc26e35 100644 --- a/types/bitcoinjs-lib/index.d.ts +++ b/types/bitcoinjs-lib/index.d.ts @@ -66,6 +66,8 @@ export class ECPair { constructor(d: null | undefined, Q: any, options?: { compressed?: boolean, network?: Network }); // Q should be ECPoint, but not sure how to define such type + d: BigInteger; + getAddress(): string; getNetwork(): Network; From 582327e65bef697883c2f27dceac2267e4aeb4ca Mon Sep 17 00:00:00 2001 From: dmayerdesign Date: Sun, 15 Oct 2017 14:44:29 -0400 Subject: [PATCH 043/828] Correct type-o in IOrder --- types/stripe-node/index.d.ts | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/types/stripe-node/index.d.ts b/types/stripe-node/index.d.ts index 9bf45d3411..379fe4550a 100644 --- a/types/stripe-node/index.d.ts +++ b/types/stripe-node/index.d.ts @@ -1,4 +1,4 @@ -// Type definitions for stripe-node 4.7.0 +// Type definitions for stripe-node 4.7.1 // Project: https://github.com/stripe/stripe-node/ // Definitions by: William Johnston , Peter Harris , Sampson Oliver // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped @@ -2338,7 +2338,7 @@ declare namespace StripeNode { /** * The timestamps at which the order status was updated */ - status_transactions: { + status_transitions: { canceled: number; fulfiled: number; paid: number; From 95479db2fd29ddc5504b490151b51bf6bac26f95 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Eloy=20Dur=C3=A1n?= Date: Wed, 18 Oct 2017 00:15:58 +0200 Subject: [PATCH 044/828] [Relay] Simplify modules by removing namespaces. --- types/react-relay/classic.d.ts | 18 +- types/react-relay/compat.d.ts | 25 +- types/react-relay/index.d.ts | 165 +- types/react-relay/modern.d.ts | 146 -- types/react-relay/test/react-relay-tests.tsx | 7 +- types/react-relay/tsconfig.json | 1 - types/relay-runtime/index.d.ts | 2115 +++++++++--------- 7 files changed, 1216 insertions(+), 1261 deletions(-) delete mode 100644 types/react-relay/modern.d.ts diff --git a/types/react-relay/classic.d.ts b/types/react-relay/classic.d.ts index 9345199d27..0db5308975 100644 --- a/types/react-relay/classic.d.ts +++ b/types/react-relay/classic.d.ts @@ -1,5 +1,5 @@ import * as React from "react"; -import { RelayCommonTypes } from "relay-runtime"; +import * as RelayRuntimeTypes from "relay-runtime"; // ~~~~~~~~~~~~~~~~~~~~~ // Maybe Fix @@ -20,24 +20,24 @@ export interface FragmentResolver { dispose(): void; resolve( fragment: RelayQuery["Fragment"], - dataIDs: RelayCommonTypes.DataID | RelayCommonTypes.DataID[] + dataIDs: RelayRuntimeTypes.DataID | RelayRuntimeTypes.DataID[] ): StoreReaderData | StoreReaderData[] | undefined | null; } export interface RelayEnvironmentInterface { forceFetch( - querySet: RelayCommonTypes.RelayQuerySet, - onReadyStateChange: RelayCommonTypes.ReadyStateChangeCallback - ): RelayCommonTypes.Abortable; + querySet: RelayRuntimeTypes.RelayQuerySet, + onReadyStateChange: RelayRuntimeTypes.ReadyStateChangeCallback + ): RelayRuntimeTypes.Abortable; getFragmentResolver(fragment: RelayQuery["Fragment"], onNext: () => void): FragmentResolver; getStoreData(): RelayStoreData; primeCache( - querySet: RelayCommonTypes.RelayQuerySet, - onReadyStateChange: RelayCommonTypes.ReadyStateChangeCallback - ): RelayCommonTypes.Abortable; + querySet: RelayRuntimeTypes.RelayQuerySet, + onReadyStateChange: RelayRuntimeTypes.ReadyStateChangeCallback + ): RelayRuntimeTypes.Abortable; read( node: RelayQuery["Node"], - dataID: RelayCommonTypes.DataID, + dataID: RelayRuntimeTypes.DataID, options?: StoreReaderOptions ): StoreReaderData | void; readQuery(root: RelayQuery["Root"], options?: StoreReaderOptions): StoreReaderData[] | void; diff --git a/types/react-relay/compat.d.ts b/types/react-relay/compat.d.ts index 74f7f55a03..bbc69a3cc4 100644 --- a/types/react-relay/compat.d.ts +++ b/types/react-relay/compat.d.ts @@ -1,6 +1,15 @@ -import { RelayRuntimeTypes, RelayCommonTypes } from "relay-runtime"; +export { + QueryRenderer, + commitMutation, + createFragmentContainer, + createPaginationContainer, + createRefetchContainer, + fetchQuery, + graphql, +} from "react-relay"; + +import * as RelayRuntimeTypes from "relay-runtime"; import { RelayEnvironmentInterface } from "react-relay/classic"; -import {} from "react-relay/modern"; // ~~~~~~~~~~~~~~~~~~~~~ // Maybe Fix @@ -13,7 +22,7 @@ type ConcreteOperationDefinition = object; // ~~~~~~~~~~~~~~~~~~~~~ // Util // ~~~~~~~~~~~~~~~~~~~~~ -export function getFragment(q: string, v?: RelayCommonTypes.Variables): string; +export function getFragment(q: string, v?: RelayRuntimeTypes.Variables): string; export interface ComponentWithFragment extends React.ComponentClass { getFragment: typeof getFragment; } @@ -35,25 +44,25 @@ export type CompatEnvironment = RelayRuntimeTypes.Environment | RelayClassicEnvi export function commitUpdate( environment: CompatEnvironment, config: RelayRuntimeTypes.MutationConfig -): RelayCommonTypes.Disposable; +): RelayRuntimeTypes.Disposable; export function applyUpdate( environment: CompatEnvironment, config: RelayRuntimeTypes.OptimisticMutationConfig -): RelayCommonTypes.Disposable; +): RelayRuntimeTypes.Disposable; // ~~~~~~~~~~~~~~~~~~~~~ // RelayCompatContainer // ~~~~~~~~~~~~~~~~~~~~~ export interface GeneratedNodeMap { - [key: string]: RelayCommonTypes.GraphQLTaggedNode; + [key: string]: RelayRuntimeTypes.GraphQLTaggedNode; } export function createContainer( Component: ReactBaseComponent, - fragmentSpec: RelayCommonTypes.GraphQLTaggedNode | GeneratedNodeMap + fragmentSpec: RelayRuntimeTypes.GraphQLTaggedNode | GeneratedNodeMap ): ReactFragmentComponent; // ~~~~~~~~~~~~~~~~~~~~~ // injectDefaultVariablesProvider // ~~~~~~~~~~~~~~~~~~~~~ -export type VariablesProvider = () => RelayCommonTypes.Variables; +export type VariablesProvider = () => RelayRuntimeTypes.Variables; export function injectDefaultVariablesProvider(variablesProvider: VariablesProvider): void; diff --git a/types/react-relay/index.d.ts b/types/react-relay/index.d.ts index cdb38afae6..fa23ac4dd7 100644 --- a/types/react-relay/index.d.ts +++ b/types/react-relay/index.d.ts @@ -6,20 +6,157 @@ // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped // TypeScript Version: 2.4 -import { RelayRuntimeTypes } from "relay-runtime"; -import * as ReactRelayModernTypes from "react-relay/modern"; +export { + commitLocalUpdate, + commitRelayModernMutation as commitMutation, + fetchRelayModernQuery as fetchQuery, + requestRelaySubscription as requestSubscription, +} from "relay-runtime"; + +import * as React from "react"; +import * as RelayRuntimeTypes from "relay-runtime"; // ~~~~~~~~~~~~~~~~~~~~~ -// React-Relay Modern +// Maybe Fix // ~~~~~~~~~~~~~~~~~~~~~ -export import QueryRenderer = ReactRelayModernTypes.ReactRelayQueryRenderer; -export import createFragmentContainer = ReactRelayModernTypes.createFragmentContainer; -export import createPaginationContainer = ReactRelayModernTypes.createPaginationContainer; -export import createRefetchContainer = ReactRelayModernTypes.createRefetchContainer; -export import graphql = ReactRelayModernTypes.graphql; -export import commitLocalUpdate = RelayRuntimeTypes.commitLocalUpdate; -export import commitMutation = RelayRuntimeTypes.commitRelayModernMutation; -export import fetchQuery = RelayRuntimeTypes.fetchRelayModernQuery; -export import requestSubscription = RelayRuntimeTypes.requestRelaySubscription; -// exported for convenience -export import ModernTypes = ReactRelayModernTypes; +type ConcreteFragment = any; +type ConcreteBatch = any; +type ConcreteFragmentDefinition = object; +type ConcreteOperationDefinition = object; +type ReactBaseComponent = React.ComponentClass | React.StatelessComponent; + +// ~~~~~~~~~~~~~~~~~~~~~ +// RelayProp +// ~~~~~~~~~~~~~~~~~~~~~ +// note: refetch and pagination containers augment this +export interface RelayProp { + environment: RelayRuntimeTypes.Environment; +} + +// ~~~~~~~~~~~~~~~~~~~~~ +// RelayQL +// ~~~~~~~~~~~~~~~~~~~~~ +export function RelayQL(strings: string[], ...substitutions: any[]): RelayRuntimeTypes.RelayConcreteNode; + +// ~~~~~~~~~~~~~~~~~~~~~ +// RelayModernGraphQLTag +// ~~~~~~~~~~~~~~~~~~~~~ +export interface GeneratedNodeMap { + [key: string]: GraphQLTaggedNode; +} +export type GraphQLTaggedNode = + | (() => ConcreteFragment | ConcreteBatch) + | { + modern(): ConcreteFragment | ConcreteBatch; + classic(relayQL: typeof RelayQL): ConcreteFragmentDefinition | ConcreteOperationDefinition; + }; +/** + * Runtime function to correspond to the `graphql` tagged template function. + * All calls to this function should be transformed by the plugin. + */ +export interface GraphqlInterface { + (strings: string[] | TemplateStringsArray): GraphQLTaggedNode; + experimental(strings: string[] | TemplateStringsArray): GraphQLTaggedNode; +} +export const graphql: GraphqlInterface; + +// ~~~~~~~~~~~~~~~~~~~~~ +// ReactRelayQueryRenderer +// ~~~~~~~~~~~~~~~~~~~~~ +export interface QueryRendererProps { + cacheConfig?: RelayRuntimeTypes.CacheConfig; + environment: RelayRuntimeTypes.Environment; + query: GraphQLTaggedNode; + render(readyState: ReadyState): React.ReactElement | undefined | null; + variables: RelayRuntimeTypes.Variables; + rerunParamExperimental?: RelayRuntimeTypes.RerunParam; +} +export interface ReadyState { + error: Error | undefined | null; + props: { [propName: string]: any } | undefined | null; + retry?(): void; +} +export interface QueryRendererState { + readyState: ReadyState; +} +export class ReactRelayQueryRenderer extends React.Component {} +export class QueryRenderer extends ReactRelayQueryRenderer {} + +// ~~~~~~~~~~~~~~~~~~~~~ +// createFragmentContainer +// ~~~~~~~~~~~~~~~~~~~~~ +export function createFragmentContainer( + Component: ReactBaseComponent, + fragmentSpec: GraphQLTaggedNode | GeneratedNodeMap +): ReactBaseComponent; + +// ~~~~~~~~~~~~~~~~~~~~~ +// createPaginationContainer +// ~~~~~~~~~~~~~~~~~~~~~ +export interface PageInfo { + endCursor: string | undefined | null; + hasNextPage: boolean; + hasPreviousPage: boolean; + startCursor: string | undefined | null; +} +export interface ConnectionData { + edges?: any[]; + pageInfo?: PageInfo; +} +export type RelayPaginationProp = RelayProp & { + hasMore(): boolean; + isLoading(): boolean; + loadMore( + pageSize: number, + callback: (error?: Error) => void, + options?: RefetchOptions + ): RelayRuntimeTypes.Disposable | undefined | null; + refetchConnection( + totalCount: number, + callback: (error?: Error) => void, + refetchVariables?: RelayRuntimeTypes.Variables + ): RelayRuntimeTypes.Disposable | undefined | null; +}; +export function FragmentVariablesGetter( + prevVars: RelayRuntimeTypes.Variables, + totalCount: number +): RelayRuntimeTypes.Variables; +export interface ConnectionConfig { + direction?: "backward" | "forward"; + getConnectionFromProps?(props: T): ConnectionData | undefined | null; + getFragmentVariables?: typeof FragmentVariablesGetter; + getVariables( + props: { [propName: string]: any }, + paginationInfo: { count: number; cursor?: string }, + fragmentVariables: RelayRuntimeTypes.Variables + ): RelayRuntimeTypes.Variables; + query: GraphQLTaggedNode; +} +export function createPaginationContainer( + Component: ReactBaseComponent, + fragmentSpec: GraphQLTaggedNode | GeneratedNodeMap, + connectionConfig: ConnectionConfig +): ReactBaseComponent; + +// ~~~~~~~~~~~~~~~~~~~~~ +// createFragmentContainer +// ~~~~~~~~~~~~~~~~~~~~~ +export interface RefetchOptions { + force?: boolean; + rerunParamExperimental?: RelayRuntimeTypes.RerunParam; +} +export type RelayRefetchProp = RelayProp & { + refetch( + refetchVariables: + | RelayRuntimeTypes.Variables + | ((fragmentVariables: RelayRuntimeTypes.Variables) => RelayRuntimeTypes.Variables), + renderVariables?: RelayRuntimeTypes.Variables, + callback?: (error?: Error) => void, + options?: RefetchOptions + ): RelayRuntimeTypes.Disposable; +}; +export function createRefetchContainer( + Component: ReactBaseComponent, + fragmentSpec: GraphQLTaggedNode | GeneratedNodeMap, + taggedNode: GraphQLTaggedNode +): ReactBaseComponent; diff --git a/types/react-relay/modern.d.ts b/types/react-relay/modern.d.ts deleted file mode 100644 index d4c422b823..0000000000 --- a/types/react-relay/modern.d.ts +++ /dev/null @@ -1,146 +0,0 @@ -import * as React from "react"; -import { RelayCommonTypes, RelayRuntimeTypes } from "relay-runtime"; - -// ~~~~~~~~~~~~~~~~~~~~~ -// Maybe Fix -// ~~~~~~~~~~~~~~~~~~~~~ -type ConcreteFragment = any; -type ConcreteBatch = any; -type ConcreteFragmentDefinition = object; -type ConcreteOperationDefinition = object; -type ReactBaseComponent = React.ComponentClass | React.StatelessComponent; - -// ~~~~~~~~~~~~~~~~~~~~~ -// RelayProp -// ~~~~~~~~~~~~~~~~~~~~~ -// note: refetch and pagination containers augment this -export interface RelayProp { - environment: RelayRuntimeTypes.Environment; -} - -// ~~~~~~~~~~~~~~~~~~~~~ -// RelayQL -// ~~~~~~~~~~~~~~~~~~~~~ -export function RelayQL(strings: string[], ...substitutions: any[]): RelayCommonTypes.RelayConcreteNode; - -// ~~~~~~~~~~~~~~~~~~~~~ -// RelayModernGraphQLTag -// ~~~~~~~~~~~~~~~~~~~~~ -export interface GeneratedNodeMap { - [key: string]: GraphQLTaggedNode; -} -export type GraphQLTaggedNode = - | (() => ConcreteFragment | ConcreteBatch) - | { - modern(): ConcreteFragment | ConcreteBatch; - classic(relayQL: typeof RelayQL): ConcreteFragmentDefinition | ConcreteOperationDefinition; - }; -/** - * Runtime function to correspond to the `graphql` tagged template function. - * All calls to this function should be transformed by the plugin. - */ -export interface GraphqlInterface { - (strings: string[] | TemplateStringsArray): GraphQLTaggedNode; - experimental(strings: string[] | TemplateStringsArray): GraphQLTaggedNode; -} -export const graphql: GraphqlInterface; - -// ~~~~~~~~~~~~~~~~~~~~~ -// ReactRelayQueryRenderer -// ~~~~~~~~~~~~~~~~~~~~~ -export interface QueryRendererProps { - cacheConfig?: RelayCommonTypes.CacheConfig; - environment: RelayRuntimeTypes.Environment; - query: GraphQLTaggedNode; - render(readyState: ReadyState): React.ReactElement | undefined | null; - variables: RelayCommonTypes.Variables; - rerunParamExperimental?: RelayCommonTypes.RerunParam; -} -export interface ReadyState { - error: Error | undefined | null; - props: { [propName: string]: any } | undefined | null; - retry?(): void; -} -export interface QueryRendererState { - readyState: ReadyState; -} -export class ReactRelayQueryRenderer extends React.Component {} - -// ~~~~~~~~~~~~~~~~~~~~~ -// createFragmentContainer -// ~~~~~~~~~~~~~~~~~~~~~ -export function createFragmentContainer( - Component: ReactBaseComponent, - fragmentSpec: GraphQLTaggedNode | GeneratedNodeMap -): ReactBaseComponent; - -// ~~~~~~~~~~~~~~~~~~~~~ -// createPaginationContainer -// ~~~~~~~~~~~~~~~~~~~~~ -export interface PageInfo { - endCursor: string | undefined | null; - hasNextPage: boolean; - hasPreviousPage: boolean; - startCursor: string | undefined | null; -} -export interface ConnectionData { - edges?: any[]; - pageInfo?: PageInfo; -} -export type RelayPaginationProp = RelayProp & { - hasMore(): boolean; - isLoading(): boolean; - loadMore( - pageSize: number, - callback: (error?: Error) => void, - options?: RefetchOptions - ): RelayCommonTypes.Disposable | undefined | null; - refetchConnection( - totalCount: number, - callback: (error?: Error) => void, - refetchVariables?: RelayCommonTypes.Variables - ): RelayCommonTypes.Disposable | undefined | null; -}; -export function FragmentVariablesGetter( - prevVars: RelayCommonTypes.Variables, - totalCount: number -): RelayCommonTypes.Variables; -export interface ConnectionConfig { - direction?: "backward" | "forward"; - getConnectionFromProps?(props: T): ConnectionData | undefined | null; - getFragmentVariables?: typeof FragmentVariablesGetter; - getVariables( - props: { [propName: string]: any }, - paginationInfo: { count: number; cursor?: string }, - fragmentVariables: RelayCommonTypes.Variables - ): RelayCommonTypes.Variables; - query: GraphQLTaggedNode; -} -export function createPaginationContainer( - Component: ReactBaseComponent, - fragmentSpec: GraphQLTaggedNode | GeneratedNodeMap, - connectionConfig: ConnectionConfig -): ReactBaseComponent; - -// ~~~~~~~~~~~~~~~~~~~~~ -// createFragmentContainer -// ~~~~~~~~~~~~~~~~~~~~~ -export interface RefetchOptions { - force?: boolean; - rerunParamExperimental?: RelayCommonTypes.RerunParam; -} -export type RelayRefetchProp = RelayProp & { - refetch( - refetchVariables: - | RelayCommonTypes.Variables - | ((fragmentVariables: RelayCommonTypes.Variables) => RelayCommonTypes.Variables), - renderVariables?: RelayCommonTypes.Variables, - callback?: (error?: Error) => void, - options?: RefetchOptions - ): RelayCommonTypes.Disposable; -}; -export function createRefetchContainer( - Component: ReactBaseComponent, - fragmentSpec: GraphQLTaggedNode | GeneratedNodeMap, - taggedNode: GraphQLTaggedNode -): ReactBaseComponent; diff --git a/types/react-relay/test/react-relay-tests.tsx b/types/react-relay/test/react-relay-tests.tsx index 80380122f7..6caf997dba 100644 --- a/types/react-relay/test/react-relay-tests.tsx +++ b/types/react-relay/test/react-relay-tests.tsx @@ -12,7 +12,8 @@ import { createRefetchContainer, requestSubscription, QueryRenderer, - ModernTypes, + RelayRefetchProp, + RelayPaginationProp } from "react-relay"; // ~~~~~~~~~~~~~~~~~~~~~ @@ -79,7 +80,7 @@ interface StoryInterface { id: string; } interface FeedStoriesProps { - relay: ModernTypes.RelayRefetchProp; + relay: RelayRefetchProp; feed: { stories: { edges: Array<{ node: StoryInterface }> }; }; @@ -134,7 +135,7 @@ const FeedRefetchContainer = createRefetchContainer( // ~~~~~~~~~~~~~~~~~~~~~ interface FeedProps { user: { feed: { edges: Array<{ node: StoryInterface }> } }; - relay: ModernTypes.RelayPaginationProp; + relay: RelayPaginationProp; } class Feed extends React.Component { render() { diff --git a/types/react-relay/tsconfig.json b/types/react-relay/tsconfig.json index 2b992f91c8..ef2af0375f 100644 --- a/types/react-relay/tsconfig.json +++ b/types/react-relay/tsconfig.json @@ -20,7 +20,6 @@ "files": [ "index.d.ts", "classic.d.ts", - "modern.d.ts", "compat.d.ts", "test/react-relay-tests.tsx", "test/react-relay-classic-tests.tsx" diff --git a/types/relay-runtime/index.d.ts b/types/relay-runtime/index.d.ts index 69f5088ab4..bbc3e07a7a 100644 --- a/types/relay-runtime/index.d.ts +++ b/types/relay-runtime/index.d.ts @@ -5,1092 +5,1047 @@ // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped // TypeScript Version: 2.4 -// note: namespace is used so react-relay can access and inter-op -export namespace RelayCommonTypes { - /** - * SOURCE: - * Relay 1.3.0 - * https://github.com/facebook/relay/blob/b85a1d69bb72be4ace67179f55c2a54a8d761c8b/packages/react-relay/classic/environment/RelayCombinedEnvironmentTypes.js - */ - // ~~~~~~~~~~~~~~~~~~~~~ - // Maybe Fix - // ~~~~~~~~~~~~~~~~~~~~~ - type RelayConcreteNode = any; - type RelayMutationTransaction = any; - type RelayMutationRequest = any; - type RelayQueryRequest = any; - type ConcreteFragment = any; - type ConcreteBatch = any; - type ConcreteFragmentDefinition = object; - type ConcreteOperationDefinition = object; +/** + * SOURCE: + * Relay 1.3.0 + * https://github.com/facebook/relay/blob/b85a1d69bb72be4ace67179f55c2a54a8d761c8b/packages/react-relay/classic/environment/RelayCombinedEnvironmentTypes.js + */ +// ~~~~~~~~~~~~~~~~~~~~~ +// Maybe Fix +// ~~~~~~~~~~~~~~~~~~~~~ +type RelayConcreteNode = any; +type RelayMutationTransaction = any; +type RelayMutationRequest = any; +type RelayQueryRequest = any; +type ConcreteFragment = any; +type ConcreteBatch = any; +type ConcreteFragmentDefinition = object; +type ConcreteOperationDefinition = object; - /** - * FIXME: RelayContainer used to be typed with ReactClass, but - * ReactClass is broken and allows for access to any property. For example - * ReactClass.getFragment('foo') is valid even though ReactClass has no - * such getFragment() type definition. When ReactClass is fixed this causes a - * lot of errors in Relay code since methods like getFragment() are used often - * but have no definition in Relay's types. Suppressing for now. - */ - type RelayContainer = any; +/** + * FIXME: RelayContainer used to be typed with ReactClass, but + * ReactClass is broken and allows for access to any property. For example + * ReactClass.getFragment('foo') is valid even though ReactClass has no + * such getFragment() type definition. When ReactClass is fixed this causes a + * lot of errors in Relay code since methods like getFragment() are used often + * but have no definition in Relay's types. Suppressing for now. + */ +type RelayContainer = any; - // ~~~~~~~~~~~~~~~~~~~~~ - // RelayQL - // ~~~~~~~~~~~~~~~~~~~~~ - type RelayQL = (strings: string[], ...substitutions: any[]) => RelayConcreteNode; +// ~~~~~~~~~~~~~~~~~~~~~ +// RelayQL +// ~~~~~~~~~~~~~~~~~~~~~ +type RelayQL = (strings: string[], ...substitutions: any[]) => RelayConcreteNode; - // ~~~~~~~~~~~~~~~~~~~~~ - // RelayModernGraphQLTag - // ~~~~~~~~~~~~~~~~~~~~~ - interface GeneratedNodeMap { - [key: string]: GraphQLTaggedNode; - } - type GraphQLTaggedNode = - | (() => ConcreteFragment | ConcreteBatch) - | { - modern(): ConcreteFragment | ConcreteBatch; - classic(relayQL: RelayQL): ConcreteFragmentDefinition | ConcreteOperationDefinition; - }; - // ~~~~~~~~~~~~~~~~~~~~~ - // General Usage - // ~~~~~~~~~~~~~~~~~~~~~ - type DataID = string; - interface Variables { - [name: string]: any; - } - type Uploadable = File | Blob; - interface UploadableMap { - [key: string]: Uploadable; - } - - // ~~~~~~~~~~~~~~~~~~~~~ - // RelayNetworkTypes - // Version: Relay 1.3.0 - // File: https://github.com/facebook/relay/blob/master/packages/relay-runtime/network/RelayNetworkTypes.js - // ~~~~~~~~~~~~~~~~~~~~~ - - interface LegacyObserver { - onCompleted?(): void; - onError?(error: Error): void; - onNext?(data: T): void; - } - interface PayloadError { - message: string; - locations?: Array<{ - line: number; - column: number; - }>; - } - /** - * A function that executes a GraphQL operation with request/response semantics. - * - * May return an Observable or Promise of a raw server response. - */ - function FetchFunction( - operation: ConcreteBatch, - variables: Variables, - cacheConfig: CacheConfig, - uploadables?: UploadableMap - ): RelayRuntimeTypes.ObservableFromValue; - - /** - * A function that executes a GraphQL subscription operation, returning one or - * more raw server responses over time. - * - * May return an Observable, otherwise must call the callbacks found in the - * fourth parameter. - */ - type SubscribeFunction = ( - operation: ConcreteBatch, - variables: Variables, - cacheConfig: CacheConfig, - observer: LegacyObserver - ) => RelayRuntimeTypes.RelayObservable | Disposable; - - // ~~~~~~~~~~~~~~~~~~~~~ - // RelayStoreTypes - // Version: Relay 1.3.0 - // File: https://github.com/facebook/relay/blob/master/packages/relay-runtime/store/RelayStoreTypes.js - // ~~~~~~~~~~~~~~~~~~~~~ - /** - * A function that receives a proxy over the store and may trigger side-effects - * (indirectly) by calling `set*` methods on the store or its record proxies. - */ - type StoreUpdater = (store: RecordSourceProxy) => void; - - /** - * Similar to StoreUpdater, but accepts a proxy tied to a specific selector in - * order to easily access the root fields of a query/mutation as well as a - * second argument of the response object of the mutation. - */ - type SelectorStoreUpdater = ( - store: RecordSourceSelectorProxy, - // Actually RelayCombinedEnvironmentTypes#SelectorData, but mixed is - // inconvenient to access deeply in product code. - data: any // FLOW FIXME - ) => void; - - /** - * Extends the RecordSourceProxy interface with methods for accessing the root - * fields of a Selector. - */ - interface RecordSourceSelectorProxy { - create(dataID: DataID, typeName: string): RecordProxy; - delete(dataID: DataID): void; - get(dataID: DataID): RecordProxy | null; - getRoot(): RecordProxy; - getRootField(fieldName: string): RecordProxy | null; - getPluralRootField(fieldName: string): RecordProxy[] | null; - } - - interface RecordProxy { - copyFieldsFrom(source: RecordProxy): void; - getDataID(): DataID; - getLinkedRecord(name: string, args?: Variables): RecordProxy | null; - getLinkedRecords(name: string, args?: Variables): Array | null; - getOrCreateLinkedRecord(name: string, typeName: string, args?: Variables): RecordProxy; - getType(): string; - getValue(name: string, args?: Variables): any; - setLinkedRecord(record: RecordProxy, name: string, args?: Variables): RecordProxy; - setLinkedRecords( - records: Array | undefined | null, - name: string, - args?: Variables - ): RecordProxy; - setValue(value: any, name: string, args?: Variables): RecordProxy; - } - - interface RecordSourceProxy { - create(dataID: DataID, typeName: string): RecordProxy; - delete(dataID: DataID): void; - get(dataID: DataID): Array | null; - getRoot(): RecordProxy; - } - - interface HandleFieldPayload { - // The arguments that were fetched. - args: Variables; - // The __id of the record containing the source/handle field. - dataID: DataID; - // The (storage) key at which the original server data was written. - fieldKey: string; - // The name of the handle - handle: string; - // The (storage) key at which the handle's data should be written by the - // handler - handleKey: string; - } - interface HandlerInterface { - update(store: RecordSourceProxy, fieldPayload: HandleFieldPayload): void; - [functionName: string]: (...args: any[]) => any; - } - const Handler: HandlerInterface; - - // ~~~~~~~~~~~~~~~~~~~~~ - // RelayCombinedEnvironmentTypes - // Version: Relay 1.3.0 - // File: https://github.com/facebook/relay/blob/b85a1d69bb72be4ace67179f55c2a54a8d761c8b/packages/react-relay/classic/environment/RelayCombinedEnvironmentTypes.js - // ~~~~~~~~~~~~~~~~~~~~~ - /** - * Settings for how a query response may be cached. - * - * - `force`: causes a query to be issued unconditionally, irrespective of the - * state of any configured response cache. - * - `poll`: causes a query to live update by polling at the specified interval - * in milliseconds. (This value will be passed to setTimeout.) - */ - interface CacheConfig { - force?: boolean; - poll?: number; - } - - /** - * Represents any resource that must be explicitly disposed of. The most common - * use-case is as a return value for subscriptions, where calling `dispose()` - * would cancel the subscription. - */ - interface Disposable { - dispose(): void; - } - - /** - * Arbitrary data e.g. received by a container as props. - */ - interface Props { - [key: string]: any; - } - - /* - * An individual cached graph object. - */ - interface Record { - [key: string]: any; - } - - /** - * A collection of records keyed by id. - */ - interface RecordMap { - [dataID: string]: Record | null | undefined; - } - - /** - * A selector defines the starting point for a traversal into the graph for the - * purposes of targeting a subgraph. - */ - interface CSelector { - dataID: DataID; - node: TNode; - variables: Variables; - } - - /** - * A representation of a selector and its results at a particular point in time. - */ - type CSnapshot = CSelector & { - data: SelectorData | null | undefined; - seenRecords: RecordMap; - }; - - /** - * The results of a selector given a store/RecordSource. - */ - interface SelectorData { - [key: string]: any; - } - - /** - * The results of reading the results of a FragmentMap given some input - * `Props`. - */ - interface FragmentSpecResults { - [key: string]: any; - } - - /** - * A utility for resolving and subscribing to the results of a fragment spec - * (key -> fragment mapping) given some "props" that determine the root ID - * and variables to use when reading each fragment. When props are changed via - * `setProps()`, the resolver will update its results and subscriptions - * accordingly. Internally, the resolver: - * - Converts the fragment map & props map into a map of `Selector`s. - * - Removes any resolvers for any props that became null. - * - Creates resolvers for any props that became non-null. - * - Updates resolvers with the latest props. - */ - interface FragmentSpecResolver { - /** - * Stop watching for changes to the results of the fragments. - */ - dispose(): void; - - /** - * Get the current results. - */ - resolve(): FragmentSpecResults; - - /** - * Update the resolver with new inputs. Call `resolve()` to get the updated - * results. - */ - setProps(props: Props): void; - - /** - * Override the variables used to read the results of the fragments. Call - * `resolve()` to get the updated results. - */ - setVariables(variables: Variables): void; - } - - interface CFragmentMap { - [key: string]: TFragment; - } - - /** - * An operation selector describes a specific instance of a GraphQL operation - * with variables applied. - * - * - `root`: a selector intended for processing server results or retaining - * response data in the store. - * - `fragment`: a selector intended for use in reading or subscribing to - * the results of the the operation. - */ - interface COperationSelector { - fragment: CSelector; - node: TOperation; - root: CSelector; - variables: Variables; - } - - /** - * The public API of Relay core. Represents an encapsulated environment with its - * own in-memory cache. - */ - interface CEnvironment { - /** - * Read the results of a selector from in-memory records in the store. - */ - lookup(selector: CSelector): CSnapshot; - - /** - * Subscribe to changes to the results of a selector. The callback is called - * when data has been committed to the store that would cause the results of - * the snapshot's selector to change. - */ - subscribe(snapshot: CSnapshot, callback: (snapshot: CSnapshot) => void): Disposable; - - /** - * Ensure that all the records necessary to fulfill the given selector are - * retained in-memory. The records will not be eligible for garbage collection - * until the returned reference is disposed. - * - * Note: This is a no-op in the classic core. - */ - retain(selector: CSelector): Disposable; - - /** - * Send a query to the server with request/response semantics: the query will - * either complete successfully (calling `onNext` and `onCompleted`) or fail - * (calling `onError`). - * - * Note: Most applications should use `streamQuery` in order to - * optionally receive updated information over time, should that feature be - * supported by the network/server. A good rule of thumb is to use this method - * if you would otherwise immediately dispose the `streamQuery()` - * after receving the first `onNext` result. - */ - sendQuery(config: { - cacheConfig?: CacheConfig; - onCompleted?(): void; - onError?(error: Error): void; - onNext?(payload: TPayload): void; - operation: COperationSelector; - }): Disposable; - - /** - * Send a query to the server with request/subscription semantics: one or more - * responses may be returned (via `onNext`) over time followed by either - * the request completing (`onCompleted`) or an error (`onError`). - * - * Networks/servers that support subscriptions may choose to hold the - * subscription open indefinitely such that `onCompleted` is not called. - */ - streamQuery(config: { - cacheConfig?: CacheConfig; - onCompleted?(): void; - onError?(error: Error): void; - onNext?(payload: TPayload): void; - operation: COperationSelector; - }): Disposable; - - unstable_internal: CUnstableEnvironmentCore; - } - - interface CUnstableEnvironmentCore { - /** - * Create an instance of a FragmentSpecResolver. - * - * TODO: The FragmentSpecResolver *can* be implemented via the other methods - * defined here, so this could be moved out of core. It's convenient to have - * separate implementations until the experimental core is in OSS. - */ - createFragmentSpecResolver( - context: CRelayContext, - containerName: string, - fragments: CFragmentMap, - props: Props, - callback: () => void - ): FragmentSpecResolver; - - /** - * Creates an instance of an OperationSelector given an operation definition - * (see `getOperation`) and the variables to apply. The input variables are - * filtered to exclude variables that do not matche defined arguments on the - * operation, and default values are populated for null values. - */ - createOperationSelector(operation: TOperation, variables: Variables): COperationSelector; - - /** - * Given a graphql`...` tagged template, extract a fragment definition usable - * by this version of Relay core. Throws if the value is not a fragment. - */ - getFragment(node: TGraphQLTaggedNode): TFragment; - - /** - * Given a graphql`...` tagged template, extract an operation definition - * usable by this version of Relay core. Throws if the value is not an - * operation. - */ - getOperation(node: TGraphQLTaggedNode): TOperation; - - /** - * Determine if two selectors are equal (represent the same selection). Note - * that this function returns `false` when the two queries/fragments are - * different objects, even if they select the same fields. - */ - areEqualSelectors(a: CSelector, b: CSelector): boolean; - - /** - * Given the result `item` from a parent that fetched `fragment`, creates a - * selector that can be used to read the results of that fragment for that item. - * - * Example: - * - * Given two fragments as follows: - * - * ``` - * fragment Parent on User { - * id - * ...Child - * } - * fragment Child on User { - * name - * } - * ``` - * - * And given some object `parent` that is the results of `Parent` for id "4", - * the results of `Child` can be accessed by first getting a selector and then - * using that selector to `lookup()` the results against the environment: - * - * ``` - * const childSelector = getSelector(queryVariables, Child, parent); - * const childData = environment.lookup(childSelector).data; - * ``` - */ - getSelector(operationVariables: Variables, fragment: TFragment, prop: any): CSelector | null; - - /** - * Given the result `items` from a parent that fetched `fragment`, creates a - * selector that can be used to read the results of that fragment on those - * items. This is similar to `getSelector` but for "plural" fragments that - * expect an array of results and therefore return an array of selectors. - */ - getSelectorList( - operationVariables: Variables, - fragment: TFragment, - props: any[] - ): Array> | null; - - /** - * Given a mapping of keys -> results and a mapping of keys -> fragments, - * extracts the selectors for those fragments from the results. - * - * The canonical use-case for this function are Relay Containers, which - * use this function to convert (props, fragments) into selectors so that they - * can read the results to pass to the inner component. - */ - getSelectorsFromObject( - operationVariables: Variables, - fragments: CFragmentMap, - props: Props - ): { [key: string]: CSelector | Array> | null | undefined }; - - /** - * Given a mapping of keys -> results and a mapping of keys -> fragments, - * extracts a mapping of keys -> id(s) of the results. - * - * Similar to `getSelectorsFromObject()`, this function can be useful in - * determining the "identity" of the props passed to a component. - */ - getDataIDsFromObject( - fragments: CFragmentMap, - props: Props - ): { [key: string]: DataID | DataID[] | null | undefined }; - - /** - * Given a mapping of keys -> results and a mapping of keys -> fragments, - * extracts the merged variables that would be in scope for those - * fragments/results. - * - * This can be useful in determing what varaibles were used to fetch the data - * for a Relay container, for example. - */ - getVariablesFromObject( - operationVariables: Variables, - fragments: CFragmentMap, - props: Props - ): Variables; - } - - /** - * The type of the `relay` property set on React context by the React/Relay - * integration layer (e.g. QueryRenderer, FragmentContainer, etc). - */ - interface CRelayContext { - environment: TEnvironment; - variables: Variables; - } - - // ~~~~~~~~~~~~~~~~~~~~~ - // RelayTypes - /** - * Version: Relay 1.3.0 - * File: - * https://github.com/facebook/relay/blob/fa9f48ea209ee2402d433b59a84d1cbc046574e2/packages/react-relay/classic/tools/RelayTypes.js - */ - // ~~~~~~~~~~~~~~~~~~~~~ - interface RerunParam { - param: string; - import: string; - max_runs: number; - } - interface FIELDS_CHANGE { - type: "FIELDS_CHANGE"; - fieldIDs: { [fieldName: string]: DataID | DataID[] }; - } - interface RANGE_ADD { - type: "RANGE_ADD"; - parentName?: string; - parentID?: string; - connectionInfo?: Array<{ - key: string; - filters?: Variables; - rangeBehavior: string; - }>; - connectionName?: string; - edgeName: string; - rangeBehaviors?: RangeBehaviors; - } - interface NODE_DELETE { - type: "NODE_DELETE"; - parentName?: string; - parentID?: string; - connectionName?: string; - deletedIDFieldName: string; - } - interface RANGE_DELETE { - type: "RANGE_DELETE"; - parentName?: string; - parentID?: string; - connectionKeys?: Array<{ - key: string; - filters?: Variables; - }>; - connectionName?: string; - deletedIDFieldName: string | string[]; - pathToConnection: string[]; - } - interface REQUIRED_CHILDREN { - type: "REQUIRED_CHILDREN"; - children: RelayConcreteNode[]; - } - type RelayMutationConfig = FIELDS_CHANGE | RANGE_ADD | NODE_DELETE | RANGE_DELETE | REQUIRED_CHILDREN; - - interface RelayMutationTransactionCommitCallbacks { - onFailure?: RelayMutationTransactionCommitFailureCallback; - onSuccess?: RelayMutationTransactionCommitSuccessCallback; - } - type RelayMutationTransactionCommitFailureCallback = ( - transaction: RelayMutationTransaction, - preventAutoRollback: () => void - ) => void; - type RelayMutationTransactionCommitSuccessCallback = ( - response: { - [key: string]: any; - } - ) => void; - interface NetworkLayer { - sendMutation(request: RelayMutationRequest): Promise | null; - sendQueries(requests: RelayQueryRequest[]): Promise | null; - supports(...options: string[]): boolean; - } - interface QueryResult { - error?: Error; - ref_params?: { [name: string]: any }; - response: QueryPayload; - } - interface ReadyState { - aborted: boolean; - done: boolean; - error: Error | null; - events: ReadyStateEvent[]; - ready: boolean; - stale: boolean; - } - type RelayContainerErrorEventType = "CACHE_RESTORE_FAILED" | "NETWORK_QUERY_ERROR"; - type RelayContainerLoadingEventType = - | "ABORT" - | "CACHE_RESTORED_REQUIRED" - | "CACHE_RESTORE_START" - | "NETWORK_QUERY_RECEIVED_ALL" - | "NETWORK_QUERY_RECEIVED_REQUIRED" - | "NETWORK_QUERY_START" - | "STORE_FOUND_ALL" - | "STORE_FOUND_REQUIRED"; - type ReadyStateChangeCallback = (readyState: ReadyState) => void; - interface ReadyStateEvent { - type: RelayContainerLoadingEventType | RelayContainerErrorEventType; - error?: Error; - } - interface Abortable { - abort(): void; - } - - // ~~~~~~~~~~~~~~~~~~~~~ - // RelayInternalTypes - /** - * Version: Relay 1.3.0 - * File: - * https://github.com/facebook/relay/blob/master/packages/react-relay/classic/tools/RelayInternalTypes.js - */ - // ~~~~~~~~~~~~~~~~~~~~~ - interface QueryPayload { - [key: string]: any; - } - interface RelayQuerySet { - [queryName: string]: any; - } - type RangeBehaviorsFunction = ( - connectionArgs: { - [argName: string]: any; - } - ) => "APPEND" | "IGNORE" | "PREPEND" | "REFETCH" | "REMOVE"; - interface RangeBehaviorsObject { - [key: string]: "APPEND" | "IGNORE" | "PREPEND" | "REFETCH" | "REMOVE"; - } - type RangeBehaviors = RangeBehaviorsFunction | RangeBehaviorsObject; +// ~~~~~~~~~~~~~~~~~~~~~ +// RelayModernGraphQLTag +// ~~~~~~~~~~~~~~~~~~~~~ +interface GeneratedNodeMap { + [key: string]: GraphQLTaggedNode; } - -export namespace RelayRuntimeTypes { - // ~~~~~~~~~~~~~~~~~~~~~ - // Maybe Fix - // ~~~~~~~~~~~~~~~~~~~~~ - type RelayDebugger = any; - type OptimisticUpdate = any; - type OperationSelector = RelayCommonTypes.COperationSelector; - type Selector = RelayCommonTypes.CSelector; - type PayloadData = any; - type Snapshot = RelayCommonTypes.CSnapshot; - type RelayResponsePayload = any; - type MutableRecordSource = RecordSource; - - /** - * A function that returns an Observable representing the response of executing - * a GraphQL operation. - */ - type ExecuteFunction = ( - operation: object, - variables: RelayCommonTypes.Variables, - cacheConfig: RelayCommonTypes.CacheConfig, - uploadables?: RelayCommonTypes.UploadableMap - ) => Promise; - interface RelayNetwork { - execute: ExecuteFunction; - } - - // ~~~~~~~~~~~~~~~~~~~~~ - // RelayDefaultHandlerProvider - // ~~~~~~~~~~~~~~~~~~~~~ - function HandlerProvider(name: string): typeof RelayCommonTypes.Handler | null; - - // ~~~~~~~~~~~~~~~~~~~~~ - // RelayModernEnvironment - // ~~~~~~~~~~~~~~~~~~~~~ - interface EnvironmentConfig { - configName?: string; - handlerProvider?: typeof HandlerProvider; - network: Network; - store: Store; - } - class Environment { - constructor(config: EnvironmentConfig); - getStore(): Store; - getDebugger(): RelayDebugger; - applyUpdate(optimisticUpdate: OptimisticUpdate): RelayCommonTypes.Disposable; - revertUpdate(update: OptimisticUpdate): void; - replaceUpdate(update: OptimisticUpdate, newUpdate: OptimisticUpdate): void; - applyMutation(config: { - operation: OperationSelector; - optimisticUpdater?: RelayCommonTypes.SelectorStoreUpdater; - optimisticResponse?: object; - }): RelayCommonTypes.Disposable; - check(readSelector: Selector): boolean; - commitPayload(operationSelector: OperationSelector, payload: PayloadData): void; - commitUpdate(updater: RelayCommonTypes.StoreUpdater): void; - lookup(readSelector: Selector): Snapshot; - subscribe(snapshot: Snapshot, callback: (snapshot: Snapshot) => void): RelayCommonTypes.Disposable; - retain(selector: Selector): RelayCommonTypes.Disposable; - execute(config: { - operation: OperationSelector; - cacheConfig?: RelayCommonTypes.CacheConfig; - updater?: RelayCommonTypes.SelectorStoreUpdater; - }): RelayObservable; - executeMutation(config: { - operation: OperationSelector; - optimisticUpdater?: RelayCommonTypes.SelectorStoreUpdater; - optimisticResponse?: object; - updater?: RelayCommonTypes.SelectorStoreUpdater; - uploadables?: RelayCommonTypes.UploadableMap; - }): RelayObservable; - } - - // ~~~~~~~~~~~~~~~~~~~~~ - // RelayInMemoryRecordSource - // ~~~~~~~~~~~~~~~~~~~~~ - interface Record { - [key: string]: any; - } - interface RecordMap { - [dataID: string]: Record | null | undefined; - } - - // ~~~~~~~~~~~~~~~~~~~~~ - // Network - // ~~~~~~~~~~~~~~~~~~~~~ - class Network { - /** - * Creates an implementation of the `Network` interface defined in - * `RelayNetworkTypes` given `fetch` and `subscribe` functions. - */ - static create( - fetchFn: typeof RelayCommonTypes.FetchFunction, - subscribeFn?: RelayCommonTypes.SubscribeFunction - ): RelayNetwork; - } - - // ~~~~~~~~~~~~~~~~~~~~~ - // Network - // ~~~~~~~~~~~~~~~~~~~~~ - class RecordSource { - constructor(records?: RecordMap); - clear(): void; - delete(dataID: RelayCommonTypes.DataID): void; - get(dataID: RelayCommonTypes.DataID): Record | null; - getRecordIDs(): RelayCommonTypes.DataID[]; - getStatus(dataID: RelayCommonTypes.DataID): "EXISTENT" | "NONEXISTENT" | "UNKNOWN"; - has(dataID: RelayCommonTypes.DataID): boolean; - load(dataID: RelayCommonTypes.DataID, callback: (error: Error | null, record: Record | null) => void): void; - remove(dataID: RelayCommonTypes.DataID): void; - set(dataID: RelayCommonTypes.DataID, record: Record): void; - size(): number; - toJSON(): RecordMap; - } - - // ~~~~~~~~~~~~~~~~~~~~~ - // ModernStore - // ~~~~~~~~~~~~~~~~~~~~~ - class Store { - constructor(source: RecordSource); - getSource(): MutableRecordSource; - check(selector: Selector): boolean; - retain(selector: Selector): RelayCommonTypes.Disposable; - lookup(selector: Selector): Snapshot; - notify(): void; - publish(source: RecordSource): void; - subscribe(snapshot: Snapshot, callback: (snapshot: Snapshot) => void): RelayCommonTypes.Disposable; - } - - // ~~~~~~~~~~~~~~~~~~~~~ - // RelayRecordSourceInspector - // ~~~~~~~~~~~~~~~~~~~~~ - /** - * An internal class to provide a console-friendly string representation of a - * Record. - */ - class RecordSummary { - id: RelayCommonTypes.DataID; - type: string | null | undefined; - static createFromRecord(id: RelayCommonTypes.DataID, record: any): RecordSummary; - constructor(id: RelayCommonTypes.DataID, type: string | null | undefined); - toString(): string; - } - /** - * Internal class for inspecting a single Record. - */ - class RecordInspector { - constructor(sourceInspector: RelayRecordSourceInspector, record: Record); - /** - * Get the cache id of the given record. For types that implement the `Node` - * interface (or that have an `id`) this will be `id`, for other types it will be - * a synthesized identifier based on the field path from the nearest ancestor - * record that does have an `id`. - */ - getDataID(): RelayCommonTypes.DataID; - - /** - * Returns a list of the fields that have been fetched on the current record. - */ - getFields(): string[]; - - /** - * Returns the type of the record. - */ - getType(): string; - - /** - * Returns a copy of the internal representation of the record. - */ - inspect(): any; - - /** - * Returns the value of a scalar field. May throw if the given field is - * present but not actually scalar. - */ - getValue(name: string, args?: RelayCommonTypes.Variables): any; - - /** - * Returns an inspector for the given scalar "linked" field (a field whose - * value is another Record instead of a scalar). May throw if the field is - * present but not a scalar linked record. - */ - getLinkedRecord(name: string, args?: RelayCommonTypes.Variables): RecordInspector | null; - - /** - * Returns an array of inspectors for the given plural "linked" field (a field - * whose value is an array of Records instead of a scalar). May throw if the - * field is present but not a plural linked record. - */ - getLinkedRecords(name: string, args?: RelayCommonTypes.Variables): RecordInspector[] | null; - } - - class RelayRecordSourceInspector { - constructor(source: RecordSource); - static getForEnvironment(environment: Environment): RelayRecordSourceInspector; - /** - * Returns an inspector for the record with the given id, or null/undefined if - * that record is deleted/unfetched. - */ - get(dataID: RelayCommonTypes.DataID): RecordInspector | null; - /** - * Returns a list of ": " for each record in the store that has an - * `id`. - */ - getNodes(): RecordSummary[]; - /** - * Returns a list of ": " for all records in the store including - * those that do not have an `id`. - */ - getRecords(): RecordSummary[]; - - /** - * Returns an inspector for the synthesized "root" object, allowing access to - * e.g. the `viewer` object or the results of other fields on the "Query" - * type. - */ - getRoot(): RecordInspector; - } - - // ~~~~~~~~~~~~~~~~~~~~~ - // RelayObservable - // ~~~~~~~~~~~~~~~~~~~~~ - interface Subscription { - unsubscribe(): void; - readonly closed: boolean; - } - interface Observer { - start?(subscription: Subscription): any; - next?(nextThing: T): any; - error?(error: Error): any; - complete?(): any; - unsubscribe?(subscription: Subscription): any; - } - type Source = () => any; - interface Subscribable { - subscribe(observer: Observer): Subscription; - } - type ObservableFromValue = RelayObservable | Promise | T; - class RelayObservable implements Subscribable { - _source: Source; - - constructor(source: Source); - - /** - * When an unhandled error is detected, it is reported to the host environment - * (the ESObservable spec refers to this method as "HostReportErrors()"). - * - * The default implementation in development builds re-throws errors in a - * separate frame, and from production builds does nothing (swallowing - * uncaught errors). - * - * Called during application initialization, this method allows - * application-specific handling of uncaught errors. Allowing, for example, - * integration with error logging or developer tools. - */ - static onUnhandledError(callback: (error: Error) => any): void; - - /** - * Accepts various kinds of data sources, and always returns a RelayObservable - * useful for accepting the result of a user-provided FetchFunction. - */ - static from(obj: ObservableFromValue): RelayObservable; - - /** - * Creates a RelayObservable, given a function which expects a legacy - * Relay Observer as the last argument and which returns a Disposable. - * - * To support migration to Observable, the function may ignore the - * legacy Relay observer and directly return an Observable instead. - */ - static fromLegacy( - callback: ( - legacyObserver: RelayCommonTypes.LegacyObserver - ) => RelayCommonTypes.Disposable | RelayObservable - ): RelayObservable; - - /** - * Returns a new Observable which returns the same values as this one, but - * modified so that the provided Observer is called to perform a side-effects - * for all events emitted by the source. - * - * Any errors that are thrown in the side-effect Observer are unhandled, and - * do not affect the source Observable or its Observer. - * - * This is useful for when debugging your Observables or performing other - * side-effects such as logging or performance monitoring. - */ - do(observer: Observer): RelayObservable; - - /** - * Returns a new Observable which returns the same values as this one, but - * modified so that the finally callback is performed after completion, - * whether normal or due to error or unsubscription. - * - * This is useful for cleanup such as resource finalization. - */ - finally(fn: () => any): RelayObservable; - - /** - * Returns a new Observable which is identical to this one, unless this - * Observable completes before yielding any values, in which case the new - * Observable will yield the values from the alternate Observable. - * - * If this Observable does yield values, the alternate is never subscribed to. - * - * This is useful for scenarios where values may come from multiple sources - * which should be tried in order, i.e. from a cache before a network. - */ - ifEmpty(alternate: RelayObservable): RelayObservable; - - /** - * Observable's primary API: returns an unsubscribable Subscription to the - * source of this Observable. - */ - subscribe(observer: Observer): Subscription; - - /** - * Supports subscription of a legacy Relay Observer, returning a Disposable. - */ - subscribeLegacy(legacyObserver: RelayCommonTypes.LegacyObserver): RelayCommonTypes.Disposable; - - /** - * Returns a new Observerable where each value has been transformed by - * the mapping function. - */ - map(fn: (thing: T) => U): RelayObservable; - - /** - * Returns a new Observable where each value is replaced with a new Observable - * by the mapping function, the results of which returned as a single - * concattenated Observable. - */ - concatMap(fn: (thing: T) => ObservableFromValue): RelayObservable; - - /** - * Returns a new Observable which first mirrors this Observable, then when it - * completes, waits for `pollInterval` milliseconds before re-subscribing to - * this Observable again, looping in this manner until unsubscribed. - * - * The returned Observable never completes. - */ - poll(pollInterval: number): RelayObservable; - - /** - * Returns a Promise which resolves when this Observable yields a first value - * or when it completes with no value. - */ - toPromise(): Promise; - } - - // ~~~~~~~~~~~~~~~~~~~~~ - // commitLocalUpdate - // ~~~~~~~~~~~~~~~~~~~~~ - // exposed through RelayModern, not Runtime directly - type commitLocalUpdate = (environment: Environment, updater: RelayCommonTypes.StoreUpdater) => void; - - // ~~~~~~~~~~~~~~~~~~~~~ - // commitRelayModernMutation - // ~~~~~~~~~~~~~~~~~~~~~ - // exposed through RelayModern, not Runtime directly - interface MutationConfig { - configs?: RelayCommonTypes.RelayMutationConfig[]; - mutation: RelayCommonTypes.GraphQLTaggedNode; - variables: RelayCommonTypes.Variables; - uploadables?: RelayCommonTypes.UploadableMap; - onCompleted?(response: T, errors: RelayCommonTypes.PayloadError[] | null | undefined): void; - onError?(error?: Error): void; - optimisticUpdater?: RelayCommonTypes.SelectorStoreUpdater; - optimisticResponse?: object; - updater?: RelayCommonTypes.SelectorStoreUpdater; - } - function commitRelayModernMutation( - environment: Environment, - config: MutationConfig - ): RelayCommonTypes.Disposable; - - // ~~~~~~~~~~~~~~~~~~~~~ - // applyRelayModernOptimisticMutation - // ~~~~~~~~~~~~~~~~~~~~~ - // exposed through RelayModern, not Runtime directly - interface OptimisticMutationConfig { - configs?: RelayCommonTypes.RelayMutationConfig[]; - mutation: RelayCommonTypes.GraphQLTaggedNode; - variables: RelayCommonTypes.Variables; - optimisticUpdater?: RelayCommonTypes.SelectorStoreUpdater; - optimisticResponse?: object; - } - - // ~~~~~~~~~~~~~~~~~~~~~ - // fetchRelayModernQuery - // ~~~~~~~~~~~~~~~~~~~~~ - // exposed through RelayModern, not Runtime directly - /** - * A helper function to fetch the results of a query. Note that results for - * fragment spreads are masked: fields must be explicitly listed in the query in - * order to be accessible in the result object. - * - * NOTE: This module is primarily intended for integrating with classic APIs. - * Most product code should use a Renderer or Container. - * - * TODO(t16875667): The return type should be `Promise`, but - * that's not really helpful as `SelectorData` is essentially just `mixed`. We - * can probably leverage generated flow types here to return the real expected - * shape. - */ - function fetchRelayModernQuery( - environment: any, // FIXME - $FlowFixMe in facebook source code - taggedNode: RelayCommonTypes.GraphQLTaggedNode, - variables: RelayCommonTypes.Variables, - cacheConfig?: RelayCommonTypes.CacheConfig - ): Promise; // FIXME - $FlowFixMe in facebook source code - - // ~~~~~~~~~~~~~~~~~~~~~ - // requestRelaySubscription - // ~~~~~~~~~~~~~~~~~~~~~ - // exposed through RelayModern, not Runtime directly - interface GraphQLSubscriptionConfig { - configs?: RelayCommonTypes.RelayMutationConfig[]; - subscription: RelayCommonTypes.GraphQLTaggedNode; - variables: RelayCommonTypes.Variables; - onCompleted?(): void; - onError?(error: Error): void; - onNext?(response: object | null | undefined): void; - updater?(store: RelayCommonTypes.RecordSourceSelectorProxy): void; - } - function requestRelaySubscription( - environment: Environment, - config: GraphQLSubscriptionConfig - ): RelayCommonTypes.Disposable; +type GraphQLTaggedNode = + | (() => ConcreteFragment | ConcreteBatch) + | { + modern(): ConcreteFragment | ConcreteBatch; + classic(relayQL: RelayQL): ConcreteFragmentDefinition | ConcreteOperationDefinition; + }; +// ~~~~~~~~~~~~~~~~~~~~~ +// General Usage +// ~~~~~~~~~~~~~~~~~~~~~ +type DataID = string; +interface Variables { + [name: string]: any; +} +type Uploadable = File | Blob; +interface UploadableMap { + [key: string]: Uploadable; } // ~~~~~~~~~~~~~~~~~~~~~ -// Package Exports +// RelayNetworkTypes +// Version: Relay 1.3.0 +// File: https://github.com/facebook/relay/blob/master/packages/relay-runtime/network/RelayNetworkTypes.js // ~~~~~~~~~~~~~~~~~~~~~ -export import Environment = RelayRuntimeTypes.Environment; -export import Network = RelayRuntimeTypes.Network; -export import RecordSource = RelayRuntimeTypes.RecordSource; -export import Store = RelayRuntimeTypes.Store; -export import Observable = RelayRuntimeTypes.RelayObservable; + +interface LegacyObserver { + onCompleted?(): void; + onError?(error: Error): void; + onNext?(data: T): void; +} +interface PayloadError { + message: string; + locations?: Array<{ + line: number; + column: number; + }>; +} +/** + * A function that executes a GraphQL operation with request/response semantics. + * + * May return an Observable or Promise of a raw server response. + */ +declare function FetchFunction( + operation: ConcreteBatch, + variables: Variables, + cacheConfig: CacheConfig, + uploadables?: UploadableMap +): ObservableFromValue; + +/** + * A function that executes a GraphQL subscription operation, returning one or + * more raw server responses over time. + * + * May return an Observable, otherwise must call the callbacks found in the + * fourth parameter. + */ +type SubscribeFunction = ( + operation: ConcreteBatch, + variables: Variables, + cacheConfig: CacheConfig, + observer: LegacyObserver +) => RelayObservable | Disposable; + +// ~~~~~~~~~~~~~~~~~~~~~ +// RelayStoreTypes +// Version: Relay 1.3.0 +// File: https://github.com/facebook/relay/blob/master/packages/relay-runtime/store/RelayStoreTypes.js +// ~~~~~~~~~~~~~~~~~~~~~ +/** + * A function that receives a proxy over the store and may trigger side-effects + * (indirectly) by calling `set*` methods on the store or its record proxies. + */ +type StoreUpdater = (store: RecordSourceProxy) => void; + +/** + * Similar to StoreUpdater, but accepts a proxy tied to a specific selector in + * order to easily access the root fields of a query/mutation as well as a + * second argument of the response object of the mutation. + */ +type SelectorStoreUpdater = ( + store: RecordSourceSelectorProxy, + // Actually RelayCombinedEnvironmentTypes#SelectorData, but mixed is + // inconvenient to access deeply in product code. + data: any // FLOW FIXME +) => void; + +/** + * Extends the RecordSourceProxy interface with methods for accessing the root + * fields of a Selector. + */ +interface RecordSourceSelectorProxy { + create(dataID: DataID, typeName: string): RecordProxy; + delete(dataID: DataID): void; + get(dataID: DataID): RecordProxy | null; + getRoot(): RecordProxy; + getRootField(fieldName: string): RecordProxy | null; + getPluralRootField(fieldName: string): RecordProxy[] | null; +} + +interface RecordProxy { + copyFieldsFrom(source: RecordProxy): void; + getDataID(): DataID; + getLinkedRecord(name: string, args?: Variables): RecordProxy | null; + getLinkedRecords(name: string, args?: Variables): Array | null; + getOrCreateLinkedRecord(name: string, typeName: string, args?: Variables): RecordProxy; + getType(): string; + getValue(name: string, args?: Variables): any; + setLinkedRecord(record: RecordProxy, name: string, args?: Variables): RecordProxy; + setLinkedRecords( + records: Array | undefined | null, + name: string, + args?: Variables + ): RecordProxy; + setValue(value: any, name: string, args?: Variables): RecordProxy; +} + +interface RecordSourceProxy { + create(dataID: DataID, typeName: string): RecordProxy; + delete(dataID: DataID): void; + get(dataID: DataID): Array | null; + getRoot(): RecordProxy; +} + +interface HandleFieldPayload { + // The arguments that were fetched. + args: Variables; + // The __id of the record containing the source/handle field. + dataID: DataID; + // The (storage) key at which the original server data was written. + fieldKey: string; + // The name of the handle + handle: string; + // The (storage) key at which the handle's data should be written by the + // handler + handleKey: string; +} +interface HandlerInterface { + update(store: RecordSourceProxy, fieldPayload: HandleFieldPayload): void; + [functionName: string]: (...args: any[]) => any; +} +export const ConnectionHandler: HandlerInterface; +export const ViewerHandler: HandlerInterface; + +// ~~~~~~~~~~~~~~~~~~~~~ +// RelayCombinedEnvironmentTypes +// Version: Relay 1.3.0 +// File: https://github.com/facebook/relay/blob/b85a1d69bb72be4ace67179f55c2a54a8d761c8b/packages/react-relay/classic/environment/RelayCombinedEnvironmentTypes.js +// ~~~~~~~~~~~~~~~~~~~~~ +/** + * Settings for how a query response may be cached. + * + * - `force`: causes a query to be issued unconditionally, irrespective of the + * state of any configured response cache. + * - `poll`: causes a query to live update by polling at the specified interval + * in milliseconds. (This value will be passed to setTimeout.) + */ +interface CacheConfig { + force?: boolean; + poll?: number; +} + +/** + * Represents any resource that must be explicitly disposed of. The most common + * use-case is as a return value for subscriptions, where calling `dispose()` + * would cancel the subscription. + */ +interface Disposable { + dispose(): void; +} + +/** + * Arbitrary data e.g. received by a container as props. + */ +interface Props { + [key: string]: any; +} + +/** + * A selector defines the starting point for a traversal into the graph for the + * purposes of targeting a subgraph. + */ +interface CSelector { + dataID: DataID; + node: TNode; + variables: Variables; +} + +/** + * A representation of a selector and its results at a particular point in time. + */ +type CSnapshot = CSelector & { + data: SelectorData | null | undefined; + seenRecords: RecordMap; +}; + +/** + * The results of a selector given a store/RecordSource. + */ +interface SelectorData { + [key: string]: any; +} + +/** + * The results of reading the results of a FragmentMap given some input + * `Props`. + */ +interface FragmentSpecResults { + [key: string]: any; +} + +/** + * A utility for resolving and subscribing to the results of a fragment spec + * (key -> fragment mapping) given some "props" that determine the root ID + * and variables to use when reading each fragment. When props are changed via + * `setProps()`, the resolver will update its results and subscriptions + * accordingly. Internally, the resolver: + * - Converts the fragment map & props map into a map of `Selector`s. + * - Removes any resolvers for any props that became null. + * - Creates resolvers for any props that became non-null. + * - Updates resolvers with the latest props. + */ +interface FragmentSpecResolver { + /** + * Stop watching for changes to the results of the fragments. + */ + dispose(): void; + + /** + * Get the current results. + */ + resolve(): FragmentSpecResults; + + /** + * Update the resolver with new inputs. Call `resolve()` to get the updated + * results. + */ + setProps(props: Props): void; + + /** + * Override the variables used to read the results of the fragments. Call + * `resolve()` to get the updated results. + */ + setVariables(variables: Variables): void; +} + +interface CFragmentMap { + [key: string]: TFragment; +} + +/** + * An operation selector describes a specific instance of a GraphQL operation + * with variables applied. + * + * - `root`: a selector intended for processing server results or retaining + * response data in the store. + * - `fragment`: a selector intended for use in reading or subscribing to + * the results of the the operation. + */ +interface COperationSelector { + fragment: CSelector; + node: TOperation; + root: CSelector; + variables: Variables; +} + +/** + * The public API of Relay core. Represents an encapsulated environment with its + * own in-memory cache. + */ +interface CEnvironment { + /** + * Read the results of a selector from in-memory records in the store. + */ + lookup(selector: CSelector): CSnapshot; + + /** + * Subscribe to changes to the results of a selector. The callback is called + * when data has been committed to the store that would cause the results of + * the snapshot's selector to change. + */ + subscribe(snapshot: CSnapshot, callback: (snapshot: CSnapshot) => void): Disposable; + + /** + * Ensure that all the records necessary to fulfill the given selector are + * retained in-memory. The records will not be eligible for garbage collection + * until the returned reference is disposed. + * + * Note: This is a no-op in the classic core. + */ + retain(selector: CSelector): Disposable; + + /** + * Send a query to the server with request/response semantics: the query will + * either complete successfully (calling `onNext` and `onCompleted`) or fail + * (calling `onError`). + * + * Note: Most applications should use `streamQuery` in order to + * optionally receive updated information over time, should that feature be + * supported by the network/server. A good rule of thumb is to use this method + * if you would otherwise immediately dispose the `streamQuery()` + * after receving the first `onNext` result. + */ + sendQuery(config: { + cacheConfig?: CacheConfig; + onCompleted?(): void; + onError?(error: Error): void; + onNext?(payload: TPayload): void; + operation: COperationSelector; + }): Disposable; + + /** + * Send a query to the server with request/subscription semantics: one or more + * responses may be returned (via `onNext`) over time followed by either + * the request completing (`onCompleted`) or an error (`onError`). + * + * Networks/servers that support subscriptions may choose to hold the + * subscription open indefinitely such that `onCompleted` is not called. + */ + streamQuery(config: { + cacheConfig?: CacheConfig; + onCompleted?(): void; + onError?(error: Error): void; + onNext?(payload: TPayload): void; + operation: COperationSelector; + }): Disposable; + + unstable_internal: CUnstableEnvironmentCore; +} + +interface CUnstableEnvironmentCore { + /** + * Create an instance of a FragmentSpecResolver. + * + * TODO: The FragmentSpecResolver *can* be implemented via the other methods + * defined here, so this could be moved out of core. It's convenient to have + * separate implementations until the experimental core is in OSS. + */ + createFragmentSpecResolver( + context: CRelayContext, + containerName: string, + fragments: CFragmentMap, + props: Props, + callback: () => void + ): FragmentSpecResolver; + + /** + * Creates an instance of an OperationSelector given an operation definition + * (see `getOperation`) and the variables to apply. The input variables are + * filtered to exclude variables that do not matche defined arguments on the + * operation, and default values are populated for null values. + */ + createOperationSelector(operation: TOperation, variables: Variables): COperationSelector; + + /** + * Given a graphql`...` tagged template, extract a fragment definition usable + * by this version of Relay core. Throws if the value is not a fragment. + */ + getFragment(node: TGraphQLTaggedNode): TFragment; + + /** + * Given a graphql`...` tagged template, extract an operation definition + * usable by this version of Relay core. Throws if the value is not an + * operation. + */ + getOperation(node: TGraphQLTaggedNode): TOperation; + + /** + * Determine if two selectors are equal (represent the same selection). Note + * that this function returns `false` when the two queries/fragments are + * different objects, even if they select the same fields. + */ + areEqualSelectors(a: CSelector, b: CSelector): boolean; + + /** + * Given the result `item` from a parent that fetched `fragment`, creates a + * selector that can be used to read the results of that fragment for that item. + * + * Example: + * + * Given two fragments as follows: + * + * ``` + * fragment Parent on User { + * id + * ...Child + * } + * fragment Child on User { + * name + * } + * ``` + * + * And given some object `parent` that is the results of `Parent` for id "4", + * the results of `Child` can be accessed by first getting a selector and then + * using that selector to `lookup()` the results against the environment: + * + * ``` + * const childSelector = getSelector(queryVariables, Child, parent); + * const childData = environment.lookup(childSelector).data; + * ``` + */ + getSelector(operationVariables: Variables, fragment: TFragment, prop: any): CSelector | null; + + /** + * Given the result `items` from a parent that fetched `fragment`, creates a + * selector that can be used to read the results of that fragment on those + * items. This is similar to `getSelector` but for "plural" fragments that + * expect an array of results and therefore return an array of selectors. + */ + getSelectorList(operationVariables: Variables, fragment: TFragment, props: any[]): Array> | null; + + /** + * Given a mapping of keys -> results and a mapping of keys -> fragments, + * extracts the selectors for those fragments from the results. + * + * The canonical use-case for this function are Relay Containers, which + * use this function to convert (props, fragments) into selectors so that they + * can read the results to pass to the inner component. + */ + getSelectorsFromObject( + operationVariables: Variables, + fragments: CFragmentMap, + props: Props + ): { [key: string]: CSelector | Array> | null | undefined }; + + /** + * Given a mapping of keys -> results and a mapping of keys -> fragments, + * extracts a mapping of keys -> id(s) of the results. + * + * Similar to `getSelectorsFromObject()`, this function can be useful in + * determining the "identity" of the props passed to a component. + */ + getDataIDsFromObject( + fragments: CFragmentMap, + props: Props + ): { [key: string]: DataID | DataID[] | null | undefined }; + + /** + * Given a mapping of keys -> results and a mapping of keys -> fragments, + * extracts the merged variables that would be in scope for those + * fragments/results. + * + * This can be useful in determing what varaibles were used to fetch the data + * for a Relay container, for example. + */ + getVariablesFromObject(operationVariables: Variables, fragments: CFragmentMap, props: Props): Variables; +} + +/** + * The type of the `relay` property set on React context by the React/Relay + * integration layer (e.g. QueryRenderer, FragmentContainer, etc). + */ +interface CRelayContext { + environment: TEnvironment; + variables: Variables; +} + +// ~~~~~~~~~~~~~~~~~~~~~ +// RelayTypes +/** + * Version: Relay 1.3.0 + * File: + * https://github.com/facebook/relay/blob/fa9f48ea209ee2402d433b59a84d1cbc046574e2/packages/react-relay/classic/tools/RelayTypes.js + */ +// ~~~~~~~~~~~~~~~~~~~~~ +interface RerunParam { + param: string; + import: string; + max_runs: number; +} +interface FIELDS_CHANGE { + type: "FIELDS_CHANGE"; + fieldIDs: { [fieldName: string]: DataID | DataID[] }; +} +interface RANGE_ADD { + type: "RANGE_ADD"; + parentName?: string; + parentID?: string; + connectionInfo?: Array<{ + key: string; + filters?: Variables; + rangeBehavior: string; + }>; + connectionName?: string; + edgeName: string; + rangeBehaviors?: RangeBehaviors; +} +interface NODE_DELETE { + type: "NODE_DELETE"; + parentName?: string; + parentID?: string; + connectionName?: string; + deletedIDFieldName: string; +} +interface RANGE_DELETE { + type: "RANGE_DELETE"; + parentName?: string; + parentID?: string; + connectionKeys?: Array<{ + key: string; + filters?: Variables; + }>; + connectionName?: string; + deletedIDFieldName: string | string[]; + pathToConnection: string[]; +} +interface REQUIRED_CHILDREN { + type: "REQUIRED_CHILDREN"; + children: RelayConcreteNode[]; +} +type RelayMutationConfig = FIELDS_CHANGE | RANGE_ADD | NODE_DELETE | RANGE_DELETE | REQUIRED_CHILDREN; + +interface RelayMutationTransactionCommitCallbacks { + onFailure?: RelayMutationTransactionCommitFailureCallback; + onSuccess?: RelayMutationTransactionCommitSuccessCallback; +} +type RelayMutationTransactionCommitFailureCallback = ( + transaction: RelayMutationTransaction, + preventAutoRollback: () => void +) => void; +type RelayMutationTransactionCommitSuccessCallback = ( + response: { + [key: string]: any; + } +) => void; +interface NetworkLayer { + sendMutation(request: RelayMutationRequest): Promise | null; + sendQueries(requests: RelayQueryRequest[]): Promise | null; + supports(...options: string[]): boolean; +} +interface QueryResult { + error?: Error; + ref_params?: { [name: string]: any }; + response: QueryPayload; +} +interface ReadyState { + aborted: boolean; + done: boolean; + error: Error | null; + events: ReadyStateEvent[]; + ready: boolean; + stale: boolean; +} +type RelayContainerErrorEventType = "CACHE_RESTORE_FAILED" | "NETWORK_QUERY_ERROR"; +type RelayContainerLoadingEventType = + | "ABORT" + | "CACHE_RESTORED_REQUIRED" + | "CACHE_RESTORE_START" + | "NETWORK_QUERY_RECEIVED_ALL" + | "NETWORK_QUERY_RECEIVED_REQUIRED" + | "NETWORK_QUERY_START" + | "STORE_FOUND_ALL" + | "STORE_FOUND_REQUIRED"; +type ReadyStateChangeCallback = (readyState: ReadyState) => void; +interface ReadyStateEvent { + type: RelayContainerLoadingEventType | RelayContainerErrorEventType; + error?: Error; +} +interface Abortable { + abort(): void; +} + +// ~~~~~~~~~~~~~~~~~~~~~ +// RelayInternalTypes +/** + * Version: Relay 1.3.0 + * File: + * https://github.com/facebook/relay/blob/master/packages/react-relay/classic/tools/RelayInternalTypes.js + */ +// ~~~~~~~~~~~~~~~~~~~~~ +interface QueryPayload { + [key: string]: any; +} +interface RelayQuerySet { + [queryName: string]: any; +} +type RangeBehaviorsFunction = ( + connectionArgs: { + [argName: string]: any; + } +) => "APPEND" | "IGNORE" | "PREPEND" | "REFETCH" | "REMOVE"; +interface RangeBehaviorsObject { + [key: string]: "APPEND" | "IGNORE" | "PREPEND" | "REFETCH" | "REMOVE"; +} +type RangeBehaviors = RangeBehaviorsFunction | RangeBehaviorsObject; + +// ~~~~~~~~~~~~~~~~~~~~~ +// Maybe Fix +// ~~~~~~~~~~~~~~~~~~~~~ +type RelayDebugger = any; +type OptimisticUpdate = any; +type OperationSelector = COperationSelector; +type Selector = CSelector; +type PayloadData = any; +type Snapshot = CSnapshot; +type RelayResponsePayload = any; +type MutableRecordSource = RecordSource; + +/** + * A function that returns an Observable representing the response of executing + * a GraphQL operation. + */ +type ExecuteFunction = ( + operation: object, + variables: Variables, + cacheConfig: CacheConfig, + uploadables?: UploadableMap +) => Promise; +interface RelayNetwork { + execute: ExecuteFunction; +} + +// ~~~~~~~~~~~~~~~~~~~~~ +// RelayDefaultHandlerProvider +// ~~~~~~~~~~~~~~~~~~~~~ +declare function HandlerProvider(name: string): HandlerInterface | null; + +// ~~~~~~~~~~~~~~~~~~~~~ +// RelayModernEnvironment +// ~~~~~~~~~~~~~~~~~~~~~ +interface EnvironmentConfig { + configName?: string; + handlerProvider?: typeof HandlerProvider; + network: Network; + store: Store; +} +export class Environment { + constructor(config: EnvironmentConfig); + getStore(): Store; + getDebugger(): RelayDebugger; + applyUpdate(optimisticUpdate: OptimisticUpdate): Disposable; + revertUpdate(update: OptimisticUpdate): void; + replaceUpdate(update: OptimisticUpdate, newUpdate: OptimisticUpdate): void; + applyMutation(config: { + operation: OperationSelector; + optimisticUpdater?: SelectorStoreUpdater; + optimisticResponse?: object; + }): Disposable; + check(readSelector: Selector): boolean; + commitPayload(operationSelector: OperationSelector, payload: PayloadData): void; + commitUpdate(updater: StoreUpdater): void; + lookup(readSelector: Selector): Snapshot; + subscribe(snapshot: Snapshot, callback: (snapshot: Snapshot) => void): Disposable; + retain(selector: Selector): Disposable; + execute(config: { + operation: OperationSelector; + cacheConfig?: CacheConfig; + updater?: SelectorStoreUpdater; + }): RelayObservable; + executeMutation(config: { + operation: OperationSelector; + optimisticUpdater?: SelectorStoreUpdater; + optimisticResponse?: object; + updater?: SelectorStoreUpdater; + uploadables?: UploadableMap; + }): RelayObservable; +} + +// ~~~~~~~~~~~~~~~~~~~~~ +// RelayInMemoryRecordSource +// ~~~~~~~~~~~~~~~~~~~~~ +interface RelayInMemoryRecordSource { + [key: string]: any; +} +interface RecordMap { + [dataID: string]: RelayInMemoryRecordSource | null | undefined; +} + +// ~~~~~~~~~~~~~~~~~~~~~ +// Network +// ~~~~~~~~~~~~~~~~~~~~~ +export class Network { + /** + * Creates an implementation of the `Network` interface defined in + * `RelayNetworkTypes` given `fetch` and `subscribe` functions. + */ + static create(fetchFn: typeof FetchFunction, subscribeFn?: SubscribeFunction): RelayNetwork; +} + +// ~~~~~~~~~~~~~~~~~~~~~ +// Network +// ~~~~~~~~~~~~~~~~~~~~~ +declare class RecordSource { + constructor(records?: RecordMap); + clear(): void; + delete(dataID: DataID): void; + get(dataID: DataID): RelayInMemoryRecordSource | null; + getRecordIDs(): DataID[]; + getStatus(dataID: DataID): "EXISTENT" | "NONEXISTENT" | "UNKNOWN"; + has(dataID: DataID): boolean; + load(dataID: DataID, callback: (error: Error | null, record: RelayInMemoryRecordSource | null) => void): void; + remove(dataID: DataID): void; + set(dataID: DataID, record: RelayInMemoryRecordSource): void; + size(): number; + toJSON(): RecordMap; +} + +// ~~~~~~~~~~~~~~~~~~~~~ +// ModernStore +// ~~~~~~~~~~~~~~~~~~~~~ +export class Store { + constructor(source: RecordSource); + getSource(): MutableRecordSource; + check(selector: Selector): boolean; + retain(selector: Selector): Disposable; + lookup(selector: Selector): Snapshot; + notify(): void; + publish(source: RecordSource): void; + subscribe(snapshot: Snapshot, callback: (snapshot: Snapshot) => void): Disposable; +} + +// ~~~~~~~~~~~~~~~~~~~~~ +// RelayRecordSourceInspector +// ~~~~~~~~~~~~~~~~~~~~~ +/** + * An internal class to provide a console-friendly string representation of a + * RelayInMemoryRecordSource. + */ +declare class RecordSummary { + id: DataID; + type: string | null | undefined; + static createFromRecord(id: DataID, record: any): RecordSummary; + constructor(id: DataID, type: string | null | undefined); + toString(): string; +} +/** + * Internal class for inspecting a single RelayInMemoryRecordSource. + */ +declare class RecordInspector { + constructor(sourceInspector: RelayRecordSourceInspector, record: RelayInMemoryRecordSource); + /** + * Get the cache id of the given record. For types that implement the `Node` + * interface (or that have an `id`) this will be `id`, for other types it will be + * a synthesized identifier based on the field path from the nearest ancestor + * record that does have an `id`. + */ + getDataID(): DataID; + + /** + * Returns a list of the fields that have been fetched on the current record. + */ + getFields(): string[]; + + /** + * Returns the type of the record. + */ + getType(): string; + + /** + * Returns a copy of the internal representation of the record. + */ + inspect(): any; + + /** + * Returns the value of a scalar field. May throw if the given field is + * present but not actually scalar. + */ + getValue(name: string, args?: Variables): any; + + /** + * Returns an inspector for the given scalar "linked" field (a field whose + * value is another RelayInMemoryRecordSource instead of a scalar). May throw if the field is + * present but not a scalar linked record. + */ + getLinkedRecord(name: string, args?: Variables): RecordInspector | null; + + /** + * Returns an array of inspectors for the given plural "linked" field (a field + * whose value is an array of Records instead of a scalar). May throw if the + * field is present but not a plural linked record. + */ + getLinkedRecords(name: string, args?: Variables): RecordInspector[] | null; +} + +declare class RelayRecordSourceInspector { + constructor(source: RecordSource); + static getForEnvironment(environment: Environment): RelayRecordSourceInspector; + /** + * Returns an inspector for the record with the given id, or null/undefined if + * that record is deleted/unfetched. + */ + get(dataID: DataID): RecordInspector | null; + /** + * Returns a list of ": " for each record in the store that has an + * `id`. + */ + getNodes(): RecordSummary[]; + /** + * Returns a list of ": " for all records in the store including + * those that do not have an `id`. + */ + getRecords(): RecordSummary[]; + + /** + * Returns an inspector for the synthesized "root" object, allowing access to + * e.g. the `viewer` object or the results of other fields on the "Query" + * type. + */ + getRoot(): RecordInspector; +} + // note RecordSourceInspector is only available in dev environment -export import RecordSourceInspector = RelayRuntimeTypes.RelayRecordSourceInspector; -export import ConnectionHandler = RelayCommonTypes.Handler; -export import ViewerHandler = RelayCommonTypes.Handler; +export type RecordSourceInspector = RelayRecordSourceInspector; + +// ~~~~~~~~~~~~~~~~~~~~~ +// RelayObservable +// ~~~~~~~~~~~~~~~~~~~~~ +interface Subscription { + unsubscribe(): void; + readonly closed: boolean; +} +interface Observer { + start?(subscription: Subscription): any; + next?(nextThing: T): any; + error?(error: Error): any; + complete?(): any; + unsubscribe?(subscription: Subscription): any; +} +type Source = () => any; +interface Subscribable { + subscribe(observer: Observer): Subscription; +} +type ObservableFromValue = RelayObservable | Promise | T; +declare class RelayObservable implements Subscribable { + _source: Source; + + constructor(source: Source); + + /** + * When an unhandled error is detected, it is reported to the host environment + * (the ESObservable spec refers to this method as "HostReportErrors()"). + * + * The default implementation in development builds re-throws errors in a + * separate frame, and from production builds does nothing (swallowing + * uncaught errors). + * + * Called during application initialization, this method allows + * application-specific handling of uncaught errors. Allowing, for example, + * integration with error logging or developer tools. + */ + static onUnhandledError(callback: (error: Error) => any): void; + + /** + * Accepts various kinds of data sources, and always returns a RelayObservable + * useful for accepting the result of a user-provided FetchFunction. + */ + static from(obj: ObservableFromValue): RelayObservable; + + /** + * Creates a RelayObservable, given a function which expects a legacy + * Relay Observer as the last argument and which returns a Disposable. + * + * To support migration to Observable, the function may ignore the + * legacy Relay observer and directly return an Observable instead. + */ + static fromLegacy( + callback: (legacyObserver: LegacyObserver) => Disposable | RelayObservable + ): RelayObservable; + + /** + * Returns a new Observable which returns the same values as this one, but + * modified so that the provided Observer is called to perform a side-effects + * for all events emitted by the source. + * + * Any errors that are thrown in the side-effect Observer are unhandled, and + * do not affect the source Observable or its Observer. + * + * This is useful for when debugging your Observables or performing other + * side-effects such as logging or performance monitoring. + */ + do(observer: Observer): RelayObservable; + + /** + * Returns a new Observable which returns the same values as this one, but + * modified so that the finally callback is performed after completion, + * whether normal or due to error or unsubscription. + * + * This is useful for cleanup such as resource finalization. + */ + finally(fn: () => any): RelayObservable; + + /** + * Returns a new Observable which is identical to this one, unless this + * Observable completes before yielding any values, in which case the new + * Observable will yield the values from the alternate Observable. + * + * If this Observable does yield values, the alternate is never subscribed to. + * + * This is useful for scenarios where values may come from multiple sources + * which should be tried in order, i.e. from a cache before a network. + */ + ifEmpty(alternate: RelayObservable): RelayObservable; + + /** + * Observable's primary API: returns an unsubscribable Subscription to the + * source of this Observable. + */ + subscribe(observer: Observer): Subscription; + + /** + * Supports subscription of a legacy Relay Observer, returning a Disposable. + */ + subscribeLegacy(legacyObserver: LegacyObserver): Disposable; + + /** + * Returns a new Observerable where each value has been transformed by + * the mapping function. + */ + map(fn: (thing: T) => U): RelayObservable; + + /** + * Returns a new Observable where each value is replaced with a new Observable + * by the mapping function, the results of which returned as a single + * concattenated Observable. + */ + concatMap(fn: (thing: T) => ObservableFromValue): RelayObservable; + + /** + * Returns a new Observable which first mirrors this Observable, then when it + * completes, waits for `pollInterval` milliseconds before re-subscribing to + * this Observable again, looping in this manner until unsubscribed. + * + * The returned Observable never completes. + */ + poll(pollInterval: number): RelayObservable; + + /** + * Returns a Promise which resolves when this Observable yields a first value + * or when it completes with no value. + */ + toPromise(): Promise; +} + +export type Observable = RelayObservable; + +// ~~~~~~~~~~~~~~~~~~~~~ +// commitLocalUpdate +// ~~~~~~~~~~~~~~~~~~~~~ +// exposed through RelayModern, not Runtime directly +type commitLocalUpdate = (environment: Environment, updater: StoreUpdater) => void; + +// ~~~~~~~~~~~~~~~~~~~~~ +// commitRelayModernMutation +// ~~~~~~~~~~~~~~~~~~~~~ +// exposed through RelayModern, not Runtime directly +interface MutationConfig { + configs?: RelayMutationConfig[]; + mutation: GraphQLTaggedNode; + variables: Variables; + uploadables?: UploadableMap; + onCompleted?(response: T, errors: PayloadError[] | null | undefined): void; + onError?(error?: Error): void; + optimisticUpdater?: SelectorStoreUpdater; + optimisticResponse?: object; + updater?: SelectorStoreUpdater; +} +declare function commitRelayModernMutation(environment: Environment, config: MutationConfig): Disposable; + +// ~~~~~~~~~~~~~~~~~~~~~ +// applyRelayModernOptimisticMutation +// ~~~~~~~~~~~~~~~~~~~~~ +// exposed through RelayModern, not Runtime directly +interface OptimisticMutationConfig { + configs?: RelayMutationConfig[]; + mutation: GraphQLTaggedNode; + variables: Variables; + optimisticUpdater?: SelectorStoreUpdater; + optimisticResponse?: object; +} + +// ~~~~~~~~~~~~~~~~~~~~~ +// fetchRelayModernQuery +// ~~~~~~~~~~~~~~~~~~~~~ +// exposed through RelayModern, not Runtime directly +/** + * A helper function to fetch the results of a query. Note that results for + * fragment spreads are masked: fields must be explicitly listed in the query in + * order to be accessible in the result object. + * + * NOTE: This module is primarily intended for integrating with classic APIs. + * Most product code should use a Renderer or Container. + * + * TODO(t16875667): The return type should be `Promise`, but + * that's not really helpful as `SelectorData` is essentially just `mixed`. We + * can probably leverage generated flow types here to return the real expected + * shape. + */ +declare function fetchRelayModernQuery( + environment: any, // FIXME - $FlowFixMe in facebook source code + taggedNode: GraphQLTaggedNode, + variables: Variables, + cacheConfig?: CacheConfig +): Promise; // FIXME - $FlowFixMe in facebook source code + +// ~~~~~~~~~~~~~~~~~~~~~ +// requestRelaySubscription +// ~~~~~~~~~~~~~~~~~~~~~ +// exposed through RelayModern, not Runtime directly +interface GraphQLSubscriptionConfig { + configs?: RelayMutationConfig[]; + subscription: GraphQLTaggedNode; + variables: Variables; + onCompleted?(): void; + onError?(error: Error): void; + onNext?(response: object | null | undefined): void; + updater?(store: RecordSourceSelectorProxy): void; +} +declare function requestRelaySubscription(environment: Environment, config: GraphQLSubscriptionConfig): Disposable; From 7b8aacb5d6852526ed1d859950918340126c2f4c Mon Sep 17 00:00:00 2001 From: voxmatt Date: Tue, 17 Oct 2017 18:11:40 -0700 Subject: [PATCH 045/828] removing deprecated types --- types/react-relay/v1/classic.d.ts | 42 ------------------------------- types/react-relay/v1/compat.d.ts | 24 ------------------ 2 files changed, 66 deletions(-) delete mode 100644 types/react-relay/v1/classic.d.ts delete mode 100644 types/react-relay/v1/compat.d.ts diff --git a/types/react-relay/v1/classic.d.ts b/types/react-relay/v1/classic.d.ts deleted file mode 100644 index d6c3352457..0000000000 --- a/types/react-relay/v1/classic.d.ts +++ /dev/null @@ -1,42 +0,0 @@ -// Type definitions for react-relay/classic 1.3 -// Project: https://github.com/facebook/relay -// Definitions by: Johannes Schickling , Matt Martin -// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -// TypeScript Version: 2.4 - -// ~~~~~~~~~~~~~~~~~~~~~ -// React-Relay Classic -// ~~~~~~~~~~~~~~~~~~~~~ -// kind of gross, but maintains compatability with previous version of types -export { - ClientMutationID, - Fragments, - CreateContainerOpts, - RelayVariables, - RelayContainerClass, - RelayQueryRequestResolve, - RelayMutationStatus, - RelayMutationTransaction, - RelayMutationRequest, - RelayQueryRequest, - RelayNetworkLayer, - DefaultNetworkLayer, - createContainer, - injectNetworkLayer, - isContainer, - QL, - Route, - Mutation, - Transaction, - StoreUpdateCallbacks, - Store, - RootContainer, - RootContainerProps, - Renderer, - RendererProps, - RenderStateConfig, - RenderCallback, - ReadyStateEvent, - OnReadyStateChange, - RelayProp, -} from './lib/react-relay-classic'; diff --git a/types/react-relay/v1/compat.d.ts b/types/react-relay/v1/compat.d.ts deleted file mode 100644 index ef11bfc509..0000000000 --- a/types/react-relay/v1/compat.d.ts +++ /dev/null @@ -1,24 +0,0 @@ -// Type definitions for react-relay/compat 1.3 -// Project: https://github.com/facebook/relay -// Definitions by: Johannes Schickling , Matt Martin -// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -// TypeScript Version: 2.4 - -import { RelayRuntimeTypes } from 'relay-runtime'; -import * as ReactRelayModernTypes from './lib/react-relay-modern'; -import * as ReactRelayCompatTypes from './lib/react-relay-compat'; - -// ~~~~~~~~~~~~~~~~~~~~~ -// React-Relay Compat -// ~~~~~~~~~~~~~~~~~~~~~ -export import applyOptimisticMutation = ReactRelayCompatTypes.applyUpdate; -export import commitMutation = ReactRelayCompatTypes.commitUpdate; -export import createFragmentContainer = ReactRelayCompatTypes.createContainer; -export import createPaginationContainer = ReactRelayCompatTypes.createContainer; -export import createRefetchContainer = ReactRelayCompatTypes.createContainer; -export import injectDefaultVariablesProvider = ReactRelayCompatTypes.injectDefaultVariablesProvider; -export import QueryRenderer = ReactRelayModernTypes.ReactRelayQueryRenderer; -export import graphql = ReactRelayModernTypes.graphql; -export import fetchQuery = RelayRuntimeTypes.fetchRelayModernQuery; -// exported for convenience -export import CompatTypes = ReactRelayCompatTypes; From d12367fe0a66c7a443d52a9a9b26509c64e6485d Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Eloy=20Dur=C3=A1n?= Date: Wed, 18 Oct 2017 12:30:27 +0200 Subject: [PATCH 046/828] [Relay] Fix linter issues. --- types/react-relay/compat.d.ts | 12 +- types/react-relay/index.d.ts | 16 +- types/relay-runtime/index.d.ts | 832 +++++++++++++++--------------- types/relay-runtime/tsconfig.json | 1 + 4 files changed, 431 insertions(+), 430 deletions(-) diff --git a/types/react-relay/compat.d.ts b/types/react-relay/compat.d.ts index bbc69a3cc4..d214e451ae 100644 --- a/types/react-relay/compat.d.ts +++ b/types/react-relay/compat.d.ts @@ -6,18 +6,18 @@ export { createRefetchContainer, fetchQuery, graphql, -} from "react-relay"; +} from "./index"; import * as RelayRuntimeTypes from "relay-runtime"; -import { RelayEnvironmentInterface } from "react-relay/classic"; +import { RelayEnvironmentInterface } from "./classic"; // ~~~~~~~~~~~~~~~~~~~~~ // Maybe Fix // ~~~~~~~~~~~~~~~~~~~~~ -type ConcreteFragment = any; -type ConcreteBatch = any; -type ConcreteFragmentDefinition = object; -type ConcreteOperationDefinition = object; +export type ConcreteFragment = any; +export type ConcreteBatch = any; +export type ConcreteFragmentDefinition = object; +export type ConcreteOperationDefinition = object; // ~~~~~~~~~~~~~~~~~~~~~ // Util diff --git a/types/react-relay/index.d.ts b/types/react-relay/index.d.ts index fa23ac4dd7..04c173e9e2 100644 --- a/types/react-relay/index.d.ts +++ b/types/react-relay/index.d.ts @@ -19,11 +19,11 @@ import * as RelayRuntimeTypes from "relay-runtime"; // ~~~~~~~~~~~~~~~~~~~~~ // Maybe Fix // ~~~~~~~~~~~~~~~~~~~~~ -type ConcreteFragment = any; -type ConcreteBatch = any; -type ConcreteFragmentDefinition = object; -type ConcreteOperationDefinition = object; -type ReactBaseComponent = React.ComponentClass | React.StatelessComponent; +export type ConcreteFragment = any; +export type ConcreteBatch = any; +export type ConcreteFragmentDefinition = object; +export type ConcreteOperationDefinition = object; +export type ReactBaseComponent = React.ComponentClass | React.StatelessComponent; // ~~~~~~~~~~~~~~~~~~~~~ // RelayProp @@ -51,9 +51,9 @@ export type GraphQLTaggedNode = classic(relayQL: typeof RelayQL): ConcreteFragmentDefinition | ConcreteOperationDefinition; }; /** - * Runtime function to correspond to the `graphql` tagged template function. - * All calls to this function should be transformed by the plugin. - */ + * Runtime function to correspond to the `graphql` tagged template function. + * All calls to this function should be transformed by the plugin. + */ export interface GraphqlInterface { (strings: string[] | TemplateStringsArray): GraphQLTaggedNode; experimental(strings: string[] | TemplateStringsArray): GraphQLTaggedNode; diff --git a/types/relay-runtime/index.d.ts b/types/relay-runtime/index.d.ts index bbc3e07a7a..c4c35a017e 100644 --- a/types/relay-runtime/index.d.ts +++ b/types/relay-runtime/index.d.ts @@ -6,44 +6,44 @@ // TypeScript Version: 2.4 /** - * SOURCE: - * Relay 1.3.0 - * https://github.com/facebook/relay/blob/b85a1d69bb72be4ace67179f55c2a54a8d761c8b/packages/react-relay/classic/environment/RelayCombinedEnvironmentTypes.js - */ + * SOURCE: + * Relay 1.3.0 + * https://github.com/facebook/relay/blob/b85a1d69bb72be4ace67179f55c2a54a8d761c8b/packages/react-relay/classic/environment/RelayCombinedEnvironmentTypes.js + */ // ~~~~~~~~~~~~~~~~~~~~~ // Maybe Fix // ~~~~~~~~~~~~~~~~~~~~~ -type RelayConcreteNode = any; -type RelayMutationTransaction = any; -type RelayMutationRequest = any; -type RelayQueryRequest = any; -type ConcreteFragment = any; -type ConcreteBatch = any; -type ConcreteFragmentDefinition = object; -type ConcreteOperationDefinition = object; +export type RelayConcreteNode = any; +export type RelayMutationTransaction = any; +export type RelayMutationRequest = any; +export type RelayQueryRequest = any; +export type ConcreteFragment = any; +export type ConcreteBatch = any; +export type ConcreteFragmentDefinition = object; +export type ConcreteOperationDefinition = object; /** - * FIXME: RelayContainer used to be typed with ReactClass, but - * ReactClass is broken and allows for access to any property. For example - * ReactClass.getFragment('foo') is valid even though ReactClass has no - * such getFragment() type definition. When ReactClass is fixed this causes a - * lot of errors in Relay code since methods like getFragment() are used often - * but have no definition in Relay's types. Suppressing for now. - */ -type RelayContainer = any; + * FIXME: RelayContainer used to be typed with ReactClass, but + * ReactClass is broken and allows for access to any property. For example + * ReactClass.getFragment('foo') is valid even though ReactClass has no + * such getFragment() type definition. When ReactClass is fixed this causes a + * lot of errors in Relay code since methods like getFragment() are used often + * but have no definition in Relay's types. Suppressing for now. + */ +export type RelayContainer = any; // ~~~~~~~~~~~~~~~~~~~~~ // RelayQL // ~~~~~~~~~~~~~~~~~~~~~ -type RelayQL = (strings: string[], ...substitutions: any[]) => RelayConcreteNode; +export type RelayQL = (strings: string[], ...substitutions: any[]) => RelayConcreteNode; // ~~~~~~~~~~~~~~~~~~~~~ // RelayModernGraphQLTag // ~~~~~~~~~~~~~~~~~~~~~ -interface GeneratedNodeMap { +export interface GeneratedNodeMap { [key: string]: GraphQLTaggedNode; } -type GraphQLTaggedNode = +export type GraphQLTaggedNode = | (() => ConcreteFragment | ConcreteBatch) | { modern(): ConcreteFragment | ConcreteBatch; @@ -52,12 +52,12 @@ type GraphQLTaggedNode = // ~~~~~~~~~~~~~~~~~~~~~ // General Usage // ~~~~~~~~~~~~~~~~~~~~~ -type DataID = string; -interface Variables { +export type DataID = string; +export interface Variables { [name: string]: any; } -type Uploadable = File | Blob; -interface UploadableMap { +export type Uploadable = File | Blob; +export interface UploadableMap { [key: string]: Uploadable; } @@ -67,12 +67,12 @@ interface UploadableMap { // File: https://github.com/facebook/relay/blob/master/packages/relay-runtime/network/RelayNetworkTypes.js // ~~~~~~~~~~~~~~~~~~~~~ -interface LegacyObserver { +export interface LegacyObserver { onCompleted?(): void; onError?(error: Error): void; onNext?(data: T): void; } -interface PayloadError { +export interface PayloadError { message: string; locations?: Array<{ line: number; @@ -80,11 +80,11 @@ interface PayloadError { }>; } /** - * A function that executes a GraphQL operation with request/response semantics. - * - * May return an Observable or Promise of a raw server response. - */ -declare function FetchFunction( + * A function that executes a GraphQL operation with request/response semantics. + * + * May return an Observable or Promise of a raw server response. + */ +export function FetchFunction( operation: ConcreteBatch, variables: Variables, cacheConfig: CacheConfig, @@ -92,13 +92,13 @@ declare function FetchFunction( ): ObservableFromValue; /** - * A function that executes a GraphQL subscription operation, returning one or - * more raw server responses over time. - * - * May return an Observable, otherwise must call the callbacks found in the - * fourth parameter. - */ -type SubscribeFunction = ( + * A function that executes a GraphQL subscription operation, returning one or + * more raw server responses over time. + * + * May return an Observable, otherwise must call the callbacks found in the + * fourth parameter. + */ +export type SubscribeFunction = ( operation: ConcreteBatch, variables: Variables, cacheConfig: CacheConfig, @@ -111,17 +111,17 @@ type SubscribeFunction = ( // File: https://github.com/facebook/relay/blob/master/packages/relay-runtime/store/RelayStoreTypes.js // ~~~~~~~~~~~~~~~~~~~~~ /** - * A function that receives a proxy over the store and may trigger side-effects - * (indirectly) by calling `set*` methods on the store or its record proxies. - */ -type StoreUpdater = (store: RecordSourceProxy) => void; + * A function that receives a proxy over the store and may trigger side-effects + * (indirectly) by calling `set*` methods on the store or its record proxies. + */ +export type StoreUpdater = (store: RecordSourceProxy) => void; /** - * Similar to StoreUpdater, but accepts a proxy tied to a specific selector in - * order to easily access the root fields of a query/mutation as well as a - * second argument of the response object of the mutation. - */ -type SelectorStoreUpdater = ( + * Similar to StoreUpdater, but accepts a proxy tied to a specific selector in + * order to easily access the root fields of a query/mutation as well as a + * second argument of the response object of the mutation. + */ +export type SelectorStoreUpdater = ( store: RecordSourceSelectorProxy, // Actually RelayCombinedEnvironmentTypes#SelectorData, but mixed is // inconvenient to access deeply in product code. @@ -129,10 +129,10 @@ type SelectorStoreUpdater = ( ) => void; /** - * Extends the RecordSourceProxy interface with methods for accessing the root - * fields of a Selector. - */ -interface RecordSourceSelectorProxy { + * Extends the RecordSourceProxy interface with methods for accessing the root + * fields of a Selector. + */ +export interface RecordSourceSelectorProxy { create(dataID: DataID, typeName: string): RecordProxy; delete(dataID: DataID): void; get(dataID: DataID): RecordProxy | null; @@ -141,7 +141,7 @@ interface RecordSourceSelectorProxy { getPluralRootField(fieldName: string): RecordProxy[] | null; } -interface RecordProxy { +export interface RecordProxy { copyFieldsFrom(source: RecordProxy): void; getDataID(): DataID; getLinkedRecord(name: string, args?: Variables): RecordProxy | null; @@ -158,14 +158,14 @@ interface RecordProxy { setValue(value: any, name: string, args?: Variables): RecordProxy; } -interface RecordSourceProxy { +export interface RecordSourceProxy { create(dataID: DataID, typeName: string): RecordProxy; delete(dataID: DataID): void; get(dataID: DataID): Array | null; getRoot(): RecordProxy; } -interface HandleFieldPayload { +export interface HandleFieldPayload { // The arguments that were fetched. args: Variables; // The __id of the record containing the source/handle field. @@ -178,7 +178,7 @@ interface HandleFieldPayload { // handler handleKey: string; } -interface HandlerInterface { +export interface HandlerInterface { update(store: RecordSourceProxy, fieldPayload: HandleFieldPayload): void; [functionName: string]: (...args: any[]) => any; } @@ -191,116 +191,116 @@ export const ViewerHandler: HandlerInterface; // File: https://github.com/facebook/relay/blob/b85a1d69bb72be4ace67179f55c2a54a8d761c8b/packages/react-relay/classic/environment/RelayCombinedEnvironmentTypes.js // ~~~~~~~~~~~~~~~~~~~~~ /** - * Settings for how a query response may be cached. - * - * - `force`: causes a query to be issued unconditionally, irrespective of the - * state of any configured response cache. - * - `poll`: causes a query to live update by polling at the specified interval - * in milliseconds. (This value will be passed to setTimeout.) - */ -interface CacheConfig { + * Settings for how a query response may be cached. + * + * - `force`: causes a query to be issued unconditionally, irrespective of the + * state of any configured response cache. + * - `poll`: causes a query to live update by polling at the specified interval + * in milliseconds. (This value will be passed to setTimeout.) + */ +export interface CacheConfig { force?: boolean; poll?: number; } /** - * Represents any resource that must be explicitly disposed of. The most common - * use-case is as a return value for subscriptions, where calling `dispose()` - * would cancel the subscription. - */ -interface Disposable { + * Represents any resource that must be explicitly disposed of. The most common + * use-case is as a return value for subscriptions, where calling `dispose()` + * would cancel the subscription. + */ +export interface Disposable { dispose(): void; } /** - * Arbitrary data e.g. received by a container as props. - */ -interface Props { + * Arbitrary data e.g. received by a container as props. + */ +export interface Props { [key: string]: any; } /** - * A selector defines the starting point for a traversal into the graph for the - * purposes of targeting a subgraph. - */ -interface CSelector { + * A selector defines the starting point for a traversal into the graph for the + * purposes of targeting a subgraph. + */ +export interface CSelector { dataID: DataID; node: TNode; variables: Variables; } /** - * A representation of a selector and its results at a particular point in time. - */ -type CSnapshot = CSelector & { + * A representation of a selector and its results at a particular point in time. + */ +export type CSnapshot = CSelector & { data: SelectorData | null | undefined; seenRecords: RecordMap; }; /** - * The results of a selector given a store/RecordSource. - */ -interface SelectorData { + * The results of a selector given a store/RecordSource. + */ +export interface SelectorData { [key: string]: any; } /** - * The results of reading the results of a FragmentMap given some input - * `Props`. - */ -interface FragmentSpecResults { + * The results of reading the results of a FragmentMap given some input + * `Props`. + */ +export interface FragmentSpecResults { [key: string]: any; } /** - * A utility for resolving and subscribing to the results of a fragment spec - * (key -> fragment mapping) given some "props" that determine the root ID - * and variables to use when reading each fragment. When props are changed via - * `setProps()`, the resolver will update its results and subscriptions - * accordingly. Internally, the resolver: - * - Converts the fragment map & props map into a map of `Selector`s. - * - Removes any resolvers for any props that became null. - * - Creates resolvers for any props that became non-null. - * - Updates resolvers with the latest props. - */ -interface FragmentSpecResolver { + * A utility for resolving and subscribing to the results of a fragment spec + * (key -> fragment mapping) given some "props" that determine the root ID + * and variables to use when reading each fragment. When props are changed via + * `setProps()`, the resolver will update its results and subscriptions + * accordingly. Internally, the resolver: + * - Converts the fragment map & props map into a map of `Selector`s. + * - Removes any resolvers for any props that became null. + * - Creates resolvers for any props that became non-null. + * - Updates resolvers with the latest props. + */ +export interface FragmentSpecResolver { /** - * Stop watching for changes to the results of the fragments. - */ + * Stop watching for changes to the results of the fragments. + */ dispose(): void; /** - * Get the current results. - */ + * Get the current results. + */ resolve(): FragmentSpecResults; /** - * Update the resolver with new inputs. Call `resolve()` to get the updated - * results. - */ + * Update the resolver with new inputs. Call `resolve()` to get the updated + * results. + */ setProps(props: Props): void; /** - * Override the variables used to read the results of the fragments. Call - * `resolve()` to get the updated results. - */ + * Override the variables used to read the results of the fragments. Call + * `resolve()` to get the updated results. + */ setVariables(variables: Variables): void; } -interface CFragmentMap { +export interface CFragmentMap { [key: string]: TFragment; } /** - * An operation selector describes a specific instance of a GraphQL operation - * with variables applied. - * - * - `root`: a selector intended for processing server results or retaining - * response data in the store. - * - `fragment`: a selector intended for use in reading or subscribing to - * the results of the the operation. - */ -interface COperationSelector { + * An operation selector describes a specific instance of a GraphQL operation + * with variables applied. + * + * - `root`: a selector intended for processing server results or retaining + * response data in the store. + * - `fragment`: a selector intended for use in reading or subscribing to + * the results of the the operation. + */ +export interface COperationSelector { fragment: CSelector; node: TOperation; root: CSelector; @@ -308,42 +308,42 @@ interface COperationSelector { } /** - * The public API of Relay core. Represents an encapsulated environment with its - * own in-memory cache. - */ -interface CEnvironment { + * The public API of Relay core. Represents an encapsulated environment with its + * own in-memory cache. + */ +export interface CEnvironment { /** - * Read the results of a selector from in-memory records in the store. - */ + * Read the results of a selector from in-memory records in the store. + */ lookup(selector: CSelector): CSnapshot; /** - * Subscribe to changes to the results of a selector. The callback is called - * when data has been committed to the store that would cause the results of - * the snapshot's selector to change. - */ + * Subscribe to changes to the results of a selector. The callback is called + * when data has been committed to the store that would cause the results of + * the snapshot's selector to change. + */ subscribe(snapshot: CSnapshot, callback: (snapshot: CSnapshot) => void): Disposable; /** - * Ensure that all the records necessary to fulfill the given selector are - * retained in-memory. The records will not be eligible for garbage collection - * until the returned reference is disposed. - * - * Note: This is a no-op in the classic core. - */ + * Ensure that all the records necessary to fulfill the given selector are + * retained in-memory. The records will not be eligible for garbage collection + * until the returned reference is disposed. + * + * Note: This is a no-op in the classic core. + */ retain(selector: CSelector): Disposable; /** - * Send a query to the server with request/response semantics: the query will - * either complete successfully (calling `onNext` and `onCompleted`) or fail - * (calling `onError`). - * - * Note: Most applications should use `streamQuery` in order to - * optionally receive updated information over time, should that feature be - * supported by the network/server. A good rule of thumb is to use this method - * if you would otherwise immediately dispose the `streamQuery()` - * after receving the first `onNext` result. - */ + * Send a query to the server with request/response semantics: the query will + * either complete successfully (calling `onNext` and `onCompleted`) or fail + * (calling `onError`). + * + * Note: Most applications should use `streamQuery` in order to + * optionally receive updated information over time, should that feature be + * supported by the network/server. A good rule of thumb is to use this method + * if you would otherwise immediately dispose the `streamQuery()` + * after receving the first `onNext` result. + */ sendQuery(config: { cacheConfig?: CacheConfig; onCompleted?(): void; @@ -353,13 +353,13 @@ interface CEnvironment; } -interface CUnstableEnvironmentCore { +export interface CUnstableEnvironmentCore { /** - * Create an instance of a FragmentSpecResolver. - * - * TODO: The FragmentSpecResolver *can* be implemented via the other methods - * defined here, so this could be moved out of core. It's convenient to have - * separate implementations until the experimental core is in OSS. - */ + * Create an instance of a FragmentSpecResolver. + * + * TODO: The FragmentSpecResolver *can* be implemented via the other methods + * defined here, so this could be moved out of core. It's convenient to have + * separate implementations until the experimental core is in OSS. + */ createFragmentSpecResolver( context: CRelayContext, containerName: string, @@ -388,78 +388,78 @@ interface CUnstableEnvironmentCore; /** - * Given a graphql`...` tagged template, extract a fragment definition usable - * by this version of Relay core. Throws if the value is not a fragment. - */ + * Given a graphql`...` tagged template, extract a fragment definition usable + * by this version of Relay core. Throws if the value is not a fragment. + */ getFragment(node: TGraphQLTaggedNode): TFragment; /** - * Given a graphql`...` tagged template, extract an operation definition - * usable by this version of Relay core. Throws if the value is not an - * operation. - */ + * Given a graphql`...` tagged template, extract an operation definition + * usable by this version of Relay core. Throws if the value is not an + * operation. + */ getOperation(node: TGraphQLTaggedNode): TOperation; /** - * Determine if two selectors are equal (represent the same selection). Note - * that this function returns `false` when the two queries/fragments are - * different objects, even if they select the same fields. - */ + * Determine if two selectors are equal (represent the same selection). Note + * that this function returns `false` when the two queries/fragments are + * different objects, even if they select the same fields. + */ areEqualSelectors(a: CSelector, b: CSelector): boolean; /** - * Given the result `item` from a parent that fetched `fragment`, creates a - * selector that can be used to read the results of that fragment for that item. - * - * Example: - * - * Given two fragments as follows: - * - * ``` - * fragment Parent on User { - * id - * ...Child - * } - * fragment Child on User { - * name - * } - * ``` - * - * And given some object `parent` that is the results of `Parent` for id "4", - * the results of `Child` can be accessed by first getting a selector and then - * using that selector to `lookup()` the results against the environment: - * - * ``` - * const childSelector = getSelector(queryVariables, Child, parent); - * const childData = environment.lookup(childSelector).data; - * ``` - */ + * Given the result `item` from a parent that fetched `fragment`, creates a + * selector that can be used to read the results of that fragment for that item. + * + * Example: + * + * Given two fragments as follows: + * + * ``` + * fragment Parent on User { + * id + * ...Child + * } + * fragment Child on User { + * name + * } + * ``` + * + * And given some object `parent` that is the results of `Parent` for id "4", + * the results of `Child` can be accessed by first getting a selector and then + * using that selector to `lookup()` the results against the environment: + * + * ``` + * const childSelector = getSelector(queryVariables, Child, parent); + * const childData = environment.lookup(childSelector).data; + * ``` + */ getSelector(operationVariables: Variables, fragment: TFragment, prop: any): CSelector | null; /** - * Given the result `items` from a parent that fetched `fragment`, creates a - * selector that can be used to read the results of that fragment on those - * items. This is similar to `getSelector` but for "plural" fragments that - * expect an array of results and therefore return an array of selectors. - */ + * Given the result `items` from a parent that fetched `fragment`, creates a + * selector that can be used to read the results of that fragment on those + * items. This is similar to `getSelector` but for "plural" fragments that + * expect an array of results and therefore return an array of selectors. + */ getSelectorList(operationVariables: Variables, fragment: TFragment, props: any[]): Array> | null; /** - * Given a mapping of keys -> results and a mapping of keys -> fragments, - * extracts the selectors for those fragments from the results. - * - * The canonical use-case for this function are Relay Containers, which - * use this function to convert (props, fragments) into selectors so that they - * can read the results to pass to the inner component. - */ + * Given a mapping of keys -> results and a mapping of keys -> fragments, + * extracts the selectors for those fragments from the results. + * + * The canonical use-case for this function are Relay Containers, which + * use this function to convert (props, fragments) into selectors so that they + * can read the results to pass to the inner component. + */ getSelectorsFromObject( operationVariables: Variables, fragments: CFragmentMap, @@ -467,33 +467,33 @@ interface CUnstableEnvironmentCore | Array> | null | undefined }; /** - * Given a mapping of keys -> results and a mapping of keys -> fragments, - * extracts a mapping of keys -> id(s) of the results. - * - * Similar to `getSelectorsFromObject()`, this function can be useful in - * determining the "identity" of the props passed to a component. - */ + * Given a mapping of keys -> results and a mapping of keys -> fragments, + * extracts a mapping of keys -> id(s) of the results. + * + * Similar to `getSelectorsFromObject()`, this function can be useful in + * determining the "identity" of the props passed to a component. + */ getDataIDsFromObject( fragments: CFragmentMap, props: Props ): { [key: string]: DataID | DataID[] | null | undefined }; /** - * Given a mapping of keys -> results and a mapping of keys -> fragments, - * extracts the merged variables that would be in scope for those - * fragments/results. - * - * This can be useful in determing what varaibles were used to fetch the data - * for a Relay container, for example. - */ + * Given a mapping of keys -> results and a mapping of keys -> fragments, + * extracts the merged variables that would be in scope for those + * fragments/results. + * + * This can be useful in determing what varaibles were used to fetch the data + * for a Relay container, for example. + */ getVariablesFromObject(operationVariables: Variables, fragments: CFragmentMap, props: Props): Variables; } /** - * The type of the `relay` property set on React context by the React/Relay - * integration layer (e.g. QueryRenderer, FragmentContainer, etc). - */ -interface CRelayContext { + * The type of the `relay` property set on React context by the React/Relay + * integration layer (e.g. QueryRenderer, FragmentContainer, etc). + */ +export interface CRelayContext { environment: TEnvironment; variables: Variables; } @@ -501,21 +501,21 @@ interface CRelayContext { // ~~~~~~~~~~~~~~~~~~~~~ // RelayTypes /** - * Version: Relay 1.3.0 - * File: - * https://github.com/facebook/relay/blob/fa9f48ea209ee2402d433b59a84d1cbc046574e2/packages/react-relay/classic/tools/RelayTypes.js - */ + * Version: Relay 1.3.0 + * File: + * https://github.com/facebook/relay/blob/fa9f48ea209ee2402d433b59a84d1cbc046574e2/packages/react-relay/classic/tools/RelayTypes.js + */ // ~~~~~~~~~~~~~~~~~~~~~ -interface RerunParam { +export interface RerunParam { param: string; import: string; max_runs: number; } -interface FIELDS_CHANGE { +export interface FIELDS_CHANGE { type: "FIELDS_CHANGE"; fieldIDs: { [fieldName: string]: DataID | DataID[] }; } -interface RANGE_ADD { +export interface RANGE_ADD { type: "RANGE_ADD"; parentName?: string; parentID?: string; @@ -528,14 +528,14 @@ interface RANGE_ADD { edgeName: string; rangeBehaviors?: RangeBehaviors; } -interface NODE_DELETE { +export interface NODE_DELETE { type: "NODE_DELETE"; parentName?: string; parentID?: string; connectionName?: string; deletedIDFieldName: string; } -interface RANGE_DELETE { +export interface RANGE_DELETE { type: "RANGE_DELETE"; parentName?: string; parentID?: string; @@ -547,36 +547,36 @@ interface RANGE_DELETE { deletedIDFieldName: string | string[]; pathToConnection: string[]; } -interface REQUIRED_CHILDREN { +export interface REQUIRED_CHILDREN { type: "REQUIRED_CHILDREN"; children: RelayConcreteNode[]; } -type RelayMutationConfig = FIELDS_CHANGE | RANGE_ADD | NODE_DELETE | RANGE_DELETE | REQUIRED_CHILDREN; +export type RelayMutationConfig = FIELDS_CHANGE | RANGE_ADD | NODE_DELETE | RANGE_DELETE | REQUIRED_CHILDREN; -interface RelayMutationTransactionCommitCallbacks { +export interface RelayMutationTransactionCommitCallbacks { onFailure?: RelayMutationTransactionCommitFailureCallback; onSuccess?: RelayMutationTransactionCommitSuccessCallback; } -type RelayMutationTransactionCommitFailureCallback = ( +export type RelayMutationTransactionCommitFailureCallback = ( transaction: RelayMutationTransaction, preventAutoRollback: () => void ) => void; -type RelayMutationTransactionCommitSuccessCallback = ( +export type RelayMutationTransactionCommitSuccessCallback = ( response: { [key: string]: any; } ) => void; -interface NetworkLayer { +export interface NetworkLayer { sendMutation(request: RelayMutationRequest): Promise | null; sendQueries(requests: RelayQueryRequest[]): Promise | null; supports(...options: string[]): boolean; } -interface QueryResult { +export interface QueryResult { error?: Error; ref_params?: { [name: string]: any }; response: QueryPayload; } -interface ReadyState { +export interface ReadyState { aborted: boolean; done: boolean; error: Error | null; @@ -584,8 +584,8 @@ interface ReadyState { ready: boolean; stale: boolean; } -type RelayContainerErrorEventType = "CACHE_RESTORE_FAILED" | "NETWORK_QUERY_ERROR"; -type RelayContainerLoadingEventType = +export type RelayContainerErrorEventType = "CACHE_RESTORE_FAILED" | "NETWORK_QUERY_ERROR"; +export type RelayContainerLoadingEventType = | "ABORT" | "CACHE_RESTORED_REQUIRED" | "CACHE_RESTORE_START" @@ -594,74 +594,74 @@ type RelayContainerLoadingEventType = | "NETWORK_QUERY_START" | "STORE_FOUND_ALL" | "STORE_FOUND_REQUIRED"; -type ReadyStateChangeCallback = (readyState: ReadyState) => void; -interface ReadyStateEvent { +export type ReadyStateChangeCallback = (readyState: ReadyState) => void; +export interface ReadyStateEvent { type: RelayContainerLoadingEventType | RelayContainerErrorEventType; error?: Error; } -interface Abortable { +export interface Abortable { abort(): void; } // ~~~~~~~~~~~~~~~~~~~~~ // RelayInternalTypes /** - * Version: Relay 1.3.0 - * File: - * https://github.com/facebook/relay/blob/master/packages/react-relay/classic/tools/RelayInternalTypes.js - */ + * Version: Relay 1.3.0 + * File: + * https://github.com/facebook/relay/blob/master/packages/react-relay/classic/tools/RelayInternalTypes.js + */ // ~~~~~~~~~~~~~~~~~~~~~ -interface QueryPayload { +export interface QueryPayload { [key: string]: any; } -interface RelayQuerySet { +export interface RelayQuerySet { [queryName: string]: any; } -type RangeBehaviorsFunction = ( +export type RangeBehaviorsFunction = ( connectionArgs: { [argName: string]: any; } ) => "APPEND" | "IGNORE" | "PREPEND" | "REFETCH" | "REMOVE"; -interface RangeBehaviorsObject { +export interface RangeBehaviorsObject { [key: string]: "APPEND" | "IGNORE" | "PREPEND" | "REFETCH" | "REMOVE"; } -type RangeBehaviors = RangeBehaviorsFunction | RangeBehaviorsObject; +export type RangeBehaviors = RangeBehaviorsFunction | RangeBehaviorsObject; // ~~~~~~~~~~~~~~~~~~~~~ // Maybe Fix // ~~~~~~~~~~~~~~~~~~~~~ -type RelayDebugger = any; -type OptimisticUpdate = any; -type OperationSelector = COperationSelector; -type Selector = CSelector; -type PayloadData = any; -type Snapshot = CSnapshot; -type RelayResponsePayload = any; -type MutableRecordSource = RecordSource; +export type RelayDebugger = any; +export type OptimisticUpdate = any; +export type OperationSelector = COperationSelector; +export type Selector = CSelector; +export type PayloadData = any; +export type Snapshot = CSnapshot; +export type RelayResponsePayload = any; +export type MutableRecordSource = RecordSource; /** - * A function that returns an Observable representing the response of executing - * a GraphQL operation. - */ -type ExecuteFunction = ( + * A function that returns an Observable representing the response of executing + * a GraphQL operation. + */ +export type ExecuteFunction = ( operation: object, variables: Variables, cacheConfig: CacheConfig, uploadables?: UploadableMap ) => Promise; -interface RelayNetwork { +export interface RelayNetwork { execute: ExecuteFunction; } // ~~~~~~~~~~~~~~~~~~~~~ // RelayDefaultHandlerProvider // ~~~~~~~~~~~~~~~~~~~~~ -declare function HandlerProvider(name: string): HandlerInterface | null; +export function HandlerProvider(name: string): HandlerInterface | null; // ~~~~~~~~~~~~~~~~~~~~~ // RelayModernEnvironment // ~~~~~~~~~~~~~~~~~~~~~ -interface EnvironmentConfig { +export interface EnvironmentConfig { configName?: string; handlerProvider?: typeof HandlerProvider; network: Network; @@ -702,10 +702,10 @@ export class Environment { // ~~~~~~~~~~~~~~~~~~~~~ // RelayInMemoryRecordSource // ~~~~~~~~~~~~~~~~~~~~~ -interface RelayInMemoryRecordSource { +export interface RelayInMemoryRecordSource { [key: string]: any; } -interface RecordMap { +export interface RecordMap { [dataID: string]: RelayInMemoryRecordSource | null | undefined; } @@ -714,16 +714,16 @@ interface RecordMap { // ~~~~~~~~~~~~~~~~~~~~~ export class Network { /** - * Creates an implementation of the `Network` interface defined in - * `RelayNetworkTypes` given `fetch` and `subscribe` functions. - */ + * Creates an implementation of the `Network` interface defined in + * `RelayNetworkTypes` given `fetch` and `subscribe` functions. + */ static create(fetchFn: typeof FetchFunction, subscribeFn?: SubscribeFunction): RelayNetwork; } // ~~~~~~~~~~~~~~~~~~~~~ // Network // ~~~~~~~~~~~~~~~~~~~~~ -declare class RecordSource { +export class RecordSource { constructor(records?: RecordMap); clear(): void; delete(dataID: DataID): void; @@ -756,10 +756,10 @@ export class Store { // RelayRecordSourceInspector // ~~~~~~~~~~~~~~~~~~~~~ /** - * An internal class to provide a console-friendly string representation of a - * RelayInMemoryRecordSource. - */ -declare class RecordSummary { + * An internal class to provide a console-friendly string representation of a + * RelayInMemoryRecordSource. + */ +export class RecordSummary { id: DataID; type: string | null | undefined; static createFromRecord(id: DataID, record: any): RecordSummary; @@ -767,78 +767,78 @@ declare class RecordSummary { toString(): string; } /** - * Internal class for inspecting a single RelayInMemoryRecordSource. - */ -declare class RecordInspector { + * Internal class for inspecting a single RelayInMemoryRecordSource. + */ +export class RecordInspector { constructor(sourceInspector: RelayRecordSourceInspector, record: RelayInMemoryRecordSource); /** - * Get the cache id of the given record. For types that implement the `Node` - * interface (or that have an `id`) this will be `id`, for other types it will be - * a synthesized identifier based on the field path from the nearest ancestor - * record that does have an `id`. - */ + * Get the cache id of the given record. For types that implement the `Node` + * interface (or that have an `id`) this will be `id`, for other types it will be + * a synthesized identifier based on the field path from the nearest ancestor + * record that does have an `id`. + */ getDataID(): DataID; /** - * Returns a list of the fields that have been fetched on the current record. - */ + * Returns a list of the fields that have been fetched on the current record. + */ getFields(): string[]; /** - * Returns the type of the record. - */ + * Returns the type of the record. + */ getType(): string; /** - * Returns a copy of the internal representation of the record. - */ + * Returns a copy of the internal representation of the record. + */ inspect(): any; /** - * Returns the value of a scalar field. May throw if the given field is - * present but not actually scalar. - */ + * Returns the value of a scalar field. May throw if the given field is + * present but not actually scalar. + */ getValue(name: string, args?: Variables): any; /** - * Returns an inspector for the given scalar "linked" field (a field whose - * value is another RelayInMemoryRecordSource instead of a scalar). May throw if the field is - * present but not a scalar linked record. - */ + * Returns an inspector for the given scalar "linked" field (a field whose + * value is another RelayInMemoryRecordSource instead of a scalar). May throw if the field is + * present but not a scalar linked record. + */ getLinkedRecord(name: string, args?: Variables): RecordInspector | null; /** - * Returns an array of inspectors for the given plural "linked" field (a field - * whose value is an array of Records instead of a scalar). May throw if the - * field is present but not a plural linked record. - */ + * Returns an array of inspectors for the given plural "linked" field (a field + * whose value is an array of Records instead of a scalar). May throw if the + * field is present but not a plural linked record. + */ getLinkedRecords(name: string, args?: Variables): RecordInspector[] | null; } -declare class RelayRecordSourceInspector { +export class RelayRecordSourceInspector { constructor(source: RecordSource); static getForEnvironment(environment: Environment): RelayRecordSourceInspector; /** - * Returns an inspector for the record with the given id, or null/undefined if - * that record is deleted/unfetched. - */ + * Returns an inspector for the record with the given id, or null/undefined if + * that record is deleted/unfetched. + */ get(dataID: DataID): RecordInspector | null; /** - * Returns a list of ": " for each record in the store that has an - * `id`. - */ + * Returns a list of ": " for each record in the store that has an + * `id`. + */ getNodes(): RecordSummary[]; /** - * Returns a list of ": " for all records in the store including - * those that do not have an `id`. - */ + * Returns a list of ": " for all records in the store including + * those that do not have an `id`. + */ getRecords(): RecordSummary[]; /** - * Returns an inspector for the synthesized "root" object, allowing access to - * e.g. the `viewer` object or the results of other fields on the "Query" - * type. - */ + * Returns an inspector for the synthesized "root" object, allowing access to + * e.g. the `viewer` object or the results of other fields on the "Query" + * type. + */ getRoot(): RecordInspector; } @@ -848,129 +848,129 @@ export type RecordSourceInspector = RelayRecordSourceInspector; // ~~~~~~~~~~~~~~~~~~~~~ // RelayObservable // ~~~~~~~~~~~~~~~~~~~~~ -interface Subscription { +export interface Subscription { unsubscribe(): void; readonly closed: boolean; } -interface Observer { +export interface Observer { start?(subscription: Subscription): any; next?(nextThing: T): any; error?(error: Error): any; complete?(): any; unsubscribe?(subscription: Subscription): any; } -type Source = () => any; -interface Subscribable { +export type Source = () => any; // tslint:disable-line:no-unnecessary-generics +export interface Subscribable { subscribe(observer: Observer): Subscription; } -type ObservableFromValue = RelayObservable | Promise | T; -declare class RelayObservable implements Subscribable { +export type ObservableFromValue = RelayObservable | Promise | T; +export class RelayObservable implements Subscribable { _source: Source; constructor(source: Source); /** - * When an unhandled error is detected, it is reported to the host environment - * (the ESObservable spec refers to this method as "HostReportErrors()"). - * - * The default implementation in development builds re-throws errors in a - * separate frame, and from production builds does nothing (swallowing - * uncaught errors). - * - * Called during application initialization, this method allows - * application-specific handling of uncaught errors. Allowing, for example, - * integration with error logging or developer tools. - */ + * When an unhandled error is detected, it is reported to the host environment + * (the ESObservable spec refers to this method as "HostReportErrors()"). + * + * The default implementation in development builds re-throws errors in a + * separate frame, and from production builds does nothing (swallowing + * uncaught errors). + * + * Called during application initialization, this method allows + * application-specific handling of uncaught errors. Allowing, for example, + * integration with error logging or developer tools. + */ static onUnhandledError(callback: (error: Error) => any): void; /** - * Accepts various kinds of data sources, and always returns a RelayObservable - * useful for accepting the result of a user-provided FetchFunction. - */ + * Accepts various kinds of data sources, and always returns a RelayObservable + * useful for accepting the result of a user-provided FetchFunction. + */ static from(obj: ObservableFromValue): RelayObservable; /** - * Creates a RelayObservable, given a function which expects a legacy - * Relay Observer as the last argument and which returns a Disposable. - * - * To support migration to Observable, the function may ignore the - * legacy Relay observer and directly return an Observable instead. - */ + * Creates a RelayObservable, given a function which expects a legacy + * Relay Observer as the last argument and which returns a Disposable. + * + * To support migration to Observable, the function may ignore the + * legacy Relay observer and directly return an Observable instead. + */ static fromLegacy( callback: (legacyObserver: LegacyObserver) => Disposable | RelayObservable ): RelayObservable; /** - * Returns a new Observable which returns the same values as this one, but - * modified so that the provided Observer is called to perform a side-effects - * for all events emitted by the source. - * - * Any errors that are thrown in the side-effect Observer are unhandled, and - * do not affect the source Observable or its Observer. - * - * This is useful for when debugging your Observables or performing other - * side-effects such as logging or performance monitoring. - */ + * Returns a new Observable which returns the same values as this one, but + * modified so that the provided Observer is called to perform a side-effects + * for all events emitted by the source. + * + * Any errors that are thrown in the side-effect Observer are unhandled, and + * do not affect the source Observable or its Observer. + * + * This is useful for when debugging your Observables or performing other + * side-effects such as logging or performance monitoring. + */ do(observer: Observer): RelayObservable; /** - * Returns a new Observable which returns the same values as this one, but - * modified so that the finally callback is performed after completion, - * whether normal or due to error or unsubscription. - * - * This is useful for cleanup such as resource finalization. - */ + * Returns a new Observable which returns the same values as this one, but + * modified so that the finally callback is performed after completion, + * whether normal or due to error or unsubscription. + * + * This is useful for cleanup such as resource finalization. + */ finally(fn: () => any): RelayObservable; /** - * Returns a new Observable which is identical to this one, unless this - * Observable completes before yielding any values, in which case the new - * Observable will yield the values from the alternate Observable. - * - * If this Observable does yield values, the alternate is never subscribed to. - * - * This is useful for scenarios where values may come from multiple sources - * which should be tried in order, i.e. from a cache before a network. - */ + * Returns a new Observable which is identical to this one, unless this + * Observable completes before yielding any values, in which case the new + * Observable will yield the values from the alternate Observable. + * + * If this Observable does yield values, the alternate is never subscribed to. + * + * This is useful for scenarios where values may come from multiple sources + * which should be tried in order, i.e. from a cache before a network. + */ ifEmpty(alternate: RelayObservable): RelayObservable; /** - * Observable's primary API: returns an unsubscribable Subscription to the - * source of this Observable. - */ + * Observable's primary API: returns an unsubscribable Subscription to the + * source of this Observable. + */ subscribe(observer: Observer): Subscription; /** - * Supports subscription of a legacy Relay Observer, returning a Disposable. - */ + * Supports subscription of a legacy Relay Observer, returning a Disposable. + */ subscribeLegacy(legacyObserver: LegacyObserver): Disposable; /** - * Returns a new Observerable where each value has been transformed by - * the mapping function. - */ + * Returns a new Observerable where each value has been transformed by + * the mapping function. + */ map(fn: (thing: T) => U): RelayObservable; /** - * Returns a new Observable where each value is replaced with a new Observable - * by the mapping function, the results of which returned as a single - * concattenated Observable. - */ + * Returns a new Observable where each value is replaced with a new Observable + * by the mapping function, the results of which returned as a single + * concattenated Observable. + */ concatMap(fn: (thing: T) => ObservableFromValue): RelayObservable; /** - * Returns a new Observable which first mirrors this Observable, then when it - * completes, waits for `pollInterval` milliseconds before re-subscribing to - * this Observable again, looping in this manner until unsubscribed. - * - * The returned Observable never completes. - */ + * Returns a new Observable which first mirrors this Observable, then when it + * completes, waits for `pollInterval` milliseconds before re-subscribing to + * this Observable again, looping in this manner until unsubscribed. + * + * The returned Observable never completes. + */ poll(pollInterval: number): RelayObservable; /** - * Returns a Promise which resolves when this Observable yields a first value - * or when it completes with no value. - */ + * Returns a Promise which resolves when this Observable yields a first value + * or when it completes with no value. + */ toPromise(): Promise; } @@ -980,13 +980,13 @@ export type Observable = RelayObservable; // commitLocalUpdate // ~~~~~~~~~~~~~~~~~~~~~ // exposed through RelayModern, not Runtime directly -type commitLocalUpdate = (environment: Environment, updater: StoreUpdater) => void; +export type commitLocalUpdate = (environment: Environment, updater: StoreUpdater) => void; // ~~~~~~~~~~~~~~~~~~~~~ // commitRelayModernMutation // ~~~~~~~~~~~~~~~~~~~~~ // exposed through RelayModern, not Runtime directly -interface MutationConfig { +export interface MutationConfig { configs?: RelayMutationConfig[]; mutation: GraphQLTaggedNode; variables: Variables; @@ -997,13 +997,13 @@ interface MutationConfig { optimisticResponse?: object; updater?: SelectorStoreUpdater; } -declare function commitRelayModernMutation(environment: Environment, config: MutationConfig): Disposable; +export function commitRelayModernMutation(environment: Environment, config: MutationConfig): Disposable; // ~~~~~~~~~~~~~~~~~~~~~ // applyRelayModernOptimisticMutation // ~~~~~~~~~~~~~~~~~~~~~ // exposed through RelayModern, not Runtime directly -interface OptimisticMutationConfig { +export interface OptimisticMutationConfig { configs?: RelayMutationConfig[]; mutation: GraphQLTaggedNode; variables: Variables; @@ -1016,19 +1016,19 @@ interface OptimisticMutationConfig { // ~~~~~~~~~~~~~~~~~~~~~ // exposed through RelayModern, not Runtime directly /** - * A helper function to fetch the results of a query. Note that results for - * fragment spreads are masked: fields must be explicitly listed in the query in - * order to be accessible in the result object. - * - * NOTE: This module is primarily intended for integrating with classic APIs. - * Most product code should use a Renderer or Container. - * - * TODO(t16875667): The return type should be `Promise`, but - * that's not really helpful as `SelectorData` is essentially just `mixed`. We - * can probably leverage generated flow types here to return the real expected - * shape. - */ -declare function fetchRelayModernQuery( + * A helper function to fetch the results of a query. Note that results for + * fragment spreads are masked: fields must be explicitly listed in the query in + * order to be accessible in the result object. + * + * NOTE: This module is primarily intended for integrating with classic APIs. + * Most product code should use a Renderer or Container. + * + * TODO(t16875667): The return type should be `Promise`, but + * that's not really helpful as `SelectorData` is essentially just `mixed`. We + * can probably leverage generated flow types here to return the real expected + * shape. + */ +export function fetchRelayModernQuery( environment: any, // FIXME - $FlowFixMe in facebook source code taggedNode: GraphQLTaggedNode, variables: Variables, @@ -1039,7 +1039,7 @@ declare function fetchRelayModernQuery( // requestRelaySubscription // ~~~~~~~~~~~~~~~~~~~~~ // exposed through RelayModern, not Runtime directly -interface GraphQLSubscriptionConfig { +export interface GraphQLSubscriptionConfig { configs?: RelayMutationConfig[]; subscription: GraphQLTaggedNode; variables: Variables; @@ -1048,4 +1048,4 @@ interface GraphQLSubscriptionConfig { onNext?(response: object | null | undefined): void; updater?(store: RecordSourceSelectorProxy): void; } -declare function requestRelaySubscription(environment: Environment, config: GraphQLSubscriptionConfig): Disposable; +export function requestRelaySubscription(environment: Environment, config: GraphQLSubscriptionConfig): Disposable; diff --git a/types/relay-runtime/tsconfig.json b/types/relay-runtime/tsconfig.json index dd77fca0e4..8aed884320 100644 --- a/types/relay-runtime/tsconfig.json +++ b/types/relay-runtime/tsconfig.json @@ -8,6 +8,7 @@ "noImplicitAny": true, "noImplicitThis": true, "strictNullChecks": true, + "strictFunctionTypes": true, "baseUrl": "../", "typeRoots": [ "../" From 1fb244abedbe3dbfc11e31d3e9436be9062a8cbe Mon Sep 17 00:00:00 2001 From: Josh Rutherford Date: Thu, 19 Oct 2017 05:40:47 -0500 Subject: [PATCH 047/828] react-dom: add createPortal API (#20245). (#20336) * react-dom: add createPortal API. * React, React-DOM: move portal interface to types/react, update render for class components to include ReactPortal. * react-dom: add second portal test case with jsx, allow jsx in react-dom-tests. * react, react-dom createPortal api: remove undocumented arguments, properties. --- types/react-dom/index.d.ts | 5 ++++- .../{react-dom-tests.ts => react-dom-tests.tsx} | 14 ++++++++++++++ types/react-dom/tsconfig.json | 5 +++-- types/react/index.d.ts | 12 +++++++++--- 4 files changed, 30 insertions(+), 6 deletions(-) rename types/react-dom/{react-dom-tests.ts => react-dom-tests.tsx} (93%) diff --git a/types/react-dom/index.d.ts b/types/react-dom/index.d.ts index aeac0c8081..20b870a8b8 100644 --- a/types/react-dom/index.d.ts +++ b/types/react-dom/index.d.ts @@ -4,6 +4,7 @@ // AssureSign // Microsoft // MartynasZilinskas +// Josh Rutherford // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped // TypeScript Version: 2.3 @@ -12,12 +13,14 @@ export as namespace ReactDOM; import { ReactInstance, Component, ComponentState, ReactElement, SFCElement, CElement, - DOMAttributes, DOMElement + DOMAttributes, DOMElement, ReactNode, ReactPortal } from 'react'; export function findDOMNode(instance: ReactInstance): Element; export function unmountComponentAtNode(container: Element): boolean; +export function createPortal(children: ReactNode, container: Element): ReactPortal; + export const version: string; export const render: Renderer; export const hydrate: Renderer; diff --git a/types/react-dom/react-dom-tests.ts b/types/react-dom/react-dom-tests.tsx similarity index 93% rename from types/react-dom/react-dom-tests.ts rename to types/react-dom/react-dom-tests.tsx index 08eac7afdb..3f153b0a75 100644 --- a/types/react-dom/react-dom-tests.ts +++ b/types/react-dom/react-dom-tests.tsx @@ -31,6 +31,20 @@ describe('ReactDOM', () => { ReactDOM.render(React.createElement('div'), rootElement); ReactDOM.findDOMNode(rootElement); }); + + it('createPortal', () => { + const rootElement = document.createElement('div'); + const portalTarget = document.createElement('div'); + + class ClassComponent extends React.Component { + render() { + return ReactDOM.createPortal(
, portalTarget); + } + } + + ReactDOM.createPortal(React.createElement('div'), portalTarget); + ReactDOM.render(, rootElement); + }); }); describe('ReactDOMServer', () => { diff --git a/types/react-dom/tsconfig.json b/types/react-dom/tsconfig.json index 010744a826..0d21b07029 100644 --- a/types/react-dom/tsconfig.json +++ b/types/react-dom/tsconfig.json @@ -1,7 +1,7 @@ { "files": [ "index.d.ts", - "react-dom-tests.ts", + "react-dom-tests.tsx", "server/index.d.ts", "node-stream/index.d.ts", "test-utils/index.d.ts" @@ -22,6 +22,7 @@ ], "types": [], "noEmit": true, - "forceConsistentCasingInFileNames": true + "forceConsistentCasingInFileNames": true, + "jsx": "preserve" } } \ No newline at end of file diff --git a/types/react/index.d.ts b/types/react/index.d.ts index 35feb8d0ab..93cb62fbfa 100644 --- a/types/react/index.d.ts +++ b/types/react/index.d.ts @@ -13,6 +13,7 @@ // Dovydas Navickas // Stéphane Goetz // Rich Seviora +// Josh Rutherford // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped // TypeScript Version: 2.3 @@ -123,6 +124,11 @@ declare namespace React { type: keyof ReactSVG; } + interface ReactPortal { + key: Key | null; + children: ReactNode; + } + // // Factories // ---------------------------------------------------------------------- @@ -161,7 +167,7 @@ declare namespace React { // Should be Array but type aliases cannot be recursive type ReactFragment = {} | Array; - type ReactNode = ReactChild | ReactFragment | boolean | null | undefined; + type ReactNode = ReactChild | ReactFragment | ReactPortal | string | number | boolean | null | undefined; // // Top Level API @@ -280,7 +286,7 @@ declare namespace React { // tslint:enable:unified-signatures forceUpdate(callBack?: () => any): void; - render(): JSX.Element | JSX.Element[] | string | number | null | false; + render(): JSX.Element | JSX.Element[] | ReactPortal | string | number | null | false; // React.Props is now deprecated, which means that the `children` // property is not available on `P` by default, even though you can @@ -3505,7 +3511,7 @@ declare global { // tslint:disable:no-empty-interface interface Element extends React.ReactElement { } interface ElementClass extends React.Component { - render(): Element | Element[] | string | number | null | false; + render(): Element | Element[] | React.ReactPortal | string | number | null | false; } interface ElementAttributesProperty { props: {}; } interface ElementChildrenAttribute { children: {}; } From e08d727565ea52385bb3d860e69b3ac2dc7e1728 Mon Sep 17 00:00:00 2001 From: Gregor Yushinov Date: Thu, 19 Oct 2017 15:33:20 +0200 Subject: [PATCH 048/828] Added overload function definition for eachAsync --- types/mongoose/index.d.ts | 13 ++++++++++++- 1 file changed, 12 insertions(+), 1 deletion(-) diff --git a/types/mongoose/index.d.ts b/types/mongoose/index.d.ts index 602b700958..3e1002fd3c 100644 --- a/types/mongoose/index.d.ts +++ b/types/mongoose/index.d.ts @@ -505,7 +505,18 @@ declare module "mongoose" { * Execute fn for every document in the cursor. If fn returns a promise, * will wait for the promise to resolve before iterating on to the next one. * Returns a promise that resolves when done. - * @param callback executed when all docs have been processed + * @param fn Function to be executed for every document in the cursor + * @param callback Executed when all docs have been processed + */ + eachAsync(fn: (doc: T) => any, callback?: (err: any) => void): Promise; + + /** + * Execute fn for every document in the cursor. If fn returns a promise, + * will wait for the promise to resolve before iterating on to the next one. + * Returns a promise that resolves when done. + * @param fn Function to be executed for every document in the cursor + * @param options Async options (e. g. parallel function execution) + * @param callback Executed when all docs have been processed */ eachAsync(fn: (doc: T) => any, options: EachAsyncOptions, callback?: (err: any) => void): Promise; From 0cbf897a5df2d58336c27291e11ae671fca63b4f Mon Sep 17 00:00:00 2001 From: Weeco <23424570+weeco@users.noreply.github.com> Date: Thu, 19 Oct 2017 16:39:30 +0200 Subject: [PATCH 049/828] Added eachAsync options for concurrency (#20541) * Added eachAsync options for concurrency * Added overload function definition for eachAsync --- types/mongoose/index.d.ts | 18 +++++++++++++++++- 1 file changed, 17 insertions(+), 1 deletion(-) diff --git a/types/mongoose/index.d.ts b/types/mongoose/index.d.ts index cd7bb438d4..3e1002fd3c 100644 --- a/types/mongoose/index.d.ts +++ b/types/mongoose/index.d.ts @@ -469,6 +469,11 @@ declare module "mongoose" { static Messages: Object; } + interface EachAsyncOptions { + /** defaults to 1 */ + parallel?: number; + } + /* * section querycursor.js * http://mongoosejs.com/docs/api.html#querycursor-js @@ -500,10 +505,21 @@ declare module "mongoose" { * Execute fn for every document in the cursor. If fn returns a promise, * will wait for the promise to resolve before iterating on to the next one. * Returns a promise that resolves when done. - * @param callback executed when all docs have been processed + * @param fn Function to be executed for every document in the cursor + * @param callback Executed when all docs have been processed */ eachAsync(fn: (doc: T) => any, callback?: (err: any) => void): Promise; + /** + * Execute fn for every document in the cursor. If fn returns a promise, + * will wait for the promise to resolve before iterating on to the next one. + * Returns a promise that resolves when done. + * @param fn Function to be executed for every document in the cursor + * @param options Async options (e. g. parallel function execution) + * @param callback Executed when all docs have been processed + */ + eachAsync(fn: (doc: T) => any, options: EachAsyncOptions, callback?: (err: any) => void): Promise; + /** * Registers a transform function which subsequently maps documents retrieved * via the streams interface or .next() From 4aa4400332de149258fda1bc4f3fe4de6686bfb9 Mon Sep 17 00:00:00 2001 From: Yoga Aliarham Date: Thu, 19 Oct 2017 21:48:52 +0700 Subject: [PATCH 050/828] Update ioredis type definitions (add pfcount, pfadd, pfmerge interfaces) (#20669) * Update ioredis type definitions * Add contributor name * Update interface order --- types/ioredis/index.d.ts | 15 +++++++++++---- 1 file changed, 11 insertions(+), 4 deletions(-) diff --git a/types/ioredis/index.d.ts b/types/ioredis/index.d.ts index 7a36c4b7a6..8353b4e563 100644 --- a/types/ioredis/index.d.ts +++ b/types/ioredis/index.d.ts @@ -2,6 +2,7 @@ // Project: https://github.com/luin/ioredis // Definitions by: York Yao // Christopher Eck +// Yoga Aliarham // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped /* =================== USAGE =================== @@ -325,16 +326,22 @@ declare module IORedis { evalsha(args: any[], callback?: ResCallbackT): any; evalsha(...args: any[]): any; script(args: any[], callback?: ResCallbackT): any; - script(...args: any[]): any; script(key: string, callback?: ResCallbackT): any; + script(...args: any[]): any; quit(args: any[], callback?: ResCallbackT): any; quit(...args: any[]): any; - scan(...args: any[]): any; scan(args: any[], callback?: ResCallbackT): any; - hscan(...args: any[]): any; + scan(...args: any[]): any; hscan(args: any[], callback?: ResCallbackT): any; - zscan(...args: any[]): any; + hscan(...args: any[]): any; zscan(args: any[], callback?: ResCallbackT): any; + zscan(...args: any[]): any; + pfmerge(args: any[], callback?: ResCallbackT): any; + pfmerge(...args: any[]): any; + pfadd(args: any[], callback?: ResCallbackT): any; + pfadd(...args: any[]): any; + pfcount(args: any[], callback?: ResCallbackT): any; + pfcount(...args: any[]): any; pipeline(): Pipeline; pipeline(commands: string[][]): Pipeline; From 68a737fd800032531f3f87ac9c48b540b81dd600 Mon Sep 17 00:00:00 2001 From: mattywong Date: Thu, 19 Oct 2017 23:04:18 +0800 Subject: [PATCH 051/828] [@types/next] Update Router.push() method to include UrlLike type (#20671) * [@types/next] Update Router.push() method to include UrlLike type Allow a valid UrlLike object instead of only a string type e.g ``` Router.push({ pathname: '/pathname', query: { prop1: '', prop2: '', }, }); ``` https://github.com/zeit/next.js/#with-url-object-1 * Update router.d.ts --- types/next/router.d.ts | 7 +++++-- 1 file changed, 5 insertions(+), 2 deletions(-) diff --git a/types/next/router.d.ts b/types/next/router.d.ts index 021b0dd3dc..a1d58bb42a 100644 --- a/types/next/router.d.ts +++ b/types/next/router.d.ts @@ -1,4 +1,7 @@ import * as React from 'react'; +import * as url from 'url'; + +type UrlLike = url.UrlObject | url.Url; export interface EventChangeOptions { shallow?: boolean; @@ -20,8 +23,8 @@ export interface SingletonRouter { // router methods reload(route: string): Promise; back(): void; - push(url: string, as?: string, options?: EventChangeOptions): Promise; - replace(url: string, as?: string, options?: EventChangeOptions): Promise; + push(url: string|UrlLike, as?: string|UrlLike, options?: EventChangeOptions): Promise; + replace(url: string|UrlLike, as?: string|UrlLike, options?: EventChangeOptions): Promise; prefetch(url: string): Promise>; // router events From 77eac5484737119fc124ee602659e7179f9a342f Mon Sep 17 00:00:00 2001 From: AJ Richardson Date: Thu, 19 Oct 2017 11:09:17 -0400 Subject: [PATCH 052/828] [lodash] Better chaining wrappers, overload clean-up (#19356) * [lodash] improved iterateee parameters, simplified forEach overloads * Changed ListIterator to StringIterator, cleaned up more issues with flatMap * Even more flatMap cleanup * Making wrapper types simpler and more accurate (not done) * Fixed type inference for forEach callback arguments * Converted explicit wrapper types, implemented differenceWith * Updated more functions to use new-style wrappers * Finished updating the remaining methods * Fixed lint errors * Fixed parameter type inference when using `any` (#19228) * Fixed test errors * Fixed issues with _.get * Fixed issues with _.get * consider this * removed duplicate type, added TODO * More _.get fixes * Fixed issues with mapValues with a single parameter * Modified lodash-tests to have minimal diff with upstream * Improved backwards compatibility --- types/lodash/index.d.ts | 14419 +++++++++++++-------------------- types/lodash/lodash-tests.ts | 3032 +++---- types/lodash/tslint.json | 17 +- 3 files changed, 7058 insertions(+), 10410 deletions(-) diff --git a/types/lodash/index.d.ts b/types/lodash/index.d.ts index 58698cb4f3..ac954c6107 100644 --- a/types/lodash/index.d.ts +++ b/types/lodash/index.d.ts @@ -8,7 +8,7 @@ // Junyoung Clare Jang , // e-cloud // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -// TypeScript Version: 2.4 +// TypeScript Version: 2.2 /** ### 4.0.0 Changelog (https://github.com/lodash/lodash/wiki/Changelog) @@ -244,7 +244,7 @@ Methods: export = _; export as namespace _; -declare var _: _.LoDashStatic; +declare let _: _.LoDashStatic; type PartialObject = Partial; @@ -253,46 +253,74 @@ declare namespace _ { interface LoDashStatic { /** - * Creates a lodash object which wraps the given value to enable intuitive method chaining. + * Creates a lodash object which wraps value to enable implicit method chain sequences. + * Methods that operate on and return arrays, collections, and functions can be chained together. + * Methods that retrieve a single value or may return a primitive value will automatically end the + * chain sequence and return the unwrapped value. Otherwise, the value must be unwrapped with value(). * - * In addition to Lo-Dash methods, wrappers also have the following Array methods: - * concat, join, pop, push, reverse, shift, slice, sort, splice, and unshift + * Explicit chain sequences, which must be unwrapped with value(), may be enabled using _.chain. * - * Chaining is supported in custom builds as long as the value method is implicitly or - * explicitly included in the build. + * The execution of chained methods is lazy, that is, it's deferred until value() is + * implicitly or explicitly called. * - * The chainable wrapper functions are: - * after, assign, bind, bindAll, bindKey, chain, chunk, compact, compose, concat, countBy, - * createCallback, curry, debounce, defaults, defer, delay, difference, filter, flatten, - * forEach, forEachRight, forIn, forInRight, forOwn, forOwnRight, functions, groupBy, - * keyBy, initial, intersection, invert, invoke, keys, map, max, memoize, merge, min, - * object, omit, once, pairs, partial, partialRight, pick, pluck, pull, push, range, reject, - * remove, rest, reverse, sample, shuffle, slice, sort, sortBy, splice, tap, throttle, times, - * toArray, transform, union, uniq, unset, unshift, unzip, values, where, without, wrap, and zip + * Lazy evaluation allows several methods to support shortcut fusion. Shortcut fusion + * is an optimization to merge iteratee calls; this avoids the creation of intermediate + * arrays and can greatly reduce the number of iteratee executions. Sections of a chain + * sequence qualify for shortcut fusion if the section is applied to an array and iteratees + * accept only one argument. The heuristic for whether a section qualifies for shortcut + * fusion is subject to change. * - * The non-chainable wrapper functions are: - * clone, cloneDeep, contains, escape, every, find, findIndex, findKey, findLast, - * findLastIndex, findLastKey, has, identity, indexOf, isArguments, isArray, isBoolean, - * isDate, isElement, isEmpty, isEqual, isFinite, isFunction, isNaN, isNull, isNumber, - * isObject, isPlainObject, isRegExp, isString, isUndefined, join, lastIndexOf, mixin, - * noConflict, parseInt, pop, random, reduce, reduceRight, result, shift, size, some, - * sortedIndex, runInContext, template, unescape, uniqueId, and value + * Chaining is supported in custom builds as long as the value() method is directly or + * indirectly included in the build. * - * The wrapper functions first and last return wrapped values when n is provided, otherwise - * they return unwrapped values. + * In addition to lodash methods, wrappers have Array and String methods. + * The wrapper Array methods are: + * concat, join, pop, push, shift, sort, splice, and unshift. + * The wrapper String methods are: + * replace and split. * - * Explicit chaining can be enabled by using the _.chain method. + * The wrapper methods that support shortcut fusion are: + * at, compact, drop, dropRight, dropWhile, filter, find, findLast, head, initial, last, + * map, reject, reverse, slice, tail, take, takeRight, takeRightWhile, takeWhile, and toArray + * + * The chainable wrapper methods are: + * after, ary, assign, assignIn, assignInWith, assignWith, at, before, bind, bindAll, bindKey, + * castArray, chain, chunk, commit, compact, concat, conforms, constant, countBy, create, + * curry, debounce, defaults, defaultsDeep, defer, delay, difference, differenceBy, differenceWith, + * drop, dropRight, dropRightWhile, dropWhile, extend, extendWith, fill, filter, flatMap, + * flatMapDeep, flatMapDepth, flatten, flattenDeep, flattenDepth, flip, flow, flowRight, + * fromPairs, functions, functionsIn, groupBy, initial, intersection, intersectionBy, intersectionWith, + * invert, invertBy, invokeMap, iteratee, keyBy, keys, keysIn, map, mapKeys, mapValues, + * matches, matchesProperty, memoize, merge, mergeWith, method, methodOf, mixin, negate, + * nthArg, omit, omitBy, once, orderBy, over, overArgs, overEvery, overSome, partial, partialRight, + * partition, pick, pickBy, plant, property, propertyOf, pull, pullAll, pullAllBy, pullAllWith, pullAt, + * push, range, rangeRight, rearg, reject, remove, rest, reverse, sampleSize, set, setWith, + * shuffle, slice, sort, sortBy, sortedUniq, sortedUniqBy, splice, spread, tail, take, + * takeRight, takeRightWhile, takeWhile, tap, throttle, thru, toArray, toPairs, toPairsIn, + * toPath, toPlainObject, transform, unary, union, unionBy, unionWith, uniq, uniqBy, uniqWith, + * unset, unshift, unzip, unzipWith, update, updateWith, values, valuesIn, without, wrap, + * xor, xorBy, xorWith, zip, zipObject, zipObjectDeep, and zipWith. + * + * The wrapper methods that are not chainable by default are: + * add, attempt, camelCase, capitalize, ceil, clamp, clone, cloneDeep, cloneDeepWith, cloneWith, + * conformsTo, deburr, defaultTo, divide, each, eachRight, endsWith, eq, escape, escapeRegExp, + * every, find, findIndex, findKey, findLast, findLastIndex, findLastKey, first, floor, forEach, + * forEachRight, forIn, forInRight, forOwn, forOwnRight, get, gt, gte, has, hasIn, head, + * identity, includes, indexOf, inRange, invoke, isArguments, isArray, isArrayBuffer, + * isArrayLike, isArrayLikeObject, isBoolean, isBuffer, isDate, isElement, isEmpty, isEqual, isEqualWith, + * isError, isFinite, isFunction, isInteger, isLength, isMap, isMatch, isMatchWith, isNaN, + * isNative, isNil, isNull, isNumber, isObject, isObjectLike, isPlainObject, isRegExp, + * isSafeInteger, isSet, isString, isUndefined, isTypedArray, isWeakMap, isWeakSet, join, + * kebabCase, last, lastIndexOf, lowerCase, lowerFirst, lt, lte, max, maxBy, mean, meanBy, + * min, minBy, multiply, noConflict, noop, now, nth, pad, padEnd, padStart, parseInt, pop, + * random, reduce, reduceRight, repeat, result, round, runInContext, sample, shift, size, + * snakeCase, some, sortedIndex, sortedIndexBy, sortedLastIndex, sortedLastIndexBy, startCase, + * startsWith, stubArray, stubFalse, stubObject, stubString, stubTrue, subtract, sum, sumBy, + * template, times, toFinite, toInteger, toJSON, toLength, toLower, toNumber, toSafeInteger, + * toString, toUpper, trim, trimEnd, trimStart, truncate, unescape, uniqueId, upperCase, + * upperFirst, value, and words. **/ - (value: number): LoDashImplicitWrapper; - (value: string): LoDashImplicitStringWrapper; - (value: boolean): LoDashImplicitWrapper; - (value: null | undefined): LoDashImplicitWrapper; - (value: number[]): LoDashImplicitNumberArrayWrapper; - (value: T[]): LoDashImplicitArrayWrapper; - (value: T[] | null | undefined): LoDashImplicitNillableArrayWrapper; - (value: T): LoDashImplicitObjectWrapper; - (value: T | null | undefined): LoDashImplicitNillableObjectWrapper; - (value: any): LoDashImplicitWrapper; + (value: T): LoDashImplicitWrapper; /** * The semantic version number. @@ -368,7 +396,7 @@ declare namespace _ { * @param value The value to cache. * @return Returns the cache object. */ - set(key: string, value: any): _.Dictionary; + set(key: string, value: any): Dictionary; /** * Removes all key-value entries from the map. @@ -379,66 +407,26 @@ declare namespace _ { new (): MapCache; } - interface LoDashWrapperBase { } + interface LoDashWrapper { } - interface LoDashImplicitWrapperBase extends LoDashWrapperBase { } - - interface LoDashExplicitWrapperBase extends LoDashWrapperBase { } - - interface LoDashImplicitWrapper extends LoDashImplicitWrapperBase> { } - - interface LoDashExplicitWrapper extends LoDashExplicitWrapperBase> { } - - interface LoDashImplicitStringWrapper extends LoDashImplicitWrapper { } - - interface LoDashExplicitStringWrapper extends LoDashExplicitWrapper { } - - interface LoDashImplicitObjectWrapperBase extends LoDashImplicitWrapperBase { } - - interface LoDashImplicitObjectWrapper extends LoDashImplicitObjectWrapperBase> { } - - interface LoDashImplicitNillableObjectWrapper extends LoDashImplicitObjectWrapperBase> { } - - interface LoDashExplicitObjectWrapperBase extends LoDashExplicitWrapperBase { } - - interface LoDashExplicitObjectWrapper extends LoDashExplicitObjectWrapperBase> { } - - interface LoDashExplicitNillableObjectWrapper extends LoDashExplicitObjectWrapperBase> { } - - interface LoDashImplicitArrayWrapperBase extends LoDashImplicitWrapperBase { - pop(): T | undefined; - push(...items: T[]): TWrapper; - shift(): T | undefined; - sort(compareFn?: (a: T, b: T) => number): TWrapper; - splice(start: number): TWrapper; - splice(start: number, deleteCount: number, ...items: T[]): TWrapper; - unshift(...items: T[]): TWrapper; + interface LoDashImplicitWrapper extends LoDashWrapper { + pop(this: LoDashImplicitWrapper | null | undefined>): T | undefined; + push(this: LoDashImplicitWrapper | null | undefined>, ...items: T[]): this; + shift(this: LoDashImplicitWrapper | null | undefined>): T | undefined; + sort(this: LoDashImplicitWrapper | null | undefined>, compareFn?: (a: T, b: T) => number): this; + splice(this: LoDashImplicitWrapper | null | undefined>, start: number, deleteCount?: number, ...items: T[]): this; + unshift(this: LoDashImplicitWrapper | null | undefined>, ...items: T[]): this; } - interface LoDashImplicitArrayWrapper extends LoDashImplicitArrayWrapperBase> { } - - interface LoDashImplicitNillableArrayWrapper extends LoDashImplicitArrayWrapperBase> { } - - interface LoDashImplicitNumberArrayWrapperBase extends LoDashImplicitArrayWrapperBase { } - - interface LoDashImplicitNumberArrayWrapper extends LoDashImplicitArrayWrapper { } - - interface LoDashExplicitArrayWrapperBase extends LoDashExplicitWrapperBase { - pop(): LoDashExplicitObjectWrapper; - push(...items: T[]): TWrapper; - shift(): LoDashExplicitObjectWrapper; - sort(compareFn?: (a: T, b: T) => number): TWrapper; - splice(start: number): TWrapper; - splice(start: number, deleteCount: number, ...items: T[]): TWrapper; - unshift(...items: T[]): TWrapper; + interface LoDashExplicitWrapper extends LoDashWrapper { + pop(this: LoDashExplicitWrapper | null | undefined>): LoDashExplicitWrapper; + push(this: LoDashExplicitWrapper | null | undefined>, ...items: T[]): this; + shift(this: LoDashExplicitWrapper | null | undefined>): LoDashExplicitWrapper; + sort(this: LoDashExplicitWrapper | null | undefined>, compareFn?: (a: T, b: T) => number): this; + splice(this: LoDashExplicitWrapper | null | undefined>, start: number, deleteCount?: number, ...items: T[]): this; + unshift(this: LoDashExplicitWrapper | null | undefined>, ...items: T[]): this; } - interface LoDashExplicitArrayWrapper extends LoDashExplicitArrayWrapperBase> { } - - interface LoDashExplicitNillableArrayWrapper extends LoDashExplicitArrayWrapperBase> { } - - interface LoDashExplicitNumberArrayWrapper extends LoDashExplicitArrayWrapper { } - /********* * Array * *********/ @@ -459,32 +447,24 @@ declare namespace _ { ): T[][]; } - interface LoDashImplicitArrayWrapperBase { + interface LoDashImplicitWrapper { /** * @see _.chunk */ - chunk(size?: number): LoDashImplicitArrayWrapper; + chunk( + this: LoDashImplicitWrapper | null | undefined>, + size?: number, + ): LoDashImplicitWrapper; } - interface LoDashImplicitObjectWrapperBase { + interface LoDashExplicitWrapper { /** * @see _.chunk */ - chunk(size?: number): LoDashImplicitArrayWrapper; - } - - interface LoDashExplicitArrayWrapperBase { - /** - * @see _.chunk - */ - chunk(size?: number): LoDashExplicitArrayWrapper; - } - - interface LoDashExplicitObjectWrapperBase { - /** - * @see _.chunk - */ - chunk(size?: number): LoDashExplicitArrayWrapper; + chunk( + this: LoDashExplicitWrapper | null | undefined>, + size?: number, + ): LoDashExplicitWrapper; } //_.compact @@ -499,35 +479,21 @@ declare namespace _ { compact(array?: List | null | undefined): T[]; } - interface LoDashImplicitArrayWrapperBase { + interface LoDashImplicitWrapper { /** * @see _.compact */ - compact(): LoDashImplicitArrayWrapper; + compact(this: LoDashImplicitWrapper | null | undefined>): LoDashImplicitWrapper; } - interface LoDashImplicitObjectWrapperBase { + interface LoDashExplicitWrapper { /** * @see _.compact */ - compact(): LoDashImplicitArrayWrapper; + compact(this: LoDashExplicitWrapper | null | undefined>): LoDashExplicitWrapper; } - interface LoDashExplicitArrayWrapperBase { - /** - * @see _.compact - */ - compact(): LoDashExplicitArrayWrapper; - } - - interface LoDashExplicitObjectWrapperBase { - /** - * @see _.compact - */ - compact(): LoDashExplicitArrayWrapper; - } - - //_.concat DUMMY + //_.concat interface LoDashStatic { /** * Creates a new array concatenating `array` with any additional arrays @@ -550,7 +516,21 @@ declare namespace _ { * console.log(array); * // => [1] */ - concat(array: List, ...values: Array>): T[]; + concat(array: Many, ...values: Array>): T[]; + } + + interface LoDashImplicitWrapper { + /** + * @see _.compact + */ + concat(this: LoDashImplicitWrapper>, ...values: Array>): LoDashImplicitWrapper; + } + + interface LoDashExplicitWrapper { + /** + * @see _.compact + */ + concat(this: LoDashExplicitWrapper>, ...values: Array>): LoDashExplicitWrapper; } //_.difference @@ -569,32 +549,24 @@ declare namespace _ { ): T[]; } - interface LoDashImplicitArrayWrapperBase { + interface LoDashImplicitWrapper { /** * @see _.difference */ - difference(...values: Array>): LoDashImplicitArrayWrapper; + difference( + this: LoDashImplicitWrapper | null | undefined>, + ...values: Array> + ): LoDashImplicitWrapper; } - interface LoDashImplicitObjectWrapperBase { + interface LoDashExplicitWrapper { /** * @see _.difference */ - difference(...values: Array>): LoDashImplicitArrayWrapper; - } - - interface LoDashExplicitArrayWrapperBase { - /** - * @see _.difference - */ - difference(...values: Array>): LoDashExplicitArrayWrapper; - } - - interface LoDashExplicitObjectWrapperBase { - /** - * @see _.difference - */ - difference(...values: Array>): LoDashExplicitArrayWrapper; + difference( + this: LoDashExplicitWrapper | null | undefined>, + ...values: Array> + ): LoDashExplicitWrapper; } //_.differenceBy @@ -612,16 +584,7 @@ declare namespace _ { differenceBy( array: List | null | undefined, values?: List, - iteratee?: ((value: T) => any)|string - ): T[]; - - /** - * @see _.differenceBy - */ - differenceBy( - array: List | null | undefined, - values?: List, - iteratee?: W + iteratee?: ValueIteratee ): T[]; /** @@ -629,19 +592,9 @@ declare namespace _ { */ differenceBy( array: List | null | undefined, - values1?: List, - values2?: List, - iteratee?: ((value: T) => any)|string - ): T[]; - - /** - * @see _.differenceBy - */ - differenceBy( - array: List | null | undefined, - values1?: List, - values2?: List, - iteratee?: W + values1: List, + values2: List, + iteratee?: ValueIteratee ): T[]; /** @@ -649,33 +602,10 @@ declare namespace _ { */ differenceBy( array: List | null | undefined, - values1?: List, - values2?: List, - values3?: List, - iteratee?: ((value: T) => any)|string - ): T[]; - - /** - * @see _.differenceBy - */ - differenceBy( - array: List | null | undefined, - values1?: List, - values2?: List, - values3?: List, - iteratee?: W - ): T[]; - - /** - * @see _.differenceBy - */ - differenceBy( - array: List | null | undefined, - values1?: List, - values2?: List, - values3?: List, - values4?: List, - iteratee?: W + values1: List, + values2: List, + values3: List, + iteratee?: ValueIteratee ): T[]; /** @@ -683,11 +613,11 @@ declare namespace _ { */ differenceBy( array: List | null | undefined, - values1?: List, - values2?: List, - values3?: List, - values4?: List, - iteratee?: ((value: T) => any)|string + values1: List, + values2: List, + values3: List, + values4: List, + iteratee?: ValueIteratee ): T[]; /** @@ -695,25 +625,12 @@ declare namespace _ { */ differenceBy( array: List | null | undefined, - values1?: List, - values2?: List, - values3?: List, - values4?: List, - values5?: List, - iteratee?: ((value: T) => any)|string - ): T[]; - - /** - * @see _.differenceBy - */ - differenceBy( - array: List | null | undefined, - values1?: List, - values2?: List, - values3?: List, - values4?: List, - values5?: List, - iteratee?: W + values1: List, + values2: List, + values3: List, + values4: List, + values5: List, + iteratee?: ValueIteratee ): T[]; /** @@ -721,447 +638,141 @@ declare namespace _ { */ differenceBy( array: List | null | undefined, - ...values: any[] + ...values: Array | ValueIteratee> ): T[]; } - interface LoDashImplicitArrayWrapperBase { + interface LoDashImplicitWrapper { /** * @see _.differenceBy */ differenceBy( + this: LoDashImplicitWrapper | null | undefined>, values?: List, - iteratee?: ((value: T) => any)|string - ): LoDashImplicitArrayWrapper; - - /** - * @see _.differenceBy - */ - differenceBy( - values?: List, - iteratee?: W - ): LoDashImplicitArrayWrapper; + iteratee?: ValueIteratee + ): LoDashImplicitWrapper; /** * @see _.differenceBy */ differenceBy( - values1?: List, - values2?: List, - iteratee?: ((value: T) => any)|string - ): LoDashImplicitArrayWrapper; - - /** - * @see _.differenceBy - */ - differenceBy( - values1?: List, - values2?: List, - iteratee?: W - ): LoDashImplicitArrayWrapper; + this: LoDashImplicitWrapper | null | undefined>, + values1: List, + values2: List, + iteratee?: ValueIteratee + ): LoDashImplicitWrapper; /** * @see _.differenceBy */ differenceBy( - values1?: List, - values2?: List, - values3?: List, - iteratee?: ((value: T) => any)|string - ): LoDashImplicitArrayWrapper; - - /** - * @see _.differenceBy - */ - differenceBy( - values1?: List, - values2?: List, - values3?: List, - iteratee?: W - ): LoDashImplicitArrayWrapper; + this: LoDashImplicitWrapper | null | undefined>, + values1: List, + values2: List, + values3: List, + iteratee?: ValueIteratee + ): LoDashImplicitWrapper; /** * @see _.differenceBy */ differenceBy( - values1?: List, - values2?: List, - values3?: List, - values4?: List, - iteratee?: ((value: T) => any)|string - ): LoDashImplicitArrayWrapper; - - /** - * @see _.differenceBy - */ - differenceBy( - values1?: List, - values2?: List, - values3?: List, - values4?: List, - iteratee?: W - ): LoDashImplicitArrayWrapper; + this: LoDashImplicitWrapper | null | undefined>, + values1: List, + values2: List, + values3: List, + values4: List, + iteratee?: ValueIteratee + ): LoDashImplicitWrapper; /** * @see _.differenceBy */ differenceBy( - values1?: List, - values2?: List, - values3?: List, - values4?: List, - values5?: List, - iteratee?: ((value: T) => any)|string - ): LoDashImplicitArrayWrapper; - - /** - * @see _.differenceBy - */ - differenceBy( - values1?: List, - values2?: List, - values3?: List, - values4?: List, - values5?: List, - iteratee?: W - ): LoDashImplicitArrayWrapper; + this: LoDashImplicitWrapper | null | undefined>, + values1: List, + values2: List, + values3: List, + values4: List, + values5: List, + iteratee?: ValueIteratee + ): LoDashImplicitWrapper; /** * @see _.differenceBy */ differenceBy( - ...values: any[] - ): LoDashImplicitArrayWrapper; + this: LoDashImplicitWrapper | null | undefined>, + ...values: Array | ValueIteratee> + ): LoDashImplicitWrapper; } - interface LoDashImplicitObjectWrapperBase { + interface LoDashExplicitWrapper { /** * @see _.differenceBy */ differenceBy( + this: LoDashExplicitWrapper | null | undefined>, values?: List, - iteratee?: ((value: T) => any)|string - ): LoDashImplicitArrayWrapper; - - /** - * @see _.differenceBy - */ - differenceBy( - values?: List, - iteratee?: W - ): LoDashImplicitArrayWrapper; + iteratee?: ValueIteratee + ): LoDashExplicitWrapper; /** * @see _.differenceBy */ differenceBy( - values1?: List, - values2?: List, - iteratee?: ((value: T) => any)|string - ): LoDashImplicitArrayWrapper; - - /** - * @see _.differenceBy - */ - differenceBy( - values1?: List, - values2?: List, - iteratee?: W - ): LoDashImplicitArrayWrapper; + this: LoDashExplicitWrapper | null | undefined>, + values1: List, + values2: List, + iteratee?: ValueIteratee + ): LoDashExplicitWrapper; /** * @see _.differenceBy */ differenceBy( - values1?: List, - values2?: List, - values3?: List, - iteratee?: ((value: T) => any)|string - ): LoDashImplicitArrayWrapper; - - /** - * @see _.differenceBy - */ - differenceBy( - values1?: List, - values2?: List, - values3?: List, - iteratee?: W - ): LoDashImplicitArrayWrapper; + this: LoDashExplicitWrapper | null | undefined>, + values1: List, + values2: List, + values3: List, + iteratee?: ValueIteratee + ): LoDashExplicitWrapper; /** * @see _.differenceBy */ differenceBy( - values1?: List, - values2?: List, - values3?: List, - values4?: List, - iteratee?: ((value: T) => any)|string - ): LoDashImplicitArrayWrapper; - - /** - * @see _.differenceBy - */ - differenceBy( - values1?: List, - values2?: List, - values3?: List, - values4?: List, - iteratee?: W - ): LoDashImplicitArrayWrapper; + this: LoDashExplicitWrapper | null | undefined>, + values1: List, + values2: List, + values3: List, + values4: List, + iteratee?: ValueIteratee + ): LoDashExplicitWrapper; /** * @see _.differenceBy */ differenceBy( - values1?: List, - values2?: List, - values3?: List, - values4?: List, - values5?: List, - iteratee?: ((value: T) => any)|string - ): LoDashImplicitArrayWrapper; - - /** - * @see _.differenceBy - */ - differenceBy( - values1?: List, - values2?: List, - values3?: List, - values4?: List, - values5?: List, - iteratee?: W - ): LoDashImplicitArrayWrapper; + this: LoDashExplicitWrapper | null | undefined>, + values1: List, + values2: List, + values3: List, + values4: List, + values5: List, + iteratee?: ValueIteratee + ): LoDashExplicitWrapper; /** * @see _.differenceBy */ differenceBy( - ...values: any[] - ): LoDashImplicitArrayWrapper; + this: LoDashExplicitWrapper | null | undefined>, + ...values: Array | ValueIteratee> + ): LoDashExplicitWrapper; } - interface LoDashExplicitArrayWrapperBase { - /** - * @see _.differenceBy - */ - differenceBy( - values?: List, - iteratee?: ((value: T) => any)|string - ): LoDashExplicitArrayWrapper; - - /** - * @see _.differenceBy - */ - differenceBy( - values?: List, - iteratee?: W - ): LoDashExplicitArrayWrapper; - - /** - * @see _.differenceBy - */ - differenceBy( - values1?: List, - values2?: List, - iteratee?: ((value: T) => any)|string - ): LoDashExplicitArrayWrapper; - - /** - * @see _.differenceBy - */ - differenceBy( - values1?: List, - values2?: List, - iteratee?: W - ): LoDashExplicitArrayWrapper; - - /** - * @see _.differenceBy - */ - differenceBy( - values1?: List, - values2?: List, - values3?: List, - iteratee?: ((value: T) => any)|string - ): LoDashExplicitArrayWrapper; - - /** - * @see _.differenceBy - */ - differenceBy( - values1?: List, - values2?: List, - values3?: List, - iteratee?: W - ): LoDashExplicitArrayWrapper; - - /** - * @see _.differenceBy - */ - differenceBy( - values1?: List, - values2?: List, - values3?: List, - values4?: List, - iteratee?: ((value: T) => any)|string - ): LoDashExplicitArrayWrapper; - - /** - * @see _.differenceBy - */ - differenceBy( - values1?: List, - values2?: List, - values3?: List, - values4?: List, - iteratee?: W - ): LoDashExplicitArrayWrapper; - - /** - * @see _.differenceBy - */ - differenceBy( - values1?: List, - values2?: List, - values3?: List, - values4?: List, - values5?: List, - iteratee?: ((value: T) => any)|string - ): LoDashExplicitArrayWrapper; - - /** - * @see _.differenceBy - */ - differenceBy( - values1?: List, - values2?: List, - values3?: List, - values4?: List, - values5?: List, - iteratee?: W - ): LoDashExplicitArrayWrapper; - - /** - * @see _.differenceBy - */ - differenceBy( - ...values: any[] - ): LoDashExplicitArrayWrapper; - } - - interface LoDashExplicitObjectWrapperBase { - /** - * @see _.differenceBy - */ - differenceBy( - values?: List, - iteratee?: ((value: T) => any)|string - ): LoDashExplicitArrayWrapper; - - /** - * @see _.differenceBy - */ - differenceBy( - values?: List, - iteratee?: W - ): LoDashExplicitArrayWrapper; - - /** - * @see _.differenceBy - */ - differenceBy( - values1?: List, - values2?: List, - iteratee?: ((value: T) => any)|string - ): LoDashExplicitArrayWrapper; - - /** - * @see _.differenceBy - */ - differenceBy( - values1?: List, - values2?: List, - iteratee?: W - ): LoDashExplicitArrayWrapper; - - /** - * @see _.differenceBy - */ - differenceBy( - values1?: List, - values2?: List, - values3?: List, - iteratee?: ((value: T) => any)|string - ): LoDashExplicitArrayWrapper; - - /** - * @see _.differenceBy - */ - differenceBy( - values1?: List, - values2?: List, - values3?: List, - iteratee?: W - ): LoDashExplicitArrayWrapper; - - /** - * @see _.differenceBy - */ - differenceBy( - values1?: List, - values2?: List, - values3?: List, - values4?: List, - iteratee?: ((value: T) => any)|string - ): LoDashExplicitArrayWrapper; - - /** - * @see _.differenceBy - */ - differenceBy( - values1?: List, - values2?: List, - values3?: List, - values4?: List, - iteratee?: W - ): LoDashExplicitArrayWrapper; - - /** - * @see _.differenceBy - */ - differenceBy( - values1?: List, - values2?: List, - values3?: List, - values4?: List, - values5?: List, - iteratee?: ((value: T) => any)|string - ): LoDashExplicitArrayWrapper; - - /** - * @see _.differenceBy - */ - differenceBy( - values1?: List, - values2?: List, - values3?: List, - values4?: List, - values5?: List, - iteratee?: W - ): LoDashExplicitArrayWrapper; - - /** - * @see _.differenceBy - */ - differenceBy( - ...values: any[] - ): LoDashExplicitArrayWrapper; - } - - //_.differenceWith DUMMY + //_.differenceWith interface LoDashStatic { /** * Creates an array of unique `array` values not included in the other @@ -1171,18 +782,67 @@ declare namespace _ { * @static * @memberOf _ * @category Array - * @param {Array} array The array to inspect. - * @param {...Array} [values] The values to exclude. + * @param {...Array} [values] The arrays to inspect. + * @param {Function} [comparator] The comparator invoked per element. * @returns {Array} Returns the new array of filtered values. * @example * - * _.difference([3, 2, 1], [4, 2]); - * // => [3, 1] + * var objects = [{ 'x': 1, 'y': 2 }, { 'x': 2, 'y': 1 }]; + + * _.differenceWith(objects, [{ 'x': 1, 'y': 2 }], _.isEqual); + * // => [{ 'x': 2, 'y': 1 }] */ - differenceWith( - array: List, - ...values: any[] - ): any[]; + differenceWith( + array: List | null | undefined, + values?: List, + comparator?: Comparator + ): T[]; + + /** + * @see _.differenceWith + */ + differenceWith( + array: List | null | undefined, + ...values: Array | Comparator>, + ): T[]; + } + + interface LoDashImplicitWrapper { + /** + * @see _.differenceWith + */ + differenceWith( + this: LoDashImplicitWrapper | null | undefined>, + values?: List, + comparator?: Comparator + ): LoDashImplicitWrapper; + + /** + * @see _.differenceWith + */ + differenceWith( + this: LoDashImplicitWrapper | null | undefined>, + ...values: Array | Comparator>, + ): LoDashImplicitWrapper; + } + + interface LoDashExplicitWrapper { + /** + * @see _.differenceWith + */ + differenceWith( + this: LoDashExplicitWrapper | null | undefined>, + values?: List, + comparator?: Comparator + ): LoDashExplicitWrapper; + + /** + * @see _.differenceWith + */ + differenceWith( + this: LoDashExplicitWrapper | null | undefined>, + ...values: Array | Comparator>, + ): LoDashExplicitWrapper; } //_.drop @@ -1197,32 +857,18 @@ declare namespace _ { drop(array: List | null | undefined, n?: number): T[]; } - interface LoDashImplicitArrayWrapperBase { + interface LoDashImplicitWrapper { /** * @see _.drop */ - drop(n?: number): LoDashImplicitArrayWrapper; + drop(this: LoDashImplicitWrapper | null | undefined>, n?: number): LoDashImplicitWrapper; } - interface LoDashImplicitObjectWrapperBase { + interface LoDashExplicitWrapper { /** * @see _.drop */ - drop(n?: number): LoDashImplicitArrayWrapper; - } - - interface LoDashExplicitArrayWrapperBase { - /** - * @see _.drop - */ - drop(n?: number): LoDashExplicitArrayWrapper; - } - - interface LoDashExplicitObjectWrapperBase { - /** - * @see _.drop - */ - drop(n?: number): LoDashExplicitArrayWrapper; + drop(this: LoDashExplicitWrapper | null | undefined>, n?: number): LoDashExplicitWrapper; } //_.dropRight @@ -1240,32 +886,18 @@ declare namespace _ { ): T[]; } - interface LoDashImplicitArrayWrapperBase { + interface LoDashImplicitWrapper { /** * @see _.dropRight */ - dropRight(n?: number): LoDashImplicitArrayWrapper; + dropRight(this: LoDashImplicitWrapper | null | undefined>, n?: number): LoDashImplicitWrapper; } - interface LoDashImplicitObjectWrapperBase { + interface LoDashExplicitWrapper { /** * @see _.dropRight */ - dropRight(n?: number): LoDashImplicitArrayWrapper; - } - - interface LoDashExplicitArrayWrapperBase { - /** - * @see _.dropRight - */ - dropRight(n?: number): LoDashExplicitArrayWrapper; - } - - interface LoDashExplicitObjectWrapperBase { - /** - * @see _.dropRight - */ - dropRight(n?: number): LoDashExplicitArrayWrapper; + dropRight(this: LoDashExplicitWrapper | null | undefined>, n?: number): LoDashExplicitWrapper; } //_.dropRightWhile @@ -1288,118 +920,30 @@ declare namespace _ { * @param thisArg The this binding of predicate. * @return Returns the slice of array. */ - dropRightWhile( - array: List | null | undefined, - predicate?: ListIterator - ): TValue[]; - - /** - * @see _.dropRightWhile - */ - dropRightWhile( - array: List | null | undefined, - predicate?: string - ): TValue[]; - - /** - * @see _.dropRightWhile - */ - dropRightWhile( - array: List | null | undefined, - predicate?: TWhere - ): TValue[]; + dropRightWhile( + array: List | null | undefined, + predicate?: ListIteratee + ): T[]; } - interface LoDashImplicitArrayWrapperBase { + interface LoDashImplicitWrapper { /** * @see _.dropRightWhile */ - dropRightWhile( - predicate?: ListIterator - ): LoDashImplicitArrayWrapper; - - /** - * @see _.dropRightWhile - */ - dropRightWhile( - predicate?: string - ): LoDashImplicitArrayWrapper; - - /** - * @see _.dropRightWhile - */ - dropRightWhile( - predicate?: TWhere - ): LoDashImplicitArrayWrapper; + dropRightWhile( + this: LoDashImplicitWrapper | null | undefined>, + predicate?: ListIteratee + ): LoDashImplicitWrapper; } - interface LoDashImplicitObjectWrapperBase { + interface LoDashExplicitWrapper { /** * @see _.dropRightWhile */ - dropRightWhile( - predicate?: ListIterator - ): LoDashImplicitArrayWrapper; - - /** - * @see _.dropRightWhile - */ - dropRightWhile( - predicate?: string - ): LoDashImplicitArrayWrapper; - - /** - * @see _.dropRightWhile - */ - dropRightWhile( - predicate?: TWhere - ): LoDashImplicitArrayWrapper; - } - - interface LoDashExplicitArrayWrapperBase { - /** - * @see _.dropRightWhile - */ - dropRightWhile( - predicate?: ListIterator - ): LoDashExplicitArrayWrapper; - - /** - * @see _.dropRightWhile - */ - dropRightWhile( - predicate?: string - ): LoDashExplicitArrayWrapper; - - /** - * @see _.dropRightWhile - */ - dropRightWhile( - predicate?: TWhere - ): LoDashExplicitArrayWrapper; - } - - interface LoDashExplicitObjectWrapperBase { - /** - * @see _.dropRightWhile - */ - dropRightWhile( - predicate?: ListIterator - ): LoDashExplicitArrayWrapper; - - /** - * @see _.dropRightWhile - */ - dropRightWhile( - predicate?: string - ): LoDashExplicitArrayWrapper; - - /** - * @see _.dropRightWhile - */ - dropRightWhile( - predicate?: TWhere - ): LoDashExplicitArrayWrapper; + dropRightWhile( + this: LoDashExplicitWrapper | null | undefined>, + predicate?: ListIteratee + ): LoDashExplicitWrapper; } //_.dropWhile @@ -1422,118 +966,30 @@ declare namespace _ { * @param thisArg The this binding of predicate. * @return Returns the slice of array. */ - dropWhile( - array: List | null | undefined, - predicate?: ListIterator - ): TValue[]; - - /** - * @see _.dropWhile - */ - dropWhile( - array: List | null | undefined, - predicate?: string - ): TValue[]; - - /** - * @see _.dropWhile - */ - dropWhile( - array: List | null | undefined, - predicate?: TWhere - ): TValue[]; + dropWhile( + array: List | null | undefined, + predicate?: ListIteratee + ): T[]; } - interface LoDashImplicitArrayWrapperBase { + interface LoDashImplicitWrapper { /** * @see _.dropWhile */ - dropWhile( - predicate?: ListIterator - ): LoDashImplicitArrayWrapper; - - /** - * @see _.dropWhile - */ - dropWhile( - predicate?: string - ): LoDashImplicitArrayWrapper; - - /** - * @see _.dropWhile - */ - dropWhile( - predicate?: TWhere - ): LoDashImplicitArrayWrapper; + dropWhile( + this: LoDashImplicitWrapper | null | undefined>, + predicate?: ListIteratee + ): LoDashImplicitWrapper; } - interface LoDashImplicitObjectWrapperBase { + interface LoDashExplicitWrapper { /** * @see _.dropWhile */ - dropWhile( - predicate?: ListIterator - ): LoDashImplicitArrayWrapper; - - /** - * @see _.dropWhile - */ - dropWhile( - predicate?: string - ): LoDashImplicitArrayWrapper; - - /** - * @see _.dropWhile - */ - dropWhile( - predicate?: TWhere - ): LoDashImplicitArrayWrapper; - } - - interface LoDashExplicitArrayWrapperBase { - /** - * @see _.dropWhile - */ - dropWhile( - predicate?: ListIterator - ): LoDashExplicitArrayWrapper; - - /** - * @see _.dropWhile - */ - dropWhile( - predicate?: string - ): LoDashExplicitArrayWrapper; - - /** - * @see _.dropWhile - */ - dropWhile( - predicate?: TWhere - ): LoDashExplicitArrayWrapper; - } - - interface LoDashExplicitObjectWrapperBase { - /** - * @see _.dropWhile - */ - dropWhile( - predicate?: ListIterator - ): LoDashExplicitArrayWrapper; - - /** - * @see _.dropWhile - */ - dropWhile( - predicate?: string - ): LoDashExplicitArrayWrapper; - - /** - * @see _.dropWhile - */ - dropWhile( - predicate?: TWhere - ): LoDashExplicitArrayWrapper; + dropWhile( + this: LoDashExplicitWrapper | null | undefined>, + predicate?: ListIteratee + ): LoDashExplicitWrapper; } //_.fill @@ -1551,9 +1007,7 @@ declare namespace _ { */ fill( array: any[] | null | undefined, - value: T, - start?: number, - end?: number + value: T ): T[]; /** @@ -1561,54 +1015,104 @@ declare namespace _ { */ fill( array: List | null | undefined, - value: T, - start?: number, - end?: number + value: T ): List; + + /** + * @see _.fill + */ + fill( + array: U[] | null | undefined, + value: T, + start?: number, + end?: number + ): Array; + + /** + * @see _.fill + */ + fill( + array: List | null | undefined, + value: T, + start?: number, + end?: number + ): List; } - interface LoDashImplicitArrayWrapperBase { + interface LoDashImplicitWrapper { /** * @see _.fill */ fill( - value: T, - start?: number, - end?: number - ): LoDashImplicitArrayWrapper; - } + this: LoDashImplicitWrapper, + value: T + ): LoDashImplicitWrapper; - interface LoDashImplicitObjectWrapperBase { /** * @see _.fill */ fill( + this: LoDashImplicitWrapper | null | undefined>, + value: T + ): LoDashImplicitWrapper>; + + /** + * @see _.fill + */ + fill( + this: LoDashImplicitWrapper, value: T, start?: number, end?: number - ): LoDashImplicitObjectWrapper>; + ): LoDashImplicitWrapper>; + + /** + * @see _.fill + */ + fill( + this: LoDashImplicitWrapper | null | undefined>, + value: T, + start?: number, + end?: number + ): LoDashImplicitWrapper>; } - interface LoDashExplicitArrayWrapperBase { + interface LoDashExplicitWrapper { /** * @see _.fill */ fill( - value: T, - start?: number, - end?: number - ): LoDashExplicitArrayWrapper; - } + this: LoDashExplicitWrapper, + value: T + ): LoDashExplicitWrapper; - interface LoDashExplicitObjectWrapperBase { /** * @see _.fill */ fill( + this: LoDashExplicitWrapper | null | undefined>, + value: T + ): LoDashExplicitWrapper>; + + /** + * @see _.fill + */ + fill( + this: LoDashExplicitWrapper, value: T, start?: number, end?: number - ): LoDashExplicitObjectWrapper>; + ): LoDashExplicitWrapper>; + + /** + * @see _.fill + */ + fill( + this: LoDashExplicitWrapper | null | undefined>, + value: T, + start?: number, + end?: number + ): LoDashExplicitWrapper>; } //_.findIndex @@ -1633,129 +1137,29 @@ declare namespace _ { */ findIndex( array: List | null | undefined, - predicate?: ListIterator, + predicate?: ListIteratee, fromIndex?: number ): number; + } + interface LoDashImplicitWrapper { /** * @see _.findIndex */ findIndex( - array: List | null | undefined, - predicate?: string, - fromIndex?: number - ): number; - - /** - * @see _.findIndex - */ - findIndex( - array: List | null | undefined, - predicate?: W, + this: LoDashImplicitWrapper | null | undefined>, + predicate?: ListIteratee, fromIndex?: number ): number; } - interface LoDashImplicitArrayWrapperBase { + interface LoDashExplicitWrapper { /** * @see _.findIndex */ - findIndex( - predicate?: ListIterator, - fromIndex?: number - ): number; - - /** - * @see _.findIndex - */ - findIndex( - predicate?: string, - fromIndex?: number - ): number; - - /** - * @see _.findIndex - */ - findIndex( - predicate?: W, - fromIndex?: number - ): number; - } - - interface LoDashImplicitObjectWrapperBase { - /** - * @see _.findIndex - */ - findIndex( - predicate?: ListIterator, - fromIndex?: number - ): number; - - /** - * @see _.findIndex - */ - findIndex( - predicate?: string, - fromIndex?: number - ): number; - - /** - * @see _.findIndex - */ - findIndex( - predicate?: W, - fromIndex?: number - ): number; - } - - interface LoDashExplicitArrayWrapperBase { - /** - * @see _.findIndex - */ - findIndex( - predicate?: ListIterator, - fromIndex?: number - ): LoDashExplicitWrapper; - - /** - * @see _.findIndex - */ - findIndex( - predicate?: string, - fromIndex?: number - ): LoDashExplicitWrapper; - - /** - * @see _.findIndex - */ - findIndex( - predicate?: W, - fromIndex?: number - ): LoDashExplicitWrapper; - } - - interface LoDashExplicitObjectWrapperBase { - /** - * @see _.findIndex - */ - findIndex( - predicate?: ListIterator, - fromIndex?: number - ): LoDashExplicitWrapper; - - /** - * @see _.findIndex - */ - findIndex( - predicate?: string, - fromIndex?: number - ): LoDashExplicitWrapper; - - /** - * @see _.findIndex - */ - findIndex( - predicate?: W, + findIndex( + this: LoDashExplicitWrapper | null | undefined>, + predicate?: ListIteratee, fromIndex?: number ): LoDashExplicitWrapper; } @@ -1781,185 +1185,53 @@ declare namespace _ { */ findLastIndex( array: List | null | undefined, - predicate?: ListIterator, + predicate?: ListIteratee, fromIndex?: number ): number; + } + interface LoDashImplicitWrapper { /** * @see _.findLastIndex */ findLastIndex( - array: List | null | undefined, - predicate?: string, - fromIndex?: number - ): number; - - /** - * @see _.findLastIndex - */ - findLastIndex( - array: List | null | undefined, - predicate?: W, + this: LoDashImplicitWrapper | null | undefined>, + predicate?: ListIteratee, fromIndex?: number ): number; } - interface LoDashImplicitArrayWrapperBase { + interface LoDashExplicitWrapper { /** * @see _.findLastIndex */ - findLastIndex( - predicate?: ListIterator, - fromIndex?: number - ): number; - - /** - * @see _.findLastIndex - */ - findLastIndex( - predicate?: string, - fromIndex?: number - ): number; - - /** - * @see _.findLastIndex - */ - findLastIndex( - predicate?: W, - fromIndex?: number - ): number; - } - - interface LoDashImplicitObjectWrapperBase { - /** - * @see _.findLastIndex - */ - findLastIndex( - predicate?: ListIterator, - fromIndex?: number - ): number; - - /** - * @see _.findLastIndex - */ - findLastIndex( - predicate?: string, - fromIndex?: number - ): number; - - /** - * @see _.findLastIndex - */ - findLastIndex( - predicate?: W, - fromIndex?: number - ): number; - } - - interface LoDashExplicitArrayWrapperBase { - /** - * @see _.findLastIndex - */ - findLastIndex( - predicate?: ListIterator, - fromIndex?: number - ): LoDashExplicitWrapper; - - /** - * @see _.findLastIndex - */ - findLastIndex( - predicate?: string, - fromIndex?: number - ): LoDashExplicitWrapper; - - /** - * @see _.findLastIndex - */ - findLastIndex( - predicate?: W, - fromIndex?: number - ): LoDashExplicitWrapper; - } - - interface LoDashExplicitObjectWrapperBase { - /** - * @see _.findLastIndex - */ - findLastIndex( - predicate?: ListIterator, - fromIndex?: number - ): LoDashExplicitWrapper; - - /** - * @see _.findLastIndex - */ - findLastIndex( - predicate?: string, - fromIndex?: number - ): LoDashExplicitWrapper; - - /** - * @see _.findLastIndex - */ - findLastIndex( - predicate?: W, + findLastIndex( + this: LoDashExplicitWrapper | null | undefined>, + predicate?: ListIteratee, fromIndex?: number ): LoDashExplicitWrapper; } //_.first interface LoDashStatic { - /** - * @see _.head - */ - first(array: List | null | undefined): T | undefined; + first: typeof _.head; // tslint:disable-line:no-unnecessary-qualifier } - interface LoDashImplicitWrapper { + interface LoDashImplicitWrapper { /** * @see _.head */ - first(): string | undefined; + first(this: LoDashImplicitWrapper | null | undefined>): T | undefined; } - interface LoDashImplicitArrayWrapperBase { + interface LoDashExplicitWrapper { /** * @see _.head */ - first(): T | undefined; - } - - interface LoDashImplicitObjectWrapperBase { - /** - * @see _.head - */ - first(): T | undefined; - } - - interface LoDashExplicitWrapper { - /** - * @see _.head - */ - first(): LoDashExplicitWrapper; - } - - interface LoDashExplicitArrayWrapperBase { - /** - * @see _.head - */ - first(): T; - } - - interface LoDashExplicitObjectWrapperBase { - /** - * @see _.head - */ - first(): T; + first(this: LoDashExplicitWrapper | null | undefined>): LoDashExplicitWrapper; } interface RecursiveArray extends Array> {} - interface ListOfRecursiveArraysOrValues extends List> {} //_.flatten @@ -1978,53 +1250,30 @@ declare namespace _ { * @see _.flatten */ flatten(array: List> | null | undefined): T[]; - - /** - * @see _.flatten - */ - flatten(array: ListOfRecursiveArraysOrValues | null | undefined): RecursiveArray; } - interface LoDashImplicitWrapper { + interface LoDashImplicitWrapper { /** * @see _.flatten */ - flatten(): LoDashImplicitArrayWrapper; + flatten(this: LoDashImplicitWrapper | null | undefined>, isDeep: boolean): LoDashImplicitWrapper; + + /** + * @see _.flatten + */ + flatten(this: LoDashImplicitWrapper> | null | undefined>): LoDashImplicitWrapper; } - interface LoDashImplicitArrayWrapperBase { + interface LoDashExplicitWrapper { /** * @see _.flatten */ - flatten(isDeep?: boolean): LoDashImplicitArrayWrapper; - } + flatten(this: LoDashExplicitWrapper | null | undefined>, isDeep: boolean): LoDashExplicitWrapper; - interface LoDashImplicitObjectWrapperBase { /** * @see _.flatten */ - flatten(isDeep?: boolean): LoDashImplicitArrayWrapper; - } - - interface LoDashExplicitWrapper { - /** - * @see _.flatten - */ - flatten(): LoDashExplicitArrayWrapper; - } - - interface LoDashExplicitArrayWrapperBase { - /** - * @see _.flatten - */ - flatten(isDeep?: boolean): LoDashExplicitArrayWrapper; - } - - interface LoDashExplicitObjectWrapperBase { - /** - * @see _.flatten - */ - flatten(isDeep?: boolean): LoDashExplicitArrayWrapper; + flatten(this: LoDashExplicitWrapper> | null | undefined>): LoDashExplicitWrapper; } //_.flattenDeep @@ -2038,46 +1287,18 @@ declare namespace _ { flattenDeep(array: ListOfRecursiveArraysOrValues | null | undefined): T[]; } - interface LoDashImplicitWrapper { + interface LoDashImplicitWrapper { /** * @see _.flattenDeep */ - flattenDeep(): LoDashImplicitArrayWrapper; + flattenDeep(this: LoDashImplicitWrapper | null | undefined>): LoDashImplicitWrapper; } - interface LoDashImplicitArrayWrapperBase { + interface LoDashExplicitWrapper { /** * @see _.flattenDeep */ - flattenDeep(): LoDashImplicitArrayWrapper; - } - - interface LoDashImplicitObjectWrapperBase { - /** - * @see _.flattenDeep - */ - flattenDeep(): LoDashImplicitArrayWrapper; - } - - interface LoDashExplicitWrapper { - /** - * @see _.flattenDeep - */ - flattenDeep(): LoDashExplicitArrayWrapper; - } - - interface LoDashExplicitArrayWrapperBase { - /** - * @see _.flattenDeep - */ - flattenDeep(): LoDashExplicitArrayWrapper; - } - - interface LoDashExplicitObjectWrapperBase { - /** - * @see _.flattenDeep - */ - flattenDeep(): LoDashExplicitArrayWrapper; + flattenDeep(this: LoDashExplicitWrapper | null | undefined>): LoDashExplicitWrapper; } // _.flattenDepth @@ -2092,6 +1313,20 @@ declare namespace _ { flattenDepth(array: ListOfRecursiveArraysOrValues | null | undefined, depth?: number): T[]; } + interface LoDashImplicitWrapper { + /** + * @see _.flattenDeep + */ + flattenDepth(this: LoDashImplicitWrapper | null | undefined>, depth?: number): LoDashImplicitWrapper; + } + + interface LoDashExplicitWrapper { + /** + * @see _.flattenDeep + */ + flattenDepth(this: LoDashExplicitWrapper | null | undefined>, depth?: number): LoDashExplicitWrapper; + } + //_.fromPairs interface LoDashStatic { /** @@ -2109,7 +1344,7 @@ declare namespace _ { * // => { 'fred': 30, 'barney': 40 } */ fromPairs( - array: List<[_.StringRepresentable, T]> | null | undefined + array: List<[StringRepresentable, T]> | null | undefined ): Dictionary; /** @@ -2120,20 +1355,37 @@ declare namespace _ { ): Dictionary; } - //_.fromPairs DUMMY - interface LoDashImplicitArrayWrapperBase { + //_.fromPairs + interface LoDashImplicitWrapper { /** * @see _.fromPairs */ - fromPairs(): LoDashImplicitObjectWrapper; - } + fromPairs( + this: LoDashImplicitWrapper | null | undefined> + ): LoDashImplicitWrapper>; - //_.fromPairs DUMMY - interface LoDashExplicitArrayWrapperBase { + /** + @see _.fromPairs + */ + fromPairs( + this: LoDashImplicitWrapper | null | undefined> + ): LoDashImplicitWrapper>; + } + //_.fromPairs + interface LoDashExplicitWrapper { /** * @see _.fromPairs */ - fromPairs(): LoDashExplicitObjectWrapper; + fromPairs( + this: LoDashExplicitWrapper | null | undefined> + ): LoDashExplicitWrapper>; + + /** + @see _.fromPairs + */ + fromPairs( + this: LoDashExplicitWrapper | null | undefined> + ): LoDashExplicitWrapper>; } //_.head @@ -2149,46 +1401,18 @@ declare namespace _ { head(array: List | null | undefined): T | undefined; } - interface LoDashImplicitWrapper { + interface LoDashImplicitWrapper { /** * @see _.head */ - head(): string | undefined; + head(this: LoDashImplicitWrapper | null | undefined>): T | undefined; } - interface LoDashImplicitArrayWrapperBase { + interface LoDashExplicitWrapper { /** * @see _.head */ - head(): T | undefined; - } - - interface LoDashImplicitObjectWrapperBase { - /** - * @see _.head - */ - head(): T | undefined; - } - - interface LoDashExplicitWrapper { - /** - * @see _.head - */ - head(): LoDashExplicitWrapper; - } - - interface LoDashExplicitArrayWrapperBase { - /** - * @see _.head - */ - head(): T; - } - - interface LoDashExplicitObjectWrapperBase { - /** - * @see _.head - */ - head(): T; + head(this: LoDashExplicitWrapper | null | undefined>): LoDashExplicitWrapper; } //_.indexOf @@ -2223,277 +1447,28 @@ declare namespace _ { ): number; } - interface LoDashImplicitArrayWrapperBase { + interface LoDashImplicitWrapper { /** * @see _.indexOf */ - indexOf( + indexOf( + this: LoDashImplicitWrapper | null | undefined>, value: T, fromIndex?: boolean|number ): number; } - interface LoDashImplicitObjectWrapperBase { + interface LoDashExplicitWrapper { /** * @see _.indexOf */ - indexOf( - value: TValue, - fromIndex?: boolean|number - ): number; - } - - interface LoDashExplicitArrayWrapperBase { - /** - * @see _.indexOf - */ - indexOf( + indexOf( + this: LoDashExplicitWrapper | null | undefined>, value: T, fromIndex?: boolean|number ): LoDashExplicitWrapper; } - interface LoDashExplicitObjectWrapperBase { - /** - * @see _.indexOf - */ - indexOf( - value: TValue, - fromIndex?: boolean|number - ): LoDashExplicitWrapper; - } - - //_.intersectionBy DUMMY - interface LoDashStatic { - /** - * This method is like `_.intersection` except that it accepts `iteratee` - * which is invoked for each element of each `arrays` to generate the criterion - * by which uniqueness is computed. The iteratee is invoked with one argument: (value). - * - * @static - * @memberOf _ - * @category Array - * @param {...Array} [arrays] The arrays to inspect. - * @param {Function|Object|string} [iteratee=_.identity] The iteratee invoked per element. - * @returns {Array} Returns the new array of shared values. - * @example - * - * _.intersectionBy([2.1, 1.2], [4.3, 2.4], Math.floor); - * // => [2.1] - * - * // using the `_.property` iteratee shorthand - * _.intersectionBy([{ 'x': 1 }], [{ 'x': 2 }, { 'x': 1 }], 'x'); - * // => [{ 'x': 1 }] - */ - intersectionBy( - array: List, - ...values: any[] - ): any[]; - } - - //_.intersectionWith DUMMY - interface LoDashStatic { - /** - * This method is like `_.intersection` except that it accepts `comparator` - * which is invoked to compare elements of `arrays`. The comparator is invoked - * with two arguments: (arrVal, othVal). - * - * @static - * @memberOf _ - * @category Array - * @param {...Array} [arrays] The arrays to inspect. - * @param {Function} [comparator] The comparator invoked per element. - * @returns {Array} Returns the new array of shared values. - * @example - * - * var objects = [{ 'x': 1, 'y': 2 }, { 'x': 2, 'y': 1 }]; - * var others = [{ 'x': 1, 'y': 1 }, { 'x': 1, 'y': 2 }]; - * - * _.intersectionWith(objects, others, _.isEqual); - * // => [{ 'x': 1, 'y': 2 }] - */ - intersectionWith( - array: List, - ...values: any[] - ): any[]; - } - - //_.join - interface LoDashStatic { - /** - * Converts all elements in `array` into a string separated by `separator`. - * - * @param array The array to convert. - * @param separator The element separator. - * @returns Returns the joined string. - */ - join( - array: List | null | undefined, - separator?: string - ): string; - } - - interface LoDashImplicitWrapper { - /** - * @see _.join - */ - join(separator?: string): string; - } - - interface LoDashImplicitArrayWrapperBase { - /** - * @see _.join - */ - join(separator?: string): string; - } - - interface LoDashImplicitObjectWrapperBase { - /** - * @see _.join - */ - join(separator?: string): string; - } - - interface LoDashExplicitWrapper { - /** - * @see _.join - */ - join(separator?: string): LoDashExplicitWrapper; - } - - interface LoDashExplicitArrayWrapperBase { - /** - * @see _.join - */ - join(separator?: string): LoDashExplicitWrapper; - } - - interface LoDashExplicitObjectWrapperBase { - /** - * @see _.join - */ - join(separator?: string): LoDashExplicitWrapper; - } - - //_.pullAll DUMMY - interface LoDashStatic { - /** - * This method is like `_.pull` except that it accepts an array of values to remove. - * - * **Note:** Unlike `_.difference`, this method mutates `array`. - * - * @static - * @memberOf _ - * @category Array - * @param {Array} array The array to modify. - * @param {Array} values The values to remove. - * @returns {Array} Returns `array`. - * @example - * - * var array = [1, 2, 3, 1, 2, 3]; - * - * _.pull(array, [2, 3]); - * console.log(array); - * // => [1, 1] - */ - pullAll( - array: List, - ...values: any[] - ): any[]; - } - - //_.pullAllBy DUMMY - interface LoDashStatic { - /** - * This method is like `_.pullAll` except that it accepts `iteratee` which is - * invoked for each element of `array` and `values` to to generate the criterion - * by which uniqueness is computed. The iteratee is invoked with one argument: (value). - * - * **Note:** Unlike `_.differenceBy`, this method mutates `array`. - * - * @static - * @memberOf _ - * @category Array - * @param {Array} array The array to modify. - * @param {Array} values The values to remove. - * @param {Function|Object|string} [iteratee=_.identity] The iteratee invoked per element. - * @returns {Array} Returns `array`. - * @example - * - * var array = [{ 'x': 1 }, { 'x': 2 }, { 'x': 3 }, { 'x': 1 }]; - * - * _.pullAllBy(array, [{ 'x': 1 }, { 'x': 3 }], 'x'); - * console.log(array); - * // => [{ 'x': 2 }] - */ - pullAllBy( - array: List, - ...values: any[] - ): any[]; - } - - type Comparator = (arrVal: T, othVal: T) => boolean; - - //_.pullAllWith - interface LoDashStatic { - /** - * This method is like `_.pullAll` except that it accepts `comparator` which - * is invoked to compare elements of `array` to `values`. The comparator is - * invoked with two arguments: (arrVal, othVal). - * - * **Note:** Unlike `_.differenceWith`, this method mutates `array`. - * - * @static - * @memberOf _ - * @since 4.6.0 - * @category Array - * @param {Array} array The array to modify. - * @param {Array} values The values to remove. - * @param {Function} [comparator] The comparator invoked per element. - * @returns {Array} Returns `array`. - * @example - * - * var array = [{ 'x': 1, 'y': 2 }, { 'x': 3, 'y': 4 }, { 'x': 5, 'y': 6 }]; - * - * _.pullAllWith(array, [{ 'x': 3, 'y': 4 }], _.isEqual); - * console.log(array); - * // => [{ 'x': 1, 'y': 2 }, { 'x': 5, 'y': 6 }] - */ - pullAllWith( - array: List, - values: List, - comparator?: Comparator - ): List; - } - - //_.reverse DUMMY - interface LoDashStatic { - /** - * Reverses `array` so that the first element becomes the last, the second - * element becomes the second to last, and so on. - * - * **Note:** This method mutates `array` and is based on - * [`Array#reverse`](https://mdn.io/Array/reverse). - * - * @memberOf _ - * @category Array - * @returns {Array} Returns `array`. - * @example - * - * var array = [1, 2, 3]; - * - * _.reverse(array); - * // => [3, 2, 1] - * - * console.log(array); - * // => [3, 2, 1] - */ - reverse( - array: List, - ...values: any[] - ): any[]; - } - //_.sortedIndexOf interface LoDashStatic { /** @@ -2517,42 +1492,26 @@ declare namespace _ { ): number; } - interface LoDashImplicitArrayWrapperBase { + interface LoDashImplicitWrapper { /** * @see _.sortedIndexOf */ - sortedIndexOf( + sortedIndexOf( + this: LoDashImplicitWrapper | null | undefined>, value: T ): number; } - interface LoDashImplicitObjectWrapperBase { + interface LoDashExplicitWrapper { /** * @see _.sortedIndexOf */ - sortedIndexOf( - value: TValue - ): number; - } - - interface LoDashExplicitArrayWrapperBase { - /** - * @see _.sortedIndexOf - */ - sortedIndexOf( + sortedIndexOf( + this: LoDashExplicitWrapper | null | undefined>, value: T ): LoDashExplicitWrapper; } - interface LoDashExplicitObjectWrapperBase { - /** - * @see _.sortedIndexOf - */ - sortedIndexOf( - value: TValue - ): LoDashExplicitWrapper; - } - //_.initial interface LoDashStatic { /** @@ -2564,32 +1523,18 @@ declare namespace _ { initial(array: List | null | undefined): T[]; } - interface LoDashImplicitArrayWrapperBase { + interface LoDashImplicitWrapper { /** * @see _.initial */ - initial(): LoDashImplicitArrayWrapper; + initial(this: LoDashImplicitWrapper | null | undefined>): LoDashImplicitWrapper; } - interface LoDashImplicitObjectWrapperBase { + interface LoDashExplicitWrapper { /** * @see _.initial */ - initial(): LoDashImplicitArrayWrapper; - } - - interface LoDashExplicitArrayWrapperBase { - /** - * @see _.initial - */ - initial(): LoDashExplicitArrayWrapper; - } - - interface LoDashExplicitObjectWrapperBase { - /** - * @see _.initial - */ - initial(): LoDashExplicitArrayWrapper; + initial(this: LoDashExplicitWrapper | null | undefined>): LoDashExplicitWrapper; } //_.intersection @@ -2601,35 +1546,244 @@ declare namespace _ { * @param arrays The arrays to inspect. * @return Returns the new array of shared values. */ - intersection(...arrays: Array | null | undefined>): T[]; + intersection(...arrays: Array>): T[]; } - interface LoDashImplicitArrayWrapperBase { + interface LoDashImplicitWrapper { /** * @see _.intersection */ - intersection(...arrays: Array>): LoDashImplicitArrayWrapper; + intersection( + this: LoDashImplicitWrapper>, + ...arrays: Array> + ): LoDashImplicitWrapper; } - interface LoDashImplicitObjectWrapperBase { + interface LoDashExplicitWrapper { /** * @see _.intersection */ - intersection(...arrays: Array>): LoDashImplicitArrayWrapper; + intersection( + this: LoDashExplicitWrapper>, + ...arrays: Array> + ): LoDashExplicitWrapper; } - interface LoDashExplicitArrayWrapperBase { + //_.intersectionBy + interface LoDashStatic { /** - * @see _.intersection + * This method is like `_.intersection` except that it accepts `iteratee` + * which is invoked for each element of each `arrays` to generate the criterion + * by which uniqueness is computed. The iteratee is invoked with one argument: (value). + * + * @static + * @memberOf _ + * @category Array + * @param {...Array} [arrays] The arrays to inspect. + * @param {Function|Object|string} [iteratee=_.identity] The iteratee invoked per element. + * @returns {Array} Returns the new array of shared values. + * @example + * + * _.intersectionBy([2.1, 1.2], [4.3, 2.4], Math.floor); + * // => [2.1] + * + * // using the `_.property` iteratee shorthand + * _.intersectionBy([{ 'x': 1 }], [{ 'x': 2 }, { 'x': 1 }], 'x'); + * // => [{ 'x': 1 }] */ - intersection(...arrays: Array>): LoDashExplicitArrayWrapper; + intersectionBy( + array?: List | null | undefined, + values?: List, + iteratee?: ValueIteratee + ): T[]; + + /** + * @see _.intersectionBy + */ + intersectionBy( + array?: List | null | undefined, + ...values: Array | ValueIteratee>, + ): T[]; } - interface LoDashExplicitObjectWrapperBase { + interface LoDashImplicitWrapper { /** - * @see _.intersection + * @see _.intersectionBy */ - intersection(...arrays: Array>): LoDashExplicitArrayWrapper; + intersectionBy( + this: LoDashImplicitWrapper | null | undefined>, + values?: List, + iteratee?: ValueIteratee + ): LoDashImplicitWrapper; + + /** + * @see _.intersectionBy + */ + intersectionBy( + this: LoDashImplicitWrapper | null | undefined>, + ...values: Array | ValueIteratee>, + ): LoDashImplicitWrapper; + } + + interface LoDashExplicitWrapper { + /** + * @see _.intersectionBy + */ + intersectionBy( + this: LoDashExplicitWrapper | null | undefined>, + values?: List, + iteratee?: ValueIteratee + ): LoDashExplicitWrapper; + + /** + * @see _.intersectionBy + */ + intersectionBy( + this: LoDashExplicitWrapper | null | undefined>, + ...values: Array | ValueIteratee>, + ): LoDashExplicitWrapper; + } + + //_.intersectionWith + interface LoDashStatic { + /** + * Creates an array of unique `array` values not included in the other + * provided arrays using [`SameValueZero`](http://ecma-international.org/ecma-262/6.0/#sec-samevaluezero) + * for equality comparisons. + * + * @static + * @memberOf _ + * @category Array + * @param {...Array} [values] The arrays to inspect. + * @param {Function} [comparator] The comparator invoked per element. + * @returns {Array} Returns the new array of filtered values. + * @example + * + * var objects = [{ 'x': 1, 'y': 2 }, { 'x': 2, 'y': 1 }]; + + * _.differenceWith(objects, [{ 'x': 1, 'y': 2 }], _.isEqual); + * // => [{ 'x': 2, 'y': 1 }] + */ + intersectionWith( + array: List | null | undefined, + values?: List, + comparator?: Comparator + ): T[]; + + /** + * @see _.differenceWith + */ + intersectionWith( + array: List | null | undefined, + ...values: Array | Comparator>, + ): T[]; + } + + interface LoDashImplicitWrapper { + /** + * @see _.intersectionWith + */ + intersectionWith( + this: LoDashImplicitWrapper | null | undefined>, + values?: List, + comparator?: Comparator + ): LoDashImplicitWrapper; + + /** + * @see _.intersectionWith + */ + intersectionWith( + this: LoDashImplicitWrapper | null | undefined>, + ...values: Array | Comparator>, + ): LoDashImplicitWrapper; + } + + interface LoDashExplicitWrapper { + /** + * @see _.intersectionWith + */ + intersectionWith( + this: LoDashExplicitWrapper | null | undefined>, + values?: List, + comparator?: Comparator + ): LoDashExplicitWrapper; + + /** + * @see _.intersectionWith + */ + intersectionWith( + this: LoDashExplicitWrapper | null | undefined>, + ...values: Array | Comparator>, + ): LoDashExplicitWrapper; + } + + //_.join + interface LoDashStatic { + /** + * Converts all elements in `array` into a string separated by `separator`. + * + * @param array The array to convert. + * @param separator The element separator. + * @returns Returns the joined string. + */ + join( + array: List | null | undefined, + separator?: string + ): string; + } + + interface LoDashImplicitWrapper { + /** + * @see _.join + */ + join(separator?: string): string; + } + + interface LoDashExplicitWrapper { + /** + * @see _.join + */ + join(separator?: string): LoDashExplicitWrapper; + } + + //_.reverse + interface LoDashStatic { + /** + * Reverses `array` so that the first element becomes the last, the second + * element becomes the second to last, and so on. + * + * **Note:** This method mutates `array` and is based on + * [`Array#reverse`](https://mdn.io/Array/reverse). + * + * @memberOf _ + * @category Array + * @returns {Array} Returns `array`. + * @example + * + * var array = [1, 2, 3]; + * + * _.reverse(array); + * // => [3, 2, 1] + * + * console.log(array); + * // => [3, 2, 1] + */ + reverse>( + array: TList, + ): TList; + } + + //_.prototype.reverse + interface LoDashWrapper { + /** + * Reverses the wrapped array so the first element becomes the last, the second element becomes the second to + * last, and so on. + * + * Note: This method mutates the wrapped array. + * + * @return Returns the new reversed lodash wrapper instance. + */ + reverse(): this; } //_.last @@ -2643,46 +1797,18 @@ declare namespace _ { last(array: List | null | undefined): T | undefined; } - interface LoDashImplicitWrapper { + interface LoDashImplicitWrapper { /** * @see _.last */ - last(): string | undefined; + last(this: LoDashImplicitWrapper | null | undefined>): T | undefined; } - interface LoDashImplicitArrayWrapperBase { + interface LoDashExplicitWrapper { /** * @see _.last */ - last(): T | undefined; - } - - interface LoDashImplicitObjectWrapperBase { - /** - * @see _.last - */ - last(): T | undefined; - } - - interface LoDashExplicitWrapper { - /** - * @see _.last - */ - last(): LoDashExplicitWrapper; - } - - interface LoDashExplicitArrayWrapperBase { - /** - * @see _.last - */ - last(): T; - } - - interface LoDashExplicitObjectWrapperBase { - /** - * @see _.last - */ - last(): T; + last(this: LoDashExplicitWrapper | null | undefined>): LoDashExplicitWrapper; } //_.lastIndexOf @@ -2698,47 +1824,29 @@ declare namespace _ { lastIndexOf( array: List | null | undefined, value: T, - fromIndex?: boolean|number + fromIndex?: true|number ): number; } - interface LoDashImplicitArrayWrapperBase { + interface LoDashImplicitWrapper { /** - * @see _.lastIndexOf + * @see _.indexOf */ - lastIndexOf( + lastIndexOf( + this: LoDashImplicitWrapper | null | undefined>, value: T, - fromIndex?: boolean|number + fromIndex?: true|number ): number; } - interface LoDashImplicitObjectWrapperBase { + interface LoDashExplicitWrapper { /** - * @see _.lastIndexOf + * @see _.indexOf */ - lastIndexOf( - value: TResult, - fromIndex?: boolean|number - ): number; - } - - interface LoDashExplicitArrayWrapperBase { - /** - * @see _.lastIndexOf - */ - lastIndexOf( + lastIndexOf( + this: LoDashExplicitWrapper | null | undefined>, value: T, - fromIndex?: boolean|number - ): LoDashExplicitWrapper; - } - - interface LoDashExplicitObjectWrapperBase { - /** - * @see _.lastIndexOf - */ - lastIndexOf( - value: TResult, - fromIndex?: boolean|number + fromIndex?: true|number ): LoDashExplicitWrapper; } @@ -2757,40 +1865,24 @@ declare namespace _ { ): T | undefined; } - interface LoDashImplicitArrayWrapperBase { + interface LoDashImplicitWrapper { /** * @see _.nth */ - nth( + nth( + this: LoDashImplicitWrapper | null | undefined>, n?: number ): T | undefined; } - interface LoDashImplicitObjectWrapperBase { + interface LoDashExplicitWrapper { /** * @see _.nth */ - nth( - n?:number - ): TResult | undefined; - } - - interface LoDashExplicitArrayWrapperBase { - /** - * @see _.nth - */ - nth( - n?:number - ): LoDashExplicitWrapper; - } - - interface LoDashExplicitObjectWrapperBase { - /** - * @see _.nth - */ - nth( - n?:number - ): LoDashExplicitWrapper; + nth( + this: LoDashExplicitWrapper | null | undefined>, + n?: number + ): LoDashExplicitWrapper; } //_.pull @@ -2818,32 +1910,24 @@ declare namespace _ { ): List; } - interface LoDashImplicitArrayWrapper { + interface LoDashImplicitWrapper { /** * @see _.pull */ - pull(...values: T[]): LoDashImplicitArrayWrapper; + pull( + this: LoDashImplicitWrapper>, + ...values: T[] + ): this; } - interface LoDashImplicitObjectWrapper { + interface LoDashExplicitWrapper { /** * @see _.pull */ - pull(...values: TValue[]): LoDashImplicitObjectWrapper>; - } - - interface LoDashExplicitArrayWrapper { - /** - * @see _.pull - */ - pull(...values: T[]): LoDashExplicitArrayWrapper; - } - - interface LoDashExplicitObjectWrapper { - /** - * @see _.pull - */ - pull(...values: TValue[]): LoDashExplicitObjectWrapper>; + pull( + this: LoDashExplicitWrapper>, + ...values: T[] + ): this; } //_.pullAt @@ -2859,37 +1943,203 @@ declare namespace _ { * @return Returns the new array of removed elements. */ pullAt( - array: List, + array: T[], ...indexes: Array> ): T[]; - } - interface LoDashImplicitArrayWrapper { /** * @see _.pullAt */ - pullAt(...indexes: Array>): LoDashImplicitArrayWrapper; + pullAt( + array: List, + ...indexes: Array> + ): List; } - interface LoDashImplicitObjectWrapper { + interface LoDashWrapper { /** * @see _.pullAt */ - pullAt(...indexes: Array>): LoDashImplicitArrayWrapper; + pullAt(...indexes: Array>): this; } - interface LoDashExplicitArrayWrapper { + //_.pullAll + interface LoDashStatic { /** - * @see _.pullAt + * This method is like `_.pull` except that it accepts an array of values to remove. + * + * **Note:** Unlike `_.difference`, this method mutates `array`. + * + * @static + * @memberOf _ + * @category Array + * @param {Array} array The array to modify. + * @param {Array} values The values to remove. + * @returns {Array} Returns `array`. + * @example + * + * var array = [1, 2, 3, 1, 2, 3]; + * + * _.pull(array, [2, 3]); + * console.log(array); + * // => [1, 1] */ - pullAt(...indexes: Array>): LoDashExplicitArrayWrapper; + pullAll( + array: T[], + values?: List, + ): T[]; + + /** + * @see _.pullAll + */ + pullAll( + array: List, + values?: List, + ): List; } - interface LoDashExplicitObjectWrapper { + interface LoDashImplicitWrapper { /** - * @see _.pullAt + * @see _.pullAll */ - pullAt(...indexes: Array>): LoDashExplicitArrayWrapper; + pullAll( + this: LoDashImplicitWrapper>, + values?: List + ): this; + } + + interface LoDashExplicitWrapper { + /** + * @see _.pullAll + */ + pullAll( + this: LoDashExplicitWrapper>, + values?: List + ): this; + } + + //_.pullAllBy + interface LoDashStatic { + /** + * This method is like `_.pullAll` except that it accepts `iteratee` which is + * invoked for each element of `array` and `values` to to generate the criterion + * by which uniqueness is computed. The iteratee is invoked with one argument: (value). + * + * **Note:** Unlike `_.differenceBy`, this method mutates `array`. + * + * @static + * @memberOf _ + * @category Array + * @param {Array} array The array to modify. + * @param {Array} values The values to remove. + * @param {Function|Object|string} [iteratee=_.identity] The iteratee invoked per element. + * @returns {Array} Returns `array`. + * @example + * + * var array = [{ 'x': 1 }, { 'x': 2 }, { 'x': 3 }, { 'x': 1 }]; + * + * _.pullAllBy(array, [{ 'x': 1 }, { 'x': 3 }], 'x'); + * console.log(array); + * // => [{ 'x': 2 }] + */ + pullAllBy( + array: T[], + values?: List, + iteratee?: ValueIteratee + ): T[]; + + /** + * @see _.pullAllBy + */ + pullAllBy( + array: List, + values?: List, + iteratee?: ValueIteratee + ): List; + } + + interface LoDashImplicitWrapper { + /** + * @see _.pullAllBy + */ + pullAllBy( + this: LoDashImplicitWrapper>, + values?: List, + iteratee?: ValueIteratee + ): this; + } + + interface LoDashExplicitWrapper { + /** + * @see _.pullAllBy + */ + pullAllBy( + this: LoDashExplicitWrapper>, + values?: List, + iteratee?: ValueIteratee + ): this; + } + + //_.pullAllWith + interface LoDashStatic { + /** + * This method is like `_.pullAll` except that it accepts `comparator` which is + * invoked to compare elements of array to values. The comparator is invoked with + * two arguments: (arrVal, othVal). + * + * **Note:** Unlike `_.differenceWith`, this method mutates `array`. + * + * @static + * @memberOf _ + * @category Array + * @param {Array} array The array to modify. + * @param {Array} values The values to remove. + * @param {Function|Object|string} [iteratee=_.identity] The iteratee invoked per element. + * @returns {Array} Returns `array`. + * @example + * + * var array = [{ 'x': 1 }, { 'x': 2 }, { 'x': 3 }, { 'x': 1 }]; + * + * _.pullAllBy(array, [{ 'x': 1 }, { 'x': 3 }], 'x'); + * console.log(array); + * // => [{ 'x': 2 }] + */ + pullAllWith( + array: T[], + values?: List, + comparator?: Comparator + ): T[]; + + /** + * @see _.pullAllWith + */ + pullAllWith( + array: List, + values?: List, + comparator?: Comparator + ): List; + } + + interface LoDashImplicitWrapper { + /** + * @see _.pullAllWith + */ + pullAllWith( + this: LoDashImplicitWrapper>, + values?: List, + comparator?: Comparator + ): this; + } + + interface LoDashExplicitWrapper { + /** + * @see _.pullAllWith + */ + pullAllWith( + this: LoDashExplicitWrapper>, + values?: List, + comparator?: Comparator + ): this; } //_.remove @@ -2916,116 +2166,28 @@ declare namespace _ { */ remove( array: List, - predicate?: ListIterator + predicate?: ListIteratee ): T[]; + } + interface LoDashImplicitWrapper { /** * @see _.remove */ remove( - array: List, - predicate?: string - ): T[]; - - /** - * @see _.remove - */ - remove( - array: List, - predicate?: W - ): T[]; + this: LoDashImplicitWrapper>, + predicate?: ListIteratee + ): LoDashImplicitWrapper; } - interface LoDashImplicitArrayWrapper { + interface LoDashExplicitWrapper { /** * @see _.remove */ - remove( - predicate?: ListIterator - ): LoDashImplicitArrayWrapper; - - /** - * @see _.remove - */ - remove( - predicate?: string - ): LoDashImplicitArrayWrapper; - - /** - * @see _.remove - */ - remove( - predicate?: W - ): LoDashImplicitArrayWrapper; - } - - interface LoDashImplicitObjectWrapper { - /** - * @see _.remove - */ - remove( - predicate?: ListIterator - ): LoDashImplicitArrayWrapper; - - /** - * @see _.remove - */ - remove( - predicate?: string - ): LoDashImplicitArrayWrapper; - - /** - * @see _.remove - */ - remove( - predicate?: W - ): LoDashImplicitArrayWrapper; - } - - interface LoDashExplicitArrayWrapper { - /** - * @see _.remove - */ - remove( - predicate?: ListIterator - ): LoDashExplicitArrayWrapper; - - /** - * @see _.remove - */ - remove( - predicate?: string - ): LoDashExplicitArrayWrapper; - - /** - * @see _.remove - */ - remove( - predicate?: W - ): LoDashExplicitArrayWrapper; - } - - interface LoDashExplicitObjectWrapper { - /** - * @see _.remove - */ - remove( - predicate?: ListIterator - ): LoDashExplicitArrayWrapper; - - /** - * @see _.remove - */ - remove( - predicate?: string - ): LoDashExplicitArrayWrapper; - - /** - * @see _.remove - */ - remove( - predicate?: W - ): LoDashExplicitArrayWrapper; + remove( + this: LoDashExplicitWrapper>, + predicate?: ListIteratee + ): LoDashExplicitWrapper; } //_.tail @@ -3033,40 +2195,24 @@ declare namespace _ { /** * Gets all but the first element of array. * - * @alias _.tail - * * @param array The array to query. * @return Returns the slice of array. */ tail(array: List | null | undefined): T[]; } - interface LoDashImplicitArrayWrapperBase { + interface LoDashImplicitWrapper { /** * @see _.tail */ - tail(): LoDashImplicitArrayWrapper; + tail(this: LoDashImplicitWrapper | null | undefined>): LoDashImplicitWrapper; } - interface LoDashImplicitObjectWrapperBase { + interface LoDashExplicitWrapper { /** * @see _.tail */ - tail(): LoDashImplicitArrayWrapper; - } - - interface LoDashExplicitArrayWrapperBase { - /** - * @see _.tail - */ - tail(): LoDashExplicitArrayWrapper; - } - - interface LoDashExplicitObjectWrapperBase { - /** - * @see _.tail - */ - tail(): LoDashExplicitArrayWrapper; + tail(this: LoDashExplicitWrapper | null | undefined>): LoDashExplicitWrapper; } //_.slice @@ -3080,30 +2226,32 @@ declare namespace _ { * @return Returns the slice of array. */ slice( - array: T[] | null | undefined, + array: List | null | undefined, start?: number, end?: number ): T[]; } - interface LoDashImplicitArrayWrapperBase { + interface LoDashImplicitWrapper { /** * @see _.slice */ - slice( + slice( + this: LoDashImplicitWrapper | null | undefined>, start?: number, end?: number - ): LoDashImplicitArrayWrapper; + ): LoDashImplicitWrapper; } - interface LoDashExplicitArrayWrapperBase { + interface LoDashExplicitWrapper { /** * @see _.slice */ - slice( + slice( + this: LoDashExplicitWrapper | null | undefined>, start?: number, end?: number - ): LoDashExplicitArrayWrapper; + ): LoDashExplicitWrapper; } //_.sortedIndex @@ -3132,56 +2280,22 @@ declare namespace _ { ): number; } - interface LoDashImplicitWrapper { - /** - * @see _.sortedIndex - */ - sortedIndex( - value: string - ): number; - } - - interface LoDashImplicitArrayWrapperBase { - /** - * @see _.sortedIndex - */ - sortedIndex( - value: T - ): number; - } - - interface LoDashImplicitObjectWrapperBase { + interface LoDashImplicitWrapper { /** * @see _.sortedIndex */ sortedIndex( + this: LoDashImplicitWrapper | null | undefined>, value: T ): number; } - interface LoDashExplicitWrapper { - /** - * @see _.sortedIndex - */ - sortedIndex( - value: string - ): LoDashExplicitWrapper; - } - - interface LoDashExplicitArrayWrapperBase { - /** - * @see _.sortedIndex - */ - sortedIndex( - value: T - ): LoDashExplicitWrapper; - } - - interface LoDashExplicitObjectWrapperBase { + interface LoDashExplicitWrapper { /** * @see _.sortedIndex */ sortedIndex( + this: LoDashExplicitWrapper | null | undefined>, value: T ): LoDashExplicitWrapper; } @@ -3211,202 +2325,32 @@ declare namespace _ { * _.sortedIndexBy([{ 'x': 4 }, { 'x': 5 }], { 'x': 4 }, 'x'); * // => 0 */ - sortedIndexBy( - array: List | null | undefined, - value: T, - iteratee: (x: T) => TSort - ): number; - - /** - * @see _.sortedIndexBy - */ sortedIndexBy( array: List | null | undefined, value: T, - iteratee: (x: T) => any - ): number; - - /** - * @see _.sortedIndexBy - */ - sortedIndexBy( - array: List | null | undefined, - value: T, - iteratee: string - ): number; - - /** - * @see _.sortedIndexBy - */ - sortedIndexBy( - array: List | null | undefined, - value: T, - iteratee: W - ): number; - - /** - * @see _.sortedIndexBy - */ - sortedIndexBy( - array: List | null | undefined, - value: T, - iteratee: Object + iteratee?: ValueIteratee ): number; } - interface LoDashImplicitWrapper { + interface LoDashImplicitWrapper { /** * @see _.sortedIndexBy */ - sortedIndexBy( - value: string, - iteratee: (x: string) => TSort + sortedIndexBy( + this: LoDashImplicitWrapper | null | undefined>, + value: T, + iteratee?: ValueIteratee ): number; } - interface LoDashImplicitArrayWrapperBase { - /** - * @see _.sortedIndexBy - */ - sortedIndexBy( - value: T, - iteratee: (x: T) => TSort - ): number; - - /** - * @see _.sortedIndexBy - */ - sortedIndexBy( - value: T, - iteratee: string - ): number; - - /** - * @see _.sortedIndexBy - */ - sortedIndexBy( - value: T, - iteratee: W - ): number; - } - - interface LoDashImplicitObjectWrapperBase { - /** - * @see _.sortedIndexBy - */ - sortedIndexBy( - value: T, - iteratee: (x: T) => TSort - ): number; - + interface LoDashExplicitWrapper { /** * @see _.sortedIndexBy */ sortedIndexBy( + this: LoDashExplicitWrapper | null | undefined>, value: T, - iteratee: (x: T) => any - ): number; - - /** - * @see _.sortedIndexBy - */ - sortedIndexBy( - value: T, - iteratee: string - ): number; - - /** - * @see _.sortedIndexBy - */ - sortedIndexBy( - value: T, - iteratee: W - ): number; - - /** - * @see _.sortedIndexBy - */ - sortedIndexBy( - value: T, - iteratee: Object - ): number; - } - - interface LoDashExplicitWrapper { - /** - * @see _.sortedIndexBy - */ - sortedIndexBy( - value: string, - iteratee: (x: string) => TSort - ): LoDashExplicitWrapper; - } - - interface LoDashExplicitArrayWrapperBase { - /** - * @see _.sortedIndexBy - */ - sortedIndexBy( - value: T, - iteratee: (x: T) => TSort - ): LoDashExplicitWrapper; - - /** - * @see _.sortedIndexBy - */ - sortedIndexBy( - value: T, - iteratee: string - ): LoDashExplicitWrapper; - - /** - * @see _.sortedIndexBy - */ - sortedIndexBy( - value: T, - iteratee: W - ): LoDashExplicitWrapper; - } - - interface LoDashExplicitObjectWrapperBase { - /** - * @see _.sortedIndexBy - */ - sortedIndexBy( - value: T, - iteratee: (x: T) => TSort - ): LoDashExplicitWrapper; - - /** - * @see _.sortedIndexBy - */ - sortedIndexBy( - value: T, - iteratee: (x: T) => any - ): LoDashExplicitWrapper; - - /** - * @see _.sortedIndexBy - */ - sortedIndexBy( - value: T, - iteratee: string - ): LoDashExplicitWrapper; - - /** - * @see _.sortedIndexBy - */ - sortedIndexBy( - value: T, - iteratee: W - ): LoDashExplicitWrapper; - - /** - * @see _.sortedIndexBy - */ - sortedIndexBy( - value: T, - iteratee: Object + iteratee?: ValueIteratee ): LoDashExplicitWrapper; } @@ -3434,56 +2378,22 @@ declare namespace _ { ): number; } - interface LoDashImplicitWrapper { - /** - * @see _.sortedLastIndex - */ - sortedLastIndex( - value: string - ): number; - } - - interface LoDashImplicitArrayWrapperBase { - /** - * @see _.sortedLastIndex - */ - sortedLastIndex( - value: T - ): number; - } - - interface LoDashImplicitObjectWrapperBase { + interface LoDashImplicitWrapper { /** * @see _.sortedLastIndex */ sortedLastIndex( + this: LoDashImplicitWrapper | null | undefined>, value: T ): number; } - interface LoDashExplicitWrapper { - /** - * @see _.sortedLastIndex - */ - sortedLastIndex( - value: string - ): LoDashExplicitWrapper; - } - - interface LoDashExplicitArrayWrapperBase { - /** - * @see _.sortedLastIndex - */ - sortedLastIndex( - value: T - ): LoDashExplicitWrapper; - } - - interface LoDashExplicitObjectWrapperBase { + interface LoDashExplicitWrapper { /** * @see _.sortedLastIndex */ sortedLastIndex( + this: LoDashExplicitWrapper | null | undefined>, value: T ): LoDashExplicitWrapper; } @@ -3508,206 +2418,36 @@ declare namespace _ { * _.sortedLastIndexBy([{ 'x': 4 }, { 'x': 5 }], { 'x': 4 }, 'x'); * // => 1 */ - sortedLastIndexBy( - array: List | null | undefined, - value: T, - iteratee: (x: T) => TSort - ): number; - - /** - * @see _.sortedLastIndexBy - */ sortedLastIndexBy( array: List | null | undefined, value: T, - iteratee: (x: T) => any - ): number; - - /** - * @see _.sortedLastIndexBy - */ - sortedLastIndexBy( - array: List | null | undefined, - value: T, - iteratee: string - ): number; - - /** - * @see _.sortedLastIndexBy - */ - sortedLastIndexBy( - array: List | null | undefined, - value: T, - iteratee: W - ): number; - - /** - * @see _.sortedLastIndexBy - */ - sortedLastIndexBy( - array: List | null | undefined, - value: T, - iteratee: Object + iteratee: ValueIteratee ): number; } - interface LoDashImplicitWrapper { - /** - * @see _.sortedLastIndexBy - */ - sortedLastIndexBy( - value: string, - iteratee: (x: string) => TSort - ): number; - } - - interface LoDashImplicitArrayWrapperBase { - /** - * @see _.sortedLastIndexBy - */ - sortedLastIndexBy( - value: T, - iteratee: (x: T) => TSort - ): number; - - /** - * @see _.sortedLastIndexBy - */ - sortedLastIndexBy( - value: T, - iteratee: string - ): number; - - /** - * @see _.sortedLastIndexBy - */ - sortedLastIndexBy( - value: T, - iteratee: W - ): number; - } - - interface LoDashImplicitObjectWrapperBase { - /** - * @see _.sortedLastIndexBy - */ - sortedLastIndexBy( - value: T, - iteratee: (x: T) => TSort - ): number; - + interface LoDashImplicitWrapper { /** * @see _.sortedLastIndexBy */ sortedLastIndexBy( + this: LoDashImplicitWrapper | null | undefined>, value: T, - iteratee: (x: T) => any - ): number; - - /** - * @see _.sortedLastIndexBy - */ - sortedLastIndexBy( - value: T, - iteratee: string - ): number; - - /** - * @see _.sortedLastIndexBy - */ - sortedLastIndexBy( - value: T, - iteratee: W - ): number; - - /** - * @see _.sortedLastIndexBy - */ - sortedLastIndexBy( - value: T, - iteratee: Object + iteratee: ValueIteratee ): number; } - interface LoDashExplicitWrapper { - /** - * @see _.sortedLastIndexBy - */ - sortedLastIndexBy( - value: string, - iteratee: (x: string) => TSort - ): LoDashExplicitWrapper; - } - - interface LoDashExplicitArrayWrapperBase { - /** - * @see _.sortedLastIndexBy - */ - sortedLastIndexBy( - value: T, - iteratee: (x: T) => TSort - ): LoDashExplicitWrapper; - - /** - * @see _.sortedLastIndexBy - */ - sortedLastIndexBy( - value: T, - iteratee: string - ): LoDashExplicitWrapper; - - /** - * @see _.sortedLastIndexBy - */ - sortedLastIndexBy( - value: T, - iteratee: W - ): LoDashExplicitWrapper; - } - - interface LoDashExplicitObjectWrapperBase { - /** - * @see _.sortedLastIndexBy - */ - sortedLastIndexBy( - value: T, - iteratee: (x: T) => TSort - ): LoDashExplicitWrapper; - + interface LoDashExplicitWrapper { /** * @see _.sortedLastIndexBy */ sortedLastIndexBy( + this: LoDashExplicitWrapper | null | undefined>, value: T, - iteratee: (x: T) => any - ): LoDashExplicitWrapper; - - /** - * @see _.sortedLastIndexBy - */ - sortedLastIndexBy( - value: T, - iteratee: string - ): LoDashExplicitWrapper; - - /** - * @see _.sortedLastIndexBy - */ - sortedLastIndexBy( - value: T, - iteratee: W - ): LoDashExplicitWrapper; - - /** - * @see _.sortedLastIndexBy - */ - sortedLastIndexBy( - value: T, - iteratee: Object + iteratee: ValueIteratee ): LoDashExplicitWrapper; } - //_.sortedLastIndexOf DUMMY + //_.sortedLastIndexOf interface LoDashStatic { /** * This method is like `_.lastIndexOf` except that it performs a binary @@ -3730,40 +2470,24 @@ declare namespace _ { ): number; } - //_.tail - interface LoDashStatic { + interface LoDashImplicitWrapper { /** - * @see _.rest + * @see _.sortedLastIndexOf */ - tail(array: List | null | undefined): T[]; + sortedLastIndexOf( + this: LoDashImplicitWrapper | null | undefined>, + value: T + ): number; } - interface LoDashImplicitArrayWrapperBase { + interface LoDashExplicitWrapper { /** - * @see _.rest + * @see _.sortedLastIndexOf */ - tail(): LoDashImplicitArrayWrapper; - } - - interface LoDashImplicitObjectWrapperBase { - /** - * @see _.rest - */ - tail(): LoDashImplicitArrayWrapper; - } - - interface LoDashExplicitArrayWrapperBase { - /** - * @see _.rest - */ - tail(): LoDashExplicitArrayWrapper; - } - - interface LoDashExplicitObjectWrapperBase { - /** - * @see _.rest - */ - tail(): LoDashExplicitArrayWrapper; + sortedLastIndexOf( + this: LoDashExplicitWrapper | null | undefined>, + value: T + ): LoDashExplicitWrapper; } //_.take @@ -3781,32 +2505,24 @@ declare namespace _ { ): T[]; } - interface LoDashImplicitArrayWrapperBase { + interface LoDashImplicitWrapper { /** * @see _.take */ - take(n?: number): LoDashImplicitArrayWrapper; + take( + this: LoDashImplicitWrapper | null | undefined>, + n?: number + ): LoDashImplicitWrapper; } - interface LoDashImplicitObjectWrapperBase { + interface LoDashExplicitWrapper { /** * @see _.take */ - take(n?: number): LoDashImplicitArrayWrapper; - } - - interface LoDashExplicitArrayWrapperBase { - /** - * @see _.take - */ - take(n?: number): LoDashExplicitArrayWrapper; - } - - interface LoDashExplicitObjectWrapperBase { - /** - * @see _.take - */ - take(n?: number): LoDashExplicitArrayWrapper; + take( + this: LoDashExplicitWrapper | null | undefined>, + n?: number + ): LoDashExplicitWrapper; } //_.takeRight @@ -3824,32 +2540,24 @@ declare namespace _ { ): T[]; } - interface LoDashImplicitArrayWrapperBase { + interface LoDashImplicitWrapper { /** * @see _.takeRight */ - takeRight(n?: number): LoDashImplicitArrayWrapper; + takeRight( + this: LoDashImplicitWrapper | null | undefined>, + n?: number + ): LoDashImplicitWrapper; } - interface LoDashImplicitObjectWrapperBase { + interface LoDashExplicitWrapper { /** * @see _.takeRight */ - takeRight(n?: number): LoDashImplicitArrayWrapper; - } - - interface LoDashExplicitArrayWrapperBase { - /** - * @see _.takeRight - */ - takeRight(n?: number): LoDashExplicitArrayWrapper; - } - - interface LoDashExplicitObjectWrapperBase { - /** - * @see _.takeRight - */ - takeRight(n?: number): LoDashExplicitArrayWrapper; + takeRight( + this: LoDashExplicitWrapper | null | undefined>, + n?: number + ): LoDashExplicitWrapper; } //_.takeRightWhile @@ -3872,118 +2580,30 @@ declare namespace _ { * @param thisArg The this binding of predicate. * @return Returns the slice of array. */ - takeRightWhile( - array: List | null | undefined, - predicate?: ListIterator - ): TValue[]; - - /** - * @see _.takeRightWhile - */ - takeRightWhile( - array: List | null | undefined, - predicate?: string - ): TValue[]; - - /** - * @see _.takeRightWhile - */ - takeRightWhile( - array: List | null | undefined, - predicate?: TWhere - ): TValue[]; + takeRightWhile( + array: List | null | undefined, + predicate?: ListIteratee + ): T[]; } - interface LoDashImplicitArrayWrapperBase { + interface LoDashImplicitWrapper { /** * @see _.takeRightWhile */ - takeRightWhile( - predicate?: ListIterator - ): LoDashImplicitArrayWrapper; - - /** - * @see _.takeRightWhile - */ - takeRightWhile( - predicate?: string - ): LoDashImplicitArrayWrapper; - - /** - * @see _.takeRightWhile - */ - takeRightWhile( - predicate?: TWhere - ): LoDashImplicitArrayWrapper; + takeRightWhile( + this: LoDashImplicitWrapper | null | undefined>, + predicate?: ListIteratee + ): LoDashImplicitWrapper; } - interface LoDashImplicitObjectWrapperBase { + interface LoDashExplicitWrapper { /** * @see _.takeRightWhile */ - takeRightWhile( - predicate?: ListIterator - ): LoDashImplicitArrayWrapper; - - /** - * @see _.takeRightWhile - */ - takeRightWhile( - predicate?: string - ): LoDashImplicitArrayWrapper; - - /** - * @see _.takeRightWhile - */ - takeRightWhile( - predicate?: TWhere - ): LoDashImplicitArrayWrapper; - } - - interface LoDashExplicitArrayWrapperBase { - /** - * @see _.takeRightWhile - */ - takeRightWhile( - predicate?: ListIterator - ): LoDashExplicitArrayWrapper; - - /** - * @see _.takeRightWhile - */ - takeRightWhile( - predicate?: string - ): LoDashExplicitArrayWrapper; - - /** - * @see _.takeRightWhile - */ - takeRightWhile( - predicate?: TWhere - ): LoDashExplicitArrayWrapper; - } - - interface LoDashExplicitObjectWrapperBase { - /** - * @see _.takeRightWhile - */ - takeRightWhile( - predicate?: ListIterator - ): LoDashExplicitArrayWrapper; - - /** - * @see _.takeRightWhile - */ - takeRightWhile( - predicate?: string - ): LoDashExplicitArrayWrapper; - - /** - * @see _.takeRightWhile - */ - takeRightWhile( - predicate?: TWhere - ): LoDashExplicitArrayWrapper; + takeRightWhile( + this: LoDashExplicitWrapper | null | undefined>, + predicate?: ListIteratee + ): LoDashExplicitWrapper; } //_.takeWhile @@ -4006,118 +2626,30 @@ declare namespace _ { * @param thisArg The this binding of predicate. * @return Returns the slice of array. */ - takeWhile( - array: List | null | undefined, - predicate?: ListIterator - ): TValue[]; - - /** - * @see _.takeWhile - */ - takeWhile( - array: List | null | undefined, - predicate?: string - ): TValue[]; - - /** - * @see _.takeWhile - */ - takeWhile( - array: List | null | undefined, - predicate?: TWhere - ): TValue[]; + takeWhile( + array: List | null | undefined, + predicate?: ListIteratee + ): T[]; } - interface LoDashImplicitArrayWrapperBase { + interface LoDashImplicitWrapper { /** * @see _.takeWhile */ - takeWhile( - predicate?: ListIterator - ): LoDashImplicitArrayWrapper; - - /** - * @see _.takeWhile - */ - takeWhile( - predicate?: string - ): LoDashImplicitArrayWrapper; - - /** - * @see _.takeWhile - */ - takeWhile( - predicate?: TWhere - ): LoDashImplicitArrayWrapper; + takeWhile( + this: LoDashImplicitWrapper | null | undefined>, + predicate?: ListIteratee + ): LoDashImplicitWrapper; } - interface LoDashImplicitObjectWrapperBase { + interface LoDashExplicitWrapper { /** * @see _.takeWhile */ - takeWhile( - predicate?: ListIterator - ): LoDashImplicitArrayWrapper; - - /** - * @see _.takeWhile - */ - takeWhile( - predicate?: string - ): LoDashImplicitArrayWrapper; - - /** - * @see _.takeWhile - */ - takeWhile( - predicate?: TWhere - ): LoDashImplicitArrayWrapper; - } - - interface LoDashExplicitArrayWrapperBase { - /** - * @see _.takeWhile - */ - takeWhile( - predicate?: ListIterator - ): LoDashExplicitArrayWrapper; - - /** - * @see _.takeWhile - */ - takeWhile( - predicate?: string - ): LoDashExplicitArrayWrapper; - - /** - * @see _.takeWhile - */ - takeWhile( - predicate?: TWhere - ): LoDashExplicitArrayWrapper; - } - - interface LoDashExplicitObjectWrapperBase { - /** - * @see _.takeWhile - */ - takeWhile( - predicate?: ListIterator - ): LoDashExplicitArrayWrapper; - - /** - * @see _.takeWhile - */ - takeWhile( - predicate?: string - ): LoDashExplicitArrayWrapper; - - /** - * @see _.takeWhile - */ - takeWhile( - predicate?: TWhere - ): LoDashExplicitArrayWrapper; + takeWhile( + this: LoDashExplicitWrapper | null | undefined>, + predicate?: ListIteratee + ): LoDashExplicitWrapper; } //_.union @@ -4132,42 +2664,24 @@ declare namespace _ { union(...arrays: Array | null | undefined>): T[]; } - interface LoDashImplicitArrayWrapperBase { + interface LoDashImplicitWrapper { /** * @see _.union */ - union(...arrays: Array | null | undefined>): LoDashImplicitArrayWrapper; - - /** - * @see _.union - */ - union(...arrays: Array | null | undefined>): LoDashImplicitArrayWrapper; + union( + this: LoDashImplicitWrapper | null | undefined>, + ...arrays: Array | null | undefined> + ): LoDashImplicitWrapper; } - interface LoDashImplicitObjectWrapperBase { + interface LoDashExplicitWrapper { /** * @see _.union */ - union(...arrays: Array | null | undefined>): LoDashImplicitArrayWrapper; - } - - interface LoDashExplicitArrayWrapperBase { - /** - * @see _.union - */ - union(...arrays: Array | null | undefined>): LoDashExplicitArrayWrapper; - - /** - * @see _.union - */ - union(...arrays: Array | null | undefined>): LoDashExplicitArrayWrapper; - } - - interface LoDashExplicitObjectWrapperBase { - /** - * @see _.union - */ - union(...arrays: Array | null | undefined>): LoDashExplicitArrayWrapper; + union( + this: LoDashExplicitWrapper | null | undefined>, + ...arrays: Array | null | undefined> + ): LoDashExplicitWrapper; } //_.unionBy @@ -4183,504 +2697,258 @@ declare namespace _ { */ unionBy( arrays: List | null | undefined, - iteratee?: (value: T) => any + iteratee?: ValueIteratee ): T[]; /** * @see _.unionBy */ - unionBy( + unionBy( + arrays1: List | null | undefined, + arrays2: List | null | undefined, + iteratee?: ValueIteratee + ): T[]; + + /** + * @see _.unionBy + */ + unionBy( + arrays1: List | null | undefined, + arrays2: List | null | undefined, + arrays3: List | null | undefined, + iteratee?: ValueIteratee + ): T[]; + + /** + * @see _.unionBy + */ + unionBy( + arrays1: List | null | undefined, + arrays2: List | null | undefined, + arrays3: List | null | undefined, + arrays4: List | null | undefined, + iteratee?: ValueIteratee + ): T[]; + + /** + * @see _.unionBy + */ + unionBy( + arrays1: List | null | undefined, + arrays2: List | null | undefined, + arrays3: List | null | undefined, + arrays4: List | null | undefined, + arrays5: List | null | undefined, + ...iteratee: Array | List | null | undefined> + ): T[]; + } + + interface LoDashImplicitWrapper { + /** + * @see _.unionBy + */ + unionBy( + this: LoDashImplicitWrapper | null | undefined>, + iteratee?: ValueIteratee + ): LoDashImplicitWrapper; + + /** + * @see _.unionBy + */ + unionBy( + this: LoDashImplicitWrapper | null | undefined>, + arrays2: List | null | undefined, + iteratee?: ValueIteratee + ): LoDashImplicitWrapper; + + /** + * @see _.unionBy + */ + unionBy( + this: LoDashImplicitWrapper | null | undefined>, + arrays2: List | null | undefined, + arrays3: List | null | undefined, + iteratee?: ValueIteratee + ): LoDashImplicitWrapper; + + /** + * @see _.unionBy + */ + unionBy( + this: LoDashImplicitWrapper | null | undefined>, + arrays2: List | null | undefined, + arrays3: List | null | undefined, + arrays4: List | null | undefined, + iteratee?: ValueIteratee + ): LoDashImplicitWrapper; + + /** + * @see _.unionBy + */ + unionBy( + this: LoDashImplicitWrapper | null | undefined>, + arrays2: List | null | undefined, + arrays3: List | null | undefined, + arrays4: List | null | undefined, + arrays5: List | null | undefined, + ...iteratee: Array | List | null | undefined> + ): LoDashImplicitWrapper; + } + + interface LoDashExplicitWrapper { + /** + * @see _.unionBy + */ + unionBy( + this: LoDashExplicitWrapper | null | undefined>, + iteratee?: ValueIteratee + ): LoDashExplicitWrapper; + + /** + * @see _.unionBy + */ + unionBy( + this: LoDashExplicitWrapper | null | undefined>, + arrays2: List | null | undefined, + iteratee?: ValueIteratee + ): LoDashExplicitWrapper; + + /** + * @see _.unionBy + */ + unionBy( + this: LoDashExplicitWrapper | null | undefined>, + arrays2: List | null | undefined, + arrays3: List | null | undefined, + iteratee?: ValueIteratee + ): LoDashExplicitWrapper; + + /** + * @see _.unionBy + */ + unionBy( + this: LoDashExplicitWrapper | null | undefined>, + arrays2: List | null | undefined, + arrays3: List | null | undefined, + arrays4: List | null | undefined, + iteratee?: ValueIteratee + ): LoDashExplicitWrapper; + + /** + * @see _.unionBy + */ + unionBy( + this: LoDashExplicitWrapper | null | undefined>, + arrays2: List | null | undefined, + arrays3: List | null | undefined, + arrays4: List | null | undefined, + arrays5: List | null | undefined, + ...iteratee: Array | List | null | undefined> + ): LoDashExplicitWrapper; + } + + //_.unionWith + interface LoDashStatic { + /** + * This method is like `_.union` except that it accepts `comparator` which + * is invoked to compare elements of `arrays`. The comparator is invoked + * with two arguments: (arrVal, othVal). + * + * @static + * @memberOf _ + * @category Array + * @param {...Array} [arrays] The arrays to inspect. + * @param {Function} [comparator] The comparator invoked per element. + * @returns {Array} Returns the new array of combined values. + * @example + * + * var objects = [{ 'x': 1, 'y': 2 }, { 'x': 2, 'y': 1 }]; + * var others = [{ 'x': 1, 'y': 1 }, { 'x': 1, 'y': 2 }]; + * + * _.unionWith(objects, others, _.isEqual); + * // => [{ 'x': 1, 'y': 2 }, { 'x': 2, 'y': 1 }, { 'x': 1, 'y': 1 }] + */ + unionWith( arrays: List | null | undefined, - iteratee?: W + comparator?: Comparator ): T[]; /** * @see _.unionBy */ - unionBy( - arrays1: List | null | undefined, - arrays2: List | null | undefined, - iteratee?: (value: T) => any - ): T[]; - - /** - * @see _.unionBy - */ - unionBy( - arrays1: List | null | undefined, - arrays2: List | null | undefined, - iteratee?: W - ): T[]; - - /** - * @see _.unionBy - */ - unionBy( - arrays1: List | null | undefined, - arrays2: List | null | undefined, - arrays3: List | null | undefined, - iteratee?: (value: T) => any - ): T[]; - - /** - * @see _.unionBy - */ - unionBy( - arrays1: List | null | undefined, - arrays2: List | null | undefined, - arrays3: List | null | undefined, - iteratee?: W - ): T[]; - - /** - * @see _.unionBy - */ - unionBy( - arrays1: List | null | undefined, - arrays2: List | null | undefined, - arrays3: List | null | undefined, - arrays4: List | null | undefined, - iteratee?: (value: T) => any - ): T[]; - - /** - * @see _.unionBy - */ - unionBy( - arrays1: List | null | undefined, - arrays2: List | null | undefined, - arrays3: List | null | undefined, - arrays4: List | null | undefined, - iteratee?: W - ): T[]; - - /** - * @see _.unionBy - */ - unionBy( - arrays1: List | null | undefined, - arrays2: List | null | undefined, - arrays3: List | null | undefined, - arrays4: List | null | undefined, - arrays5: List | null | undefined, - iteratee?: (value: T) => any - ): T[]; - - /** - * @see _.unionBy - */ - unionBy( - arrays1: List | null | undefined, - arrays2: List | null | undefined, - arrays3: List | null | undefined, - arrays4: List | null | undefined, - arrays5: List | null | undefined, - iteratee?: W - ): T[]; - - /** - * @see _.unionBy - */ - unionBy( + unionWith( arrays: List | null | undefined, - ...iteratee: any[] + arrays2: List | null | undefined, + comparator?: Comparator + ): T[]; + + /** + * @see _.unionWith + */ + unionWith( + arrays: List | null | undefined, + arrays2: List | null | undefined, + arrays3: List | null | undefined, + ...comparator: Array | List | null | undefined> ): T[]; } - interface LoDashImplicitArrayWrapperBase { + interface LoDashImplicitWrapper { /** - * @see _.unionBy + * @see _.unionWith */ - unionBy( - iteratee?: (value: T) => any - ): LoDashImplicitArrayWrapper; + unionWith( + this: LoDashImplicitWrapper | null | undefined>, + comparator?: Comparator + ): LoDashImplicitWrapper; /** - * @see _.unionBy + * @see _.unionWith */ - unionBy( - iteratee?: W - ): LoDashImplicitArrayWrapper; - - /** - * @see _.unionBy - */ - unionBy( + unionWith( + this: LoDashImplicitWrapper | null | undefined>, arrays2: List | null | undefined, - iteratee?: (value: T) => any - ): LoDashImplicitArrayWrapper; + comparator?: Comparator + ): LoDashImplicitWrapper; /** - * @see _.unionBy + * @see _.unionWith */ - unionBy( - arrays2: List | null | undefined, - iteratee?: W - ): LoDashImplicitArrayWrapper; - - /** - * @see _.unionBy - */ - unionBy( + unionWith( + this: LoDashImplicitWrapper | null | undefined>, arrays2: List | null | undefined, arrays3: List | null | undefined, - iteratee?: (value: T) => any - ): LoDashImplicitArrayWrapper; - - /** - * @see _.unionBy - */ - unionBy( - arrays2: List | null | undefined, - arrays3: List | null | undefined, - iteratee?: W - ): LoDashImplicitArrayWrapper; - - /** - * @see _.unionBy - */ - unionBy( - arrays2: List | null | undefined, - arrays3: List | null | undefined, - arrays4: List | null | undefined, - iteratee?: (value: T) => any - ): LoDashImplicitArrayWrapper; - - /** - * @see _.unionBy - */ - unionBy( - arrays2: List | null | undefined, - arrays3: List | null | undefined, - arrays4: List | null | undefined, - iteratee?: W - ): LoDashImplicitArrayWrapper; - - /** - * @see _.unionBy - */ - unionBy( - arrays2: List | null | undefined, - arrays3: List | null | undefined, - arrays4: List | null | undefined, - arrays5: List | null | undefined, - iteratee?: (value: T) => any - ): LoDashImplicitArrayWrapper; - - /** - * @see _.unionBy - */ - unionBy( - arrays2: List | null | undefined, - arrays3: List | null | undefined, - arrays4: List | null | undefined, - arrays5: List | null | undefined, - iteratee?: W - ): LoDashImplicitArrayWrapper; - - /** - * @see _.unionBy - */ - unionBy( - ...iteratee: any[] - ): LoDashImplicitArrayWrapper; + ...comparator: Array | List | null | undefined> + ): LoDashImplicitWrapper; } - interface LoDashImplicitObjectWrapperBase { + interface LoDashExplicitWrapper { /** - * @see _.unionBy + * @see _.unionWith */ - unionBy( - iteratee?: (value: T) => any - ): LoDashImplicitArrayWrapper; + unionWith( + this: LoDashExplicitWrapper | null | undefined>, + comparator?: Comparator + ): LoDashExplicitWrapper; /** - * @see _.unionBy + * @see _.unionWith */ - unionBy( - iteratee?: W - ): LoDashImplicitArrayWrapper; - - /** - * @see _.unionBy - */ - unionBy( + unionWith( + this: LoDashExplicitWrapper | null | undefined>, arrays2: List | null | undefined, - iteratee?: (value: T) => any - ): LoDashImplicitArrayWrapper; + comparator?: Comparator + ): LoDashExplicitWrapper; /** - * @see _.unionBy + * @see _.unionWith */ - unionBy( - arrays2: List | null | undefined, - iteratee?: W - ): LoDashImplicitArrayWrapper; - - /** - * @see _.unionBy - */ - unionBy( + unionWith( + this: LoDashExplicitWrapper | null | undefined>, arrays2: List | null | undefined, arrays3: List | null | undefined, - iteratee?: (value: T) => any - ): LoDashImplicitArrayWrapper; - - /** - * @see _.unionBy - */ - unionBy( - arrays2: List | null | undefined, - arrays3: List | null | undefined, - iteratee?: W - ): LoDashImplicitArrayWrapper; - - /** - * @see _.unionBy - */ - unionBy( - arrays2: List | null | undefined, - arrays3: List | null | undefined, - arrays4: List | null | undefined, - iteratee?: (value: T) => any - ): LoDashImplicitArrayWrapper; - - /** - * @see _.unionBy - */ - unionBy( - arrays2: List | null | undefined, - arrays3: List | null | undefined, - arrays4: List | null | undefined, - iteratee?: W - ): LoDashImplicitArrayWrapper; - - /** - * @see _.unionBy - */ - unionBy( - arrays2: List | null | undefined, - arrays3: List | null | undefined, - arrays4: List | null | undefined, - arrays5: List | null | undefined, - iteratee?: (value: T) => any - ): LoDashImplicitArrayWrapper; - - /** - * @see _.unionBy - */ - unionBy( - arrays2: List | null | undefined, - arrays3: List | null | undefined, - arrays4: List | null | undefined, - arrays5: List | null | undefined, - iteratee?: W - ): LoDashImplicitArrayWrapper; - - /** - * @see _.unionBy - */ - unionBy( - ...iteratee: any[] - ): LoDashImplicitArrayWrapper; - } - - interface LoDashExplicitArrayWrapperBase { - /** - * @see _.unionBy - */ - unionBy( - iteratee?: (value: T) => any - ): LoDashExplicitArrayWrapper; - - /** - * @see _.unionBy - */ - unionBy( - iteratee?: W - ): LoDashExplicitArrayWrapper; - - /** - * @see _.unionBy - */ - unionBy( - arrays2: List | null | undefined, - iteratee?: (value: T) => any - ): LoDashExplicitArrayWrapper; - - /** - * @see _.unionBy - */ - unionBy( - arrays2: List | null | undefined, - iteratee?: W - ): LoDashExplicitArrayWrapper; - - /** - * @see _.unionBy - */ - unionBy( - arrays2: List | null | undefined, - arrays3: List | null | undefined, - iteratee?: (value: T) => any - ): LoDashExplicitArrayWrapper; - - /** - * @see _.unionBy - */ - unionBy( - arrays2: List | null | undefined, - arrays3: List | null | undefined, - iteratee?: W - ): LoDashExplicitArrayWrapper; - - /** - * @see _.unionBy - */ - unionBy( - arrays2: List | null | undefined, - arrays3: List | null | undefined, - arrays4: List | null | undefined, - iteratee?: (value: T) => any - ): LoDashExplicitArrayWrapper; - - /** - * @see _.unionBy - */ - unionBy( - arrays2: List | null | undefined, - arrays3: List | null | undefined, - arrays4: List | null | undefined, - iteratee?: W - ): LoDashExplicitArrayWrapper; - - /** - * @see _.unionBy - */ - unionBy( - arrays2: List | null | undefined, - arrays3: List | null | undefined, - arrays4: List | null | undefined, - arrays5: List | null | undefined, - iteratee?: (value: T) => any - ): LoDashExplicitArrayWrapper; - - /** - * @see _.unionBy - */ - unionBy( - arrays2: List | null | undefined, - arrays3: List | null | undefined, - arrays4: List | null | undefined, - arrays5: List | null | undefined, - iteratee?: W - ): LoDashExplicitArrayWrapper; - - /** - * @see _.unionBy - */ - unionBy( - ...iteratee: any[] - ): LoDashExplicitArrayWrapper; - } - - interface LoDashExplicitObjectWrapperBase { - /** - * @see _.unionBy - */ - unionBy( - iteratee?: (value: T) => any - ): LoDashExplicitArrayWrapper; - - /** - * @see _.unionBy - */ - unionBy( - iteratee?: W - ): LoDashExplicitArrayWrapper; - - /** - * @see _.unionBy - */ - unionBy( - arrays2: List | null | undefined, - iteratee?: (value: T) => any - ): LoDashExplicitArrayWrapper; - - /** - * @see _.unionBy - */ - unionBy( - arrays2: List | null | undefined, - iteratee?: W - ): LoDashExplicitArrayWrapper; - - /** - * @see _.unionBy - */ - unionBy( - arrays2: List | null | undefined, - arrays3: List | null | undefined, - iteratee?: (value: T) => any - ): LoDashExplicitArrayWrapper; - - /** - * @see _.unionBy - */ - unionBy( - arrays2: List | null | undefined, - arrays3: List | null | undefined, - iteratee?: W - ): LoDashExplicitArrayWrapper; - - /** - * @see _.unionBy - */ - unionBy( - arrays2: List | null | undefined, - arrays3: List | null | undefined, - arrays4: List | null | undefined, - iteratee?: (value: T) => any - ): LoDashExplicitArrayWrapper; - - /** - * @see _.unionBy - */ - unionBy( - arrays2: List | null | undefined, - arrays3: List | null | undefined, - arrays4: List | null | undefined, - iteratee?: W - ): LoDashExplicitArrayWrapper; - - /** - * @see _.unionBy - */ - unionBy( - arrays2: List | null | undefined, - arrays3: List | null | undefined, - arrays4: List | null | undefined, - arrays5: List | null | undefined, - iteratee?: (value: T) => any - ): LoDashExplicitArrayWrapper; - - /** - * @see _.unionBy - */ - unionBy( - arrays2: List | null | undefined, - arrays3: List | null | undefined, - arrays4: List | null | undefined, - arrays5: List | null | undefined, - iteratee?: W - ): LoDashExplicitArrayWrapper; - - /** - * @see _.unionBy - */ - unionBy( - ...iteratee: any[] - ): LoDashExplicitArrayWrapper; + ...comparator: Array | List | null | undefined> + ): LoDashExplicitWrapper; } //_.uniq @@ -4704,72 +2972,20 @@ declare namespace _ { uniq( array: List | null | undefined ): T[]; - - /** - * @see _.uniq - */ - uniq( - array: List | null | undefined - ): T[]; } - interface LoDashImplicitWrapper { + interface LoDashImplicitWrapper { /** * @see _.uniq */ - uniq(): LoDashImplicitArrayWrapper; + uniq(this: LoDashImplicitWrapper | null | undefined>): LoDashImplicitWrapper; } - interface LoDashImplicitArrayWrapperBase { + interface LoDashExplicitWrapper { /** * @see _.uniq */ - uniq(): LoDashImplicitArrayWrapper; - - /** - * @see _.uniq - */ - uniq(): LoDashImplicitArrayWrapper; - } - - interface LoDashImplicitObjectWrapperBase { - uniq(): LoDashImplicitArrayWrapper; - - /** - * @see _.uniq - */ - uniq(): LoDashImplicitArrayWrapper; - } - - interface LoDashExplicitWrapper { - /** - * @see _.uniq - */ - uniq(): LoDashExplicitArrayWrapper; - } - - interface LoDashExplicitArrayWrapperBase { - /** - * @see _.uniq - */ - uniq(): LoDashExplicitArrayWrapper; - - /** - * @see _.uniq - */ - uniq(): LoDashExplicitArrayWrapper; - } - - interface LoDashExplicitObjectWrapperBase { - /** - * @see _.uniq - */ - uniq(): LoDashExplicitArrayWrapper; - - /** - * @see _.uniq - */ - uniq(): LoDashExplicitArrayWrapper; + uniq(this: LoDashExplicitWrapper | null | undefined>): LoDashExplicitWrapper; } //_.uniqBy @@ -4794,206 +3010,100 @@ declare namespace _ { * _.uniqBy([{ 'x': 1 }, { 'x': 2 }, { 'x': 1 }], 'x'); * // => [{ 'x': 1 }, { 'x': 2 }] */ - uniqBy( - array: TString, + uniqBy( + array: string | null | undefined, iteratee: StringIterator - ): TString[]; + ): string[]; /** * @see _.uniqBy */ uniqBy( array: List | null | undefined, - iteratee: ListIterator - ): T[]; - - /** - * @see _.uniqBy - */ - uniqBy( - array: List | null | undefined, - iteratee: ListIterator - ): T[]; - - /** - * @see _.uniqBy - */ - uniqBy( - array: List | null | undefined, - iteratee: string - ): T[]; - - /** - * @see _.uniqBy - */ - uniqBy( - array: List | null | undefined, - iteratee: Object - ): T[]; - - /** - * @see _.uniqBy - */ - uniqBy( - array: List | null | undefined, - iteratee: TWhere + iteratee: ListIteratee ): T[]; } - interface LoDashImplicitStringWrapper { + interface LoDashImplicitWrapper { /** * @see _.uniqBy */ uniqBy( + this: LoDashImplicitWrapper, iteratee: StringIterator - ): LoDashImplicitArrayWrapper; + ): LoDashImplicitWrapper; + + /** + * @see _.uniqBy + */ + uniqBy( + this: LoDashImplicitWrapper | null | undefined>, + iteratee: ListIteratee + ): LoDashImplicitWrapper; } - interface LoDashExplicitStringWrapper { + interface LoDashExplicitWrapper { /** * @see _.uniqBy */ uniqBy( + this: LoDashExplicitWrapper, iteratee: StringIterator - ): LoDashExplicitArrayWrapper; - } - - interface LoDashImplicitWrapper { - /** - * @see _.uniqBy - */ - uniqBy( - iteratee: ListIterator - ): LoDashImplicitArrayWrapper; - } - - interface LoDashImplicitArrayWrapperBase { - /** - * @see _.uniqBy - */ - uniqBy( - iteratee: ListIterator - ): LoDashImplicitArrayWrapper; - - /** - * @see _.uniqBy - */ - uniqBy( - iteratee: string - ): LoDashImplicitArrayWrapper; - - /** - * @see _.uniqBy - */ - uniqBy( - iteratee: TWhere - ): LoDashImplicitArrayWrapper; - } - - interface LoDashImplicitObjectWrapperBase { - /** - * @see _.uniqBy - */ - uniqBy( - iteratee: ListIterator - ): LoDashImplicitArrayWrapper; - - /** - * @see _.uniqBy - */ - uniqBy( - iteratee: ListIterator - ): LoDashImplicitArrayWrapper; + ): LoDashExplicitWrapper; /** * @see _.uniqBy */ uniqBy( - iteratee: string - ): LoDashImplicitArrayWrapper; - - /** - * @see _.uniqBy - */ - uniqBy( - iteratee: Object - ): LoDashImplicitArrayWrapper; - - /** - * @see _.uniqBy - */ - uniqBy( - iteratee: TWhere - ): LoDashImplicitArrayWrapper; + this: LoDashExplicitWrapper | null | undefined>, + iteratee: ListIteratee + ): LoDashExplicitWrapper; } - interface LoDashExplicitWrapper { + //_.uniqWith + interface LoDashStatic { /** - * @see _.uniqBy + * This method is like `_.uniq` except that it accepts `comparator` which + * is invoked to compare elements of `array`. The comparator is invoked with + * two arguments: (arrVal, othVal). + * + * @static + * @memberOf _ + * @category Array + * @param {Array} array The array to inspect. + * @param {Function} [comparator] The comparator invoked per element. + * @returns {Array} Returns the new duplicate free array. + * @example + * + * var objects = [{ 'x': 1, 'y': 2 }, { 'x': 2, 'y': 1 }, { 'x': 1, 'y': 2 }]; + * + * _.uniqWith(objects, _.isEqual); + * // => [{ 'x': 1, 'y': 2 }, { 'x': 2, 'y': 1 }] */ - uniqBy( - iteratee: ListIterator - ): LoDashExplicitArrayWrapper; + uniqWith( + array: List | null | undefined, + comparator?: Comparator + ): T[]; } - interface LoDashExplicitArrayWrapperBase { + interface LoDashImplicitWrapper { /** - * @see _.uniqBy + * @see _.uniqWith */ - uniqBy( - iteratee: ListIterator - ): LoDashExplicitArrayWrapper; - - /** - * @see _.uniqBy - */ - uniqBy( - iteratee: string - ): LoDashExplicitArrayWrapper; - - /** - * @see _.uniqBy - */ - uniqBy( - iteratee: TWhere - ): LoDashExplicitArrayWrapper; + uniqWith( + this: LoDashImplicitWrapper | null | undefined>, + comparator?: Comparator + ): LoDashImplicitWrapper; } - interface LoDashExplicitObjectWrapperBase { + interface LoDashExplicitWrapper { /** - * @see _.uniqBy + * @see _.uniqWith */ - uniqBy( - iteratee: ListIterator - ): LoDashExplicitArrayWrapper; - - /** - * @see _.uniqBy - */ - uniqBy( - iteratee: ListIterator - ): LoDashExplicitArrayWrapper; - - /** - * @see _.uniqBy - */ - uniqBy( - iteratee: string - ): LoDashExplicitArrayWrapper; - - /** - * @see _.uniqBy - */ - uniqBy( - iteratee: Object - ): LoDashExplicitArrayWrapper; - - /** - * @see _.uniqBy - */ - uniqBy( - iteratee: TWhere - ): LoDashExplicitArrayWrapper; + uniqWith( + this: LoDashExplicitWrapper | null | undefined>, + comparator?: Comparator + ): LoDashExplicitWrapper; } //_.sortedUniq @@ -5015,72 +3125,20 @@ declare namespace _ { sortedUniq( array: List | null | undefined ): T[]; - - /** - * @see _.sortedUniq - */ - sortedUniq( - array: List | null | undefined - ): T[]; } - interface LoDashImplicitWrapper { + interface LoDashImplicitWrapper { /** * @see _.sortedUniq */ - sortedUniq(): LoDashImplicitArrayWrapper; + sortedUniq(this: LoDashImplicitWrapper | null | undefined>): LoDashImplicitWrapper; } - interface LoDashImplicitArrayWrapperBase { + interface LoDashExplicitWrapper { /** * @see _.sortedUniq */ - sortedUniq(): LoDashImplicitArrayWrapper; - - /** - * @see _.sortedUniq - */ - sortedUniq(): LoDashImplicitArrayWrapper; - } - - interface LoDashImplicitObjectWrapperBase { - sortedUniq(): LoDashImplicitArrayWrapper; - - /** - * @see _.sortedUniq - */ - sortedUniq(): LoDashImplicitArrayWrapper; - } - - interface LoDashExplicitWrapper { - /** - * @see _.sortedUniq - */ - sortedUniq(): LoDashExplicitArrayWrapper; - } - - interface LoDashExplicitArrayWrapperBase { - /** - * @see _.sortedUniq - */ - sortedUniq(): LoDashExplicitArrayWrapper; - - /** - * @see _.sortedUniq - */ - sortedUniq(): LoDashExplicitArrayWrapper; - } - - interface LoDashExplicitObjectWrapperBase { - /** - * @see _.sortedUniq - */ - sortedUniq(): LoDashExplicitArrayWrapper; - - /** - * @see _.sortedUniq - */ - sortedUniq(): LoDashExplicitArrayWrapper; + sortedUniq(this: LoDashExplicitWrapper | null | undefined>): LoDashExplicitWrapper; } //_.sortedUniqBy @@ -5100,259 +3158,54 @@ declare namespace _ { * _.sortedUniqBy([1.1, 1.2, 2.3, 2.4], Math.floor); * // => [1.1, 2.2] */ - sortedUniqBy( - array: TString, + sortedUniqBy( + array: string | null | undefined, iteratee: StringIterator - ): TString[]; + ): string[]; /** * @see _.sortedUniqBy */ sortedUniqBy( array: List | null | undefined, - iteratee: ListIterator - ): T[]; - - /** - * @see _.sortedUniqBy - */ - sortedUniqBy( - array: List | null | undefined, - iteratee: ListIterator - ): T[]; - - /** - * @see _.sortedUniqBy - */ - sortedUniqBy( - array: List | null | undefined, - iteratee: string - ): T[]; - - /** - * @see _.sortedUniqBy - */ - sortedUniqBy( - array: List | null | undefined, - iteratee: Object - ): T[]; - - /** - * @see _.sortedUniqBy - */ - sortedUniqBy( - array: List | null | undefined, - iteratee: TWhere + iteratee: ListIteratee ): T[]; } - interface LoDashImplicitStringWrapper { + interface LoDashImplicitWrapper { /** * @see _.sortedUniqBy */ sortedUniqBy( + this: LoDashImplicitWrapper, iteratee: StringIterator - ): LoDashImplicitArrayWrapper; + ): LoDashImplicitWrapper; + + /** + * @see _.sortedUniqBy + */ + sortedUniqBy( + this: LoDashImplicitWrapper | null | undefined>, + iteratee: ListIteratee + ): LoDashImplicitWrapper; } - interface LoDashExplicitStringWrapper { + interface LoDashExplicitWrapper { /** * @see _.sortedUniqBy */ sortedUniqBy( + this: LoDashExplicitWrapper, iteratee: StringIterator - ): LoDashExplicitArrayWrapper; - } - - interface LoDashImplicitWrapper { - /** - * @see _.sortedUniqBy - */ - sortedUniqBy( - iteratee: ListIterator - ): LoDashImplicitArrayWrapper; - } - - interface LoDashImplicitArrayWrapperBase { - /** - * @see _.sortedUniqBy - */ - sortedUniqBy( - iteratee: ListIterator - ): LoDashImplicitArrayWrapper; - - /** - * @see _.sortedUniqBy - */ - sortedUniqBy( - iteratee: string - ): LoDashImplicitArrayWrapper; - - /** - * @see _.sortedUniqBy - */ - sortedUniqBy( - iteratee: TWhere - ): LoDashImplicitArrayWrapper; - } - - interface LoDashImplicitObjectWrapperBase { - /** - * @see _.sortedUniqBy - */ - sortedUniqBy( - iteratee: ListIterator - ): LoDashImplicitArrayWrapper; - - /** - * @see _.sortedUniqBy - */ - sortedUniqBy( - iteratee: ListIterator - ): LoDashImplicitArrayWrapper; + ): LoDashExplicitWrapper; /** * @see _.sortedUniqBy */ sortedUniqBy( - iteratee: string - ): LoDashImplicitArrayWrapper; - - /** - * @see _.sortedUniqBy - */ - sortedUniqBy( - iteratee: Object - ): LoDashImplicitArrayWrapper; - - /** - * @see _.sortedUniqBy - */ - sortedUniqBy( - iteratee: TWhere - ): LoDashImplicitArrayWrapper; - } - - interface LoDashExplicitWrapper { - /** - * @see _.sortedUniqBy - */ - sortedUniqBy( - iteratee: ListIterator - ): LoDashExplicitArrayWrapper; - } - - interface LoDashExplicitArrayWrapperBase { - /** - * @see _.sortedUniqBy - */ - sortedUniqBy( - iteratee: ListIterator - ): LoDashExplicitArrayWrapper; - - /** - * @see _.sortedUniqBy - */ - sortedUniqBy( - iteratee: string - ): LoDashExplicitArrayWrapper; - - /** - * @see _.sortedUniqBy - */ - sortedUniqBy( - iteratee: TWhere - ): LoDashExplicitArrayWrapper; - } - - interface LoDashExplicitObjectWrapperBase { - /** - * @see _.sortedUniqBy - */ - sortedUniqBy( - iteratee: ListIterator - ): LoDashExplicitArrayWrapper; - - /** - * @see _.sortedUniqBy - */ - sortedUniqBy( - iteratee: ListIterator - ): LoDashExplicitArrayWrapper; - - /** - * @see _.sortedUniqBy - */ - sortedUniqBy( - iteratee: string - ): LoDashExplicitArrayWrapper; - - /** - * @see _.sortedUniqBy - */ - sortedUniqBy( - iteratee: Object - ): LoDashExplicitArrayWrapper; - - /** - * @see _.sortedUniqBy - */ - sortedUniqBy( - iteratee: TWhere - ): LoDashExplicitArrayWrapper; - } - - //_.unionWith DUMMY - interface LoDashStatic { - /** - * This method is like `_.union` except that it accepts `comparator` which - * is invoked to compare elements of `arrays`. The comparator is invoked - * with two arguments: (arrVal, othVal). - * - * @static - * @memberOf _ - * @category Array - * @param {...Array} [arrays] The arrays to inspect. - * @param {Function} [comparator] The comparator invoked per element. - * @returns {Array} Returns the new array of combined values. - * @example - * - * var objects = [{ 'x': 1, 'y': 2 }, { 'x': 2, 'y': 1 }]; - * var others = [{ 'x': 1, 'y': 1 }, { 'x': 1, 'y': 2 }]; - * - * _.unionWith(objects, others, _.isEqual); - * // => [{ 'x': 1, 'y': 2 }, { 'x': 2, 'y': 1 }, { 'x': 1, 'y': 1 }] - */ - unionWith( - array: List, - ...values: any[] - ): any[]; - } - - //_.uniqWith DUMMY - interface LoDashStatic { - /** - * This method is like `_.uniq` except that it accepts `comparator` which - * is invoked to compare elements of `array`. The comparator is invoked with - * two arguments: (arrVal, othVal). - * - * @static - * @memberOf _ - * @category Array - * @param {Array} array The array to inspect. - * @param {Function} [comparator] The comparator invoked per element. - * @returns {Array} Returns the new duplicate free array. - * @example - * - * var objects = [{ 'x': 1, 'y': 2 }, { 'x': 2, 'y': 1 }, { 'x': 1, 'y': 2 }]; - * - * _.uniqWith(objects, _.isEqual); - * // => [{ 'x': 1, 'y': 2 }, { 'x': 2, 'y': 1 }] - */ - uniqWith( - array: List, - ...values: any[] - ): any[]; + this: LoDashExplicitWrapper | null | undefined>, + iteratee: ListIteratee + ): LoDashExplicitWrapper; } //_.unzip @@ -5364,35 +3217,21 @@ declare namespace _ { * @param array The array of grouped elements to process. * @return Returns the new array of regrouped elements. */ - unzip(array: List> | null | undefined): T[][]; + unzip(array: T[][] | List> | null | undefined): T[][]; } - interface LoDashImplicitArrayWrapperBase { + interface LoDashImplicitWrapper { /** * @see _.unzip */ - unzip(): LoDashImplicitArrayWrapper; + unzip(this: LoDashImplicitWrapper> | null | undefined>): LoDashImplicitWrapper; } - interface LoDashImplicitObjectWrapperBase { + interface LoDashExplicitWrapper { /** * @see _.unzip */ - unzip(): LoDashImplicitArrayWrapper; - } - - interface LoDashExplicitArrayWrapperBase { - /** - * @see _.unzip - */ - unzip(): LoDashExplicitArrayWrapper; - } - - interface LoDashExplicitObjectWrapperBase { - /** - * @see _.unzip - */ - unzip(): LoDashExplicitArrayWrapper; + unzip(this: LoDashExplicitWrapper> | null | undefined>): LoDashExplicitWrapper; } //_.unzipWith @@ -5407,28 +3246,51 @@ declare namespace _ { * @param thisArg The this binding of iteratee. * @return Returns the new array of regrouped elements. */ - unzipWith( - array: List> | null | undefined, - iteratee?: MemoIterator + unzipWith( + array: List> | null | undefined, + iteratee: (...values: T[]) => TResult ): TResult[]; - } - interface LoDashImplicitArrayWrapperBase { /** * @see _.unzipWith */ - unzipWith( - iteratee?: MemoIterator - ): LoDashImplicitArrayWrapper; + unzipWith( + array: List> | null | undefined + ): T[][]; } - interface LoDashImplicitObjectWrapperBase { + interface LoDashImplicitWrapper { /** * @see _.unzipWith */ - unzipWith( - iteratee?: MemoIterator - ): LoDashImplicitArrayWrapper; + unzipWith( + this: LoDashImplicitWrapper> | null | undefined>, + iteratee: (...values: T[]) => TResult + ): LoDashImplicitWrapper; + + /** + * @see _.unzipWith + */ + unzipWith( + this: LoDashImplicitWrapper> | null | undefined> + ): LoDashImplicitWrapper; + } + + interface LoDashExplicitWrapper { + /** + * @see _.unzipWith + */ + unzipWith( + this: LoDashExplicitWrapper> | null | undefined>, + iteratee: (...values: T[]) => TResult + ): LoDashExplicitWrapper; + + /** + * @see _.unzipWith + */ + unzipWith( + this: LoDashExplicitWrapper> | null | undefined> + ): LoDashExplicitWrapper; } //_.without @@ -5446,32 +3308,24 @@ declare namespace _ { ): T[]; } - interface LoDashImplicitArrayWrapperBase { + interface LoDashImplicitWrapper { /** * @see _.without */ - without(...values: T[]): LoDashImplicitArrayWrapper; + without( + this: LoDashImplicitWrapper | null | undefined>, + ...values: T[] + ): LoDashImplicitWrapper; } - interface LoDashImplicitObjectWrapperBase { + interface LoDashExplicitWrapper { /** * @see _.without */ - without(...values: T[]): LoDashImplicitArrayWrapper; - } - - interface LoDashExplicitArrayWrapperBase { - /** - * @see _.without - */ - without(...values: T[]): LoDashExplicitArrayWrapper; - } - - interface LoDashExplicitObjectWrapperBase { - /** - * @see _.without - */ - without(...values: T[]): LoDashExplicitArrayWrapper; + without( + this: LoDashExplicitWrapper | null | undefined>, + ...values: T[] + ): LoDashExplicitWrapper; } //_.xor @@ -5485,35 +3339,27 @@ declare namespace _ { xor(...arrays: Array | null | undefined>): T[]; } - interface LoDashImplicitArrayWrapperBase { + interface LoDashImplicitWrapper { /** * @see _.xor */ - xor(...arrays: Array | null | undefined>): LoDashImplicitArrayWrapper; + xor( + this: LoDashImplicitWrapper | null | undefined>, + ...arrays: Array | null | undefined> + ): LoDashImplicitWrapper; } - interface LoDashImplicitObjectWrapperBase { + interface LoDashExplicitWrapper { /** * @see _.xor */ - xor(...arrays: Array | null | undefined>): LoDashImplicitArrayWrapper; + xor( + this: LoDashExplicitWrapper | null | undefined>, + ...arrays: Array | null | undefined> + ): LoDashExplicitWrapper; } - interface LoDashExplicitArrayWrapperBase { - /** - * @see _.xor - */ - xor(...arrays: Array | null | undefined>): LoDashExplicitArrayWrapper; - } - - interface LoDashExplicitObjectWrapperBase { - /** - * @see _.xor - */ - xor(...arrays: Array | null | undefined>): LoDashExplicitArrayWrapper; - } - - //_.xorBy DUMMY + //_.xorBy interface LoDashStatic { /** * This method is like `_.xor` except that it accepts `iteratee` which is @@ -5535,13 +3381,90 @@ declare namespace _ { * _.xorBy([{ 'x': 1 }], [{ 'x': 2 }, { 'x': 1 }], 'x'); * // => [{ 'x': 2 }] */ - xorBy( - array: List, - ...values: any[] - ): any[]; + xorBy( + arrays?: List | null | undefined, + iteratee?: ValueIteratee + ): T[]; + + /** + * @see _.xorBy + */ + xorBy( + arrays: List | null | undefined, + arrays2: List | null | undefined, + iteratee?: ValueIteratee + ): T[]; + + /** + * @see _.xorBy + */ + xorBy( + arrays: List | null | undefined, + arrays2: List | null | undefined, + arrays3: List | null | undefined, + ...iteratee: Array | List | null | undefined> + ): T[]; } - //_.xorWith DUMMY + interface LoDashImplicitWrapper { + /** + * @see _.xor + */ + xorBy( + this: LoDashImplicitWrapper | null | undefined>, + iteratee?: ValueIteratee + ): LoDashImplicitWrapper; + + /** + * @see _.xorBy + */ + xorBy( + this: LoDashImplicitWrapper | null | undefined>, + arrays2: List | null | undefined, + iteratee?: ValueIteratee + ): LoDashImplicitWrapper; + + /** + * @see _.xorBy + */ + xorBy( + this: LoDashImplicitWrapper | null | undefined>, + arrays2: List | null | undefined, + arrays3: List | null | undefined, + ...iteratee: Array | List | null | undefined> + ): LoDashImplicitWrapper; + } + + interface LoDashExplicitWrapper { + /** + * @see _.xorBy + */ + xorBy( + this: LoDashExplicitWrapper | null | undefined>, + iteratee?: ValueIteratee + ): LoDashExplicitWrapper; + + /** + * @see _.xorBy + */ + xorBy( + this: LoDashExplicitWrapper | null | undefined>, + arrays2: List | null | undefined, + iteratee?: ValueIteratee + ): LoDashExplicitWrapper; + + /** + * @see _.xorBy + */ + xorBy( + this: LoDashExplicitWrapper | null | undefined>, + arrays2: List | null | undefined, + arrays3: List | null | undefined, + ...iteratee: Array | List | null | undefined> + ): LoDashExplicitWrapper; + } + + //_.xorWith interface LoDashStatic { /** * This method is like `_.xor` except that it accepts `comparator` which is @@ -5562,10 +3485,87 @@ declare namespace _ { * _.xorWith(objects, others, _.isEqual); * // => [{ 'x': 2, 'y': 1 }, { 'x': 1, 'y': 1 }] */ - xorWith( - array: List, - ...values: any[] - ): any[]; + xorWith( + arrays?: List | null | undefined, + comparator?: Comparator + ): T[]; + + /** + * @see _.xorWith + */ + xorWith( + arrays: List | null | undefined, + arrays2: List | null | undefined, + comparator?: Comparator + ): T[]; + + /** + * @see _.xorWith + */ + xorWith( + arrays: List | null | undefined, + arrays2: List | null | undefined, + arrays3: List | null | undefined, + ...comparator: Array | List | null | undefined> + ): T[]; + } + + interface LoDashImplicitWrapper { + /** + * @see _.xorWith + */ + xorWith( + this: LoDashImplicitWrapper | null | undefined>, + comparator?: Comparator + ): LoDashImplicitWrapper; + + /** + * @see _.xorWith + */ + xorWith( + this: LoDashImplicitWrapper | null | undefined>, + arrays2: List | null | undefined, + comparator?: Comparator + ): LoDashImplicitWrapper; + + /** + * @see _.xorWith + */ + xorWith( + this: LoDashImplicitWrapper | null | undefined>, + arrays2: List | null | undefined, + arrays3: List | null | undefined, + ...comparator: Array | List | null | undefined> + ): LoDashImplicitWrapper; + } + + interface LoDashExplicitWrapper { + /** + * @see _.xorWith + */ + xorWith( + this: LoDashExplicitWrapper | null | undefined>, + comparator?: Comparator + ): LoDashExplicitWrapper; + + /** + * @see _.xorWith + */ + xorWith( + this: LoDashExplicitWrapper | null | undefined>, + arrays2: List | null | undefined, + comparator?: Comparator + ): LoDashExplicitWrapper; + + /** + * @see _.xorWith + */ + xorWith( + this: LoDashExplicitWrapper | null | undefined>, + arrays2: List | null | undefined, + arrays3: List | null | undefined, + ...comparator: Array | List | null | undefined> + ): LoDashExplicitWrapper; } //_.zip @@ -5580,32 +3580,24 @@ declare namespace _ { zip(...arrays: Array | null | undefined>): T[][]; } - interface LoDashImplicitArrayWrapperBase { + interface LoDashImplicitWrapper { /** * @see _.zip */ - zip(...arrays: Array | null | undefined>): _.LoDashImplicitArrayWrapper; + zip( + this: LoDashImplicitWrapper | null | undefined>, + ...arrays: Array | null | undefined> + ): LoDashImplicitWrapper; } - interface LoDashImplicitObjectWrapperBase { + interface LoDashExplicitWrapper { /** * @see _.zip */ - zip(...arrays: Array | null | undefined>): _.LoDashImplicitArrayWrapper; - } - - interface LoDashExplicitArrayWrapperBase { - /** - * @see _.zip - */ - zip(...arrays: Array | null | undefined>): _.LoDashExplicitArrayWrapper; - } - - interface LoDashExplicitObjectWrapperBase { - /** - * @see _.zip - */ - zip(...arrays: Array | null | undefined>): _.LoDashExplicitArrayWrapper; + zip( + this: LoDashExplicitWrapper | null | undefined>, + ...arrays: Array | null | undefined> + ): LoDashExplicitWrapper; } //_.zipObject @@ -5618,10 +3610,24 @@ declare namespace _ { * @param values The property values. * @return Returns the new object. */ - zipObject( - props: List|List>, - values?: List + zipObject( + props: List, + values: List ): TResult; + + /** + * @see _.zipObject + */ + zipObject( + props: List|List>, + values?: List + ): any; + + /** + * @see _.zipObject + */ + zipObject(): {}; + /** * This method is like _.zipObject except that it supports property paths. * @@ -5629,204 +3635,83 @@ declare namespace _ { * @param values The property values. * @return Returns the new object. */ - zipObjectDeep( - props: List|List>, - values?: List - ): TResult; - - /** - * @see _.zipObject - */ - zipObject( - props: List|List>, - values?: List - ): TResult; - /** - * @see _.zipObjectDeep - */ - zipObjectDeep( - props: List|List>, - values?: List - ): TResult; - - /** - * @see _.zipObject - */ - zipObject( - props: List|List>, - values?: List - ): _.Dictionary; - /** - * @see _.zipObjectDeep - */ zipObjectDeep( props: List|List>, values?: List - ): _.Dictionary; + ): any; + + /** + * @see _.zipObjectDeep + */ + zipObjectDeep(): {}; } - interface LoDashImplicitArrayWrapper { + interface LoDashImplicitWrapper { /** * @see _.zipObject */ - zipObject( - values?: List - ): _.LoDashImplicitObjectWrapper; - /** - * @see _.zipObjectDeep - */ - zipObjectDeep( - values?: List - ): _.LoDashImplicitObjectWrapper; - - /** - * @see _.zipObject - */ - zipObject( - values?: List - ): _.LoDashImplicitObjectWrapper; - /** - * @see _.zipObjectDeep - */ - zipObjectDeep( - values?: List - ): _.LoDashImplicitObjectWrapper; + zipObject( + this: LoDashImplicitWrapper>, + values: List + ): LoDashImplicitWrapper; /** * @see _.zipObject */ zipObject( + this: LoDashImplicitWrapper|List>>, values?: List - ): _.LoDashImplicitObjectWrapper<_.Dictionary>; + ): LoDashImplicitWrapper; + /** * @see _.zipObjectDeep */ zipObjectDeep( + this: LoDashImplicitWrapper|List>>, values?: List - ): _.LoDashImplicitObjectWrapper<_.Dictionary>; + ): LoDashImplicitWrapper; + + /** + * @see _.zipObjectDeep + */ + zipObjectDeep( + this: LoDashImplicitWrapper|List>>, + values?: List + ): LoDashImplicitWrapper; } - interface LoDashImplicitObjectWrapper { + interface LoDashExplicitWrapper { /** * @see _.zipObject */ - zipObject( - values?: List - ): _.LoDashImplicitObjectWrapper; - /** - * @see _.zipObjectDeep - */ - zipObjectDeep( - values?: List - ): _.LoDashImplicitObjectWrapper; - - /** - * @see _.zipObject - */ - zipObject( - values?: List - ): _.LoDashImplicitObjectWrapper; - /** - * @see _.zipObjectDeep - */ - zipObjectDeep( - values?: List - ): _.LoDashImplicitObjectWrapper; + zipObject( + this: LoDashExplicitWrapper>, + values: List + ): LoDashExplicitWrapper; /** * @see _.zipObject */ zipObject( + this: LoDashExplicitWrapper|List>>, values?: List - ): _.LoDashImplicitObjectWrapper<_.Dictionary>; + ): LoDashExplicitWrapper; + /** * @see _.zipObjectDeep */ zipObjectDeep( + this: LoDashExplicitWrapper|List>>, values?: List - ): _.LoDashImplicitObjectWrapper<_.Dictionary>; - } + ): LoDashExplicitWrapper; - interface LoDashExplicitArrayWrapper { - /** - * @see _.zipObject - */ - zipObject( - values?: List - ): _.LoDashExplicitObjectWrapper; /** * @see _.zipObjectDeep */ - zipObjectDeep( - values?: List - ): _.LoDashExplicitObjectWrapper; - - /** - * @see _.zipObject - */ - zipObject( + zipObjectDeep( + this: LoDashExplicitWrapper|List>>, values?: List - ): _.LoDashExplicitObjectWrapper; - /** - * @see _.zipObjectDeep - */ - zipObjectDeep( - values?: List - ): _.LoDashExplicitObjectWrapper; - - /** - * @see _.zipObject - */ - zipObject( - values?: List - ): _.LoDashExplicitObjectWrapper<_.Dictionary>; - /** - * @see _.zipObjectDeep - */ - zipObjectDeep( - values?: List - ): _.LoDashExplicitObjectWrapper<_.Dictionary>; - } - - interface LoDashExplicitObjectWrapper { - /** - * @see _.zipObject - */ - zipObject( - values?: List - ): _.LoDashExplicitObjectWrapper; - /** - * @see _.zipObjectDeep - */ - zipObjectDeep( - values?: List - ): _.LoDashExplicitObjectWrapper; - - /** - * @see _.zipObject - */ - zipObject( - values?: List - ): _.LoDashExplicitObjectWrapper; - /** - * @see _.zipObjectDeep - */ - zipObjectDeep( - values?: List - ): _.LoDashExplicitObjectWrapper; - - /** - * @see _.zipObject - */ - zipObject( - values?: List - ): _.LoDashExplicitObjectWrapper<_.Dictionary>; - /** - * @see _.zipObjectDeep - */ - zipObjectDeep( - values?: List - ): _.LoDashExplicitObjectWrapper<_.Dictionary>; + ): LoDashExplicitWrapper; } //_.zipWith @@ -5840,14 +3725,179 @@ declare namespace _ { * @param {*} [thisArg] The `this` binding of `iteratee`. * @return Returns the new array of grouped elements. */ - zipWith(...args: any[]): TResult[]; - } + zipWith( + ...arrays: Array | null | undefined> + ): T[][]; - interface LoDashImplicitArrayWrapper { /** * @see _.zipWith */ - zipWith(...args: any[]): LoDashImplicitArrayWrapper; + zipWith( + arrays: List | null | undefined, + iteratee: (value1: T) => TResult + ): TResult[]; + + /** + * @see _.zipWith + */ + zipWith( + arrays: List | null | undefined, + arrays2: List | null | undefined, + iteratee: (value1: T, value2: T) => TResult + ): TResult[]; + + /** + * @see _.zipWith + */ + zipWith( + arrays: List | null | undefined, + arrays2: List | null | undefined, + arrays3: List | null | undefined, + iteratee: (value1: T, value2: T, value3: T) => TResult + ): TResult[]; + + /** + * @see _.zipWith + */ + zipWith( + arrays: List | null | undefined, + arrays2: List | null | undefined, + arrays3: List | null | undefined, + arrays4: List | null | undefined, + iteratee: (value1: T, value2: T, value3: T, value4: T) => TResult + ): TResult[]; + + /** + * @see _.zipWith + */ + zipWith( + arrays: List | null | undefined, + arrays2: List | null | undefined, + arrays3: List | null | undefined, + arrays4: List | null | undefined, + arrays5: List | null | undefined, + ...iteratee: Array<((...group: T[]) => TResult) | List | null | undefined> + ): TResult[]; + } + + interface LoDashImplicitWrapper { + /** + * @see _.zipWith + */ + zipWith( + this: LoDashImplicitWrapper | null | undefined>, + ...arrays: Array | null | undefined> + ): LoDashImplicitWrapper; + + /** + * @see _.zipWith + */ + zipWith( + this: LoDashImplicitWrapper | null | undefined>, + iteratee: (value1: T) => TResult + ): LoDashImplicitWrapper; + + /** + * @see _.zipWith + */ + zipWith( + this: LoDashImplicitWrapper | null | undefined>, + arrays2: List | null | undefined, + iteratee: (value1: T, value2: T) => TResult + ): LoDashImplicitWrapper; + + /** + * @see _.zipWith + */ + zipWith( + this: LoDashImplicitWrapper | null | undefined>, + arrays2: List | null | undefined, + arrays3: List | null | undefined, + iteratee: (value1: T, value2: T, value3: T) => TResult + ): LoDashImplicitWrapper; + + /** + * @see _.zipWith + */ + zipWith( + this: LoDashImplicitWrapper | null | undefined>, + arrays2: List | null | undefined, + arrays3: List | null | undefined, + arrays4: List | null | undefined, + iteratee: (value1: T, value2: T, value3: T, value4: T) => TResult + ): LoDashImplicitWrapper; + + /** + * @see _.zipWith + */ + zipWith( + this: LoDashImplicitWrapper | null | undefined>, + arrays2: List | null | undefined, + arrays3: List | null | undefined, + arrays4: List | null | undefined, + arrays5: List | null | undefined, + ...iteratee: Array<((...group: T[]) => TResult) | List | null | undefined> + ): LoDashImplicitWrapper; + } + + interface LoDashExplicitWrapper { + /** + * @see _.zipWith + */ + zipWith( + this: LoDashExplicitWrapper | null | undefined>, + ...arrays: Array | null | undefined> + ): LoDashExplicitWrapper; + + /** + * @see _.zipWith + */ + zipWith( + this: LoDashExplicitWrapper | null | undefined>, + iteratee: (value1: T) => TResult + ): LoDashExplicitWrapper; + + /** + * @see _.zipWith + */ + zipWith( + this: LoDashExplicitWrapper | null | undefined>, + arrays2: List | null | undefined, + iteratee: (value1: T, value2: T) => TResult + ): LoDashExplicitWrapper; + + /** + * @see _.zipWith + */ + zipWith( + this: LoDashExplicitWrapper | null | undefined>, + arrays2: List | null | undefined, + arrays3: List | null | undefined, + iteratee: (value1: T, value2: T, value3: T) => TResult + ): LoDashExplicitWrapper; + + /** + * @see _.zipWith + */ + zipWith( + this: LoDashExplicitWrapper | null | undefined>, + arrays2: List | null | undefined, + arrays3: List | null | undefined, + arrays4: List | null | undefined, + iteratee: (value1: T, value2: T, value3: T, value4: T) => TResult + ): LoDashExplicitWrapper; + + /** + * @see _.zipWith + */ + zipWith( + this: LoDashExplicitWrapper | null | undefined>, + arrays2: List | null | undefined, + arrays3: List | null | undefined, + arrays4: List | null | undefined, + arrays5: List | null | undefined, + ...iteratee: Array<((...group: T[]) => TResult) | List | null | undefined> + ): LoDashExplicitWrapper; } /********* @@ -5862,66 +3912,21 @@ declare namespace _ { * @param value The value to wrap. * @return Returns the new lodash wrapper instance. */ - chain(value: number): LoDashExplicitWrapper; - chain(value: string): LoDashExplicitWrapper; - chain(value: boolean): LoDashExplicitWrapper; - chain(value: null | undefined): LoDashExplicitWrapper; - chain(value: T[]): LoDashExplicitArrayWrapper; - chain(value: ReadonlyArray): LoDashExplicitArrayWrapper; - chain(value: T[] | null | undefined): LoDashExplicitNillableArrayWrapper; - chain(value: ReadonlyArray | null | undefined): LoDashExplicitNillableArrayWrapper; - chain(value: T): LoDashExplicitObjectWrapper; - chain(value: T | null | undefined): LoDashExplicitObjectWrapper; - chain(value: any): LoDashExplicitWrapper; + chain(value: T): LoDashExplicitWrapper; } - interface LoDashImplicitStringWrapper { + interface LoDashImplicitWrapper { /** * @see _.chain */ - chain(): LoDashExplicitStringWrapper; + chain(): LoDashExplicitWrapper; } - interface LoDashImplicitWrapper { + interface LoDashExplicitWrapper { /** * @see _.chain */ - chain(): LoDashExplicitWrapper; - } - - interface LoDashImplicitArrayWrapper { - /** - * @see _.chain - */ - chain(): LoDashExplicitArrayWrapper; - } - - interface LoDashImplicitNillableArrayWrapper { - /** - * @see _.chain - */ - chain(): LoDashExplicitNillableArrayWrapper; - } - - interface LoDashImplicitObjectWrapper { - /** - * @see _.chain - */ - chain(): LoDashExplicitObjectWrapper; - } - - interface LoDashImplicitNillableObjectWrapper { - /** - * @see _.chain - */ - chain(): LoDashExplicitNillableObjectWrapper; - } - - interface LoDashExplicitWrapperBase { - /** - * @see _.chain - */ - chain(): TWrapper; + chain(): this; } //_.tap @@ -5942,22 +3947,13 @@ declare namespace _ { ): T; } - interface LoDashImplicitWrapperBase { + interface LoDashWrapper { /** * @see _.tap */ tap( - interceptor: (value: T) => void - ): TWrapper; - } - - interface LoDashExplicitWrapperBase { - /** - * @see _.tap - */ - tap( - interceptor: (value: T) => void - ): TWrapper; + interceptor: (value: TValue) => void + ): this; } //_.thru @@ -5976,237 +3972,57 @@ declare namespace _ { ): TResult; } - interface LoDashImplicitWrapperBase { + interface LoDashImplicitWrapper { /** * @see _.thru */ - thru( - interceptor: (value: T) => TResult): LoDashImplicitWrapper; - - /** - * @see _.thru - */ - thru( - interceptor: (value: T) => TResult): LoDashImplicitWrapper; - - /** - * @see _.thru - */ - thru( - interceptor: (value: T) => TResult): LoDashImplicitWrapper; - - /** - * @see _.thru - */ - thru( - interceptor: (value: T) => TResult): LoDashImplicitObjectWrapper; - - /** - * @see _.thru - */ - thru( - interceptor: (value: T) => TResult[]): LoDashImplicitArrayWrapper; + thru(interceptor: (value: TValue) => TResult): LoDashImplicitWrapper; } - interface LoDashExplicitWrapperBase { + interface LoDashExplicitWrapper { /** * @see _.thru */ - thru( - interceptor: (value: T) => TResult - ): LoDashExplicitWrapper; - - /** - * @see _.thru - */ - thru( - interceptor: (value: T) => TResult - ): LoDashExplicitWrapper; - - /** - * @see _.thru - */ - thru( - interceptor: (value: T) => TResult - ): LoDashExplicitWrapper; - - /** - * @see _.thru - */ - thru( - interceptor: (value: T) => TResult - ): LoDashExplicitObjectWrapper; - - /** - * @see _.thru - */ - thru( - interceptor: (value: T) => TResult[] - ): LoDashExplicitArrayWrapper; + thru(interceptor: (value: TValue) => TResult): LoDashExplicitWrapper; } //_.prototype.commit - interface LoDashImplicitWrapperBase { + interface LoDashWrapper { /** * Executes the chained sequence and returns the wrapped result. * * @return Returns the new lodash wrapper instance. */ - commit(): TWrapper; - } - - interface LoDashExplicitWrapperBase { - /** - * @see _.commit - */ - commit(): TWrapper; - } - - //_.prototype.concat - interface LoDashImplicitWrapperBase { - /** - * Creates a new array joining a wrapped array with any additional arrays and/or values. - * - * @param items - * @return Returns the new concatenated array. - */ - concat(...items: Array>): LoDashImplicitArrayWrapper; - - /** - * @see _.concat - */ - concat(...items: Array>): LoDashImplicitArrayWrapper; - } - - interface LoDashExplicitWrapperBase { - /** - * @see _.concat - */ - concat(...items: Array>): LoDashExplicitArrayWrapper; - - /** - * @see _.concat - */ - concat(...items: Array>): LoDashExplicitArrayWrapper; + commit(): this; } //_.prototype.plant - interface LoDashImplicitWrapperBase { + interface LoDashImplicitWrapper { /** * Creates a clone of the chained sequence planting value as the wrapped value. * @param value The value to plant as the wrapped value. * @return Returns the new lodash wrapper instance. */ - plant(value: number): LoDashImplicitWrapper; - - /** - * @see _.plant - */ - plant(value: string): LoDashImplicitStringWrapper; - - /** - * @see _.plant - */ - plant(value: boolean): LoDashImplicitWrapper; - - /** - * @see _.plant - */ - plant(value: number[]): LoDashImplicitNumberArrayWrapper; - - /** - * @see _.plant - */ - plant(value: T[]): LoDashImplicitArrayWrapper; - - /** - * @see _.plant - */ - plant(value: ReadonlyArray): LoDashImplicitArrayWrapper; - - /** - * @see _.plant - */ - plant(value: T): LoDashImplicitObjectWrapper; - - /** - * @see _.plant - */ - plant(value: any): LoDashImplicitWrapper; + plant(value: T): LoDashImplicitWrapper; } - interface LoDashExplicitWrapperBase { + interface LoDashExplicitWrapper { /** * @see _.plant */ - plant(value: number): LoDashExplicitWrapper; - - /** - * @see _.plant - */ - plant(value: string): LoDashExplicitStringWrapper; - - /** - * @see _.plant - */ - plant(value: boolean): LoDashExplicitWrapper; - - /** - * @see _.plant - */ - plant(value: number[]): LoDashExplicitNumberArrayWrapper; - - /** - * @see _.plant - */ - plant(value: T[]): LoDashExplicitArrayWrapper; - - /** - * @see _.plant - */ - plant(value: ReadonlyArray): LoDashExplicitArrayWrapper; - - /** - * @see _.plant - */ - plant(value: T): LoDashExplicitObjectWrapper; - - /** - * @see _.plant - */ - plant(value: any): LoDashExplicitWrapper; - } - - //_.prototype.reverse - interface LoDashImplicitArrayWrapper { - /** - * Reverses the wrapped array so the first element becomes the last, the second element becomes the second to - * last, and so on. - * - * Note: This method mutates the wrapped array. - * - * @return Returns the new reversed lodash wrapper instance. - */ - reverse(): LoDashImplicitArrayWrapper; - } - - interface LoDashExplicitArrayWrapper { - /** - * @see _.reverse - */ - reverse(): LoDashExplicitArrayWrapper; + plant(value: T): LoDashExplicitWrapper; } //_.prototype.toJSON - interface LoDashWrapperBase { + interface LoDashWrapper { /** * @see _.value */ - toJSON(): T; + toJSON(): TValue; } //_.prototype.toString - interface LoDashWrapperBase { + interface LoDashWrapper { /** * Produces the result of coercing the unwrapped value to a string. * @@ -6216,7 +4032,7 @@ declare namespace _ { } //_.prototype.value - interface LoDashWrapperBase { + interface LoDashWrapper { /** * Executes the chained sequence to extract the unwrapped value. * @@ -6224,15 +4040,15 @@ declare namespace _ { * * @return Returns the resolved unwrapped value. */ - value(): T; + value(): TValue; } //_.valueOf - interface LoDashWrapperBase { + interface LoDashWrapper { /** * @see _.value */ - valueOf(): T; + valueOf(): TValue; } /************** @@ -6245,42 +4061,58 @@ declare namespace _ { * Creates an array of elements corresponding to the given keys, or indexes, of collection. Keys may be * specified as individual arguments or as arrays of keys. * - * @param collection The collection to iterate over. + * @param object The object to iterate over. * @param props The property names or indexes of elements to pick, specified individually or in arrays. * @return Returns the new array of picked elements. */ at( - collection: List|Dictionary | null | undefined, + object: List | Dictionary | null | undefined, ...props: Array> ): T[]; - } - interface LoDashImplicitArrayWrapperBase { /** * @see _.at */ - at(...props: Array>): LoDashImplicitArrayWrapper; + at( + object: T | null | undefined, + ...props: Array> + ): Array; } - interface LoDashImplicitObjectWrapperBase { + interface LoDashImplicitWrapper { /** * @see _.at */ - at(...props: Array>): LoDashImplicitArrayWrapper; - } + at( + this: LoDashImplicitWrapper | Dictionary | null | undefined>, + ...props: Array> + ): LoDashImplicitWrapper; - interface LoDashExplicitArrayWrapperBase { /** * @see _.at */ - at(...props: Array>): LoDashExplicitArrayWrapper; + at( + this: LoDashImplicitWrapper, + ...props: Array> + ): LoDashImplicitWrapper>; } - interface LoDashExplicitObjectWrapperBase { + interface LoDashExplicitWrapper { /** * @see _.at */ - at(...props: Array>): LoDashExplicitArrayWrapper; + at( + this: LoDashExplicitWrapper | Dictionary | null | undefined>, + ...props: Array> + ): LoDashExplicitWrapper; + + /** + * @see _.at + */ + at( + this: LoDashExplicitWrapper, + ...props: Array> + ): LoDashExplicitWrapper>; } //_.countBy @@ -6307,15 +4139,7 @@ declare namespace _ { */ countBy( collection: List | null | undefined, - iteratee?: ListIterator - ): Dictionary; - - /** - * @see _.countBy - */ - countBy( - collection: Dictionary | null | undefined, - iteratee?: DictionaryIterator + iteratee?: ListIteratee ): Dictionary; /** @@ -6323,260 +4147,146 @@ declare namespace _ { */ countBy( collection: NumericDictionary | null | undefined, - iteratee?: NumericDictionaryIterator + iteratee?: NumericDictionaryIteratee ): Dictionary; /** * @see _.countBy */ - countBy( - collection: List|Dictionary|NumericDictionary | null | undefined, - iteratee?: string - ): Dictionary; - - /** - * @see _.countBy - */ - countBy( - collection: List|Dictionary|NumericDictionary | null | undefined, - iteratee?: W - ): Dictionary; - - /** - * @see _.countBy - */ - countBy( - collection: List|Dictionary|NumericDictionary | null | undefined, - iteratee?: Object + countBy( + collection: T | null | undefined, + iteratee?: ObjectIteratee ): Dictionary; } - interface LoDashImplicitWrapper { - /** - * @see _.countBy - */ - countBy( - iteratee?: ListIterator - ): LoDashImplicitObjectWrapper>; - } - - interface LoDashImplicitArrayWrapperBase { - /** - * @see _.countBy - */ - countBy( - iteratee?: ListIterator - ): LoDashImplicitObjectWrapper>; - - /** - * @see _.countBy - */ - countBy( - iteratee?: string - ): LoDashImplicitObjectWrapper>; - - /** - * @see _.countBy - */ - countBy( - iteratee?: W - ): LoDashImplicitObjectWrapper>; - } - - interface LoDashImplicitObjectWrapperBase { + interface LoDashImplicitWrapper { /** * @see _.countBy */ countBy( - iteratee?: ListIterator|DictionaryIterator|NumericDictionaryIterator - ): LoDashImplicitObjectWrapper>; + this: LoDashImplicitWrapper | null | undefined>, + iteratee?: ListIteratee + ): LoDashImplicitWrapper>; /** * @see _.countBy */ - countBy( - iteratee?: string - ): LoDashImplicitObjectWrapper>; + countBy( + this: LoDashImplicitWrapper, + iteratee?: ObjectIteratee + ): LoDashImplicitWrapper>; - /** - * @see _.countBy - */ - countBy( - iteratee?: W - ): LoDashImplicitObjectWrapper>; - } - - interface LoDashExplicitWrapper { - /** - * @see _.countBy - */ - countBy( - iteratee?: ListIterator - ): LoDashExplicitObjectWrapper>; - } - - interface LoDashExplicitArrayWrapperBase { - /** - * @see _.countBy - */ - countBy( - iteratee?: ListIterator - ): LoDashExplicitObjectWrapper>; - - /** - * @see _.countBy - */ - countBy( - iteratee?: string - ): LoDashExplicitObjectWrapper>; - - /** - * @see _.countBy - */ - countBy( - iteratee?: W - ): LoDashExplicitObjectWrapper>; - } - - interface LoDashExplicitObjectWrapperBase { /** * @see _.countBy */ countBy( - iteratee?: ListIterator|DictionaryIterator|NumericDictionaryIterator - ): LoDashExplicitObjectWrapper>; + this: LoDashImplicitWrapper | null | undefined>, + iteratee?: NumericDictionaryIteratee + ): LoDashImplicitWrapper>; + } + + interface LoDashExplicitWrapper { + /** + * @see _.countBy + */ + countBy( + this: LoDashExplicitWrapper | null | undefined>, + iteratee?: ListIteratee + ): LoDashExplicitWrapper>; /** * @see _.countBy */ - countBy( - iteratee?: string - ): LoDashExplicitObjectWrapper>; + countBy( + this: LoDashExplicitWrapper, + iteratee?: ObjectIteratee + ): LoDashExplicitWrapper>; /** * @see _.countBy */ - countBy( - iteratee?: W - ): LoDashExplicitObjectWrapper>; + countBy( + this: LoDashExplicitWrapper | null | undefined>, + iteratee?: NumericDictionaryIteratee + ): LoDashExplicitWrapper>; } //_.each interface LoDashStatic { - each: typeof _.forEach; + each: typeof _.forEach; // tslint:disable-line:no-unnecessary-qualifier } - interface LoDashImplicitWrapper { + interface LoDashWrapper { + /** + * @see _.forEach + */ + each( + this: LoDashWrapper, + iteratee?: ArrayIterator + ): this; + /** * @see _.forEach */ each( - iteratee: StringIterator - ): LoDashImplicitWrapper; - } + this: LoDashWrapper, + iteratee?: StringIterator + ): this; - interface LoDashImplicitArrayWrapperBase { /** * @see _.forEach */ - each( - iteratee: ListIterator - ): TWrapper; - } + each( + this: LoDashWrapper | null | undefined>, + iteratee?: ListIterator + ): this; - interface LoDashImplicitObjectWrapperBase { /** * @see _.forEach */ - each( - iteratee?: ListIterator|DictionaryIterator - ): TWrapper; - } - - interface LoDashExplicitWrapper { - /** - * @see _.forEach - */ - each( - iteratee: StringIterator - ): LoDashExplicitWrapper; - } - - interface LoDashExplicitArrayWrapperBase { - /** - * @see _.forEach - */ - each( - iteratee: ListIterator - ): TWrapper; - } - - interface LoDashExplicitObjectWrapperBase { - /** - * @see _.forEach - */ - each( - iteratee?: ListIterator|DictionaryIterator - ): TWrapper; + each( + this: LoDashWrapper, + iteratee?: ObjectIterator + ): this; } //_.eachRight interface LoDashStatic { - eachRight: typeof _.forEachRight; + eachRight: typeof _.forEachRight; // tslint:disable-line:no-unnecessary-qualifier } - interface LoDashImplicitWrapper { + interface LoDashWrapper { + /** + * @see _.forEachRight + */ + eachRight( + this: LoDashWrapper, + iteratee?: ArrayIterator + ): this; + /** * @see _.forEachRight */ eachRight( - iteratee: StringIterator - ): LoDashImplicitWrapper; - } + this: LoDashWrapper, + iteratee?: StringIterator + ): this; - interface LoDashImplicitArrayWrapperBase { /** * @see _.forEachRight */ - eachRight( - iteratee: ListIterator - ): TWrapper; - } + eachRight( + this: LoDashWrapper | null | undefined>, + iteratee?: ListIterator + ): this; - interface LoDashImplicitObjectWrapperBase { /** * @see _.forEachRight */ - eachRight( - iteratee?: ListIterator|DictionaryIterator - ): TWrapper; - } - - interface LoDashExplicitWrapper { - /** - * @see _.forEachRight - */ - eachRight( - iteratee: StringIterator - ): LoDashExplicitWrapper; - } - - interface LoDashExplicitArrayWrapperBase { - /** - * @see _.forEachRight - */ - eachRight( - iteratee: ListIterator - ): TWrapper; - } - - interface LoDashExplicitObjectWrapperBase { - /** - * @see _.forEachRight - */ - eachRight( - iteratee?: ListIterator|DictionaryIterator - ): TWrapper; + eachRight( + this: LoDashWrapper, + iteratee?: ObjectIterator + ): this; } //_.every @@ -6591,15 +4301,7 @@ declare namespace _ { */ every( collection: List | null | undefined, - predicate?: ListIterator - ): boolean; - - /** - * @see _.every - */ - every( - collection: Dictionary | null | undefined, - predicate?: DictionaryIterator + predicate?: ListIteratee ): boolean; /** @@ -6607,107 +4309,67 @@ declare namespace _ { */ every( collection: NumericDictionary | null | undefined, - predicate?: NumericDictionaryIterator + predicate?: NumericDictionaryIteratee + ): boolean; + + /** + * @see _.every + */ + every( + collection: T | null | undefined, + predicate?: ObjectIteratee + ): boolean; + } + + interface LoDashImplicitWrapper { + /** + * @see _.every + */ + every( + this: LoDashImplicitWrapper | null | undefined>, + predicate?: ListIteratee + ): boolean; + + /** + * @see _.every + */ + every( + this: LoDashImplicitWrapper, + predicate?: ObjectIteratee ): boolean; /** * @see _.every */ every( - collection: List|Dictionary|NumericDictionary | null | undefined, - predicate?: string|any[]|PartialObject + this: LoDashImplicitWrapper | null | undefined>, + predicate?: NumericDictionaryIteratee ): boolean; } - interface LoDashImplicitArrayWrapperBase { + interface LoDashExplicitWrapper { /** * @see _.every */ - every( - predicate?: ListIterator|NumericDictionaryIterator - ): boolean; - - /** - * @see _.every - */ - every( - predicate?: string|any[] - ): boolean; - - /** - * @see _.every - */ - every( - predicate?: PartialObject - ): boolean; - } - - interface LoDashImplicitObjectWrapperBase { - /** - * @see _.every - */ - every( - predicate?: ListIterator|DictionaryIterator|NumericDictionaryIterator - ): boolean; - - /** - * @see _.every - */ - every( - predicate?: string|any[] - ): boolean; - - /** - * @see _.every - */ - every( - predicate?: PartialObject - ): boolean; - } - - interface LoDashExplicitArrayWrapperBase { - /** - * @see _.every - */ - every( - predicate?: ListIterator|NumericDictionaryIterator + every( + this: LoDashExplicitWrapper | null | undefined>, + predicate?: ListIteratee ): LoDashExplicitWrapper; /** * @see _.every */ - every( - predicate?: string|any[] + every( + this: LoDashExplicitWrapper, + predicate?: ObjectIteratee ): LoDashExplicitWrapper; /** * @see _.every */ - every( - predicate?: PartialObject - ): LoDashExplicitWrapper; - } - - interface LoDashExplicitObjectWrapperBase { - /** - * @see _.every - */ - every( - predicate?: ListIterator|DictionaryIterator|NumericDictionaryIterator - ): LoDashExplicitWrapper; - - /** - * @see _.every - */ - every( - predicate?: string|any[] - ): LoDashExplicitWrapper; - - /** - * @see _.every - */ - every( - predicate?: PartialObject + every( + this: LoDashExplicitWrapper | null | undefined>, + predicate?: NumericDictionaryIteratee ): LoDashExplicitWrapper; } @@ -6731,132 +4393,126 @@ declare namespace _ { * @param thisArg The this binding of predicate. * @return Returns the new filtered array. */ - filter( - collection: List | null | undefined, - predicate: ListIteratorTypeGuard - ): S[]; - - /** - * @see _.filter - */ - filter( - collection: List | null | undefined, - predicate?: ListIterator - ): T[]; - - /** - * @see _.filter - */ - filter( - collection: Dictionary | null | undefined, - predicate: DictionaryIteratorTypeGuard - ): S[]; - - /** - * @see _.filter - */ - filter( - collection: Dictionary | null | undefined, - predicate?: DictionaryIterator - ): T[]; - - /** - * @see _.filter - */ filter( collection: string | null | undefined, - predicate?: StringIterator + predicate?: StringIterator ): string[]; + /** + * @see _.filter + */ + filter( + collection: List | null | undefined, + predicate: ListIteratorTypeGuard + ): S[]; + /** * @see _.filter */ filter( - collection: List|Dictionary | null | undefined, - predicate: string | [string, any] | RegExp | PartialObject + collection: List | null | undefined, + predicate?: ListIteratee ): T[]; + + /** + * @see _.filter + */ + filter( + collection: T | null | undefined, + predicate: ObjectIteratorTypeGuard + ): S[]; + + /** + * @see _.filter + */ + filter( + collection: T | null | undefined, + predicate?: ObjectIteratee + ): Array; } - interface LoDashImplicitWrapper { + interface LoDashImplicitWrapper { /** * @see _.filter */ filter( - predicate?: StringIterator - ): LoDashImplicitArrayWrapper; - } + this: LoDashImplicitWrapper, + predicate?: StringIterator + ): LoDashImplicitWrapper; - interface LoDashImplicitArrayWrapperBase { - /** - * @see _.filter - */ - filter( - predicate: ListIteratorTypeGuard - ): LoDashImplicitArrayWrapper; - - /** - * @see _.filter - */ - filter( - predicate: ListIterator | string | [string, any] | RegExp | PartialObject - ): LoDashImplicitArrayWrapper; - } - - interface LoDashImplicitObjectWrapperBase { /** * @see _.filter */ filter( + this: LoDashImplicitWrapper | null | undefined>, predicate: ListIteratorTypeGuard - ): LoDashImplicitArrayWrapper; + ): LoDashImplicitWrapper; /** * @see _.filter */ filter( - predicate: ListIterator | DictionaryIterator | string | [string, any] | RegExp | PartialObject - ): LoDashImplicitArrayWrapper; + this: LoDashImplicitWrapper | null | undefined>, + predicate?: ListIteratee + ): LoDashImplicitWrapper; + + /** + * @see _.filter + */ + filter( + this: LoDashImplicitWrapper, + predicate: ObjectIteratorTypeGuard + ): LoDashImplicitWrapper; + + /** + * @see _.filter + */ + filter( + this: LoDashImplicitWrapper, + predicate?: ObjectIteratee + ): LoDashImplicitWrapper>; } - interface LoDashExplicitWrapper { + interface LoDashExplicitWrapper { /** * @see _.filter */ filter( - predicate?: StringIterator - ): LoDashExplicitArrayWrapper; - } + this: LoDashExplicitWrapper, + predicate?: StringIterator + ): LoDashExplicitWrapper; - interface LoDashExplicitArrayWrapperBase { - /** - * @see _.filter - */ - filter( - predicate: ListIteratorTypeGuard - ): LoDashExplicitArrayWrapper; - - /** - * @see _.filter - */ - filter( - predicate: ListIterator | string | [string, any] | RegExp | PartialObject - ): LoDashExplicitArrayWrapper; - } - - interface LoDashExplicitObjectWrapperBase { /** * @see _.filter */ filter( + this: LoDashExplicitWrapper | null | undefined>, predicate: ListIteratorTypeGuard - ): LoDashExplicitArrayWrapper; + ): LoDashExplicitWrapper; /** * @see _.filter */ filter( - predicate: ListIterator | DictionaryIterator | string | [string, any] | RegExp | PartialObject - ): LoDashExplicitArrayWrapper; + this: LoDashExplicitWrapper | null | undefined>, + predicate?: ListIteratee + ): LoDashExplicitWrapper; + + /** + * @see _.filter + */ + filter( + this: LoDashExplicitWrapper, + predicate: ObjectIteratorTypeGuard + ): LoDashExplicitWrapper; + + /** + * @see _.filter + */ + filter( + this: LoDashExplicitWrapper, + predicate?: ObjectIteratee + ): LoDashExplicitWrapper>; } //_.find @@ -6890,43 +4546,35 @@ declare namespace _ { */ find( collection: List | null | undefined, - predicate?: ListIterator, + predicate?: ListIteratee, fromIndex?: number ): T|undefined; /** * @see _.find */ - find( - collection: Dictionary | null | undefined, - predicate: DictionaryIteratorTypeGuard, + find( + collection: T | null | undefined, + predicate: ObjectIteratorTypeGuard, fromIndex?: number ): S|undefined; /** * @see _.find */ - find( - collection: Dictionary | null | undefined, - predicate?: DictionaryIterator, + find( + collection: T | null | undefined, + predicate?: ObjectIteratee, fromIndex?: number - ): T|undefined; - - /** - * @see _.find - */ - find( - collection: List|Dictionary | null | undefined, - predicate?: string | PartialObject | [string, any], - fromIndex?: number - ): T|undefined; + ): T[keyof T]|undefined; } - interface LoDashImplicitArrayWrapperBase { + interface LoDashImplicitWrapper { /** * @see _.find */ - find( + find( + this: LoDashImplicitWrapper | null | undefined>, predicate: ListIteratorTypeGuard, fromIndex?: number ): S|undefined; @@ -6934,30 +4582,67 @@ declare namespace _ { /** * @see _.find */ - find( - predicate?: ListIterator | string | PartialObject | [string, any], + find( + this: LoDashImplicitWrapper | null | undefined>, + predicate?: ListIteratee, fromIndex?: number ): T|undefined; - } - interface LoDashImplicitObjectWrapperBase { /** * @see _.find */ - find( - predicate?: ListIterator | DictionaryIterator | string | PartialObject | [string, any], + find( + this: LoDashImplicitWrapper, + predicate: ObjectIteratorTypeGuard, fromIndex?: number - ): TResult|undefined; - } + ): S|undefined; - interface LoDashExplicitWrapperBase { /** * @see _.find */ - find( - predicate?: ListIterator | string | PartialObject | [string, any], + find( + this: LoDashImplicitWrapper, + predicate?: ObjectIteratee, fromIndex?: number - ): any; + ): T[keyof T]|undefined; + } + + interface LoDashExplicitWrapper { + /** + * @see _.find + */ + find( + this: LoDashExplicitWrapper | null | undefined>, + predicate: ListIteratorTypeGuard, + fromIndex?: number + ): LoDashExplicitWrapper; + + /** + * @see _.find + */ + find( + this: LoDashExplicitWrapper | null | undefined>, + predicate?: ListIteratee, + fromIndex?: number + ): LoDashExplicitWrapper; + + /** + * @see _.find + */ + find( + this: LoDashExplicitWrapper, + predicate: ObjectIteratorTypeGuard, + fromIndex?: number + ): LoDashExplicitWrapper; + + /** + * @see _.find + */ + find( + this: LoDashExplicitWrapper, + predicate?: ObjectIteratee, + fromIndex?: number + ): LoDashExplicitWrapper; } //_.findLast @@ -6981,74 +4666,103 @@ declare namespace _ { */ findLast( collection: List | null | undefined, - predicate?: ListIterator, + predicate?: ListIteratee, fromIndex?: number ): T|undefined; + /** + * @see _.findLast + */ + findLast( + collection: T | null | undefined, + predicate: ObjectIteratorTypeGuard, + fromIndex?: number + ): S|undefined; + + /** + * @see _.findLast + */ + findLast( + collection: T | null | undefined, + predicate?: ObjectIteratee, + fromIndex?: number + ): T[keyof T]|undefined; + } + + interface LoDashImplicitWrapper { /** * @see _.findLast */ findLast( - collection: Dictionary | null | undefined, - predicate: DictionaryIteratorTypeGuard, - fromIndex?: number - ): S|undefined; - - /** - * @see _.findLast - */ - findLast( - collection: Dictionary | null | undefined, - predicate?: DictionaryIterator, - fromIndex?: number - ): T|undefined; - - /** - * @see _.findLast - */ - findLast( - collection: List|Dictionary | null | undefined, - predicate?: string | PartialObject | [string, any], - fromIndex?: number - ): T|undefined; - } - - interface LoDashImplicitArrayWrapperBase { - /** - * @see _.findLast - */ - findLast( + this: LoDashImplicitWrapper | null | undefined>, predicate: ListIteratorTypeGuard, fromIndex?: number + ): S | undefined; + + /** + * @see _.findLast + */ + findLast( + this: LoDashImplicitWrapper | null | undefined>, + predicate?: ListIteratee, + fromIndex?: number + ): T | undefined; + + /** + * @see _.findLast + */ + findLast( + this: LoDashImplicitWrapper, + predicate: ObjectIteratorTypeGuard, + fromIndex?: number ): S|undefined; /** * @see _.findLast */ - findLast( - predicate?: ListIterator | string | PartialObject | [string, any], + findLast( + this: LoDashImplicitWrapper, + predicate?: ObjectIteratee, fromIndex?: number - ): T|undefined; + ): T[keyof T]|undefined; } - interface LoDashImplicitObjectWrapperBase { + interface LoDashExplicitWrapper { /** * @see _.findLast */ - findLast( - predicate?: ListIterator | DictionaryIterator | string | PartialObject | [string, any], + findLast( + this: LoDashExplicitWrapper | null | undefined>, + predicate: ListIteratorTypeGuard, fromIndex?: number - ): TResult|undefined; - } + ): LoDashExplicitWrapper; - interface LoDashExplicitWrapperBase { /** * @see _.findLast */ - findLast( - predicate?: ListIterator | string | PartialObject | [string, any], + findLast( + this: LoDashExplicitWrapper | null | undefined>, + predicate?: ListIteratee, fromIndex?: number - ): any; + ): LoDashExplicitWrapper; + + /** + * @see _.findLast + */ + findLast( + this: LoDashExplicitWrapper, + predicate: ObjectIteratorTypeGuard, + fromIndex?: number + ): LoDashExplicitWrapper; + + /** + * @see _.findLast + */ + findLast( + this: LoDashExplicitWrapper, + predicate?: ObjectIteratee, + fromIndex?: number + ): LoDashExplicitWrapper; } //_.flatMap @@ -7071,15 +4785,7 @@ declare namespace _ { */ flatMap( collection: List | null | undefined, - iteratee: ListIterator> | string - ): TResult[]; - - /** - * @see _.flatMap - */ - flatMap( - collection: Dictionary | null | undefined, - iteratee: DictionaryIterator> | string + iteratee: ListIterator> ): TResult[]; /** @@ -7087,17 +4793,25 @@ declare namespace _ { */ flatMap( collection: NumericDictionary | null | undefined, - iteratee: NumericDictionaryIterator> | string + iteratee: NumericDictionaryIterator> ): TResult[]; /** * @see _.flatMap */ - flatMap( - collection: object | null | undefined, - iteratee?: ObjectIterator> | string + flatMap( + collection: T | null | undefined, + iteratee: ObjectIterator> ): TResult[]; + /** + * @see _.flatMap + */ + flatMap( + collection: object | null | undefined, + iteratee: string + ): any[]; + /** * @see _.flatMap */ @@ -7107,130 +4821,94 @@ declare namespace _ { ): boolean[]; } - interface LoDashImplicitWrapper { + interface LoDashImplicitWrapper { /** * @see _.flatMap */ - flatMap( - iteratee: StringIterator> - ): LoDashImplicitArrayWrapper; + flatMap(this: LoDashImplicitWrapper> | Dictionary> | NumericDictionary> | null | undefined>): LoDashImplicitWrapper; - /** - * @see _.flatMap - */ - flatMap(): LoDashImplicitArrayWrapper; - } - - interface LoDashImplicitArrayWrapperBase { - /** - * @see _.flatMap - */ - flatMap( - iteratee: ListIterator>|string - ): LoDashImplicitArrayWrapper; - - /** - * @see _.flatMap - */ - flatMap( - iteratee: object - ): LoDashImplicitArrayWrapper; - - /** - * @see _.flatMap - */ - flatMap(): LoDashImplicitArrayWrapper; - } - - interface LoDashImplicitObjectWrapperBase { /** * @see _.flatMap */ flatMap( - iteratee: ListIterator>|DictionaryIterator>|NumericDictionaryIterator> - ): LoDashImplicitArrayWrapper; + this: LoDashImplicitWrapper | null | undefined>, + iteratee: ListIterator> + ): LoDashImplicitWrapper; /** * @see _.flatMap */ - flatMap( - iteratee: ObjectIterator>|string - ): LoDashImplicitArrayWrapper; + flatMap( + this: LoDashImplicitWrapper, + iteratee: ObjectIterator> + ): LoDashImplicitWrapper; - /** - * @see _.flatMap - */ - flatMap( - iteratee: object - ): LoDashImplicitArrayWrapper; - - /** - * @see _.flatMap - */ - flatMap(): LoDashImplicitArrayWrapper; - } - - interface LoDashExplicitWrapper { - /** - * @see _.flatMap - */ - flatMap( - iteratee: StringIterator> - ): LoDashExplicitArrayWrapper; - - /** - * @see _.flatMap - */ - flatMap(): LoDashExplicitArrayWrapper; - } - - interface LoDashExplicitArrayWrapperBase { - /** - * @see _.flatMap - */ - flatMap( - iteratee: ListIterator>|string - ): LoDashExplicitArrayWrapper; - - /** - * @see _.flatMap - */ - flatMap( - iteratee: object - ): LoDashExplicitArrayWrapper; - - /** - * @see _.flatMap - */ - flatMap(): LoDashExplicitArrayWrapper; - } - - interface LoDashExplicitObjectWrapperBase { /** * @see _.flatMap */ flatMap( - iteratee: ListIterator>|DictionaryIterator>|NumericDictionaryIterator> - ): LoDashExplicitArrayWrapper; + this: LoDashImplicitWrapper | null | undefined>, + iteratee: NumericDictionaryIterator> + ): LoDashImplicitWrapper; /** * @see _.flatMap */ - flatMap( - iteratee: ObjectIterator>|string - ): LoDashExplicitArrayWrapper; + flatMap( + iteratee: string + ): LoDashImplicitWrapper; /** * @see _.flatMap */ flatMap( iteratee: object - ): LoDashExplicitArrayWrapper; + ): LoDashImplicitWrapper; + } + + interface LoDashExplicitWrapper { + /** + * @see _.flatMap + */ + flatMap(this: LoDashExplicitWrapper> | Dictionary> | NumericDictionary> | null | undefined>): LoDashExplicitWrapper; /** * @see _.flatMap */ - flatMap(): LoDashExplicitArrayWrapper; + flatMap( + this: LoDashExplicitWrapper | null | undefined>, + iteratee: ListIterator> + ): LoDashExplicitWrapper; + + /** + * @see _.flatMap + */ + flatMap( + this: LoDashExplicitWrapper | null | undefined>, + iteratee: NumericDictionaryIterator> + ): LoDashExplicitWrapper; + + /** + * @see _.flatMap + */ + flatMap( + this: LoDashExplicitWrapper, + iteratee: ObjectIterator> + ): LoDashExplicitWrapper; + + /** + * @see _.flatMap + */ + flatMap( + iteratee: string + ): LoDashExplicitWrapper; + + /** + * @see _.flatMap + */ + flatMap( + iteratee: object + ): LoDashExplicitWrapper; } //_.flatMapDeep @@ -7256,7 +4934,7 @@ declare namespace _ { * // => [1, 1, 2, 2] */ flatMapDeep( - collection: List> | Dictionary> | NumericDictionary> | null | undefined + collection: List | T> | Dictionary | T> | NumericDictionary | T> | null | undefined ): T[]; /** @@ -7264,15 +4942,7 @@ declare namespace _ { */ flatMapDeep( collection: List | null | undefined, - iteratee: ListIterator> | string - ): TResult[]; - - /** - * @see _.flatMapDeep - */ - flatMapDeep( - collection: Dictionary | null | undefined, - iteratee: DictionaryIterator> | string + iteratee: ListIterator | TResult> ): TResult[]; /** @@ -7280,17 +4950,25 @@ declare namespace _ { */ flatMapDeep( collection: NumericDictionary | null | undefined, - iteratee: NumericDictionaryIterator> | string + iteratee: NumericDictionaryIterator | TResult> ): TResult[]; /** * @see _.flatMapDeep */ - flatMapDeep( - collection: object | null | undefined, - iteratee?: ObjectIterator> | string + flatMapDeep( + collection: T | null | undefined, + iteratee: ObjectIterator | TResult> ): TResult[]; + /** + * @see _.flatMapDeep + */ + flatMapDeep( + collection: object | null | undefined, + iteratee: string + ): any[]; + /** * @see _.flatMapDeep */ @@ -7300,130 +4978,102 @@ declare namespace _ { ): boolean[]; } - interface LoDashImplicitWrapper { + interface LoDashImplicitWrapper { /** * @see _.flatMapDeep */ - flatMapDeep( - iteratee: StringIterator> - ): LoDashImplicitArrayWrapper; + flatMapDeep( + this: LoDashImplicitWrapper | T> | Dictionary | T> | NumericDictionary | T> | null | undefined> + ): LoDashImplicitWrapper; - /** - * @see _.flatMapDeep - */ - flatMapDeep(): LoDashImplicitArrayWrapper; - } - - interface LoDashImplicitArrayWrapperBase { - /** - * @see _.flatMapDeep - */ - flatMapDeep( - iteratee: ListIterator>|string - ): LoDashImplicitArrayWrapper; - - /** - * @see _.flatMapDeep - */ - flatMapDeep( - iteratee: object - ): LoDashImplicitArrayWrapper; - - /** - * @see _.flatMapDeep - */ - flatMapDeep(): LoDashImplicitArrayWrapper; - } - - interface LoDashImplicitObjectWrapperBase { /** * @see _.flatMapDeep */ flatMapDeep( - iteratee: ListIterator>|DictionaryIterator>|NumericDictionaryIterator> - ): LoDashImplicitArrayWrapper; + this: LoDashImplicitWrapper | null | undefined>, + iteratee: ListIterator | TResult> + ): LoDashImplicitWrapper; - /** - * @see _.flatMapDeep - */ - flatMapDeep( - iteratee: ObjectIterator>|string - ): LoDashImplicitArrayWrapper; - - /** - * @see _.flatMapDeep - */ - flatMapDeep( - iteratee: object - ): LoDashImplicitArrayWrapper; - - /** - * @see _.flatMapDeep - */ - flatMapDeep(): LoDashImplicitArrayWrapper; - } - - interface LoDashExplicitWrapper { - /** - * @see _.flatMapDeep - */ - flatMapDeep( - iteratee: StringIterator> - ): LoDashExplicitArrayWrapper; - - /** - * @see _.flatMapDeep - */ - flatMapDeep(): LoDashExplicitArrayWrapper; - } - - interface LoDashExplicitArrayWrapperBase { - /** - * @see _.flatMapDeep - */ - flatMapDeep( - iteratee: ListIterator>|string - ): LoDashExplicitArrayWrapper; - - /** - * @see _.flatMapDeep - */ - flatMapDeep( - iteratee: object - ): LoDashExplicitArrayWrapper; - - /** - * @see _.flatMapDeep - */ - flatMapDeep(): LoDashExplicitArrayWrapper; - } - - interface LoDashExplicitObjectWrapperBase { /** * @see _.flatMapDeep */ flatMapDeep( - iteratee: ListIterator>|DictionaryIterator>|NumericDictionaryIterator> - ): LoDashExplicitArrayWrapper; + this: LoDashImplicitWrapper | null | undefined>, + iteratee: NumericDictionaryIterator | TResult> + ): LoDashImplicitWrapper; /** * @see _.flatMapDeep */ - flatMapDeep( - iteratee: ObjectIterator>|string - ): LoDashExplicitArrayWrapper; + flatMapDeep( + this: LoDashImplicitWrapper, + iteratee: ObjectIterator | TResult> + ): LoDashImplicitWrapper; /** * @see _.flatMapDeep */ flatMapDeep( - iteratee: object - ): LoDashExplicitArrayWrapper; + this: LoDashImplicitWrapper, + iteratee: string + ): LoDashImplicitWrapper; /** * @see _.flatMapDeep */ - flatMapDeep(): LoDashExplicitArrayWrapper; + flatMapDeep( + this: LoDashImplicitWrapper, + iteratee: object + ): LoDashImplicitWrapper; + } + + interface LoDashExplicitWrapper { + /** + * @see _.flatMapDeep + */ + flatMapDeep( + this: LoDashExplicitWrapper | T> | Dictionary | T> | NumericDictionary | T> | null | undefined> + ): LoDashExplicitWrapper; + + /** + * @see _.flatMapDeep + */ + flatMapDeep( + this: LoDashExplicitWrapper | null | undefined>, + iteratee: ListIterator | TResult> + ): LoDashExplicitWrapper; + + /** + * @see _.flatMapDeep + */ + flatMapDeep( + this: LoDashExplicitWrapper | null | undefined>, + iteratee: NumericDictionaryIterator | TResult> + ): LoDashExplicitWrapper; + + /** + * @see _.flatMapDeep + */ + flatMapDeep( + this: LoDashExplicitWrapper, + iteratee: ObjectIterator | TResult> + ): LoDashExplicitWrapper; + + /** + * @see _.flatMapDeep + */ + flatMapDeep( + this: LoDashExplicitWrapper, + iteratee: string + ): LoDashExplicitWrapper; + + /** + * @see _.flatMapDeep + */ + flatMapDeep( + this: LoDashExplicitWrapper, + iteratee: object + ): LoDashExplicitWrapper; } //_.flatMapDepth @@ -7450,8 +5100,7 @@ declare namespace _ { * // => [[1, 1], [2, 2]] */ flatMapDepth( - collection: List> | Dictionary> | NumericDictionary> | null | undefined, - depth?: number + collection: List | T> | Dictionary | T> | NumericDictionary | T> | null | undefined ): T[]; /** @@ -7459,16 +5108,7 @@ declare namespace _ { */ flatMapDepth( collection: List | null | undefined, - iteratee: ListIterator> | string, - depth?: number - ): TResult[]; - - /** - * @see _.flatMapDepth - */ - flatMapDepth( - collection: Dictionary | null | undefined, - iteratee: DictionaryIterator> | string, + iteratee: ListIterator | TResult>, depth?: number ): TResult[]; @@ -7477,19 +5117,28 @@ declare namespace _ { */ flatMapDepth( collection: NumericDictionary | null | undefined, - iteratee: NumericDictionaryIterator> | string, + iteratee: NumericDictionaryIterator | TResult>, depth?: number ): TResult[]; /** * @see _.flatMapDepth */ - flatMapDepth( - collection: object | null | undefined, - iteratee?: ObjectIterator> | string, + flatMapDepth( + collection: T | null | undefined, + iteratee: ObjectIterator | TResult>, depth?: number ): TResult[]; + /** + * @see _.flatMapDepth + */ + flatMapDepth( + collection: object | null | undefined, + iteratee: string, + depth?: number + ): any[]; + /** * @see _.flatMapDepth */ @@ -7500,142 +5149,112 @@ declare namespace _ { ): boolean[]; } - interface LoDashImplicitWrapper { + interface LoDashImplicitWrapper { /** * @see _.flatMapDepth */ - flatMapDepth( - iteratee: StringIterator>, - depth?: number - ): LoDashImplicitArrayWrapper; + flatMapDepth( + this: LoDashImplicitWrapper | T> | Dictionary | T> | NumericDictionary | T> | null | undefined> + ): LoDashImplicitWrapper; - /** - * @see _.flatMapDepth - */ - flatMapDepth(): LoDashImplicitArrayWrapper; - } - - interface LoDashImplicitArrayWrapperBase { - /** - * @see _.flatMapDepth - */ - flatMapDepth( - iteratee: ListIterator>|string, - depth?: number - ): LoDashImplicitArrayWrapper; - - /** - * @see _.flatMapDepth - */ - flatMapDepth( - iteratee: object, - depth?: number - ): LoDashImplicitArrayWrapper; - - /** - * @see _.flatMapDepth - */ - flatMapDepth(): LoDashImplicitArrayWrapper; - } - - interface LoDashImplicitObjectWrapperBase { /** * @see _.flatMapDepth */ flatMapDepth( - iteratee: ListIterator>|DictionaryIterator>|NumericDictionaryIterator>, + this: LoDashImplicitWrapper | null | undefined>, + iteratee: ListIterator | TResult>, depth?: number - ): LoDashImplicitArrayWrapper; + ): LoDashImplicitWrapper; - /** - * @see _.flatMapDepth - */ - flatMapDepth( - iteratee: ObjectIterator>|string, - depth?: number - ): LoDashImplicitArrayWrapper; - - /** - * @see _.flatMapDepth - */ - flatMapDepth( - iteratee: object, - depth?: number - ): LoDashImplicitArrayWrapper; - - /** - * @see _.flatMapDepth - */ - flatMapDepth(): LoDashImplicitArrayWrapper; - } - - interface LoDashExplicitWrapper { - /** - * @see _.flatMapDepth - */ - flatMapDepth( - iteratee: StringIterator>, - depth?: number - ): LoDashExplicitArrayWrapper; - - /** - * @see _.flatMapDepth - */ - flatMapDepth(): LoDashExplicitArrayWrapper; - } - - interface LoDashExplicitArrayWrapperBase { - /** - * @see _.flatMapDepth - */ - flatMapDepth( - iteratee: ListIterator>|string, - depth?: number - ): LoDashExplicitArrayWrapper; - - /** - * @see _.flatMapDepth - */ - flatMapDepth( - iteratee: object, - depth?: number - ): LoDashExplicitArrayWrapper; - - /** - * @see _.flatMapDepth - */ - flatMapDepth(): LoDashExplicitArrayWrapper; - } - - interface LoDashExplicitObjectWrapperBase { /** * @see _.flatMapDepth */ flatMapDepth( - iteratee: ListIterator>|DictionaryIterator>|NumericDictionaryIterator>, + this: LoDashImplicitWrapper | null | undefined>, + iteratee: NumericDictionaryIterator | TResult>, depth?: number - ): LoDashExplicitArrayWrapper; + ): LoDashImplicitWrapper; /** * @see _.flatMapDepth */ - flatMapDepth( - iteratee: ObjectIterator>|string, + flatMapDepth( + this: LoDashImplicitWrapper, + iteratee: ObjectIterator | TResult>, depth?: number - ): LoDashExplicitArrayWrapper; + ): LoDashImplicitWrapper; /** * @see _.flatMapDepth */ flatMapDepth( - iteratee: object, + this: LoDashImplicitWrapper, + iteratee: string, depth?: number - ): LoDashExplicitArrayWrapper; + ): LoDashImplicitWrapper; /** * @see _.flatMapDepth */ - flatMapDepth(): LoDashExplicitArrayWrapper; + flatMapDepth( + this: LoDashImplicitWrapper, + iteratee: object, + depth?: number + ): LoDashImplicitWrapper; + } + + interface LoDashExplicitWrapper { + /** + * @see _.flatMapDepth + */ + flatMapDepth( + this: LoDashExplicitWrapper | T> | Dictionary | T> | NumericDictionary | T> | null | undefined> + ): LoDashExplicitWrapper; + + /** + * @see _.flatMapDepth + */ + flatMapDepth( + this: LoDashExplicitWrapper | null | undefined>, + iteratee: ListIterator | TResult>, + depth?: number + ): LoDashExplicitWrapper; + + /** + * @see _.flatMapDepth + */ + flatMapDepth( + this: LoDashExplicitWrapper | null | undefined>, + iteratee: NumericDictionaryIterator | TResult>, + depth?: number + ): LoDashExplicitWrapper; + + /** + * @see _.flatMapDepth + */ + flatMapDepth( + this: LoDashExplicitWrapper, + iteratee: ObjectIterator | TResult>, + depth?: number + ): LoDashExplicitWrapper; + + /** + * @see _.flatMapDepth + */ + flatMapDepth( + this: LoDashExplicitWrapper, + iteratee: string, + depth?: number + ): LoDashExplicitWrapper; + + /** + * @see _.flatMapDepth + */ + flatMapDepth( + this: LoDashExplicitWrapper, + iteratee: object, + depth?: number + ): LoDashExplicitWrapper; } //_.forEach @@ -7654,6 +5273,46 @@ declare namespace _ { * @param iteratee The function invoked per iteration. * @param thisArg The this binding of iteratee. */ + forEach( + collection: T[], + iteratee?: ArrayIterator + ): T[]; + + /** + * @see _.forEach + */ + forEach( + collection: string, + iteratee?: StringIterator + ): string; + + /** + * @see _.forEach + */ + forEach( + collection: List, + iteratee?: ListIterator + ): List; + + /** + * @see _.forEach + */ + forEach( + collection: T, + iteratee?: ObjectIterator + ): T; + + /** + * @see _.forEach + */ + forEach( + collection: TArray & (T[] | null | undefined), + iteratee?: ArrayIterator + ): TArray; + + /** + * @see _.forEach + */ forEach( collection: TString, iteratee?: StringIterator @@ -7670,72 +5329,44 @@ declare namespace _ { /** * @see _.forEach */ - forEach | null | undefined>( - collection: TDictionary & (Dictionary | null | undefined), - iteratee?: DictionaryIterator - ): TDictionary; + forEach( + collection: T | null | undefined, + iteratee?: ObjectIterator + ): T | null | undefined; + } + interface LoDashWrapper { /** * @see _.forEach */ - forEach( - collection: T, - iteratee?: ObjectIterator - ): T; - } + forEach( + this: LoDashWrapper, + iteratee?: ArrayIterator + ): this; - interface LoDashImplicitWrapper { /** * @see _.forEach */ forEach( - iteratee: StringIterator - ): LoDashImplicitWrapper; - } + this: LoDashWrapper, + iteratee?: StringIterator + ): this; - interface LoDashImplicitArrayWrapperBase { /** * @see _.forEach */ - forEach( - iteratee: ListIterator - ): TWrapper; - } + forEach( + this: LoDashWrapper | null | undefined>, + iteratee?: ListIterator + ): this; - interface LoDashImplicitObjectWrapperBase { /** * @see _.forEach */ - forEach( - iteratee?: ListIterator|DictionaryIterator - ): TWrapper; - } - - interface LoDashExplicitWrapper { - /** - * @see _.forEach - */ - forEach( - iteratee: StringIterator - ): LoDashExplicitWrapper; - } - - interface LoDashExplicitArrayWrapperBase { - /** - * @see _.forEach - */ - forEach( - iteratee: ListIterator - ): TWrapper; - } - - interface LoDashExplicitObjectWrapperBase { - /** - * @see _.forEach - */ - forEach( - iteratee?: ListIterator|DictionaryIterator - ): TWrapper; + forEach( + this: LoDashWrapper, + iteratee?: ObjectIterator + ): this; } //_.forEachRight @@ -7749,6 +5380,46 @@ declare namespace _ { * @param iteratee The function called per iteration. * @param thisArg The this binding of callback. */ + forEachRight( + collection: T[], + iteratee?: ArrayIterator + ): T[]; + + /** + * @see _.forEachRight + */ + forEachRight( + collection: string, + iteratee?: StringIterator + ): string; + + /** + * @see _.forEachRight + */ + forEachRight( + collection: List, + iteratee?: ListIterator + ): List; + + /** + * @see _.forEachRight + */ + forEachRight( + collection: T, + iteratee?: ObjectIterator + ): T; + + /** + * @see _.forEachRight + */ + forEachRight( + collection: TArray & (T[] | null | undefined), + iteratee?: ArrayIterator + ): TArray; + + /** + * @see _.forEachRight + */ forEachRight( collection: TString, iteratee?: StringIterator @@ -7765,72 +5436,44 @@ declare namespace _ { /** * @see _.forEachRight */ - forEachRight | null | undefined>( - collection: TDictionary & (Dictionary | null | undefined), - iteratee?: DictionaryIterator - ): TDictionary; + forEachRight( + collection: T | null | undefined, + iteratee?: ObjectIterator + ): T | null | undefined; + } + interface LoDashWrapper { /** * @see _.forEachRight */ - forEachRight( - collection: T, - iteratee?: ObjectIterator - ): T; - } + forEachRight( + this: LoDashWrapper, + iteratee?: ArrayIterator + ): this; - interface LoDashImplicitWrapper { /** * @see _.forEachRight */ forEachRight( - iteratee: StringIterator - ): LoDashImplicitWrapper; - } + this: LoDashWrapper, + iteratee?: StringIterator + ): this; - interface LoDashImplicitArrayWrapperBase { /** * @see _.forEachRight */ - forEachRight( - iteratee: ListIterator - ): TWrapper; - } + forEachRight( + this: LoDashWrapper | null | undefined>, + iteratee?: ListIterator + ): this; - interface LoDashImplicitObjectWrapperBase { /** * @see _.forEachRight */ - forEachRight( - iteratee?: ListIterator|DictionaryIterator - ): TWrapper; - } - - interface LoDashExplicitWrapper { - /** - * @see _.forEachRight - */ - forEachRight( - iteratee: StringIterator - ): LoDashExplicitWrapper; - } - - interface LoDashExplicitArrayWrapperBase { - /** - * @see _.forEachRight - */ - forEachRight( - iteratee: ListIterator - ): TWrapper; - } - - interface LoDashExplicitObjectWrapperBase { - /** - * @see _.forEachRight - */ - forEachRight( - iteratee?: ListIterator|DictionaryIterator - ): TWrapper; + forEachRight( + this: LoDashWrapper, + iteratee?: ObjectIterator + ): this; } //_.groupBy @@ -7855,226 +5498,102 @@ declare namespace _ { * @param thisArg The this binding of iteratee. * @return Returns the composed aggregate object. */ - groupBy( - collection: TString, - iteratee?: StringIterator - ): Dictionary; + groupBy( + collection: string | null | undefined, + iteratee?: StringIterator + ): Dictionary; /** * @see _.groupBy */ - groupBy( + groupBy( collection: List | null | undefined, - iteratee?: ListIterator + iteratee?: ListIteratee ): Dictionary; /** * @see _.groupBy */ groupBy( - collection: List | null | undefined, - iteratee?: ListIterator + collection: NumericDictionary | null | undefined, + iteratee?: NumericDictionaryIteratee ): Dictionary; /** * @see _.groupBy */ - groupBy( - collection: Dictionary | null | undefined, - iteratee?: DictionaryIterator - ): Dictionary; - - /** - * @see _.groupBy - */ - groupBy( - collection: Dictionary | null | undefined, - iteratee?: DictionaryIterator - ): Dictionary; - - /** - * @see _.groupBy - */ - groupBy( - collection: List|Dictionary | null | undefined, - iteratee?: string - ): Dictionary; - - /** - * @see _.groupBy - */ - groupBy( - collection: List|Dictionary | null | undefined, - iteratee?: string - ): Dictionary; - - /** - * @see _.groupBy - */ - groupBy( - collection: List|Dictionary | null | undefined, - iteratee?: TWhere - ): Dictionary; - - /** - * @see _.groupBy - */ - groupBy( - collection: List|Dictionary | null | undefined, - iteratee?: Object - ): Dictionary; + groupBy( + collection: T | null | undefined, + iteratee?: ObjectIteratee + ): Dictionary>; } - interface LoDashImplicitWrapper { + interface LoDashImplicitWrapper { /** * @see _.groupBy */ - groupBy( - iteratee?: ListIterator - ): LoDashImplicitObjectWrapper>; + groupBy( + this: LoDashImplicitWrapper, + iteratee?: StringIterator + ): LoDashImplicitWrapper>; + + /** + * @see _.groupBy + */ + groupBy( + this: LoDashImplicitWrapper | null | undefined>, + iteratee?: ListIteratee + ): LoDashImplicitWrapper>; + + /** + * @see _.groupBy + */ + groupBy( + this: LoDashImplicitWrapper, + iteratee?: ObjectIteratee + ): LoDashImplicitWrapper>>; + + /** + * @see _.groupBy + */ + groupBy( + this: LoDashImplicitWrapper | null | undefined>, + iteratee?: NumericDictionaryIteratee + ): LoDashImplicitWrapper>; } - interface LoDashImplicitArrayWrapperBase { + interface LoDashExplicitWrapper { /** * @see _.groupBy */ - groupBy( - iteratee?: ListIterator - ): LoDashImplicitObjectWrapper>; - - /** - * @see _.groupBy - */ - groupBy( - iteratee?: string - ): LoDashImplicitObjectWrapper>; - - /** - * @see _.groupBy - */ - groupBy( - iteratee?: TWhere - ): LoDashImplicitObjectWrapper>; - } - - interface LoDashImplicitObjectWrapperBase { - /** - * @see _.groupBy - */ - groupBy( - iteratee?: ListIterator|DictionaryIterator - ): LoDashImplicitObjectWrapper>; + groupBy( + this: LoDashExplicitWrapper, + iteratee?: StringIterator + ): LoDashExplicitWrapper>; /** * @see _.groupBy */ groupBy( - iteratee?: ListIterator|DictionaryIterator - ): LoDashImplicitObjectWrapper>; - - /** - * @see _.groupBy - */ - groupBy( - iteratee?: string - ): LoDashImplicitObjectWrapper>; + this: LoDashExplicitWrapper | null | undefined>, + iteratee?: ListIteratee + ): LoDashExplicitWrapper>; /** * @see _.groupBy */ groupBy( - iteratee?: string - ): LoDashImplicitObjectWrapper>; + this: LoDashExplicitWrapper | null | undefined>, + iteratee?: NumericDictionaryIteratee + ): LoDashExplicitWrapper>; /** * @see _.groupBy */ - groupBy( - iteratee?: TWhere - ): LoDashImplicitObjectWrapper>; - - /** - * @see _.groupBy - */ - groupBy( - iteratee?: Object - ): LoDashImplicitObjectWrapper>; - } - - interface LoDashExplicitWrapper { - /** - * @see _.groupBy - */ - groupBy( - iteratee?: ListIterator - ): LoDashExplicitObjectWrapper>; - } - - interface LoDashExplicitArrayWrapperBase { - /** - * @see _.groupBy - */ - groupBy( - iteratee?: ListIterator - ): LoDashExplicitObjectWrapper>; - - /** - * @see _.groupBy - */ - groupBy( - iteratee?: string - ): LoDashExplicitObjectWrapper>; - - /** - * @see _.groupBy - */ - groupBy( - iteratee?: TWhere - ): LoDashExplicitObjectWrapper>; - } - - interface LoDashExplicitObjectWrapperBase { - /** - * @see _.groupBy - */ - groupBy( - iteratee?: ListIterator|DictionaryIterator - ): LoDashExplicitObjectWrapper>; - - /** - * @see _.groupBy - */ - groupBy( - iteratee?: ListIterator|DictionaryIterator - ): LoDashExplicitObjectWrapper>; - - /** - * @see _.groupBy - */ - groupBy( - iteratee?: string - ): LoDashExplicitObjectWrapper>; - - /** - * @see _.groupBy - */ - groupBy( - iteratee?: string - ): LoDashExplicitObjectWrapper>; - - /** - * @see _.groupBy - */ - groupBy( - iteratee?: TWhere - ): LoDashExplicitObjectWrapper>; - - /** - * @see _.groupBy - */ - groupBy( - iteratee?: Object - ): LoDashExplicitObjectWrapper>; + groupBy( + this: LoDashExplicitWrapper, + iteratee?: ObjectIteratee + ): LoDashExplicitWrapper>>; } //_.includes @@ -8093,77 +5612,30 @@ declare namespace _ { target: T, fromIndex?: number ): boolean; - - /** - * @see _.includes - */ - includes( - collection: string | null | undefined, - target: string, - fromIndex?: number - ): boolean; } - interface LoDashImplicitArrayWrapperBase { + interface LoDashImplicitWrapper { /** * @see _.includes */ - includes( + includes( + this: LoDashImplicitWrapper | Dictionary | null | undefined>, target: T, fromIndex?: number ): boolean; } - interface LoDashImplicitObjectWrapperBase { + interface LoDashExplicitWrapper { /** * @see _.includes */ - includes( - target: TValue, - fromIndex?: number - ): boolean; - } - - interface LoDashImplicitWrapper { - /** - * @see _.includes - */ - includes( - target: string, - fromIndex?: number - ): boolean; - } - - interface LoDashExplicitArrayWrapperBase { - /** - * @see _.includes - */ - includes( + includes( + this: LoDashExplicitWrapper | Dictionary | null | undefined>, target: T, fromIndex?: number ): LoDashExplicitWrapper; } - interface LoDashExplicitObjectWrapperBase { - /** - * @see _.includes - */ - includes( - target: TValue, - fromIndex?: number - ): LoDashExplicitWrapper; - } - - interface LoDashExplicitWrapper { - /** - * @see _.includes - */ - includes( - target: string, - fromIndex?: number - ): LoDashExplicitWrapper; - } - //_.keyBy interface LoDashStatic { /** @@ -8188,190 +5660,76 @@ declare namespace _ { */ keyBy( collection: List | null | undefined, - iteratee?: ListIterator + iteratee?: ListIteratee ): Dictionary; + /** + * @see _.keyBy + */ + keyBy( + collection: T | null | undefined, + iteratee?: ObjectIteratee + ): Dictionary; + /** * @see _.keyBy */ keyBy( collection: NumericDictionary | null | undefined, - iteratee?: NumericDictionaryIterator - ): Dictionary; - - /** - * @see _.keyBy - */ - keyBy( - collection: Dictionary | null | undefined, - iteratee?: DictionaryIterator - ): Dictionary; - - /** - * @see _.keyBy - */ - keyBy( - collection: List|NumericDictionary|Dictionary | null | undefined, - iteratee?: string - ): Dictionary; - - /** - * @see _.keyBy - */ - keyBy( - collection: List|NumericDictionary|Dictionary | null | undefined, - iteratee?: W - ): Dictionary; - - /** - * @see _.keyBy - */ - keyBy( - collection: List|NumericDictionary|Dictionary | null | undefined, - iteratee?: Object + iteratee?: NumericDictionaryIteratee ): Dictionary; } - interface LoDashImplicitStringWrapper { - /** - * @see _.keyBy - */ - keyBy( - iteratee?: StringIterator | undefined - ): LoDashImplicitObjectWrapper> - } - - interface LoDashExplicitStringWrapper { - /** - * @see _.keyBy - */ - keyBy( - iteratee?: StringIterator | undefined - ): LoDashExplicitObjectWrapper> - } - - interface LoDashImplicitWrapper { - /** - * @see _.keyBy - */ - keyBy( - iteratee?: ListIterator - ): LoDashImplicitObjectWrapper>; - } - - interface LoDashImplicitArrayWrapperBase { - /** - * @see _.keyBy - */ - keyBy( - iteratee?: ListIterator - ): LoDashImplicitObjectWrapper>; - - /** - * @see _.keyBy - */ - keyBy( - iteratee?: string - ): LoDashImplicitObjectWrapper>; - - /** - * @see _.keyBy - */ - keyBy( - iteratee?: W - ): LoDashImplicitObjectWrapper>; - } - - interface LoDashImplicitObjectWrapperBase { + interface LoDashImplicitWrapper { /** * @see _.keyBy */ keyBy( - iteratee?: ListIterator|NumericDictionaryIterator|DictionaryIterator - ): LoDashImplicitObjectWrapper>; + this: LoDashImplicitWrapper | null | undefined>, + iteratee?: ListIteratee + ): LoDashImplicitWrapper>; + + /** + * @see _.keyBy + */ + keyBy( + this: LoDashImplicitWrapper, + iteratee?: ObjectIteratee + ): LoDashImplicitWrapper>; /** * @see _.keyBy */ keyBy( - iteratee?: string - ): LoDashImplicitObjectWrapper>; - - /** - * @see _.keyBy - */ - keyBy( - iteratee?: W - ): LoDashImplicitObjectWrapper>; - - /** - * @see _.keyBy - */ - keyBy( - iteratee?: Object - ): LoDashImplicitObjectWrapper>; + this: LoDashImplicitWrapper | null | undefined>, + iteratee?: NumericDictionaryIteratee + ): LoDashImplicitWrapper>; } - interface LoDashExplicitWrapper { - /** - * @see _.keyBy - */ - keyBy( - iteratee?: ListIterator - ): LoDashExplicitObjectWrapper>; - } - - interface LoDashExplicitArrayWrapperBase { - /** - * @see _.keyBy - */ - keyBy( - iteratee?: ListIterator - ): LoDashExplicitObjectWrapper>; - - /** - * @see _.keyBy - */ - keyBy( - iteratee?: string - ): LoDashExplicitObjectWrapper>; - - /** - * @see _.keyBy - */ - keyBy( - iteratee?: W - ): LoDashExplicitObjectWrapper>; - } - - interface LoDashExplicitObjectWrapperBase { + interface LoDashExplicitWrapper { /** * @see _.keyBy */ keyBy( - iteratee?: ListIterator|NumericDictionaryIterator|DictionaryIterator - ): LoDashExplicitObjectWrapper>; + this: LoDashExplicitWrapper | null | undefined>, + iteratee?: ListIteratee + ): LoDashExplicitWrapper>; + + /** + * @see _.keyBy + */ + keyBy( + this: LoDashExplicitWrapper, + iteratee?: ObjectIteratee + ): LoDashExplicitWrapper>; /** * @see _.keyBy */ keyBy( - iteratee?: string - ): LoDashExplicitObjectWrapper>; - - /** - * @see _.keyBy - */ - keyBy( - iteratee?: W - ): LoDashExplicitObjectWrapper>; - - /** - * @see _.keyBy - */ - keyBy( - iteratee?: Object - ): LoDashExplicitObjectWrapper>; + this: LoDashExplicitWrapper | null | undefined>, + iteratee?: NumericDictionaryIteratee + ): LoDashExplicitWrapper>; } //_.invoke @@ -8382,62 +5740,28 @@ declare namespace _ { * @param path The path of the method to invoke. * @param args The arguments to invoke the method with. **/ - invoke( - object: TObject, - path: Many, - ...args: any[]): TResult; - - /** - * @see _.invoke - **/ - invoke( - object: Dictionary|TValue[], - path: Many, - ...args: any[]): TResult; - - /** - * @see _.invoke - **/ - invoke( + invoke( object: any, path: Many, - ...args: any[]): TResult; + ...args: any[]): any; } - interface LoDashImplicitArrayWrapper { + interface LoDashImplicitWrapper { /** * @see _.invoke **/ - invoke( + invoke( path: Many, - ...args: any[]): TResult; + ...args: any[]): any; } - interface LoDashImplicitObjectWrapper { + interface LoDashExplicitWrapper { /** * @see _.invoke **/ - invoke( + invoke( path: Many, - ...args: any[]): TResult; - } - - interface LoDashExplicitArrayWrapper { - /** - * @see _.invoke - **/ - invoke( - path: Many, - ...args: any[]): TResult; - } - - interface LoDashExplicitObjectWrapper { - /** - * @see _.invoke - **/ - invoke( - path: Many, - ...args: any[]): TResult; + ...args: any[]): LoDashExplicitWrapper; } //_.invokeMap @@ -8451,130 +5775,50 @@ declare namespace _ { * @param methodName The name of the method to invoke. * @param args Arguments to invoke the method with. **/ - invokeMap( - collection: TValue[] | null | undefined, + invokeMap( + collection: object | null | undefined, methodName: string, - ...args: any[]): TResult[]; - - /** - * @see _.invokeMap - **/ - invokeMap( - collection: Dictionary | null | undefined, - methodName: string, - ...args: any[]): TResult[]; + ...args: any[]): any[]; /** * @see _.invokeMap **/ invokeMap( - collection: Array<{}> | null | undefined, - methodName: string, - ...args: any[]): TResult[]; - - /** - * @see _.invokeMap - **/ - invokeMap( - collection: Dictionary<{}> | null | undefined, - methodName: string, - ...args: any[]): TResult[]; - - /** - * @see _.invokeMap - **/ - invokeMap( - collection: TValue[] | null | undefined, - method: (...args: any[]) => TResult, - ...args: any[]): TResult[]; - - /** - * @see _.invokeMap - **/ - invokeMap( - collection: Dictionary | null | undefined, - method: (...args: any[]) => TResult, - ...args: any[]): TResult[]; - - /** - * @see _.invokeMap - **/ - invokeMap( - collection: Array<{}> | null | undefined, - method: (...args: any[]) => TResult, - ...args: any[]): TResult[]; - - /** - * @see _.invokeMap - **/ - invokeMap( - collection: Dictionary<{}> | null | undefined, + collection: object | null | undefined, method: (...args: any[]) => TResult, ...args: any[]): TResult[]; } - interface LoDashImplicitArrayWrapperBase { + interface LoDashImplicitWrapper { /** * @see _.invokeMap **/ - invokeMap( + invokeMap( methodName: string, - ...args: any[]): LoDashImplicitArrayWrapper; + ...args: any[]): LoDashImplicitWrapper; /** * @see _.invokeMap **/ invokeMap( method: (...args: any[]) => TResult, - ...args: any[]): LoDashImplicitArrayWrapper; + ...args: any[]): LoDashImplicitWrapper; } - interface LoDashImplicitObjectWrapperBase { + interface LoDashExplicitWrapper { /** * @see _.invokeMap **/ - invokeMap( + invokeMap( methodName: string, - ...args: any[]): LoDashImplicitArrayWrapper; + ...args: any[]): LoDashExplicitWrapper; /** * @see _.invokeMap **/ invokeMap( method: (...args: any[]) => TResult, - ...args: any[]): LoDashImplicitArrayWrapper; - } - - interface LoDashExplicitArrayWrapperBase { - /** - * @see _.invokeMap - **/ - invokeMap( - methodName: string, - ...args: any[]): LoDashExplicitArrayWrapper; - - /** - * @see _.invokeMap - **/ - invokeMap( - method: (...args: any[]) => TResult, - ...args: any[]): LoDashExplicitArrayWrapper; - } - - interface LoDashExplicitObjectWrapperBase { - /** - * @see _.invokeMap - **/ - invokeMap( - methodName: string, - ...args: any[]): LoDashExplicitArrayWrapper; - - /** - * @see _.invokeMap - **/ - invokeMap( - method: (...args: any[]) => TResult, - ...args: any[]): LoDashExplicitArrayWrapper; + ...args: any[]): LoDashExplicitWrapper; } //_.map @@ -8613,33 +5857,28 @@ declare namespace _ { /** * @see _.map */ - map(collection: List | null | undefined): T[]; + map(collection: List | Dictionary | null | undefined): T[]; /** * @see _.map */ - map( + map( collection: Dictionary | null | undefined, iteratee: DictionaryIterator ): TResult[]; /** @see _.map */ map( - collection: Dictionary | null | undefined, + collection: List | Dictionary | null | undefined, iteratee: K - ): T[K][]; + ): Array; /** @see _.map */ - map(collection: Dictionary | null | undefined): T[]; - - map( + map( collection: NumericDictionary | null | undefined, iteratee?: NumericDictionaryIterator ): TResult[]; - /** @see _.map */ - map(collection: List | null | undefined, iteratee: K): T[K][]; - /** * @see _.map */ @@ -8651,125 +5890,114 @@ declare namespace _ { /** * @see _.map */ - map( + map( collection: List|Dictionary|NumericDictionary | null | undefined, - iteratee?: TObject + iteratee?: object ): boolean[]; } - interface LoDashImplicitArrayWrapperBase { + interface LoDashImplicitWrapper { /** * @see _.map */ - map( + map( + this: LoDashImplicitWrapper | null | undefined>, iteratee: ListIterator - ): LoDashImplicitArrayWrapper; + ): LoDashImplicitWrapper; /** * @see _.map */ - map(): LoDashImplicitArrayWrapper; + map(this: LoDashImplicitWrapper | Dictionary | null | undefined>): LoDashImplicitWrapper; + + /** + * @see _.map + */ + map( + this: LoDashImplicitWrapper | null | undefined>, + iteratee: DictionaryIterator + ): LoDashImplicitWrapper; /** @see _.map */ - map(iteratee: K): LoDashImplicitArrayWrapper; + map( + this: LoDashImplicitWrapper | Dictionary | null | undefined>, + iteratee: K + ): LoDashImplicitWrapper>; + + /** @see _.map */ + map( + this: LoDashImplicitWrapper | null | undefined>, + iteratee?: NumericDictionaryIterator + ): LoDashImplicitWrapper; /** * @see _.map */ - map( - iteratee: string - ): LoDashImplicitArrayWrapper; + map( + this: LoDashImplicitWrapper | Dictionary | NumericDictionary | null | undefined>, + iteratee?: string + ): LoDashImplicitWrapper; /** * @see _.map */ - map( - iteratee: TObject - ): LoDashImplicitArrayWrapper; + map( + this: LoDashImplicitWrapper | Dictionary | NumericDictionary | null | undefined>, + iteratee?: object + ): LoDashImplicitWrapper; } - interface LoDashImplicitObjectWrapperBase { + interface LoDashExplicitWrapper { /** * @see _.map */ - map( - iteratee: ListIterator|DictionaryIterator - ): LoDashImplicitArrayWrapper; - - /** @see _.map */ - map(): LoDashImplicitArrayWrapper; - - /** @see _.map */ - map(iteratee: K): LoDashImplicitArrayWrapper; - - /** - * @see _.map - */ - map( - iteratee: string - ): LoDashImplicitArrayWrapper; - - /** - * @see _.map - */ - map( - iteratee: TObject - ): LoDashImplicitArrayWrapper; - } - - interface LoDashExplicitArrayWrapperBase { - /** - * @see _.map - */ - map( + map( + this: LoDashExplicitWrapper | null | undefined>, iteratee: ListIterator - ): LoDashExplicitArrayWrapper; + ): LoDashExplicitWrapper; + + /** + * @see _.map + */ + map(this: LoDashExplicitWrapper | Dictionary | null | undefined>): LoDashExplicitWrapper; + + /** + * @see _.map + */ + map( + this: LoDashExplicitWrapper | null | undefined>, + iteratee: DictionaryIterator + ): LoDashExplicitWrapper; /** @see _.map */ - map(): LoDashExplicitArrayWrapper; - - /** @see _.map */ - map(iteratee: K): LoDashExplicitArrayWrapper; + map( + this: LoDashExplicitWrapper | Dictionary | null | undefined>, + iteratee: K + ): LoDashExplicitWrapper>; /** * @see _.map */ - map( - iteratee: string - ): LoDashExplicitArrayWrapper; + map( + this: LoDashExplicitWrapper | null | undefined>, + iteratee?: NumericDictionaryIterator + ): LoDashExplicitWrapper; /** * @see _.map */ - map( - iteratee: TObject - ): LoDashExplicitArrayWrapper; - } - - interface LoDashExplicitObjectWrapperBase { - /** - * @see _.map - */ - map( - iteratee: ListIterator|DictionaryIterator - ): LoDashExplicitArrayWrapper; - - /** @see _.map */ - map(): LoDashExplicitArrayWrapper; + map( + this: LoDashExplicitWrapper | Dictionary | NumericDictionary | null | undefined>, + iteratee?: string + ): LoDashExplicitWrapper; /** * @see _.map */ - map( - iteratee: string - ): LoDashExplicitArrayWrapper; - - /** - * @see _.map - */ - map( - iteratee: TObject - ): LoDashExplicitArrayWrapper; + map( + this: LoDashExplicitWrapper | Dictionary | NumericDictionary | null | undefined>, + iteratee?: object + ): LoDashExplicitWrapper; } //_.partition @@ -8795,123 +6023,52 @@ declare namespace _ { **/ partition( collection: List | null | undefined, - callback: ListIterator): T[][]; + callback: ValueIteratee + ): T[][]; /** * @see _.partition - **/ - partition( - collection: Dictionary | null | undefined, - callback: DictionaryIterator): T[][]; - - /** - * @see _.partition - **/ - partition( - collection: List | null | undefined, - whereValue: W): T[][]; - - /** - * @see _.partition - **/ - partition( - collection: Dictionary | null | undefined, - whereValue: W): T[][]; - - /** - * @see _.partition - **/ - partition( - collection: List | null | undefined, - path: string, - srcValue: any): T[][]; - - /** - * @see _.partition - **/ - partition( - collection: Dictionary | null | undefined, - path: string, - srcValue: any): T[][]; - - /** - * @see _.partition - **/ - partition( - collection: List | null | undefined, - pluckValue: string): T[][]; - - /** - * @see _.partition - **/ - partition( - collection: Dictionary | null | undefined, - pluckValue: string): T[][]; + */ + partition( + collection: T | null | undefined, + callback: ValueIteratee + ): Array>; } - interface LoDashImplicitStringWrapper { + interface LoDashImplicitWrapper { /** * @see _.partition */ - partition( - callback: ListIterator): LoDashImplicitArrayWrapper; + partition( + this: LoDashImplicitWrapper | null | undefined>, + callback: ValueIteratee + ): LoDashImplicitWrapper; + + /** + * @see _.partition + */ + partition( + this: LoDashImplicitWrapper, + callback: ValueIteratee + ): LoDashImplicitWrapper>>; } - interface LoDashImplicitArrayWrapperBase { + interface LoDashExplicitWrapper { /** * @see _.partition */ - partition( - callback: ListIterator): LoDashImplicitArrayWrapper; - /** - * @see _.partition - */ - partition( - whereValue: W): LoDashImplicitArrayWrapper; - /** - * @see _.partition - */ - partition( - path: string, - srcValue: any): LoDashImplicitArrayWrapper; - /** - * @see _.partition - */ - partition( - pluckValue: string): LoDashImplicitArrayWrapper; - } - - interface LoDashImplicitObjectWrapperBase { - /** - * @see _.partition - */ - partition( - callback: ListIterator): LoDashImplicitArrayWrapper; + partition( + this: LoDashExplicitWrapper | null | undefined>, + callback: ValueIteratee + ): LoDashExplicitWrapper; /** * @see _.partition */ - partition( - callback: DictionaryIterator): LoDashImplicitArrayWrapper; - - /** - * @see _.partition - */ - partition( - whereValue: W): LoDashImplicitArrayWrapper; - - /** - * @see _.partition - */ - partition( - path: string, - srcValue: any): LoDashImplicitArrayWrapper; - - /** - * @see _.partition - */ - partition( - pluckValue: string): LoDashImplicitArrayWrapper; + partition( + this: LoDashExplicitWrapper, + callback: ValueIteratee + ): LoDashExplicitWrapper>>; } //_.reduce @@ -8925,125 +6082,212 @@ declare namespace _ { * @param collection The collection to iterate over. * @param callback The function called per iteration. * @param accumulator Initial value of the accumulator. - * @param thisArg The this binding of callback. * @return Returns the accumulated value. **/ reduce( collection: T[] | null | undefined, - callback: MemoIterator, - accumulator: TResult): TResult; + callback: MemoListIterator, + accumulator: TResult + ): TResult; /** - * @see _.reduce - **/ + * @see _.reduce + **/ reduce( collection: List | null | undefined, - callback: MemoIterator, - accumulator: TResult): TResult; + callback: MemoListIterator>, + accumulator: TResult + ): TResult; /** - * @see _.reduce - **/ - reduce( - collection: Dictionary | null | undefined, - callback: MemoIterator, - accumulator: TResult): TResult; + * @see _.reduce + **/ + reduce( + collection: T | null | undefined, + callback: MemoObjectIterator, + accumulator: TResult + ): TResult; /** - * @see _.reduce - **/ + * @see _.reduce + **/ reduce( collection: NumericDictionary | null | undefined, - callback: MemoIterator, - accumulator: TResult): TResult; + callback: MemoListIterator>, + accumulator: TResult + ): TResult; /** - * @see _.reduce - **/ + * @see _.reduce + **/ reduce( collection: T[] | null | undefined, - callback: MemoIterator): TResult | undefined; + callback: MemoListIterator + ): TResult | undefined; /** * @see _.reduce **/ reduce( collection: List | null | undefined, - callback: MemoIterator): TResult | undefined; + callback: MemoListIterator> + ): TResult | undefined; /** - * @see _.reduce - **/ - reduce( - collection: Dictionary | null | undefined, - callback: MemoIterator): TResult | undefined; + * @see _.reduce + **/ + reduce( + collection: T | null | undefined, + callback: MemoObjectIterator + ): TResult | undefined; /** * @see _.reduce **/ reduce( collection: NumericDictionary | null | undefined, - callback: MemoIterator): TResult | undefined; + callback: MemoListIterator> + ): TResult | undefined; } - interface LoDashImplicitArrayWrapperBase { + interface LoDashImplicitWrapper { /** * @see _.reduce **/ - reduce( - callback: MemoIterator, - accumulator: TResult): TResult; - - /** - * @see _.reduce - **/ - reduce( - callback: MemoIterator): TResult | undefined; - } - - interface LoDashImplicitObjectWrapperBase { - /** - * @see _.reduce - **/ - reduce( - callback: MemoIterator, - accumulator: TResult): TResult; - - /** - * @see _.reduce - **/ - reduce( - callback: MemoIterator): TResult | undefined; - } - - interface LoDashExplicitObjectWrapperBase { - /** - * @see _.reduce - **/ - reduce( - callback: MemoIterator, - accumulator: TResult): LoDashExplicitObjectWrapper; - - /** - * @see _.reduce - **/ - reduce( - callback: MemoIterator): LoDashExplicitObjectWrapper; - } - - interface LoDashExplicitArrayWrapperBase { - /**LoDashExplicitWrapper - * @see _.reduce - */ - reduce( - callback: MemoIterator, - accumulator: TResult): LoDashExplicitWrapper; + reduce( + this: LoDashImplicitWrapper, + callback: MemoListIterator, + accumulator: TResult + ): TResult; /** * @see _.reduce - */ - reduce( - callback: MemoIterator): LoDashExplicitWrapper; + **/ + reduce( + this: LoDashImplicitWrapper | null | undefined>, + callback: MemoListIterator>, + accumulator: TResult + ): TResult; + + /** + * @see _.reduce + **/ + reduce( + this: LoDashImplicitWrapper, + callback: MemoObjectIterator, + accumulator: TResult + ): TResult; + + /** + * @see _.reduce + **/ + reduce( + this: LoDashImplicitWrapper | null | undefined>, + callback: MemoListIterator>, + accumulator: TResult + ): TResult; + + /** + * @see _.reduce + **/ + reduce( + this: LoDashImplicitWrapper, + callback: MemoListIterator + ): TResult | undefined; + + /** + * @see _.reduce + **/ + reduce( + this: LoDashImplicitWrapper | null | undefined>, + callback: MemoListIterator> + ): TResult | undefined; + + /** + * @see _.reduce + **/ + reduce( + this: LoDashImplicitWrapper, + callback: MemoObjectIterator + ): TResult | undefined; + + /** + * @see _.reduce + **/ + reduce( + this: LoDashImplicitWrapper | null | undefined>, + callback: MemoListIterator> + ): TResult | undefined; + } + + interface LoDashExplicitWrapper { + /** + * @see _.reduce + **/ + reduce( + this: LoDashExplicitWrapper, + callback: MemoListIterator, + accumulator: TResult + ): LoDashExplicitWrapper; + + /** + * @see _.reduce + **/ + reduce( + this: LoDashExplicitWrapper | null | undefined>, + callback: MemoListIterator>, + accumulator: TResult + ): LoDashExplicitWrapper; + + /** + * @see _.reduce + **/ + reduce( + this: LoDashExplicitWrapper, + callback: MemoObjectIterator, + accumulator: TResult + ): LoDashExplicitWrapper; + + /** + * @see _.reduce + **/ + reduce( + this: LoDashExplicitWrapper | null | undefined>, + callback: MemoListIterator>, + accumulator: TResult + ): LoDashExplicitWrapper; + + /** + * @see _.reduce + **/ + reduce( + this: LoDashExplicitWrapper, + callback: MemoListIterator + ): LoDashExplicitWrapper; + + /** + * @see _.reduce + **/ + reduce( + this: LoDashExplicitWrapper | null | undefined>, + callback: MemoListIterator> + ): LoDashExplicitWrapper; + + /** + * @see _.reduce + **/ + reduce( + this: LoDashExplicitWrapper, + callback: MemoObjectIterator + ): LoDashExplicitWrapper; + + /** + * @see _.reduce + **/ + reduce( + this: LoDashExplicitWrapper | null | undefined>, + callback: MemoListIterator> + ): LoDashExplicitWrapper; } //_.reduceRight @@ -9054,50 +6298,212 @@ declare namespace _ { * @param collection The collection to iterate over. * @param callback The function called per iteration. * @param accumulator Initial value of the accumulator. - * @param thisArg The this binding of callback. * @return The accumulated value. **/ reduceRight( collection: T[] | null | undefined, - callback: MemoIterator, - accumulator: TResult): TResult; + callback: MemoListIterator, + accumulator: TResult + ): TResult; /** * @see _.reduceRight **/ reduceRight( collection: List | null | undefined, - callback: MemoIterator, - accumulator: TResult): TResult; + callback: MemoListIterator>, + accumulator: TResult + ): TResult; + + /** + * @see _.reduceRight + **/ + reduceRight( + collection: T | null | undefined, + callback: MemoObjectIterator, + accumulator: TResult + ): TResult; /** * @see _.reduceRight **/ reduceRight( - collection: Dictionary | null | undefined, - callback: MemoIterator, - accumulator: TResult): TResult; + collection: NumericDictionary | null | undefined, + callback: MemoListIterator>, + accumulator: TResult + ): TResult; /** * @see _.reduceRight **/ reduceRight( collection: T[] | null | undefined, - callback: MemoIterator): TResult | undefined; + callback: MemoListIterator + ): TResult | undefined; /** * @see _.reduceRight **/ reduceRight( collection: List | null | undefined, - callback: MemoIterator): TResult | undefined; + callback: MemoListIterator> + ): TResult | undefined; + + /** + * @see _.reduceRight + **/ + reduceRight( + collection: T | null | undefined, + callback: MemoObjectIterator + ): TResult | undefined; /** * @see _.reduceRight **/ reduceRight( - collection: Dictionary | null | undefined, - callback: MemoIterator): TResult | undefined; + collection: NumericDictionary | null | undefined, + callback: MemoListIterator> + ): TResult | undefined; + } + + interface LoDashImplicitWrapper { + /** + * @see _.reduceRight + **/ + reduceRight( + this: LoDashImplicitWrapper, + callback: MemoListIterator, + accumulator: TResult + ): TResult; + + /** + * @see _.reduceRight + **/ + reduceRight( + this: LoDashImplicitWrapper | null | undefined>, + callback: MemoListIterator>, + accumulator: TResult + ): TResult; + + /** + * @see _.reduceRight + **/ + reduceRight( + this: LoDashImplicitWrapper, + callback: MemoObjectIterator, + accumulator: TResult + ): TResult; + + /** + * @see _.reduceRight + **/ + reduceRight( + this: LoDashImplicitWrapper | null | undefined>, + callback: MemoListIterator>, + accumulator: TResult + ): TResult; + + /** + * @see _.reduceRight + **/ + reduceRight( + this: LoDashImplicitWrapper, + callback: MemoListIterator + ): TResult | undefined; + + /** + * @see _.reduceRight + **/ + reduceRight( + this: LoDashImplicitWrapper | null | undefined>, + callback: MemoListIterator> + ): TResult | undefined; + + /** + * @see _.reduceRight + **/ + reduceRight( + this: LoDashImplicitWrapper, + callback: MemoObjectIterator + ): TResult | undefined; + + /** + * @see _.reduceRight + **/ + reduceRight( + this: LoDashImplicitWrapper | null | undefined>, + callback: MemoListIterator> + ): TResult | undefined; + } + + interface LoDashExplicitWrapper { + /** + * @see _.reduceRight + **/ + reduceRight( + this: LoDashExplicitWrapper, + callback: MemoListIterator, + accumulator: TResult + ): LoDashExplicitWrapper; + + /** + * @see _.reduceRight + **/ + reduceRight( + this: LoDashExplicitWrapper | null | undefined>, + callback: MemoListIterator>, + accumulator: TResult + ): LoDashExplicitWrapper; + + /** + * @see _.reduceRight + **/ + reduceRight( + this: LoDashExplicitWrapper, + callback: MemoObjectIterator, + accumulator: TResult + ): LoDashExplicitWrapper; + + /** + * @see _.reduceRight + **/ + reduceRight( + this: LoDashExplicitWrapper | null | undefined>, + callback: MemoListIterator>, + accumulator: TResult + ): LoDashExplicitWrapper; + + /** + * @see _.reduceRight + **/ + reduceRight( + this: LoDashExplicitWrapper, + callback: MemoListIterator + ): LoDashExplicitWrapper; + + /** + * @see _.reduceRight + **/ + reduceRight( + this: LoDashExplicitWrapper | null | undefined>, + callback: MemoListIterator> + ): LoDashExplicitWrapper; + + /** + * @see _.reduceRight + **/ + reduceRight( + this: LoDashExplicitWrapper, + callback: MemoObjectIterator + ): LoDashExplicitWrapper; + + /** + * @see _.reduceRight + **/ + reduceRight( + this: LoDashExplicitWrapper | null | undefined>, + callback: MemoListIterator> + ): LoDashExplicitWrapper; } //_.reject @@ -9111,144 +6517,78 @@ declare namespace _ { * @param thisArg The this binding of predicate. * @return Returns the new filtered array. */ - reject( - collection: List | null | undefined, - predicate?: ListIterator - ): T[]; - - /** - * @see _.reject - */ - reject( - collection: Dictionary | null | undefined, - predicate?: DictionaryIterator - ): T[]; - - /** - * @see _.reject - */ reject( collection: string | null | undefined, - predicate?: StringIterator + predicate?: StringIterator ): string[]; /** * @see _.reject */ reject( - collection: List|Dictionary | null | undefined, - predicate: string + collection: List | null | undefined, + predicate?: ListIteratee ): T[]; /** * @see _.reject */ - reject( - collection: List|Dictionary | null | undefined, - predicate: W - ): T[]; + reject( + collection: T | null | undefined, + predicate?: ObjectIteratee + ): Array; } - interface LoDashImplicitWrapper { + interface LoDashImplicitWrapper { /** * @see _.reject */ reject( - predicate?: StringIterator - ): LoDashImplicitArrayWrapper; - } - - interface LoDashImplicitArrayWrapperBase { - /** - * @see _.reject - */ - reject( - predicate: ListIterator - ): LoDashImplicitArrayWrapper; - - /** - * @see _.reject - */ - reject( - predicate: string - ): LoDashImplicitArrayWrapper; - - /** - * @see _.reject - */ - reject(predicate: W): LoDashImplicitArrayWrapper; - } - - interface LoDashImplicitObjectWrapperBase { - /** - * @see _.reject - */ - reject( - predicate: ListIterator|DictionaryIterator - ): LoDashImplicitArrayWrapper; + this: LoDashImplicitWrapper, + predicate?: StringIterator + ): LoDashImplicitWrapper; /** * @see _.reject */ reject( - predicate: string - ): LoDashImplicitArrayWrapper; + this: LoDashImplicitWrapper | null | undefined>, + predicate?: ListIteratee + ): LoDashImplicitWrapper; /** * @see _.reject */ - reject(predicate: W): LoDashImplicitArrayWrapper; + reject( + this: LoDashImplicitWrapper, + predicate?: ObjectIteratee + ): LoDashImplicitWrapper>; } - interface LoDashExplicitWrapper { + interface LoDashExplicitWrapper { /** * @see _.reject */ reject( - predicate?: StringIterator - ): LoDashExplicitArrayWrapper; - } - - interface LoDashExplicitArrayWrapperBase { - /** - * @see _.reject - */ - reject( - predicate: ListIterator - ): LoDashExplicitArrayWrapper; - - /** - * @see _.reject - */ - reject( - predicate: string - ): LoDashExplicitArrayWrapper; - - /** - * @see _.reject - */ - reject(predicate: W): LoDashExplicitArrayWrapper; - } - - interface LoDashExplicitObjectWrapperBase { - /** - * @see _.reject - */ - reject( - predicate: ListIterator|DictionaryIterator - ): LoDashExplicitArrayWrapper; + this: LoDashExplicitWrapper, + predicate?: StringIterator + ): LoDashExplicitWrapper; /** * @see _.reject */ reject( - predicate: string - ): LoDashExplicitArrayWrapper; + this: LoDashExplicitWrapper | null | undefined>, + predicate?: ListIteratee + ): LoDashExplicitWrapper; /** * @see _.reject */ - reject(predicate: W): LoDashExplicitArrayWrapper; + reject( + this: LoDashExplicitWrapper, + predicate?: ObjectIteratee + ): LoDashExplicitWrapper>; } //_.sample @@ -9260,50 +6600,68 @@ declare namespace _ { * @return Returns the random element. */ sample( - collection: List | Dictionary | NumericDictionary | object | null | undefined + collection: List | Dictionary | NumericDictionary | null | undefined ): T | undefined; - } - interface LoDashImplicitWrapper { /** * @see _.sample */ - sample(): string | undefined; - } + sample( + collection: T + ): T[keyof T]; - interface LoDashImplicitArrayWrapperBase { /** * @see _.sample */ - sample(): T | undefined; + sample( + collection: T | null | undefined + ): T[keyof T] | undefined; } - interface LoDashImplicitObjectWrapperBase { + interface LoDashImplicitWrapper { /** * @see _.sample */ - sample(): T | undefined; - } + sample( + this: LoDashImplicitWrapper | Dictionary | NumericDictionary | null | undefined> + ): T | undefined; - interface LoDashExplicitWrapper { /** * @see _.sample */ - sample(): LoDashExplicitWrapper; - } + sample( + this: LoDashImplicitWrapper, + ): T[keyof T]; - interface LoDashExplicitArrayWrapperBase { /** * @see _.sample */ - sample(): TWrapper; + sample( + this: LoDashImplicitWrapper + ): T[keyof T] | undefined; } - interface LoDashExplicitObjectWrapperBase { + interface LoDashExplicitWrapper { /** * @see _.sample */ - sample(): TWrapper; + sample( + this: LoDashExplicitWrapper | Dictionary | NumericDictionary | null | undefined> + ): LoDashExplicitWrapper; + + /** + * @see _.sample + */ + sample( + this: LoDashExplicitWrapper, + ): LoDashExplicitWrapper; + + /** + * @see _.sample + */ + sample( + this: LoDashExplicitWrapper + ): LoDashExplicitWrapper; } //_.sampleSize @@ -9323,72 +6681,46 @@ declare namespace _ { /** * @see _.sampleSize */ - sampleSize( - collection: O | null | undefined, + sampleSize( + collection: T | null | undefined, n?: number - ): T[]; + ): Array; + } + interface LoDashImplicitWrapper { /** * @see _.sampleSize */ sampleSize( - collection: Object | null | undefined, + this: LoDashImplicitWrapper|Dictionary|NumericDictionary | null | undefined>, n?: number - ): T[]; - } + ): LoDashImplicitWrapper; - interface LoDashImplicitWrapper { /** * @see _.sampleSize */ - sampleSize( + sampleSize( + this: LoDashImplicitWrapper, n?: number - ): LoDashImplicitArrayWrapper; + ): LoDashImplicitWrapper>; } - interface LoDashImplicitArrayWrapperBase { - /** - * @see _.sampleSize - */ - sampleSize( - n?: number - ): LoDashImplicitArrayWrapper; - } - - interface LoDashImplicitObjectWrapperBase { + interface LoDashExplicitWrapper { /** * @see _.sampleSize */ sampleSize( + this: LoDashExplicitWrapper|Dictionary|NumericDictionary | null | undefined>, n?: number - ): LoDashImplicitArrayWrapper; - } + ): LoDashExplicitWrapper; - interface LoDashExplicitWrapper { /** * @see _.sampleSize */ - sampleSize( + sampleSize( + this: LoDashExplicitWrapper, n?: number - ): LoDashExplicitArrayWrapper; - } - - interface LoDashExplicitArrayWrapperBase { - /** - * @see _.sampleSize - */ - sampleSize( - n?: number - ): LoDashExplicitArrayWrapper; - } - - interface LoDashExplicitObjectWrapperBase { - /** - * @see _.sampleSize - */ - sampleSize( - n?: number - ): LoDashExplicitArrayWrapper; + ): LoDashExplicitWrapper>; } //_.shuffle @@ -9399,54 +6731,36 @@ declare namespace _ { * @param collection The collection to shuffle. * @return Returns the new shuffled array. */ - shuffle(collection: List|Dictionary | null | undefined): T[]; + shuffle(collection: List | null | undefined): T[]; /** * @see _.shuffle */ - shuffle(collection: string | null | undefined): string[]; + shuffle(collection: T | null | undefined): Array; } - interface LoDashImplicitWrapper { + interface LoDashImplicitWrapper { /** * @see _.shuffle */ - shuffle(): LoDashImplicitArrayWrapper; + shuffle(this: LoDashImplicitWrapper | null | undefined>): LoDashImplicitWrapper; + + /** + * @see _.shuffle + */ + shuffle(this: LoDashImplicitWrapper): LoDashImplicitWrapper>; } - interface LoDashImplicitArrayWrapperBase { + interface LoDashExplicitWrapper { /** * @see _.shuffle */ - shuffle(): LoDashImplicitArrayWrapper; - } + shuffle(this: LoDashExplicitWrapper | null | undefined>): LoDashExplicitWrapper; - interface LoDashImplicitObjectWrapperBase { /** * @see _.shuffle */ - shuffle(): LoDashImplicitArrayWrapper; - } - - interface LoDashExplicitWrapper { - /** - * @see _.shuffle - */ - shuffle(): LoDashExplicitArrayWrapper; - } - - interface LoDashExplicitArrayWrapperBase { - /** - * @see _.shuffle - */ - shuffle(): LoDashExplicitArrayWrapper; - } - - interface LoDashExplicitObjectWrapperBase { - /** - * @see _.shuffle - */ - shuffle(): LoDashExplicitArrayWrapper; + shuffle(this: LoDashExplicitWrapper): LoDashExplicitWrapper>; } //_.size @@ -9458,50 +6772,17 @@ declare namespace _ { * @param collection The collection to inspect. * @return Returns the size of collection. */ - size(collection: List|Dictionary | null | undefined): number; - - /** - * @see _.size - */ - size(collection: string | null | undefined): number; + size(collection: object | string | null | undefined): number; } - interface LoDashImplicitWrapper { + interface LoDashImplicitWrapper { /** * @see _.size */ size(): number; } - interface LoDashImplicitArrayWrapperBase { - /** - * @see _.size - */ - size(): number; - } - - interface LoDashImplicitObjectWrapperBase { - /** - * @see _.size - */ - size(): number; - } - - interface LoDashExplicitWrapper { - /** - * @see _.size - */ - size(): LoDashExplicitWrapper; - } - - interface LoDashExplicitArrayWrapperBase { - /** - * @see _.size - */ - size(): LoDashExplicitWrapper; - } - - interface LoDashExplicitObjectWrapperBase { + interface LoDashExplicitWrapper { /** * @see _.size */ @@ -9520,15 +6801,15 @@ declare namespace _ { */ some( collection: List | null | undefined, - predicate?: ListIterator + predicate?: ListIteratee ): boolean; /** * @see _.some */ - some( - collection: Dictionary | null | undefined, - predicate?: DictionaryIterator + some( + collection: T | null | undefined, + predicate?: ObjectIteratee ): boolean; /** @@ -9536,146 +6817,59 @@ declare namespace _ { */ some( collection: NumericDictionary | null | undefined, - predicate?: NumericDictionaryIterator + predicate?: NumericDictionaryIteratee + ): boolean; + } + + interface LoDashImplicitWrapper { + /** + * @see _.some + */ + some( + this: LoDashImplicitWrapper | null | undefined>, + predicate?: ListIteratee ): boolean; /** * @see _.some */ - some( - collection: Object | null | undefined, - predicate?: ObjectIterator + some( + this: LoDashImplicitWrapper, + predicate?: ObjectIteratee ): boolean; /** * @see _.some */ some( - collection: List|Dictionary|NumericDictionary | null | undefined, - predicate?: string|[string, any] + this: LoDashImplicitWrapper | null | undefined>, + predicate?: NumericDictionaryIteratee ): boolean; + } + + interface LoDashExplicitWrapper { + /** + * @see _.some + */ + some( + this: LoDashExplicitWrapper | null | undefined>, + predicate?: ListIteratee + ): LoDashExplicitWrapper; /** * @see _.some */ - some( - collection: Object | null | undefined, - predicate?: string|[string, any] - ): boolean; + some( + this: LoDashExplicitWrapper, + predicate?: ObjectIteratee + ): LoDashExplicitWrapper; /** * @see _.some */ some( - collection: List|Dictionary|NumericDictionary | null | undefined, - predicate?: PartialObject - ): boolean; - - /** - * @see _.some - */ - some( - collection: List|Dictionary|NumericDictionary | null | undefined, - predicate?: PartialObject - ): boolean; - - /** - * @see _.some - */ - some( - collection: Object | null | undefined, - predicate?: PartialObject - ): boolean; - } - - interface LoDashImplicitArrayWrapperBase { - /** - * @see _.some - */ - some( - predicate?: ListIterator|NumericDictionaryIterator - ): boolean; - - /** - * @see _.some - */ - some( - predicate?: string|[string, any] - ): boolean; - - /** - * @see _.some - */ - some( - predicate?: PartialObject - ): boolean; - } - - interface LoDashImplicitObjectWrapperBase { - /** - * @see _.some - */ - some( - predicate?: ListIterator|DictionaryIterator|NumericDictionaryIterator|ObjectIterator - ): boolean; - /** - * @see _.some - */ - some( - predicate?: string|[string, any] - ): boolean; - - /** - * @see _.some - */ - some( - predicate?: PartialObject - ): boolean; - } - - interface LoDashExplicitArrayWrapperBase { - /** - * @see _.some - */ - some( - predicate?: ListIterator|NumericDictionaryIterator - ): LoDashExplicitWrapper; - - /** - * @see _.some - */ - some( - predicate?: string|[string, any] - ): LoDashExplicitWrapper; - - /** - * @see _.some - */ - some( - predicate?: PartialObject - ): LoDashExplicitWrapper; - } - - interface LoDashExplicitObjectWrapperBase { - /** - * @see _.some - */ - some( - predicate?: ListIterator|DictionaryIterator|NumericDictionaryIterator|ObjectIterator - ): LoDashExplicitWrapper; - - /** - * @see _.some - */ - some( - predicate?: string|[string, any] - ): LoDashExplicitWrapper; - - /** - * @see _.some - */ - some( - predicate?: PartialObject + this: LoDashExplicitWrapper | null | undefined>, + predicate?: NumericDictionaryIteratee ): LoDashExplicitWrapper; } @@ -9714,163 +6908,54 @@ declare namespace _ { * }); * // => objects for [['barney', 36], ['barney', 34], ['fred', 48], ['fred', 42]] */ - sortBy( - collection: List | null | undefined, - iteratee?: ListIterator - ): T[]; - - /** - * @see _.sortBy - */ - sortBy( - collection: Dictionary | null | undefined, - iteratee?: DictionaryIterator - ): T[]; - - /** - * @see _.sortBy - */ - sortBy( - collection: List|Dictionary | null | undefined, - iteratee: string - ): T[]; - - /** - * @see _.sortBy - */ - sortBy( - collection: List|Dictionary | null | undefined, - whereValue: W - ): T[]; - - /** - * @see _.sortBy - */ - sortBy( - collection: List|Dictionary | null | undefined - ): T[]; - - /** - * @see _.sortBy - */ sortBy( collection: List | null | undefined, - iteratees: Array|string|Object> + ...iteratees: Array>> ): T[]; + /** + * @see _.sortBy + */ + sortBy( + collection: T | null | undefined, + ...iteratees: Array>> + ): Array; + } + + interface LoDashImplicitWrapper { /** * @see _.sortBy */ sortBy( - collection: List | null | undefined, - ...iteratees: Array|Object|string> - ): T[]; + this: LoDashImplicitWrapper | null | undefined>, + ...iteratees: Array>> + ): LoDashImplicitWrapper; + + /** + * @see _.sortBy + */ + sortBy( + this: LoDashImplicitWrapper, + ...iteratees: Array>> + ): LoDashImplicitWrapper>; } - interface LoDashImplicitArrayWrapperBase { + interface LoDashExplicitWrapper { /** * @see _.sortBy */ - sortBy( - iteratee?: ListIterator - ): LoDashImplicitArrayWrapper; + sortBy( + this: LoDashExplicitWrapper | null | undefined>, + ...iteratees: Array>> + ): LoDashExplicitWrapper; /** * @see _.sortBy */ - sortBy(iteratee: string): LoDashImplicitArrayWrapper; - - /** - * @see _.sortBy - */ - sortBy(whereValue: W): LoDashImplicitArrayWrapper; - - /** - * @see _.sortBy - */ - sortBy(): LoDashImplicitArrayWrapper; - - /** - * @see _.sortBy - */ - sortBy(...iteratees: Array|Object|string>): LoDashImplicitArrayWrapper; - - /** - * @see _.sortBy - **/ - sortBy(iteratees: Array|string|Object>): LoDashImplicitArrayWrapper; - } - - interface LoDashImplicitObjectWrapperBase { - /** - * @see _.sortBy - */ - sortBy( - iteratee?: ListIterator|DictionaryIterator - ): LoDashImplicitArrayWrapper; - - /** - * @see _.sortBy - */ - sortBy(iteratee: string): LoDashImplicitArrayWrapper; - - /** - * @see _.sortBy - */ - sortBy(whereValue: W): LoDashImplicitArrayWrapper; - - /** - * @see _.sortBy - */ - sortBy(): LoDashImplicitArrayWrapper; - } - - interface LoDashExplicitArrayWrapperBase { - /** - * @see _.sortBy - */ - sortBy( - iteratee?: ListIterator - ): LoDashExplicitArrayWrapper; - - /** - * @see _.sortBy - */ - sortBy(iteratee: string): LoDashExplicitArrayWrapper; - - /** - * @see _.sortBy - */ - sortBy(whereValue: W): LoDashExplicitArrayWrapper; - - /** - * @see _.sortBy - */ - sortBy(): LoDashExplicitArrayWrapper; - } - - interface LoDashExplicitObjectWrapperBase { - /** - * @see _.sortBy - */ - sortBy( - iteratee?: ListIterator|DictionaryIterator - ): LoDashExplicitArrayWrapper; - - /** - * @see _.sortBy - */ - sortBy(iteratee: string): LoDashExplicitArrayWrapper; - - /** - * @see _.sortBy - */ - sortBy(whereValue: W): LoDashExplicitArrayWrapper; - - /** - * @see _.sortBy - */ - sortBy(): LoDashExplicitArrayWrapper; + sortBy( + this: LoDashExplicitWrapper, + ...iteratees: Array>> + ): LoDashExplicitWrapper>; } //_.orderBy @@ -9902,9 +6987,9 @@ declare namespace _ { * _.orderBy(users, ['user', 'age'], ['asc', 'desc']); * // => objects for [['barney', 36], ['barney', 34], ['fred', 48], ['fred', 42]] */ - orderBy( + orderBy( collection: List | null | undefined, - iteratees?: Many|string|W>, + iteratees?: Many>, orders?: Many ): T[]; @@ -9913,16 +6998,34 @@ declare namespace _ { */ orderBy( collection: List | null | undefined, - iteratees?: Many|string|Object>, + iteratees?: Many>, orders?: Many ): T[]; /** * @see _.orderBy */ - orderBy( + orderBy( + collection: T | null | undefined, + iteratees?: Many>, + orders?: Many + ): Array; + + /** + * @see _.orderBy + */ + orderBy( + collection: T | null | undefined, + iteratees?: Many>, + orders?: Many + ): Array; + + /** + * @see _.orderBy + */ + orderBy( collection: NumericDictionary | null | undefined, - iteratees?: Many|string|W>, + iteratees?: Many>, orders?: Many ): T[]; @@ -9931,167 +7034,121 @@ declare namespace _ { */ orderBy( collection: NumericDictionary | null | undefined, - iteratees?: Many|string|Object>, - orders?: Many - ): T[]; - - /** - * @see _.orderBy - */ - orderBy( - collection: Dictionary | null | undefined, - iteratees?: Many|string|W>, - orders?: Many - ): T[]; - - /** - * @see _.orderBy - */ - orderBy( - collection: Dictionary | null | undefined, - iteratees?: Many|string|Object>, + iteratees?: Many>, orders?: Many ): T[]; } - interface LoDashImplicitWrapper { + interface LoDashImplicitWrapper { /** * @see _.orderBy */ - orderBy( - iteratees?: Many|string>, + orderBy( + this: LoDashImplicitWrapper | null | undefined>, + iteratees?: Many>, orders?: Many - ): LoDashImplicitArrayWrapper; + ): LoDashImplicitWrapper; + + /** + * @see _.orderBy + */ + orderBy( + this: LoDashImplicitWrapper | null | undefined>, + iteratees?: Many>, + orders?: Many + ): LoDashImplicitWrapper; + + /** + * @see _.orderBy + */ + orderBy( + this: LoDashImplicitWrapper, + iteratees?: Many>, + orders?: Many + ): LoDashImplicitWrapper>; + + /** + * @see _.orderBy + */ + orderBy( + this: LoDashImplicitWrapper, + iteratees?: Many>, + orders?: Many + ): LoDashImplicitWrapper>; + + /** + * @see _.orderBy + */ + orderBy( + this: LoDashImplicitWrapper | null | undefined>, + iteratees?: Many>, + orders?: Many + ): LoDashImplicitWrapper; + + /** + * @see _.orderBy + */ + orderBy( + this: LoDashImplicitWrapper | null | undefined>, + iteratees?: Many>, + orders?: Many + ): LoDashImplicitWrapper; } - interface LoDashImplicitArrayWrapperBase { + interface LoDashExplicitWrapper { /** * @see _.orderBy */ - orderBy( - iteratees?: Many|string|W>, + orderBy( + this: LoDashExplicitWrapper | null | undefined>, + iteratees?: Many>, orders?: Many - ): LoDashImplicitArrayWrapper; - } - - interface LoDashImplicitObjectWrapperBase { - /** - * @see _.orderBy - */ - orderBy( - iteratees?: Many|string|W>, - orders?: Many - ): LoDashImplicitArrayWrapper; + ): LoDashExplicitWrapper; /** * @see _.orderBy */ orderBy( - iteratees?: Many|string|Object>, + this: LoDashExplicitWrapper | null | undefined>, + iteratees?: Many>, orders?: Many - ): LoDashImplicitArrayWrapper; + ): LoDashExplicitWrapper; /** * @see _.orderBy */ - orderBy( - iteratees?: Many|string|W>, + orderBy( + this: LoDashExplicitWrapper, + iteratees?: Many>, orders?: Many - ): LoDashImplicitArrayWrapper; + ): LoDashExplicitWrapper>; + + /** + * @see _.orderBy + */ + orderBy( + this: LoDashExplicitWrapper, + iteratees?: Many>, + orders?: Many + ): LoDashExplicitWrapper>; /** * @see _.orderBy */ orderBy( - iteratees?: Many|string|Object>, + this: LoDashExplicitWrapper | null | undefined>, + iteratees?: Many>, orders?: Many - ): LoDashImplicitArrayWrapper; - - /** - * @see _.orderBy - */ - orderBy( - iteratees?: Many|string|W>, - orders?: Many - ): LoDashImplicitArrayWrapper; + ): LoDashExplicitWrapper; /** * @see _.orderBy */ orderBy( - iteratees?: Many|string|Object>, + this: LoDashExplicitWrapper | null | undefined>, + iteratees?: Many>, orders?: Many - ): LoDashImplicitArrayWrapper; - } - - interface LoDashExplicitWrapper { - /** - * @see _.orderBy - */ - orderBy( - iteratees?: Many|string>, - orders?: Many - ): LoDashExplicitArrayWrapper; - } - - interface LoDashExplicitArrayWrapperBase { - /** - * @see _.orderBy - */ - orderBy( - iteratees?: Many|string|W|(ListIterator|string|W)>, - orders?: Many - ): LoDashExplicitArrayWrapper; - } - - interface LoDashExplicitObjectWrapperBase { - /** - * @see _.orderBy - */ - orderBy( - iteratees?: Many|string|W>, - orders?: Many - ): LoDashExplicitArrayWrapper; - - /** - * @see _.orderBy - */ - orderBy( - iteratees?: Many|string|Object>, - orders?: Many - ): LoDashExplicitArrayWrapper; - - /** - * @see _.orderBy - */ - orderBy( - iteratees?: Many|string|W>, - orders?: Many - ): LoDashExplicitArrayWrapper; - - /** - * @see _.orderBy - */ - orderBy( - iteratees?: Many|string|Object>, - orders?: Many - ): LoDashExplicitArrayWrapper; - - /** - * @see _.orderBy - */ - orderBy( - iteratees?: Many|string|W>, - orders?: Many - ): LoDashExplicitArrayWrapper; - - /** - * @see _.orderBy - */ - orderBy( - iteratees?: Many|string|Object>, - orders?: Many - ): LoDashExplicitArrayWrapper; + ): LoDashExplicitWrapper; } /******** @@ -10108,14 +7165,14 @@ declare namespace _ { now(): number; } - interface LoDashImplicitWrapperBase { + interface LoDashImplicitWrapper { /** * @see _.now */ now(): number; } - interface LoDashExplicitWrapperBase { + interface LoDashExplicitWrapper { /** * @see _.now */ @@ -10135,24 +7192,24 @@ declare namespace _ { * @param func The function to restrict. * @return Returns the new restricted function. */ - after( + after any>( n: number, func: TFunc ): TFunc; } - interface LoDashImplicitWrapper { + interface LoDashImplicitWrapper { /** * @see _.after **/ - after(func: TFunc): LoDashImplicitObjectWrapper; + after any>(func: TFunc): LoDashImplicitWrapper; } - interface LoDashExplicitWrapper { + interface LoDashExplicitWrapper { /** * @see _.after **/ - after(func: TFunc): LoDashExplicitObjectWrapper; + after any>(func: TFunc): LoDashExplicitWrapper; } //_.ary @@ -10164,29 +7221,24 @@ declare namespace _ { * @param n The arity cap. * @returns Returns the new function. */ - ary( - func: Function, + ary( + func: (...args: any[]) => any, n?: number - ): TResult; - - ary( - func: T, - n?: number - ): TResult; + ): (...args: any[]) => any; } - interface LoDashImplicitObjectWrapper { + interface LoDashImplicitWrapper { /** * @see _.ary */ - ary(n?: number): LoDashImplicitObjectWrapper; + ary(n?: number): LoDashImplicitWrapper<(...args: any[]) => any>; } - interface LoDashExplicitObjectWrapper { + interface LoDashExplicitWrapper { /** * @see _.ary */ - ary(n?: number): LoDashExplicitObjectWrapper; + ary(n?: number): LoDashExplicitWrapper<(...args: any[]) => any>; } //_.before @@ -10200,41 +7252,35 @@ declare namespace _ { * @param func The function to restrict. * @return Returns the new restricted function. */ - before( + before any>( n: number, func: TFunc ): TFunc; } - interface LoDashImplicitWrapper { + interface LoDashImplicitWrapper { /** * @see _.before **/ - before(func: TFunc): LoDashImplicitObjectWrapper; + before any>(func: TFunc): LoDashImplicitWrapper; } - interface LoDashExplicitWrapper { + interface LoDashExplicitWrapper { /** * @see _.before **/ - before(func: TFunc): LoDashExplicitObjectWrapper; + before any>(func: TFunc): LoDashExplicitWrapper; } //_.bind interface FunctionBind { placeholder: any; - ( - func: T, + ( + func: (...args: any[]) => any, thisArg: any, ...partials: any[] - ): TResult; - - ( - func: Function, - thisArg: any, - ...partials: any[] - ): TResult; + ): (...args: any[]) => any; } interface LoDashStatic { @@ -10255,24 +7301,24 @@ declare namespace _ { bind: FunctionBind; } - interface LoDashImplicitObjectWrapper { + interface LoDashImplicitWrapper { /** * @see _.bind */ - bind( + bind( thisArg: any, ...partials: any[] - ): LoDashImplicitObjectWrapper; + ): LoDashImplicitWrapper<(...args: any[]) => any>; } - interface LoDashExplicitObjectWrapper { + interface LoDashExplicitWrapper { /** * @see _.bind */ - bind( + bind( thisArg: any, ...partials: any[] - ): LoDashExplicitObjectWrapper; + ): LoDashExplicitWrapper<(...args: any[]) => any>; } //_.bindAll @@ -10295,35 +7341,22 @@ declare namespace _ { ): T; } - interface LoDashImplicitObjectWrapper { + interface LoDashWrapper { /** * @see _.bindAll */ - bindAll(...methodNames: Array>): LoDashImplicitObjectWrapper; - } - - interface LoDashExplicitObjectWrapper { - /** - * @see _.bindAll - */ - bindAll(...methodNames: Array>): LoDashExplicitObjectWrapper; + bindAll(...methodNames: Array>): this; } //_.bindKey interface FunctionBindKey { placeholder: any; - ( - object: T, - key: any, + ( + object: object, + key: string, ...partials: any[] - ): TResult; - - ( - object: Object, - key: any, - ...partials: any[] - ): TResult; + ): (...args: any[]) => any; } interface LoDashStatic { @@ -10345,64 +7378,24 @@ declare namespace _ { bindKey: FunctionBindKey; } - interface LoDashImplicitObjectWrapper { + interface LoDashImplicitWrapper { /** * @see _.bindKey */ - bindKey( - key: any, + bindKey( + key: string, ...partials: any[] - ): LoDashImplicitObjectWrapper; + ): LoDashImplicitWrapper<(...args: any[]) => any>; } - interface LoDashExplicitObjectWrapper { + interface LoDashExplicitWrapper { /** * @see _.bindKey */ - bindKey( - key: any, + bindKey( + key: string, ...partials: any[] - ): LoDashExplicitObjectWrapper; - } - - //_.createCallback - interface LoDashStatic { - /** - * Produces a callback bound to an optional thisArg. If func is a property name the created - * callback will return the property value for a given element. If func is an object the created - * callback will return true for elements that contain the equivalent object properties, - * otherwise it will return false. - * @param func The value to convert to a callback. - * @param thisArg The this binding of the created callback. - * @param argCount The number of arguments the callback accepts. - * @return A callback function. - **/ - createCallback( - func: string, - argCount?: number): () => any; - - /** - * @see _.createCallback - **/ - createCallback( - func: Dictionary, - argCount?: number): () => boolean; - } - - interface LoDashImplicitWrapper { - /** - * @see _.createCallback - **/ - createCallback( - argCount?: number): LoDashImplicitObjectWrapper<() => any>; - } - - interface LoDashImplicitObjectWrapper { - /** - * @see _.createCallback - **/ - createCallback( - argCount?: number): LoDashImplicitObjectWrapper<() => any>; + ): LoDashExplicitWrapper<(...args: any[]) => any>; } //_.curry @@ -10412,45 +7405,50 @@ declare namespace _ { * its result, if all func arguments have been provided, or returns a function that accepts one or more of the * remaining func arguments, and so on. The arity of func may be specified if func.length is not sufficient. * @param func The function to curry. + * @param arity The arity of func. * @return Returns the new curried function. */ - curry(func: (t1: T1) => R): + curry(func: (t1: T1) => R, arity?: number): CurriedFunction1; /** * Creates a function that accepts one or more arguments of func that when called either invokes func returning * its result, if all func arguments have been provided, or returns a function that accepts one or more of the * remaining func arguments, and so on. The arity of func may be specified if func.length is not sufficient. * @param func The function to curry. + * @param arity The arity of func. * @return Returns the new curried function. */ - curry(func: (t1: T1, t2: T2) => R): + curry(func: (t1: T1, t2: T2) => R, arity?: number): CurriedFunction2; /** * Creates a function that accepts one or more arguments of func that when called either invokes func returning * its result, if all func arguments have been provided, or returns a function that accepts one or more of the * remaining func arguments, and so on. The arity of func may be specified if func.length is not sufficient. * @param func The function to curry. + * @param arity The arity of func. * @return Returns the new curried function. */ - curry(func: (t1: T1, t2: T2, t3: T3) => R): + curry(func: (t1: T1, t2: T2, t3: T3) => R, arity?: number): CurriedFunction3; /** * Creates a function that accepts one or more arguments of func that when called either invokes func returning * its result, if all func arguments have been provided, or returns a function that accepts one or more of the * remaining func arguments, and so on. The arity of func may be specified if func.length is not sufficient. * @param func The function to curry. + * @param arity The arity of func. * @return Returns the new curried function. */ - curry(func: (t1: T1, t2: T2, t3: T3, t4: T4) => R): + curry(func: (t1: T1, t2: T2, t3: T3, t4: T4) => R, arity?: number): CurriedFunction4; /** * Creates a function that accepts one or more arguments of func that when called either invokes func returning * its result, if all func arguments have been provided, or returns a function that accepts one or more of the * remaining func arguments, and so on. The arity of func may be specified if func.length is not sufficient. * @param func The function to curry. + * @param arity The arity of func. * @return Returns the new curried function. */ - curry(func: (t1: T1, t2: T2, t3: T3, t4: T4, t5: T5) => R): + curry(func: (t1: T1, t2: T2, t3: T3, t4: T4, t5: T5) => R, arity?: number): CurriedFunction5; /** * Creates a function that accepts one or more arguments of func that when called either invokes func returning @@ -10460,9 +7458,7 @@ declare namespace _ { * @param arity The arity of func. * @return Returns the new curried function. */ - curry( - func: Function, - arity?: number): TResult; + curry(func: (...args: any[]) => any, arity?: number): (...args: any[]) => any; } interface CurriedFunction1 { @@ -10499,42 +7495,109 @@ declare namespace _ { (t1: T1, t2: T2, t3: T3, t4: T4): CurriedFunction1; (t1: T1, t2: T2, t3: T3, t4: T4, t5: T5): R; } - interface RightCurriedFunction1{ - ():RightCurriedFunction1 - (t1:T1):R - } - interface RightCurriedFunction2{ - ():RightCurriedFunction2 - (t2:T2):RightCurriedFunction1 - (t1:T1,t2:T2):R + interface RightCurriedFunction1 { + (): RightCurriedFunction1; + (t1: T1): R; } - interface RightCurriedFunction3{ - ():RightCurriedFunction3 - (t3:T3):RightCurriedFunction2 - (t2:T2,t3:T3):RightCurriedFunction1 - (t1:T1,t2:T2,t3:T3):R + interface RightCurriedFunction2 { + (): RightCurriedFunction2; + (t2: T2): RightCurriedFunction1; + (t1: T1, t2: T2): R; } - interface RightCurriedFunction4{ - ():RightCurriedFunction4 - (t4:T4):RightCurriedFunction3 - (t3:T3,t4:T4):RightCurriedFunction2 - (t2:T2,t3:T3,t4:T4):RightCurriedFunction1 - (t1:T1,t2:T2,t3:T3,t4:T4):R + interface RightCurriedFunction3 { + (): RightCurriedFunction3; + (t3: T3): RightCurriedFunction2; + (t2: T2, t3: T3): RightCurriedFunction1; + (t1: T1, t2: T2, t3: T3): R; } - interface RightCurriedFunction5{ - ():RightCurriedFunction5 - (t5:T5):RightCurriedFunction4 - (t4:T4,t5:T5):RightCurriedFunction3 - (t3:T3,t4:T4,t5:T5):RightCurriedFunction2 - (t2:T2,t3:T3,t4:T4,t5:T5):RightCurriedFunction1 - (t1:T1,t2:T2,t3:T3,t4:T4,t5:T5):R + interface RightCurriedFunction4 { + (): RightCurriedFunction4; + (t4: T4): RightCurriedFunction3; + (t3: T3, t4: T4): RightCurriedFunction2; + (t2: T2, t3: T3, t4: T4): RightCurriedFunction1; + (t1: T1, t2: T2, t3: T3, t4: T4): R; + } + interface RightCurriedFunction5 { + (): RightCurriedFunction5; + (t5: T5): RightCurriedFunction4; + (t4: T4, t5: T5): RightCurriedFunction3; + (t3: T3, t4: T4, t5: T5): RightCurriedFunction2; + (t2: T2, t3: T3, t4: T4, t5: T5): RightCurriedFunction1; + (t1: T1, t2: T2, t3: T3, t4: T4, t5: T5): R; } - interface LoDashImplicitObjectWrapper { + interface LoDashImplicitWrapper { /** * @see _.curry **/ - curry(arity?: number): LoDashImplicitObjectWrapper; + curry(this: LoDashImplicitWrapper<(t1: T1) => R>, arity?: number): + LoDashImplicitWrapper>; + + /** + * @see _.curry + **/ + curry(this: LoDashImplicitWrapper<(t1: T1, t2: T2) => R>, arity?: number): + LoDashImplicitWrapper>; + + /** + * @see _.curry + **/ + curry(this: LoDashImplicitWrapper<(t1: T1, t2: T2, t3: T3) => R>, arity?: number): + LoDashImplicitWrapper>; + + /** + * @see _.curry + **/ + curry(this: LoDashImplicitWrapper<(t1: T1, t2: T2, t3: T3, t4: T4) => R>, arity?: number): + LoDashImplicitWrapper>; + + /** + * @see _.curry + **/ + curry(this: LoDashImplicitWrapper<(t1: T1, t2: T2, t3: T3, t4: T4, t5: T5) => R>, arity?: number): + LoDashImplicitWrapper>; + + /** + * @see _.curry + **/ + curry(arity?: number): LoDashImplicitWrapper<(...args: any[]) => any>; + } + + interface LoDashExplicitWrapper { + /** + * @see _.curry + **/ + curry(this: LoDashExplicitWrapper<(t1: T1) => R>): + LoDashExplicitWrapper>; + + /** + * @see _.curry + **/ + curry(this: LoDashExplicitWrapper<(t1: T1, t2: T2) => R>): + LoDashExplicitWrapper>; + + /** + * @see _.curry + **/ + curry(this: LoDashExplicitWrapper<(t1: T1, t2: T2, t3: T3) => R>): + LoDashExplicitWrapper>; + + /** + * @see _.curry + **/ + curry(this: LoDashExplicitWrapper<(t1: T1, t2: T2, t3: T3, t4: T4) => R>): + LoDashExplicitWrapper>; + + /** + * @see _.curry + **/ + curry(this: LoDashExplicitWrapper<(t1: T1, t2: T2, t3: T3, t4: T4, t5: T5) => R>): + LoDashExplicitWrapper>; + + /** + * @see _.curry + **/ + curry(arity?: number): LoDashExplicitWrapper<(...args: any[]) => any>; } //_.curryRight @@ -10543,41 +7606,46 @@ declare namespace _ { * This method is like _.curry except that arguments are applied to func in the manner of _.partialRight * instead of _.partial. * @param func The function to curry. + * @param arity The arity of func. * @return Returns the new curried function. */ - curryRight(func: (t1: T1) => R): + curryRight(func: (t1: T1) => R, arity?: number): RightCurriedFunction1; /** * This method is like _.curry except that arguments are applied to func in the manner of _.partialRight * instead of _.partial. * @param func The function to curry. + * @param arity The arity of func. * @return Returns the new curried function. */ - curryRight(func: (t1: T1, t2: T2) => R): + curryRight(func: (t1: T1, t2: T2) => R, arity?: number): RightCurriedFunction2; /** * This method is like _.curry except that arguments are applied to func in the manner of _.partialRight * instead of _.partial. * @param func The function to curry. + * @param arity The arity of func. * @return Returns the new curried function. */ - curryRight(func: (t1: T1, t2: T2, t3: T3) => R): + curryRight(func: (t1: T1, t2: T2, t3: T3) => R, arity?: number): RightCurriedFunction3; /** * This method is like _.curry except that arguments are applied to func in the manner of _.partialRight * instead of _.partial. * @param func The function to curry. + * @param arity The arity of func. * @return Returns the new curried function. */ - curryRight(func: (t1: T1, t2: T2, t3: T3, t4: T4) => R): + curryRight(func: (t1: T1, t2: T2, t3: T3, t4: T4) => R, arity?: number): RightCurriedFunction4; /** * This method is like _.curry except that arguments are applied to func in the manner of _.partialRight * instead of _.partial. * @param func The function to curry. + * @param arity The arity of func. * @return Returns the new curried function. */ - curryRight(func: (t1: T1, t2: T2, t3: T3, t4: T4, t5: T5) => R): + curryRight(func: (t1: T1, t2: T2, t3: T3, t4: T4, t5: T5) => R, arity?: number): RightCurriedFunction5; /** * This method is like _.curry except that arguments are applied to func in the manner of _.partialRight @@ -10586,16 +7654,81 @@ declare namespace _ { * @param arity The arity of func. * @return Returns the new curried function. */ - curryRight( - func: Function, - arity?: number): TResult; + curryRight(func: (...args: any[]) => any, arity?: number): (...args: any[]) => any; } - interface LoDashImplicitObjectWrapper { + interface LoDashImplicitWrapper { /** * @see _.curryRight **/ - curryRight(arity?: number): LoDashImplicitObjectWrapper; + curryRight(this: LoDashImplicitWrapper<(t1: T1) => R>, arity?: number): + LoDashImplicitWrapper>; + + /** + * @see _.curryRight + **/ + curryRight(this: LoDashImplicitWrapper<(t1: T1, t2: T2) => R>, arity?: number): + LoDashImplicitWrapper>; + + /** + * @see _.curryRight + **/ + curryRight(this: LoDashImplicitWrapper<(t1: T1, t2: T2, t3: T3) => R>, arity?: number): + LoDashImplicitWrapper>; + + /** + * @see _.curryRight + **/ + curryRight(this: LoDashImplicitWrapper<(t1: T1, t2: T2, t3: T3, t4: T4) => R>, arity?: number): + LoDashImplicitWrapper>; + + /** + * @see _.curryRight + **/ + curryRight(this: LoDashImplicitWrapper<(t1: T1, t2: T2, t3: T3, t4: T4, t5: T5) => R>, arity?: number): + LoDashImplicitWrapper>; + + /** + * @see _.curryRight + **/ + curryRight(arity?: number): LoDashImplicitWrapper<(...args: any[]) => any>; + } + + interface LoDashExplicitWrapper { + /** + * @see _.curryRight + **/ + curryRight(this: LoDashExplicitWrapper<(t1: T1) => R>, arity?: number): + LoDashExplicitWrapper>; + + /** + * @see _.curryRight + **/ + curryRight(this: LoDashExplicitWrapper<(t1: T1, t2: T2) => R>, arity?: number): + LoDashExplicitWrapper>; + + /** + * @see _.curryRight + **/ + curryRight(this: LoDashExplicitWrapper<(t1: T1, t2: T2, t3: T3) => R>, arity?: number): + LoDashExplicitWrapper>; + + /** + * @see _.curryRight + **/ + curryRight(this: LoDashExplicitWrapper<(t1: T1, t2: T2, t3: T3, t4: T4) => R>, arity?: number): + LoDashExplicitWrapper>; + + /** + * @see _.curryRight + **/ + curryRight(this: LoDashExplicitWrapper<(t1: T1, t2: T2, t3: T3, t4: T4, t5: T5) => R>, arity?: number): + LoDashExplicitWrapper>; + + /** + * @see _.curryRight + **/ + curryRight(arity?: number): LoDashExplicitWrapper<(...args: any[]) => any>; } //_.debounce @@ -10637,31 +7770,31 @@ declare namespace _ { * @param options.trailing Specify invoking on the trailing edge of the timeout. * @return Returns the new debounced function. */ - debounce( + debounce any>( func: T, wait?: number, options?: DebounceSettings ): T & Cancelable; } - interface LoDashImplicitObjectWrapper { + interface LoDashImplicitWrapper { /** * @see _.debounce */ debounce( wait?: number, options?: DebounceSettings - ): LoDashImplicitObjectWrapper; + ): LoDashImplicitWrapper; } - interface LoDashExplicitObjectWrapper { + interface LoDashExplicitWrapper { /** * @see _.debounce */ debounce( wait?: number, options?: DebounceSettings - ): LoDashExplicitObjectWrapper; + ): LoDashExplicitWrapper; } //_.defer @@ -10674,20 +7807,20 @@ declare namespace _ { * @param args The arguments to invoke the function with. * @return Returns the timer id. */ - defer( - func: T, + defer( + func: (...args: any[]) => any, ...args: any[] ): number; } - interface LoDashImplicitObjectWrapper { + interface LoDashImplicitWrapper { /** * @see _.defer */ defer(...args: any[]): LoDashImplicitWrapper; } - interface LoDashExplicitObjectWrapper { + interface LoDashExplicitWrapper { /** * @see _.defer */ @@ -10704,14 +7837,14 @@ declare namespace _ { * @param args The arguments to invoke the function with. * @return Returns the timer id. */ - delay( - func: T, + delay( + func: (...args: any[]) => any, wait: number, ...args: any[] ): number; } - interface LoDashImplicitObjectWrapper { + interface LoDashImplicitWrapper { /** * @see _.delay */ @@ -10721,7 +7854,7 @@ declare namespace _ { ): LoDashImplicitWrapper; } - interface LoDashExplicitObjectWrapper { + interface LoDashExplicitWrapper { /** * @see _.delay */ @@ -10749,21 +7882,14 @@ declare namespace _ { * flipped('a', 'b', 'c', 'd'); * // => ['d', 'c', 'b', 'a'] */ - flip(func: T): T; + flip any>(func: T): T; } - interface LoDashImplicitObjectWrapper { + interface LoDashWrapper { /** * @see _.flip */ - flip(): LoDashImplicitObjectWrapper; - } - - interface LoDashExplicitObjectWrapper { - /** - * @see _.flip - */ - flip(): LoDashExplicitObjectWrapper; + flip(): this; } //_.flow @@ -10811,30 +7937,93 @@ declare namespace _ { flow(f1: (a1: A1, a2: A2, a3: A3, a4: A4) => R1, f2: (a: R1) => R2, f3: (a: R2) => R3, f4: (a: R3) => R4, f5: (a: R4) => R5, f6: (a: R5) => R6): (a1: A1, a2: A2, a3: A3, a4: A4) => R6; flow(f1: (a1: A1, a2: A2, a3: A3, a4: A4) => R1, f2: (a: R1) => R2, f3: (a: R2) => R3, f4: (a: R3) => R4, f5: (a: R4) => R5, f6: (a: R5) => R6, f7: (a: R6) => R7): (a1: A1, a2: A2, a3: A3, a4: A4) => R7; // generic function - flow(...funcs: Function[]): TResult; - flow(funcs: Function[]): TResult; + flow(...funcs: Array any>>): (...args: any[]) => any; } - interface LoDashImplicitObjectWrapper { + interface LoDashImplicitWrapper { /** * @see _.flow */ - flow(...funcs: Function[]): LoDashImplicitObjectWrapper; - /** - * @see _.flow - */ - flow(funcs: Function[]): LoDashImplicitObjectWrapper; + // 0-argument first function + flow(this: LoDashImplicitWrapper<() => R1>, f2: (a: R1) => R2): LoDashImplicitWrapper<() => R2>; + flow(this: LoDashImplicitWrapper<() => R1>, f2: (a: R1) => R2, f3: (a: R2) => R3): LoDashImplicitWrapper<() => R3>; + flow(this: LoDashImplicitWrapper<() => R1>, f2: (a: R1) => R2, f3: (a: R2) => R3, f4: (a: R3) => R4): LoDashImplicitWrapper<() => R4>; + flow(this: LoDashImplicitWrapper<() => R1>, f2: (a: R1) => R2, f3: (a: R2) => R3, f4: (a: R3) => R4, f5: (a: R4) => R5): LoDashImplicitWrapper<() => R5>; + flow(this: LoDashImplicitWrapper<() => R1>, f2: (a: R1) => R2, f3: (a: R2) => R3, f4: (a: R3) => R4, f5: (a: R4) => R5, f6: (a: R5) => R6): LoDashImplicitWrapper<() => R6>; + flow(this: LoDashImplicitWrapper<() => R1>, f2: (a: R1) => R2, f3: (a: R2) => R3, f4: (a: R3) => R4, f5: (a: R4) => R5, f6: (a: R5) => R6, f7: (a: R6) => R7): LoDashImplicitWrapper<() => R7>; + // 1-argument first function + flow(this: LoDashImplicitWrapper<(a1: A1) => R1>, f2: (a: R1) => R2): LoDashImplicitWrapper<(a1: A1) => R2>; + flow(this: LoDashImplicitWrapper<(a1: A1) => R1>, f2: (a: R1) => R2, f3: (a: R2) => R3): LoDashImplicitWrapper<(a1: A1) => R3>; + flow(this: LoDashImplicitWrapper<(a1: A1) => R1>, f2: (a: R1) => R2, f3: (a: R2) => R3, f4: (a: R3) => R4): LoDashImplicitWrapper<(a1: A1) => R4>; + flow(this: LoDashImplicitWrapper<(a1: A1) => R1>, f2: (a: R1) => R2, f3: (a: R2) => R3, f4: (a: R3) => R4, f5: (a: R4) => R5): LoDashImplicitWrapper<(a1: A1) => R5>; + flow(this: LoDashImplicitWrapper<(a1: A1) => R1>, f2: (a: R1) => R2, f3: (a: R2) => R3, f4: (a: R3) => R4, f5: (a: R4) => R5, f6: (a: R5) => R6): LoDashImplicitWrapper<(a1: A1) => R6>; + flow(this: LoDashImplicitWrapper<(a1: A1) => R1>, f2: (a: R1) => R2, f3: (a: R2) => R3, f4: (a: R3) => R4, f5: (a: R4) => R5, f6: (a: R5) => R6, f7: (a: R6) => R7): LoDashImplicitWrapper<(a1: A1) => R7>; + // 2-argument first function + flow(this: LoDashImplicitWrapper<(a1: A1, a2: A2) => R1>, f2: (a: R1) => R2): LoDashImplicitWrapper<(a1: A1, a2: A2) => R2>; + flow(this: LoDashImplicitWrapper<(a1: A1, a2: A2) => R1>, f2: (a: R1) => R2, f3: (a: R2) => R3): LoDashImplicitWrapper<(a1: A1, a2: A2) => R3>; + flow(this: LoDashImplicitWrapper<(a1: A1, a2: A2) => R1>, f2: (a: R1) => R2, f3: (a: R2) => R3, f4: (a: R3) => R4): LoDashImplicitWrapper<(a1: A1, a2: A2) => R4>; + flow(this: LoDashImplicitWrapper<(a1: A1, a2: A2) => R1>, f2: (a: R1) => R2, f3: (a: R2) => R3, f4: (a: R3) => R4, f5: (a: R4) => R5): LoDashImplicitWrapper<(a1: A1, a2: A2) => R5>; + flow(this: LoDashImplicitWrapper<(a1: A1, a2: A2) => R1>, f2: (a: R1) => R2, f3: (a: R2) => R3, f4: (a: R3) => R4, f5: (a: R4) => R5, f6: (a: R5) => R6): LoDashImplicitWrapper<(a1: A1, a2: A2) => R6>; + flow(this: LoDashImplicitWrapper<(a1: A1, a2: A2) => R1>, f2: (a: R1) => R2, f3: (a: R2) => R3, f4: (a: R3) => R4, f5: (a: R4) => R5, f6: (a: R5) => R6, f7: (a: R6) => R7): LoDashImplicitWrapper<(a1: A1, a2: A2) => R7>; + // 3-argument first function + flow(this: LoDashImplicitWrapper<(a1: A1, a2: A2, a3: A3) => R1>, f2: (a: R1) => R2): LoDashImplicitWrapper<(a1: A1, a2: A2, a3: A3) => R2>; + flow(this: LoDashImplicitWrapper<(a1: A1, a2: A2, a3: A3) => R1>, f2: (a: R1) => R2, f3: (a: R2) => R3): LoDashImplicitWrapper<(a1: A1, a2: A2, a3: A3) => R3>; + flow(this: LoDashImplicitWrapper<(a1: A1, a2: A2, a3: A3) => R1>, f2: (a: R1) => R2, f3: (a: R2) => R3, f4: (a: R3) => R4): LoDashImplicitWrapper<(a1: A1, a2: A2, a3: A3) => R4>; + flow(this: LoDashImplicitWrapper<(a1: A1, a2: A2, a3: A3) => R1>, f2: (a: R1) => R2, f3: (a: R2) => R3, f4: (a: R3) => R4, f5: (a: R4) => R5): LoDashImplicitWrapper<(a1: A1, a2: A2, a3: A3) => R5>; + flow(this: LoDashImplicitWrapper<(a1: A1, a2: A2, a3: A3) => R1>, f2: (a: R1) => R2, f3: (a: R2) => R3, f4: (a: R3) => R4, f5: (a: R4) => R5, f6: (a: R5) => R6): LoDashImplicitWrapper<(a1: A1, a2: A2, a3: A3) => R6>; + flow(this: LoDashImplicitWrapper<(a1: A1, a2: A2, a3: A3) => R1>, f2: (a: R1) => R2, f3: (a: R2) => R3, f4: (a: R3) => R4, f5: (a: R4) => R5, f6: (a: R5) => R6, f7: (a: R6) => R7): LoDashImplicitWrapper<(a1: A1, a2: A2, a3: A3) => R7>; + // 4-argument first function + flow(this: LoDashImplicitWrapper<(a1: A1, a2: A2, a3: A3, a4: A4) => R1>, f2: (a: R1) => R2): LoDashImplicitWrapper<(a1: A1, a2: A2, a3: A3, a4: A4) => R2>; + flow(this: LoDashImplicitWrapper<(a1: A1, a2: A2, a3: A3, a4: A4) => R1>, f2: (a: R1) => R2, f3: (a: R2) => R3): LoDashImplicitWrapper<(a1: A1, a2: A2, a3: A3, a4: A4) => R3>; + flow(this: LoDashImplicitWrapper<(a1: A1, a2: A2, a3: A3, a4: A4) => R1>, f2: (a: R1) => R2, f3: (a: R2) => R3, f4: (a: R3) => R4): LoDashImplicitWrapper<(a1: A1, a2: A2, a3: A3, a4: A4) => R4>; + flow(this: LoDashImplicitWrapper<(a1: A1, a2: A2, a3: A3, a4: A4) => R1>, f2: (a: R1) => R2, f3: (a: R2) => R3, f4: (a: R3) => R4, f5: (a: R4) => R5): LoDashImplicitWrapper<(a1: A1, a2: A2, a3: A3, a4: A4) => R5>; + flow(this: LoDashImplicitWrapper<(a1: A1, a2: A2, a3: A3, a4: A4) => R1>, f2: (a: R1) => R2, f3: (a: R2) => R3, f4: (a: R3) => R4, f5: (a: R4) => R5, f6: (a: R5) => R6): LoDashImplicitWrapper<(a1: A1, a2: A2, a3: A3, a4: A4) => R6>; + flow(this: LoDashImplicitWrapper<(a1: A1, a2: A2, a3: A3, a4: A4) => R1>, f2: (a: R1) => R2, f3: (a: R2) => R3, f4: (a: R3) => R4, f5: (a: R4) => R5, f6: (a: R5) => R6, f7: (a: R6) => R7): LoDashImplicitWrapper<(a1: A1, a2: A2, a3: A3, a4: A4) => R7>; + // generic function + flow(...funcs: Array any>>): LoDashImplicitWrapper<(...args: any[]) => any>; } - interface LoDashExplicitObjectWrapper { + interface LoDashExplicitWrapper { /** * @see _.flow */ - flow(...funcs: Function[]): LoDashExplicitObjectWrapper; - /** - * @see _.flow - */ - flow(funcs: Function[]): LoDashExplicitObjectWrapper; + // 0-argument first function + flow(this: LoDashExplicitWrapper<() => R1>, f2: (a: R1) => R2): LoDashExplicitWrapper<() => R2>; + flow(this: LoDashExplicitWrapper<() => R1>, f2: (a: R1) => R2, f3: (a: R2) => R3): LoDashExplicitWrapper<() => R3>; + flow(this: LoDashExplicitWrapper<() => R1>, f2: (a: R1) => R2, f3: (a: R2) => R3, f4: (a: R3) => R4): LoDashExplicitWrapper<() => R4>; + flow(this: LoDashExplicitWrapper<() => R1>, f2: (a: R1) => R2, f3: (a: R2) => R3, f4: (a: R3) => R4, f5: (a: R4) => R5): LoDashExplicitWrapper<() => R5>; + flow(this: LoDashExplicitWrapper<() => R1>, f2: (a: R1) => R2, f3: (a: R2) => R3, f4: (a: R3) => R4, f5: (a: R4) => R5, f6: (a: R5) => R6): LoDashExplicitWrapper<() => R6>; + flow(this: LoDashExplicitWrapper<() => R1>, f2: (a: R1) => R2, f3: (a: R2) => R3, f4: (a: R3) => R4, f5: (a: R4) => R5, f6: (a: R5) => R6, f7: (a: R6) => R7): LoDashExplicitWrapper<() => R7>; + // 1-argument first function + flow(this: LoDashExplicitWrapper<(a1: A1) => R1>, f2: (a: R1) => R2): LoDashExplicitWrapper<(a1: A1) => R2>; + flow(this: LoDashExplicitWrapper<(a1: A1) => R1>, f2: (a: R1) => R2, f3: (a: R2) => R3): LoDashExplicitWrapper<(a1: A1) => R3>; + flow(this: LoDashExplicitWrapper<(a1: A1) => R1>, f2: (a: R1) => R2, f3: (a: R2) => R3, f4: (a: R3) => R4): LoDashExplicitWrapper<(a1: A1) => R4>; + flow(this: LoDashExplicitWrapper<(a1: A1) => R1>, f2: (a: R1) => R2, f3: (a: R2) => R3, f4: (a: R3) => R4, f5: (a: R4) => R5): LoDashExplicitWrapper<(a1: A1) => R5>; + flow(this: LoDashExplicitWrapper<(a1: A1) => R1>, f2: (a: R1) => R2, f3: (a: R2) => R3, f4: (a: R3) => R4, f5: (a: R4) => R5, f6: (a: R5) => R6): LoDashExplicitWrapper<(a1: A1) => R6>; + flow(this: LoDashExplicitWrapper<(a1: A1) => R1>, f2: (a: R1) => R2, f3: (a: R2) => R3, f4: (a: R3) => R4, f5: (a: R4) => R5, f6: (a: R5) => R6, f7: (a: R6) => R7): LoDashExplicitWrapper<(a1: A1) => R7>; + // 2-argument first function + flow(this: LoDashExplicitWrapper<(a1: A1, a2: A2) => R1>, f2: (a: R1) => R2): LoDashExplicitWrapper<(a1: A1, a2: A2) => R2>; + flow(this: LoDashExplicitWrapper<(a1: A1, a2: A2) => R1>, f2: (a: R1) => R2, f3: (a: R2) => R3): LoDashExplicitWrapper<(a1: A1, a2: A2) => R3>; + flow(this: LoDashExplicitWrapper<(a1: A1, a2: A2) => R1>, f2: (a: R1) => R2, f3: (a: R2) => R3, f4: (a: R3) => R4): LoDashExplicitWrapper<(a1: A1, a2: A2) => R4>; + flow(this: LoDashExplicitWrapper<(a1: A1, a2: A2) => R1>, f2: (a: R1) => R2, f3: (a: R2) => R3, f4: (a: R3) => R4, f5: (a: R4) => R5): LoDashExplicitWrapper<(a1: A1, a2: A2) => R5>; + flow(this: LoDashExplicitWrapper<(a1: A1, a2: A2) => R1>, f2: (a: R1) => R2, f3: (a: R2) => R3, f4: (a: R3) => R4, f5: (a: R4) => R5, f6: (a: R5) => R6): LoDashExplicitWrapper<(a1: A1, a2: A2) => R6>; + flow(this: LoDashExplicitWrapper<(a1: A1, a2: A2) => R1>, f2: (a: R1) => R2, f3: (a: R2) => R3, f4: (a: R3) => R4, f5: (a: R4) => R5, f6: (a: R5) => R6, f7: (a: R6) => R7): LoDashExplicitWrapper<(a1: A1, a2: A2) => R7>; + // 3-argument first function + flow(this: LoDashExplicitWrapper<(a1: A1, a2: A2, a3: A3) => R1>, f2: (a: R1) => R2): LoDashExplicitWrapper<(a1: A1, a2: A2, a3: A3) => R2>; + flow(this: LoDashExplicitWrapper<(a1: A1, a2: A2, a3: A3) => R1>, f2: (a: R1) => R2, f3: (a: R2) => R3): LoDashExplicitWrapper<(a1: A1, a2: A2, a3: A3) => R3>; + flow(this: LoDashExplicitWrapper<(a1: A1, a2: A2, a3: A3) => R1>, f2: (a: R1) => R2, f3: (a: R2) => R3, f4: (a: R3) => R4): LoDashExplicitWrapper<(a1: A1, a2: A2, a3: A3) => R4>; + flow(this: LoDashExplicitWrapper<(a1: A1, a2: A2, a3: A3) => R1>, f2: (a: R1) => R2, f3: (a: R2) => R3, f4: (a: R3) => R4, f5: (a: R4) => R5): LoDashExplicitWrapper<(a1: A1, a2: A2, a3: A3) => R5>; + flow(this: LoDashExplicitWrapper<(a1: A1, a2: A2, a3: A3) => R1>, f2: (a: R1) => R2, f3: (a: R2) => R3, f4: (a: R3) => R4, f5: (a: R4) => R5, f6: (a: R5) => R6): LoDashExplicitWrapper<(a1: A1, a2: A2, a3: A3) => R6>; + flow(this: LoDashExplicitWrapper<(a1: A1, a2: A2, a3: A3) => R1>, f2: (a: R1) => R2, f3: (a: R2) => R3, f4: (a: R3) => R4, f5: (a: R4) => R5, f6: (a: R5) => R6, f7: (a: R6) => R7): LoDashExplicitWrapper<(a1: A1, a2: A2, a3: A3) => R7>; + // 4-argument first function + flow(this: LoDashExplicitWrapper<(a1: A1, a2: A2, a3: A3, a4: A4) => R1>, f2: (a: R1) => R2): LoDashExplicitWrapper<(a1: A1, a2: A2, a3: A3, a4: A4) => R2>; + flow(this: LoDashExplicitWrapper<(a1: A1, a2: A2, a3: A3, a4: A4) => R1>, f2: (a: R1) => R2, f3: (a: R2) => R3): LoDashExplicitWrapper<(a1: A1, a2: A2, a3: A3, a4: A4) => R3>; + flow(this: LoDashExplicitWrapper<(a1: A1, a2: A2, a3: A3, a4: A4) => R1>, f2: (a: R1) => R2, f3: (a: R2) => R3, f4: (a: R3) => R4): LoDashExplicitWrapper<(a1: A1, a2: A2, a3: A3, a4: A4) => R4>; + flow(this: LoDashExplicitWrapper<(a1: A1, a2: A2, a3: A3, a4: A4) => R1>, f2: (a: R1) => R2, f3: (a: R2) => R3, f4: (a: R3) => R4, f5: (a: R4) => R5): LoDashExplicitWrapper<(a1: A1, a2: A2, a3: A3, a4: A4) => R5>; + flow(this: LoDashExplicitWrapper<(a1: A1, a2: A2, a3: A3, a4: A4) => R1>, f2: (a: R1) => R2, f3: (a: R2) => R3, f4: (a: R3) => R4, f5: (a: R4) => R5, f6: (a: R5) => R6): LoDashExplicitWrapper<(a1: A1, a2: A2, a3: A3, a4: A4) => R6>; + flow(this: LoDashExplicitWrapper<(a1: A1, a2: A2, a3: A3, a4: A4) => R1>, f2: (a: R1) => R2, f3: (a: R2) => R3, f4: (a: R3) => R4, f5: (a: R4) => R5, f6: (a: R5) => R6, f7: (a: R6) => R7): LoDashExplicitWrapper<(a1: A1, a2: A2, a3: A3, a4: A4) => R7>; + // generic function + flow(...funcs: Array any>>): LoDashExplicitWrapper<(...args: any[]) => any>; } //_.flowRight @@ -10846,37 +8035,25 @@ declare namespace _ { * @param funcs Functions to invoke. * @return Returns the new function. */ - flowRight(...funcs: Function[]): TResult; - /** - * @see _.flowRight - */ - flowRight(funcs: Function[]): TResult; + flowRight(...funcs: Array any>>): (...args: any[]) => any; } - interface LoDashImplicitObjectWrapper { + interface LoDashImplicitWrapper { /** * @see _.flowRight */ - flowRight(...funcs: Function[]): LoDashImplicitObjectWrapper; - /** - * @see _.flowRight - */ - flowRight(funcs: Function[]): LoDashImplicitObjectWrapper; + flowRight(...funcs: Array any>>): LoDashImplicitWrapper<(...args: any[]) => any>; } - interface LoDashExplicitObjectWrapper { + interface LoDashExplicitWrapper { /** * @see _.flowRight */ - flowRight(...funcs: Function[]): LoDashExplicitObjectWrapper; - /** - * @see _.flowRight - */ - flowRight(funcs: Function[]): LoDashExplicitObjectWrapper; + flowRight(...funcs: Array any>>): LoDashExplicitWrapper<(...args: any[]) => any>; } //_.memoize - interface MemoizedFunction extends Function { + interface MemoizedFunction { cache: MapCache; } @@ -10892,23 +8069,23 @@ declare namespace _ { * @return Returns the new memoizing function. */ memoize: { - (func: T, resolver?: Function): T & MemoizedFunction; + any>(func: T, resolver?: (...args: any[]) => any): T & MemoizedFunction; Cache: MapCacheConstructor; }; } - interface LoDashImplicitObjectWrapper { + interface LoDashImplicitWrapper { /** * @see _.memoize */ - memoize(resolver?: Function): LoDashImplicitObjectWrapper; + memoize(resolver?: (...args: any[]) => any): LoDashImplicitWrapper; } - interface LoDashExplicitObjectWrapper { + interface LoDashExplicitWrapper { /** * @see _.memoize */ - memoize(resolver?: Function): LoDashExplicitObjectWrapper; + memoize(resolver?: (...args: any[]) => any): LoDashExplicitWrapper; } //_.overArgs (was _.modArgs) @@ -10921,42 +8098,24 @@ declare namespace _ { * of functions. * @return Returns the new function. */ - overArgs( - func: T, - ...transforms: Function[] - ): TResult; - - /** - * @see _.overArgs - */ - overArgs( - func: T, - transforms: Function[] - ): TResult; + overArgs( + func: (...args: any[]) => any, + ...transforms: Array any>> + ): (...args: any[]) => any; } - interface LoDashImplicitObjectWrapper { + interface LoDashImplicitWrapper { /** * @see _.overArgs */ - overArgs(...transforms: Function[]): LoDashImplicitObjectWrapper; - - /** - * @see _.overArgs - */ - overArgs(transforms: Function[]): LoDashImplicitObjectWrapper; + overArgs(...transforms: Array any>>): LoDashImplicitWrapper<(...args: any[]) => any>; } - interface LoDashExplicitObjectWrapper { + interface LoDashExplicitWrapper { /** * @see _.overArgs */ - overArgs(...transforms: Function[]): LoDashExplicitObjectWrapper; - - /** - * @see _.overArgs - */ - overArgs(transforms: Function[]): LoDashExplicitObjectWrapper; + overArgs(...transforms: Array any>>): LoDashExplicitWrapper<(...args: any[]) => any>; } //_.negate @@ -10968,36 +8127,14 @@ declare namespace _ { * @param predicate The predicate to negate. * @return Returns the new function. */ - negate(predicate: T): (...args: any[]) => boolean; - - /** - * @see _.negate - */ - negate(predicate: T): TResult; + negate any>(predicate: T): T; } - interface LoDashImplicitObjectWrapper { + interface LoDashWrapper { /** * @see _.negate */ - negate(): LoDashImplicitObjectWrapper<(...args: any[]) => boolean>; - - /** - * @see _.negate - */ - negate(): LoDashImplicitObjectWrapper; - } - - interface LoDashExplicitObjectWrapper { - /** - * @see _.negate - */ - negate(): LoDashExplicitObjectWrapper<(...args: any[]) => boolean>; - - /** - * @see _.negate - */ - negate(): LoDashExplicitObjectWrapper; + negate(): this; } //_.once @@ -11009,21 +8146,14 @@ declare namespace _ { * @param func The function to restrict. * @return Returns the new restricted function. */ - once(func: T): T; + once any>(func: T): T; } - interface LoDashImplicitObjectWrapper { + interface LoDashWrapper { /** * @see _.once */ - once(): LoDashImplicitObjectWrapper; - } - - interface LoDashExplicitObjectWrapper { - /** - * @see _.once - */ - once(): LoDashExplicitObjectWrapper; + once(): this; } //_.partial @@ -11039,6 +8169,20 @@ declare namespace _ { partial: Partial; } + interface LoDashImplicitWrapper { + /** + * @see _.partial + */ + partial: ImplicitPartial; + } + + interface LoDashExplicitWrapper { + /** + * @see _.partial + */ + partial: ExplicitPartial; + } + type PH = LoDashStatic; type Function0 = () => R; @@ -11085,7 +8229,89 @@ declare namespace _ { (func: Function4, plc1: PH, arg2: T2, arg3: T3, arg4: T4): Function1; (func: Function4, arg1: T1, arg2: T2, arg3: T3, arg4: T4): Function0< R>; // catch-all - (func: Function, ...args: any[]): Function; + (func: (...args: any[]) => any, ...args: any[]): (...args: any[]) => any; + } + + interface ImplicitPartial { + // arity 0 + (this: LoDashImplicitWrapper>): LoDashImplicitWrapper>; + // arity 1 + (this: LoDashImplicitWrapper>): LoDashImplicitWrapper>; + (this: LoDashImplicitWrapper>, arg1: T1): LoDashImplicitWrapper>; + // arity 2 + (this: LoDashImplicitWrapper>): LoDashImplicitWrapper>; + (this: LoDashImplicitWrapper>, arg1: T1): LoDashImplicitWrapper>; + (this: LoDashImplicitWrapper>, plc1: PH, arg2: T2): LoDashImplicitWrapper>; + (this: LoDashImplicitWrapper>, arg1: T1, arg2: T2): LoDashImplicitWrapper>; + // arity 3 + (this: LoDashImplicitWrapper>): LoDashImplicitWrapper>; + (this: LoDashImplicitWrapper>, arg1: T1): LoDashImplicitWrapper>; + (this: LoDashImplicitWrapper>, plc1: PH, arg2: T2): LoDashImplicitWrapper>; + (this: LoDashImplicitWrapper>, arg1: T1, arg2: T2): LoDashImplicitWrapper>; + (this: LoDashImplicitWrapper>, plc1: PH, plc2: PH, arg3: T3): LoDashImplicitWrapper>; + (this: LoDashImplicitWrapper>, arg1: T1, plc2: PH, arg3: T3): LoDashImplicitWrapper>; + (this: LoDashImplicitWrapper>, plc1: PH, arg2: T2, arg3: T3): LoDashImplicitWrapper>; + (this: LoDashImplicitWrapper>, arg1: T1, arg2: T2, arg3: T3): LoDashImplicitWrapper>; + // arity 4 + (this: LoDashImplicitWrapper>): LoDashImplicitWrapper>; + (this: LoDashImplicitWrapper>, arg1: T1): LoDashImplicitWrapper>; + (this: LoDashImplicitWrapper>, plc1: PH, arg2: T2): LoDashImplicitWrapper>; + (this: LoDashImplicitWrapper>, arg1: T1, arg2: T2): LoDashImplicitWrapper>; + (this: LoDashImplicitWrapper>, plc1: PH, plc2: PH, arg3: T3): LoDashImplicitWrapper>; + (this: LoDashImplicitWrapper>, arg1: T1, plc2: PH, arg3: T3): LoDashImplicitWrapper>; + (this: LoDashImplicitWrapper>, plc1: PH, arg2: T2, arg3: T3): LoDashImplicitWrapper>; + (this: LoDashImplicitWrapper>, arg1: T1, arg2: T2, arg3: T3): LoDashImplicitWrapper>; + (this: LoDashImplicitWrapper>, plc1: PH, plc2: PH, plc3: PH, arg4: T4): LoDashImplicitWrapper>; + (this: LoDashImplicitWrapper>, arg1: T1, plc2: PH, plc3: PH, arg4: T4): LoDashImplicitWrapper>; + (this: LoDashImplicitWrapper>, plc1: PH, arg2: T2, plc3: PH, arg4: T4): LoDashImplicitWrapper>; + (this: LoDashImplicitWrapper>, arg1: T1, arg2: T2, plc3: PH, arg4: T4): LoDashImplicitWrapper>; + (this: LoDashImplicitWrapper>, plc1: PH, plc2: PH, arg3: T3, arg4: T4): LoDashImplicitWrapper>; + (this: LoDashImplicitWrapper>, arg1: T1, plc2: PH, arg3: T3, arg4: T4): LoDashImplicitWrapper>; + (this: LoDashImplicitWrapper>, plc1: PH, arg2: T2, arg3: T3, arg4: T4): LoDashImplicitWrapper>; + (this: LoDashImplicitWrapper>, arg1: T1, arg2: T2, arg3: T3, arg4: T4): LoDashImplicitWrapper>; + // catch-all + (...args: any[]): LoDashImplicitWrapper<(...args: any[]) => any>; + } + + interface ExplicitPartial { + // arity 0 + (this: LoDashExplicitWrapper>): LoDashExplicitWrapper>; + // arity 1 + (this: LoDashExplicitWrapper>): LoDashExplicitWrapper>; + (this: LoDashExplicitWrapper>, arg1: T1): LoDashExplicitWrapper>; + // arity 2 + (this: LoDashExplicitWrapper>): LoDashExplicitWrapper>; + (this: LoDashExplicitWrapper>, arg1: T1): LoDashExplicitWrapper>; + (this: LoDashExplicitWrapper>, plc1: PH, arg2: T2): LoDashExplicitWrapper>; + (this: LoDashExplicitWrapper>, arg1: T1, arg2: T2): LoDashExplicitWrapper>; + // arity 3 + (this: LoDashExplicitWrapper>): LoDashExplicitWrapper>; + (this: LoDashExplicitWrapper>, arg1: T1): LoDashExplicitWrapper>; + (this: LoDashExplicitWrapper>, plc1: PH, arg2: T2): LoDashExplicitWrapper>; + (this: LoDashExplicitWrapper>, arg1: T1, arg2: T2): LoDashExplicitWrapper>; + (this: LoDashExplicitWrapper>, plc1: PH, plc2: PH, arg3: T3): LoDashExplicitWrapper>; + (this: LoDashExplicitWrapper>, arg1: T1, plc2: PH, arg3: T3): LoDashExplicitWrapper>; + (this: LoDashExplicitWrapper>, plc1: PH, arg2: T2, arg3: T3): LoDashExplicitWrapper>; + (this: LoDashExplicitWrapper>, arg1: T1, arg2: T2, arg3: T3): LoDashExplicitWrapper>; + // arity 4 + (this: LoDashExplicitWrapper>): LoDashExplicitWrapper>; + (this: LoDashExplicitWrapper>, arg1: T1): LoDashExplicitWrapper>; + (this: LoDashExplicitWrapper>, plc1: PH, arg2: T2): LoDashExplicitWrapper>; + (this: LoDashExplicitWrapper>, arg1: T1, arg2: T2): LoDashExplicitWrapper>; + (this: LoDashExplicitWrapper>, plc1: PH, plc2: PH, arg3: T3): LoDashExplicitWrapper>; + (this: LoDashExplicitWrapper>, arg1: T1, plc2: PH, arg3: T3): LoDashExplicitWrapper>; + (this: LoDashExplicitWrapper>, plc1: PH, arg2: T2, arg3: T3): LoDashExplicitWrapper>; + (this: LoDashExplicitWrapper>, arg1: T1, arg2: T2, arg3: T3): LoDashExplicitWrapper>; + (this: LoDashExplicitWrapper>, plc1: PH, plc2: PH, plc3: PH, arg4: T4): LoDashExplicitWrapper>; + (this: LoDashExplicitWrapper>, arg1: T1, plc2: PH, plc3: PH, arg4: T4): LoDashExplicitWrapper>; + (this: LoDashExplicitWrapper>, plc1: PH, arg2: T2, plc3: PH, arg4: T4): LoDashExplicitWrapper>; + (this: LoDashExplicitWrapper>, arg1: T1, arg2: T2, plc3: PH, arg4: T4): LoDashExplicitWrapper>; + (this: LoDashExplicitWrapper>, plc1: PH, plc2: PH, arg3: T3, arg4: T4): LoDashExplicitWrapper>; + (this: LoDashExplicitWrapper>, arg1: T1, plc2: PH, arg3: T3, arg4: T4): LoDashExplicitWrapper>; + (this: LoDashExplicitWrapper>, plc1: PH, arg2: T2, arg3: T3, arg4: T4): LoDashExplicitWrapper>; + (this: LoDashExplicitWrapper>, arg1: T1, arg2: T2, arg3: T3, arg4: T4): LoDashExplicitWrapper>; + // catch-all + (...args: any[]): LoDashExplicitWrapper<(...args: any[]) => any>; } //_.partialRight @@ -11100,6 +8326,20 @@ declare namespace _ { partialRight: PartialRight; } + interface LoDashImplicitWrapper { + /** + * @see _.partialRight + */ + partialRight: ImplicitPartialRight; + } + + interface LoDashExplicitWrapper { + /** + * @see _.partialRight + */ + partialRight: ExplicitPartialRight; + } + interface PartialRight { // arity 0 (func: Function0): Function0; @@ -11138,7 +8378,89 @@ declare namespace _ { (func: Function4, arg2: T2, arg3: T3, arg4: T4): Function1; (func: Function4, arg1: T1, arg2: T2, arg3: T3, arg4: T4): Function0< R>; // catch-all - (func: Function, ...args: any[]): Function; + (func: (...args: any[]) => any, ...args: any[]): (...args: any[]) => any; + } + + interface ImplicitPartialRight { + // arity 0 + (this: LoDashImplicitWrapper>): LoDashImplicitWrapper>; + // arity 1 + (this: LoDashImplicitWrapper>): LoDashImplicitWrapper>; + (this: LoDashImplicitWrapper>, arg1: T1): LoDashImplicitWrapper>; + // arity 2 + (this: LoDashImplicitWrapper>): LoDashImplicitWrapper>; + (this: LoDashImplicitWrapper>, arg1: T1, plc2: PH): LoDashImplicitWrapper>; + (this: LoDashImplicitWrapper>, arg2: T2): LoDashImplicitWrapper>; + (this: LoDashImplicitWrapper>, arg1: T1, arg2: T2): LoDashImplicitWrapper>; + // arity 3 + (this: LoDashImplicitWrapper>): LoDashImplicitWrapper>; + (this: LoDashImplicitWrapper>, arg1: T1, plc2: PH, plc3: PH): LoDashImplicitWrapper>; + (this: LoDashImplicitWrapper>, arg2: T2, plc3: PH): LoDashImplicitWrapper>; + (this: LoDashImplicitWrapper>, arg1: T1, arg2: T2, plc3: PH): LoDashImplicitWrapper>; + (this: LoDashImplicitWrapper>, arg3: T3): LoDashImplicitWrapper>; + (this: LoDashImplicitWrapper>, arg1: T1, plc2: PH, arg3: T3): LoDashImplicitWrapper>; + (this: LoDashImplicitWrapper>, arg2: T2, arg3: T3): LoDashImplicitWrapper>; + (this: LoDashImplicitWrapper>, arg1: T1, arg2: T2, arg3: T3): LoDashImplicitWrapper>; + // arity 4 + (this: LoDashImplicitWrapper>): LoDashImplicitWrapper>; + (this: LoDashImplicitWrapper>, arg1: T1, plc2: PH, plc3: PH, plc4: PH): LoDashImplicitWrapper>; + (this: LoDashImplicitWrapper>, arg2: T2, plc3: PH, plc4: PH): LoDashImplicitWrapper>; + (this: LoDashImplicitWrapper>, arg1: T1, arg2: T2, plc3: PH, plc4: PH): LoDashImplicitWrapper>; + (this: LoDashImplicitWrapper>, arg3: T3, plc4: PH): LoDashImplicitWrapper>; + (this: LoDashImplicitWrapper>, arg1: T1, plc2: PH, arg3: T3, plc4: PH): LoDashImplicitWrapper>; + (this: LoDashImplicitWrapper>, arg2: T2, arg3: T3, plc4: PH): LoDashImplicitWrapper>; + (this: LoDashImplicitWrapper>, arg1: T1, arg2: T2, arg3: T3, plc4: PH): LoDashImplicitWrapper>; + (this: LoDashImplicitWrapper>, arg4: T4): LoDashImplicitWrapper>; + (this: LoDashImplicitWrapper>, arg1: T1, plc2: PH, plc3: PH, arg4: T4): LoDashImplicitWrapper>; + (this: LoDashImplicitWrapper>, arg2: T2, plc3: PH, arg4: T4): LoDashImplicitWrapper>; + (this: LoDashImplicitWrapper>, arg1: T1, arg2: T2, plc3: PH, arg4: T4): LoDashImplicitWrapper>; + (this: LoDashImplicitWrapper>, arg3: T3, arg4: T4): LoDashImplicitWrapper>; + (this: LoDashImplicitWrapper>, arg1: T1, plc2: PH, arg3: T3, arg4: T4): LoDashImplicitWrapper>; + (this: LoDashImplicitWrapper>, arg2: T2, arg3: T3, arg4: T4): LoDashImplicitWrapper>; + (this: LoDashImplicitWrapper>, arg1: T1, arg2: T2, arg3: T3, arg4: T4): LoDashImplicitWrapper>; + // catch-all + (...args: any[]): LoDashImplicitWrapper<(...args: any[]) => any>; + } + + interface ExplicitPartialRight { + // arity 0 + (this: LoDashExplicitWrapper>): LoDashExplicitWrapper>; + // arity 1 + (this: LoDashExplicitWrapper>): LoDashExplicitWrapper>; + (this: LoDashExplicitWrapper>, arg1: T1): LoDashExplicitWrapper>; + // arity 2 + (this: LoDashExplicitWrapper>): LoDashExplicitWrapper>; + (this: LoDashExplicitWrapper>, arg1: T1, plc2: PH): LoDashExplicitWrapper>; + (this: LoDashExplicitWrapper>, arg2: T2): LoDashExplicitWrapper>; + (this: LoDashExplicitWrapper>, arg1: T1, arg2: T2): LoDashExplicitWrapper>; + // arity 3 + (this: LoDashExplicitWrapper>): LoDashExplicitWrapper>; + (this: LoDashExplicitWrapper>, arg1: T1, plc2: PH, plc3: PH): LoDashExplicitWrapper>; + (this: LoDashExplicitWrapper>, arg2: T2, plc3: PH): LoDashExplicitWrapper>; + (this: LoDashExplicitWrapper>, arg1: T1, arg2: T2, plc3: PH): LoDashExplicitWrapper>; + (this: LoDashExplicitWrapper>, arg3: T3): LoDashExplicitWrapper>; + (this: LoDashExplicitWrapper>, arg1: T1, plc2: PH, arg3: T3): LoDashExplicitWrapper>; + (this: LoDashExplicitWrapper>, arg2: T2, arg3: T3): LoDashExplicitWrapper>; + (this: LoDashExplicitWrapper>, arg1: T1, arg2: T2, arg3: T3): LoDashExplicitWrapper>; + // arity 4 + (this: LoDashExplicitWrapper>): LoDashExplicitWrapper>; + (this: LoDashExplicitWrapper>, arg1: T1, plc2: PH, plc3: PH, plc4: PH): LoDashExplicitWrapper>; + (this: LoDashExplicitWrapper>, arg2: T2, plc3: PH, plc4: PH): LoDashExplicitWrapper>; + (this: LoDashExplicitWrapper>, arg1: T1, arg2: T2, plc3: PH, plc4: PH): LoDashExplicitWrapper>; + (this: LoDashExplicitWrapper>, arg3: T3, plc4: PH): LoDashExplicitWrapper>; + (this: LoDashExplicitWrapper>, arg1: T1, plc2: PH, arg3: T3, plc4: PH): LoDashExplicitWrapper>; + (this: LoDashExplicitWrapper>, arg2: T2, arg3: T3, plc4: PH): LoDashExplicitWrapper>; + (this: LoDashExplicitWrapper>, arg1: T1, arg2: T2, arg3: T3, plc4: PH): LoDashExplicitWrapper>; + (this: LoDashExplicitWrapper>, arg4: T4): LoDashExplicitWrapper>; + (this: LoDashExplicitWrapper>, arg1: T1, plc2: PH, plc3: PH, arg4: T4): LoDashExplicitWrapper>; + (this: LoDashExplicitWrapper>, arg2: T2, plc3: PH, arg4: T4): LoDashExplicitWrapper>; + (this: LoDashExplicitWrapper>, arg1: T1, arg2: T2, plc3: PH, arg4: T4): LoDashExplicitWrapper>; + (this: LoDashExplicitWrapper>, arg3: T3, arg4: T4): LoDashExplicitWrapper>; + (this: LoDashExplicitWrapper>, arg1: T1, plc2: PH, arg3: T3, arg4: T4): LoDashExplicitWrapper>; + (this: LoDashExplicitWrapper>, arg2: T2, arg3: T3, arg4: T4): LoDashExplicitWrapper>; + (this: LoDashExplicitWrapper>, arg1: T1, arg2: T2, arg3: T3, arg4: T4): LoDashExplicitWrapper>; + // catch-all + (...args: any[]): LoDashExplicitWrapper<(...args: any[]) => any>; } //_.rearg @@ -11151,24 +8473,21 @@ declare namespace _ { * @param indexes The arranged argument indexes, specified as individual indexes or arrays of indexes. * @return Returns the new function. */ - rearg(func: Function, indexes: number[]): TResult; - - /** - * @see _.rearg - */ - rearg(func: Function, ...indexes: number[]): TResult; + rearg(func: (...args: any[]) => any, ...indexes: Array>): (...args: any[]) => any; } - interface LoDashImplicitObjectWrapper { + interface LoDashImplicitWrapper { /** * @see _.rearg */ - rearg(indexes: number[]): LoDashImplicitObjectWrapper; + rearg(...indexes: Array>): LoDashImplicitWrapper<(...args: any[]) => any>; + } + interface LoDashExplicitWrapper { /** * @see _.rearg */ - rearg(...indexes: number[]): LoDashImplicitObjectWrapper; + rearg(...indexes: Array>): LoDashExplicitWrapper<(...args: any[]) => any>; } //_.rest @@ -11183,32 +8502,24 @@ declare namespace _ { * @param start The start position of the rest parameter. * @return Returns the new function. */ - rest( - func: Function, + rest( + func: (...args: any[]) => any, start?: number - ): TResult; - - /** - * @see _.rest - */ - rest( - func: TFunc, - start?: number - ): TResult; + ): (...args: any[]) => any; } - interface LoDashImplicitObjectWrapper { + interface LoDashImplicitWrapper { /** * @see _.rest */ - rest(start?: number): LoDashImplicitObjectWrapper; + rest(start?: number): LoDashImplicitWrapper<(...args: any[]) => any>; } - interface LoDashExplicitObjectWrapper { + interface LoDashExplicitWrapper { /** * @see _.rest */ - rest(start?: number): LoDashExplicitObjectWrapper; + rest(start?: number): LoDashExplicitWrapper<(...args: any[]) => any>; } //_.spread @@ -11222,26 +8533,36 @@ declare namespace _ { * @param func The function to spread arguments over. * @return Returns the new function. */ - spread(func: F): T; + spread(func: (...args: any[]) => TResult): (...args: any[]) => TResult; /** * @see _.spread */ - spread(func: Function): T; + spread(func: (...args: any[]) => TResult, start: number): (...args: any[]) => TResult; } - interface LoDashImplicitObjectWrapper { + interface LoDashImplicitWrapper { /** * @see _.spread */ - spread(): LoDashImplicitObjectWrapper; + spread(this: LoDashImplicitWrapper<(...args: any[]) => TResult>): LoDashImplicitWrapper<(...args: any[]) => TResult>; + + /** + * @see _.spread + */ + spread(this: LoDashImplicitWrapper<(...args: any[]) => TResult>, start: number): LoDashImplicitWrapper<(...args: any[]) => TResult>; } - interface LoDashExplicitObjectWrapper { + interface LoDashExplicitWrapper { /** * @see _.spread */ - spread(): LoDashExplicitObjectWrapper; + spread(this: LoDashExplicitWrapper<(...args: any[]) => TResult>): LoDashExplicitWrapper<(...args: any[]) => TResult>; + + /** + * @see _.spread + */ + spread(this: LoDashExplicitWrapper<(...args: any[]) => TResult>, start: number): LoDashExplicitWrapper<(...args: any[]) => TResult>; } //_.throttle @@ -11274,31 +8595,31 @@ declare namespace _ { * @param options.trailing Specify invoking on the trailing edge of the timeout. * @return Returns the new throttled function. */ - throttle( + throttle any>( func: T, wait?: number, options?: ThrottleSettings ): T & Cancelable; } - interface LoDashImplicitObjectWrapper { + interface LoDashImplicitWrapper { /** * @see _.throttle */ throttle( wait?: number, options?: ThrottleSettings - ): LoDashImplicitObjectWrapper; + ): LoDashImplicitWrapper; } - interface LoDashExplicitObjectWrapper { + interface LoDashExplicitWrapper { /** * @see _.throttle */ throttle( wait?: number, options?: ThrottleSettings - ): LoDashExplicitObjectWrapper; + ): LoDashExplicitWrapper; } //_.unary @@ -11317,21 +8638,21 @@ declare namespace _ { * _.map(['6', '8', '10'], _.unary(parseInt)); * // => [6, 8, 10] */ - unary(func: T): T; + unary(func: (arg1: T, ...args: any[]) => TResult): (arg1: T) => TResult; } - interface LoDashImplicitObjectWrapper { + interface LoDashImplicitWrapper { /** * @see _.unary */ - unary(): LoDashImplicitObjectWrapper; + unary(this: LoDashImplicitWrapper<(arg1: T, ...args: any[]) => TResult>): LoDashImplicitWrapper<(arg1: T) => TResult>; } - interface LoDashExplicitObjectWrapper { + interface LoDashExplicitWrapper { /** * @see _.unary */ - unary(): LoDashExplicitObjectWrapper; + unary(this: LoDashExplicitWrapper<(arg1: T, ...args: any[]) => TResult>): LoDashExplicitWrapper<(arg1: T) => TResult>; } //_.wrap @@ -11345,98 +8666,53 @@ declare namespace _ { * @param wrapper The wrapper function. * @return Returns the new function. */ - wrap( - value: V, - wrapper: W - ): R; + wrap( + value: T, + wrapper: (value: T, ...args: TArgs[]) => TResult + ): (...args: TArgs[]) => TResult; /** * @see _.wrap */ - wrap( - value: V, - wrapper: Function - ): R; - - /** - * @see _.wrap - */ - wrap( - value: any, - wrapper: Function - ): R; + wrap( + value: T, + wrapper: (value: T, ...args: any[]) => TResult + ): (...args: any[]) => TResult; } - interface LoDashImplicitWrapper { + interface LoDashImplicitWrapper { /** * @see _.wrap */ - wrap(wrapper: W): LoDashImplicitObjectWrapper; + wrap( + wrapper: (value: TValue, ...args: TArgs[]) => TResult + ): LoDashImplicitWrapper<(...args: TArgs[]) => TResult>; /** * @see _.wrap */ - wrap(wrapper: Function): LoDashImplicitObjectWrapper; + wrap( + wrapper: (value: TValue, ...args: any[]) => TResult + ): LoDashImplicitWrapper<(...args: any[]) => TResult>; } - interface LoDashImplicitArrayWrapperBase { + interface LoDashExplicitWrapper { /** * @see _.wrap */ - wrap(wrapper: W): LoDashImplicitObjectWrapper; + /** + * @see _.wrap + */ + wrap( + wrapper: (value: TValue, ...args: TArgs[]) => TResult + ): LoDashExplicitWrapper<(...args: TArgs[]) => TResult>; /** * @see _.wrap */ - wrap(wrapper: Function): LoDashImplicitObjectWrapper; - } - - interface LoDashImplicitObjectWrapperBase { - /** - * @see _.wrap - */ - wrap(wrapper: W): LoDashImplicitObjectWrapper; - - /** - * @see _.wrap - */ - wrap(wrapper: Function): LoDashImplicitObjectWrapper; - } - - interface LoDashExplicitWrapper { - /** - * @see _.wrap - */ - wrap(wrapper: W): LoDashExplicitObjectWrapper; - - /** - * @see _.wrap - */ - wrap(wrapper: Function): LoDashExplicitObjectWrapper; - } - - interface LoDashExplicitArrayWrapperBase { - /** - * @see _.wrap - */ - wrap(wrapper: W): LoDashExplicitObjectWrapper; - - /** - * @see _.wrap - */ - wrap(wrapper: Function): LoDashExplicitObjectWrapper; - } - - interface LoDashExplicitObjectWrapperBase { - /** - * @see _.wrap - */ - wrap(wrapper: W): LoDashExplicitObjectWrapper; - - /** - * @see _.wrap - */ - wrap(wrapper: Function): LoDashExplicitObjectWrapper; + wrap( + wrapper: (value: TValue, ...args: any[]) => TResult + ): LoDashExplicitWrapper<(...args: any[]) => TResult>; } /******** @@ -11454,46 +8730,18 @@ declare namespace _ { castArray(value?: Many): T[]; } - interface LoDashImplicitWrapper { + interface LoDashImplicitWrapper { /** * @see _.castArray */ - castArray(): LoDashImplicitArrayWrapper; + castArray(this: LoDashImplicitWrapper>): LoDashImplicitWrapper; } - interface LoDashImplicitArrayWrapperBase { + interface LoDashExplicitWrapper { /** * @see _.castArray */ - castArray(): TWrapper; - } - - interface LoDashImplicitObjectWrapperBase { - /** - * @see _.castArray - */ - castArray(): LoDashImplicitArrayWrapper; - } - - interface LoDashExplicitWrapper { - /** - * @see _.castArray - */ - castArray(): LoDashExplicitArrayWrapper; - } - - interface LoDashExplicitArrayWrapperBase { - /** - * @see _.castArray - */ - castArray(): TWrapper; - } - - interface LoDashExplicitObjectWrapperBase { - /** - * @see _.castArray - */ - castArray(): LoDashExplicitArrayWrapper; + castArray(this: LoDashExplicitWrapper>): LoDashExplicitWrapper; } //_.clone @@ -11512,46 +8760,18 @@ declare namespace _ { clone(value: T): T; } - interface LoDashImplicitWrapper { + interface LoDashImplicitWrapper { /** * @see _.clone */ - clone(): T; + clone(): TValue; } - interface LoDashImplicitArrayWrapperBase { + interface LoDashExplicitWrapper { /** * @see _.clone */ - clone(): TArray; - } - - interface LoDashImplicitObjectWrapperBase { - /** - * @see _.clone - */ - clone(): TObject; - } - - interface LoDashExplicitWrapper { - /** - * @see _.clone - */ - clone(): LoDashExplicitWrapper; - } - - interface LoDashExplicitArrayWrapperBase { - /** - * @see _.clone - */ - clone(): TWrapper; - } - - interface LoDashExplicitObjectWrapperBase { - /** - * @see _.clone - */ - clone(): TWrapper; + clone(): this; } //_.cloneDeep @@ -11565,50 +8785,22 @@ declare namespace _ { cloneDeep(value: T): T; } - interface LoDashImplicitWrapper { + interface LoDashImplicitWrapper { /** * @see _.cloneDeep */ - cloneDeep(): T; + cloneDeep(): TValue; } - interface LoDashImplicitArrayWrapperBase { + interface LoDashExplicitWrapper { /** * @see _.cloneDeep */ - cloneDeep(): TArray; - } - - interface LoDashImplicitObjectWrapperBase { - /** - * @see _.cloneDeep - */ - cloneDeep(): TObject; - } - - interface LoDashExplicitWrapper { - /** - * @see _.cloneDeep - */ - cloneDeep(): LoDashExplicitWrapper; - } - - interface LoDashExplicitArrayWrapperBase { - /** - * @see _.cloneDeep - */ - cloneDeep(): TWrapper; - } - - interface LoDashExplicitObjectWrapperBase { - /** - * @see _.cloneDeep - */ - cloneDeep(): TWrapper; + cloneDeep(): this; } //_.cloneDeepWith - type CloneDeepWithCustomizer = (value: TValue, key?: number|string, object?: any, stack?: any) => TResult; + type CloneDeepWithCustomizer = (value: any, key: number | string | undefined, object: TObject | undefined, stack: any) => any; interface LoDashStatic { /** @@ -11618,118 +8810,47 @@ declare namespace _ { * @param customizer The function to customize cloning. * @return Returns the deep cloned value. */ - cloneDeepWith( - value: any, - customizer?: CloneDeepWithCustomizer - ): TResult; - - /** - * @see _.clonDeepeWith - */ - cloneDeepWith( + cloneDeepWith( value: T, - customizer?: CloneDeepWithCustomizer - ): TResult; + customizer: CloneDeepWithCustomizer + ): any; + + /** + * @see _.cloneDeepWith + */ + cloneDeepWith(value: T): T; } - interface LoDashImplicitWrapper { + interface LoDashImplicitWrapper { /** * @see _.cloneDeepWith */ - cloneDeepWith( - customizer?: CloneDeepWithCustomizer - ): TResult; + cloneDeepWith( + customizer: CloneDeepWithCustomizer + ): any; + + /** + * @see _.cloneDeepWith + */ + cloneDeepWith(): TValue; } - interface LoDashImplicitArrayWrapperBase { + interface LoDashExplicitWrapper { /** * @see _.cloneDeepWith */ - cloneDeepWith( - customizer?: CloneDeepWithCustomizer - ): TResult; - } - - interface LoDashImplicitObjectWrapperBase { - /** - * @see _.cloneDeepWith - */ - cloneDeepWith( - customizer?: CloneDeepWithCustomizer - ): TResult; - } - - interface LoDashExplicitWrapper { - /** - * @see _.cloneDeepWith - */ - cloneDeepWith( - customizer?: CloneDeepWithCustomizer - ): LoDashExplicitWrapper; + cloneDeepWith( + customizer: CloneDeepWithCustomizer + ): LoDashExplicitWrapper; /** * @see _.cloneDeepWith */ - cloneDeepWith( - customizer?: CloneDeepWithCustomizer - ): LoDashExplicitArrayWrapper; - - /** - * @see _.cloneDeepWith - */ - cloneDeepWith( - customizer?: CloneDeepWithCustomizer - ): LoDashExplicitObjectWrapper; - } - - interface LoDashExplicitArrayWrapperBase { - /** - * @see _.cloneDeepWith - */ - cloneDeepWith( - customizer?: CloneDeepWithCustomizer - ): LoDashExplicitWrapper; - - /** - * @see _.cloneDeepWith - */ - cloneDeepWith( - customizer?: CloneDeepWithCustomizer - ): LoDashExplicitArrayWrapper; - - /** - * @see _.cloneDeepWith - */ - cloneDeepWith( - customizer?: CloneDeepWithCustomizer - ): LoDashExplicitObjectWrapper; - } - - interface LoDashExplicitObjectWrapperBase { - /** - * @see _.cloneDeepWith - */ - cloneDeepWith( - customizer?: CloneDeepWithCustomizer - ): LoDashExplicitWrapper; - - /** - * @see _.cloneDeepWith - */ - cloneDeepWith( - customizer?: CloneDeepWithCustomizer - ): LoDashExplicitArrayWrapper; - - /** - * @see _.cloneDeepWith - */ - cloneDeepWith( - customizer?: CloneDeepWithCustomizer - ): LoDashExplicitObjectWrapper; + cloneDeepWith(): this; } //_.cloneWith - type CloneWithCustomizer = (value: TValue, key?: number|string, object?: any, stack?: any) => TResult; + type CloneWithCustomizer = (value: TValue, key: number | string | undefined, object: any, stack: any) => TResult; interface LoDashStatic { /** @@ -11740,9 +8861,9 @@ declare namespace _ { * @param customizer The function to customize cloning. * @return Returns the cloned value. */ - cloneWith( - value: any, - customizer?: CloneWithCustomizer + cloneWith( + value: T, + customizer: CloneWithCustomizer ): TResult; /** @@ -11750,111 +8871,62 @@ declare namespace _ { */ cloneWith( value: T, - customizer?: CloneWithCustomizer - ): TResult; + customizer: CloneWithCustomizer + ): TResult | T; + + /** + * @see _.cloneWith + */ + cloneWith(value: T): T; } - interface LoDashImplicitWrapper { + interface LoDashImplicitWrapper { + /** + * @see _.cloneWith + */ + cloneWith( + customizer: CloneWithCustomizer + ): TResult; + /** * @see _.cloneWith */ cloneWith( - customizer?: CloneWithCustomizer - ): TResult; - } + customizer: CloneWithCustomizer + ): TResult | TValue; - interface LoDashImplicitArrayWrapperBase { /** * @see _.cloneWith */ - cloneWith( - customizer?: CloneWithCustomizer - ): TResult; + cloneWith(): TValue; } - interface LoDashImplicitObjectWrapperBase { + interface LoDashExplicitWrapper { /** * @see _.cloneWith */ - cloneWith( - customizer?: CloneWithCustomizer - ): TResult; - } - - interface LoDashExplicitWrapper { - /** - * @see _.cloneWith - */ - cloneWith( - customizer?: CloneWithCustomizer + cloneWith( + customizer: CloneWithCustomizer ): LoDashExplicitWrapper; /** * @see _.cloneWith */ cloneWith( - customizer?: CloneWithCustomizer - ): LoDashExplicitArrayWrapper; + customizer: CloneWithCustomizer + ): LoDashExplicitWrapper; /** * @see _.cloneWith */ - cloneWith( - customizer?: CloneWithCustomizer - ): LoDashExplicitObjectWrapper; - } - - interface LoDashExplicitArrayWrapperBase { - /** - * @see _.cloneWith - */ - cloneWith( - customizer?: CloneWithCustomizer - ): LoDashExplicitWrapper; - - /** - * @see _.cloneWith - */ - cloneWith( - customizer?: CloneWithCustomizer - ): LoDashExplicitArrayWrapper; - - /** - * @see _.cloneWith - */ - cloneWith( - customizer?: CloneWithCustomizer - ): LoDashExplicitObjectWrapper; - } - - interface LoDashExplicitObjectWrapperBase { - /** - * @see _.cloneWith - */ - cloneWith( - customizer?: CloneWithCustomizer - ): LoDashExplicitWrapper; - - /** - * @see _.cloneWith - */ - cloneWith( - customizer?: CloneWithCustomizer - ): LoDashExplicitArrayWrapper; - - /** - * @see _.cloneWith - */ - cloneWith( - customizer?: CloneWithCustomizer - ): LoDashExplicitObjectWrapper; + cloneWith(): this; } /** * An object containing predicate functions for each property of T */ type ConformsPredicateObject = { - [P in keyof T]: (val: T[P]) => boolean; + [P in keyof T]?: (val: T[P]) => boolean; }; //_.conforms @@ -11863,7 +8935,21 @@ declare namespace _ { * Creates a function that invokes the predicate properties of `source` with the corresponding * property values of a given object, returning true if all predicates return truthy, else false. */ - conforms(source: ConformsPredicateObject): (Target: T) => boolean; + conforms(source: ConformsPredicateObject): (value: T) => boolean; + } + + interface LoDashImplicitWrapper { + /** + * @see _.conforms + */ + conforms(this: LoDashImplicitWrapper>): LoDashImplicitWrapper<(value: T) => boolean>; + } + + interface LoDashExplicitWrapper { + /** + * @see _.conforms + */ + conforms(this: LoDashExplicitWrapper>): LoDashExplicitWrapper<(value: T) => boolean>; } //_.conformsTo @@ -11877,6 +8963,20 @@ declare namespace _ { conformsTo(object: T, source: ConformsPredicateObject): boolean; } + interface LoDashImplicitWrapper { + /** + * @see _.conformsTo + */ + conformsTo(source: ConformsPredicateObject): boolean; + } + + interface LoDashExplicitWrapper { + /** + * @see _.conformsTo + */ + conformsTo(source: ConformsPredicateObject): LoDashExplicitWrapper; + } + type CondPair = [(val: T) => boolean, (val: T) => R] //_.cond @@ -11951,18 +9051,18 @@ declare namespace _ { ): boolean; } - interface LoDashImplicitWrapperBase { + interface LoDashImplicitWrapper { /** - * @see _.isEqual + * @see _.eq */ eq( other: any ): boolean; } - interface LoDashExplicitWrapperBase { + interface LoDashExplicitWrapper { /** - * @see _.isEqual + * @see _.eq */ eq( other: any @@ -11984,14 +9084,14 @@ declare namespace _ { ): boolean; } - interface LoDashImplicitWrapperBase { + interface LoDashImplicitWrapper { /** * @see _.gt */ gt(other: any): boolean; } - interface LoDashExplicitWrapperBase { + interface LoDashExplicitWrapper { /** * @see _.gt */ @@ -12013,14 +9113,14 @@ declare namespace _ { ): boolean; } - interface LoDashImplicitWrapperBase { + interface LoDashImplicitWrapper { /** * @see _.gte */ gte(other: any): boolean; } - interface LoDashExplicitWrapperBase { + interface LoDashExplicitWrapper { /** * @see _.gte */ @@ -12038,14 +9138,14 @@ declare namespace _ { isArguments(value?: any): value is IArguments; } - interface LoDashImplicitWrapperBase { + interface LoDashImplicitWrapper { /** * @see _.isArguments */ isArguments(): boolean; } - interface LoDashExplicitWrapperBase { + interface LoDashExplicitWrapper { /** * @see _.isArguments */ @@ -12068,14 +9168,14 @@ declare namespace _ { isArray(value?: any): value is any[]; } - interface LoDashImplicitWrapperBase { + interface LoDashImplicitWrapper { /** * @see _.isArray */ isArray(): boolean; } - interface LoDashExplicitWrapperBase { + interface LoDashExplicitWrapper { /** * @see _.isArray */ @@ -12093,14 +9193,14 @@ declare namespace _ { isArrayBuffer(value?: any): value is ArrayBuffer; } - interface LoDashImplicitWrapperBase { + interface LoDashImplicitWrapper { /** * @see _.isArrayBuffer */ isArrayBuffer(): boolean; } - interface LoDashExplicitWrapperBase { + interface LoDashExplicitWrapper { /** * @see _.isArrayBuffer */ @@ -12139,27 +9239,22 @@ declare namespace _ { /** * @see _.isArrayLike */ - isArrayLike(value?: Function): value is never; + isArrayLike(value?: ((...args: any[]) => any) | Function | null | undefined): value is never; /** * @see _.isArrayLike */ - isArrayLike(value: T | Function): value is T & { length: number }; - - /** - * DEPRECATED - */ - isArrayLike(value?: any): value is any[]; + isArrayLike(value: any): value is { length: number }; } - interface LoDashImplicitWrapperBase { + interface LoDashImplicitWrapper { /** * @see _.isArrayLike */ isArrayLike(): boolean; } - interface LoDashExplicitWrapperBase { + interface LoDashExplicitWrapper { /** * @see _.isArrayLike */ @@ -12197,27 +9292,22 @@ declare namespace _ { /** * @see _.isArrayLike */ - isArrayLikeObject(value?: Function | string | boolean | number): value is never; + isArrayLikeObject(value?: ((...args: any[]) => any) | Function | string | boolean | number | null | undefined): value is never; /** * @see _.isArrayLike */ - isArrayLikeObject(value: T | Function | string | boolean | number): value is T & { length: number }; - - /** - * DEPRECATED - */ - isArrayLikeObject(value?: any): value is any[]; + isArrayLikeObject(value: T | string | boolean | number | null | undefined): value is T & { length: number }; } - interface LoDashImplicitWrapperBase { + interface LoDashImplicitWrapper { /** * @see _.isArrayLikeObject */ isArrayLikeObject(): boolean; } - interface LoDashExplicitWrapperBase { + interface LoDashExplicitWrapper { /** * @see _.isArrayLikeObject */ @@ -12235,14 +9325,14 @@ declare namespace _ { isBoolean(value?: any): value is boolean; } - interface LoDashImplicitWrapperBase { + interface LoDashImplicitWrapper { /** * @see _.isBoolean */ isBoolean(): boolean; } - interface LoDashExplicitWrapperBase { + interface LoDashExplicitWrapper { /** * @see _.isBoolean */ @@ -12260,14 +9350,14 @@ declare namespace _ { isBuffer(value?: any): boolean; } - interface LoDashImplicitWrapperBase { + interface LoDashImplicitWrapper { /** * @see _.isBuffer */ isBuffer(): boolean; } - interface LoDashExplicitWrapperBase { + interface LoDashExplicitWrapper { /** * @see _.isBuffer */ @@ -12285,14 +9375,14 @@ declare namespace _ { isDate(value?: any): value is Date; } - interface LoDashImplicitWrapperBase { + interface LoDashImplicitWrapper { /** * @see _.isDate */ isDate(): boolean; } - interface LoDashExplicitWrapperBase { + interface LoDashExplicitWrapper { /** * @see _.isDate */ @@ -12310,14 +9400,14 @@ declare namespace _ { isElement(value?: any): boolean; } - interface LoDashImplicitWrapperBase { + interface LoDashImplicitWrapper { /** * @see _.isElement */ isElement(): boolean; } - interface LoDashExplicitWrapperBase { + interface LoDashExplicitWrapper { /** * @see _.isElement */ @@ -12336,14 +9426,14 @@ declare namespace _ { isEmpty(value?: any): boolean; } - interface LoDashImplicitWrapperBase { + interface LoDashImplicitWrapper { /** * @see _.isEmpty */ isEmpty(): boolean; } - interface LoDashExplicitWrapperBase { + interface LoDashExplicitWrapper { /** * @see _.isEmpty */ @@ -12385,7 +9475,7 @@ declare namespace _ { ): boolean; } - interface LoDashImplicitWrapperBase { + interface LoDashImplicitWrapper { /** * @see _.isEqual */ @@ -12394,7 +9484,7 @@ declare namespace _ { ): boolean; } - interface LoDashExplicitWrapperBase { + interface LoDashExplicitWrapper { /** * @see _.isEqual */ @@ -12445,7 +9535,7 @@ declare namespace _ { ): boolean; } - interface LoDashImplicitWrapperBase { + interface LoDashImplicitWrapper { /** * @see _.isEqualWith */ @@ -12455,7 +9545,7 @@ declare namespace _ { ): boolean; } - interface LoDashExplicitWrapperBase { + interface LoDashExplicitWrapper { /** * @see _.isEqualWith */ @@ -12477,14 +9567,14 @@ declare namespace _ { isError(value: any): value is Error; } - interface LoDashImplicitWrapperBase { + interface LoDashImplicitWrapper { /** * @see _.isError */ isError(): boolean; } - interface LoDashExplicitWrapperBase { + interface LoDashExplicitWrapper { /** * @see _.isError */ @@ -12504,14 +9594,14 @@ declare namespace _ { isFinite(value?: any): boolean; } - interface LoDashImplicitWrapperBase { + interface LoDashImplicitWrapper { /** * @see _.isFinite */ isFinite(): boolean; } - interface LoDashExplicitWrapperBase { + interface LoDashExplicitWrapper { /** * @see _.isFinite */ @@ -12526,17 +9616,17 @@ declare namespace _ { * @param value The value to check. * @return Returns true if value is correctly classified, else false. */ - isFunction(value?: any): value is Function; + isFunction(value?: any): value is ((...args: any[]) => any) | Function; } - interface LoDashImplicitWrapperBase { + interface LoDashImplicitWrapper { /** * @see _.isFunction */ isFunction(): boolean; } - interface LoDashExplicitWrapperBase { + interface LoDashExplicitWrapper { /** * @see _.isFunction */ @@ -12572,14 +9662,14 @@ declare namespace _ { isInteger(value?: any): boolean; } - interface LoDashImplicitWrapperBase { + interface LoDashImplicitWrapper { /** * @see _.isInteger */ isInteger(): boolean; } - interface LoDashExplicitWrapperBase { + interface LoDashExplicitWrapper { /** * @see _.isInteger */ @@ -12615,14 +9705,14 @@ declare namespace _ { isLength(value?: any): boolean; } - interface LoDashImplicitWrapperBase { + interface LoDashImplicitWrapper { /** * @see _.isLength */ isLength(): boolean; } - interface LoDashExplicitWrapperBase { + interface LoDashExplicitWrapper { /** * @see _.isLength */ @@ -12637,17 +9727,17 @@ declare namespace _ { * @param value The value to check. * @returns Returns true if value is correctly classified, else false. */ - isMap(value?: any): value is Map; + isMap(value?: any): value is Map; } - interface LoDashImplicitWrapperBase { + interface LoDashImplicitWrapper { /** * @see _.isMap */ isMap(): boolean; } - interface LoDashExplicitWrapperBase { + interface LoDashExplicitWrapper { /** * @see _.isMap */ @@ -12680,14 +9770,14 @@ declare namespace _ { * _.isMatch(object, { 'age': 36 }); * // => false */ - isMatch(object: Object, source: Object): boolean; + isMatch(object: object, source: object): boolean; } - interface LoDashImplicitObjectWrapper { + interface LoDashImplicitWrapper { /** * @see _.isMatch */ - isMatch(source: Object): boolean; + isMatch(source: object): boolean; } //_.isMatchWith @@ -12725,14 +9815,14 @@ declare namespace _ { * _.isMatchWith(object, source, customizer); * // => true */ - isMatchWith(object: Object, source: Object, customizer: isMatchWithCustomizer): boolean; + isMatchWith(object: object, source: object, customizer: isMatchWithCustomizer): boolean; } - interface LoDashImplicitObjectWrapper { + interface LoDashImplicitWrapper { /** * @see _.isMatchWith */ - isMatchWith(source: Object, customizer: isMatchWithCustomizer): boolean; + isMatchWith(source: object, customizer: isMatchWithCustomizer): boolean; } //_.isNaN @@ -12748,14 +9838,14 @@ declare namespace _ { isNaN(value?: any): boolean; } - interface LoDashImplicitWrapperBase { + interface LoDashImplicitWrapper { /** * @see _.isNaN */ isNaN(): boolean; } - interface LoDashExplicitWrapperBase { + interface LoDashExplicitWrapper { /** * @see _.isNaN */ @@ -12770,17 +9860,17 @@ declare namespace _ { * * @retrun Returns true if value is a native function, else false. */ - isNative(value: any): value is Function; + isNative(value: any): value is ((...args: any[]) => any) | Function; } - interface LoDashImplicitWrapperBase { + interface LoDashImplicitWrapper { /** * see _.isNative */ isNative(): boolean; } - interface LoDashExplicitWrapperBase { + interface LoDashExplicitWrapper { /** * see _.isNative */ @@ -12811,14 +9901,14 @@ declare namespace _ { isNil(value: any): value is null | undefined; } - interface LoDashImplicitWrapperBase { + interface LoDashImplicitWrapper { /** * see _.isNil */ isNil(): boolean; } - interface LoDashExplicitWrapperBase { + interface LoDashExplicitWrapper { /** * see _.isNil */ @@ -12836,14 +9926,14 @@ declare namespace _ { isNull(value: any): value is null; } - interface LoDashImplicitWrapperBase { + interface LoDashImplicitWrapper { /** * see _.isNull */ isNull(): boolean; } - interface LoDashExplicitWrapperBase { + interface LoDashExplicitWrapper { /** * see _.isNull */ @@ -12863,14 +9953,14 @@ declare namespace _ { isNumber(value?: any): value is number; } - interface LoDashImplicitWrapperBase { + interface LoDashImplicitWrapper { /** * see _.isNumber */ isNumber(): boolean; } - interface LoDashExplicitWrapperBase { + interface LoDashExplicitWrapper { /** * see _.isNumber */ @@ -12889,14 +9979,14 @@ declare namespace _ { isObject(value?: any): boolean; } - interface LoDashImplicitWrapperBase { + interface LoDashImplicitWrapper { /** * see _.isObject */ isObject(): boolean; } - interface LoDashExplicitWrapperBase { + interface LoDashExplicitWrapper { /** * see _.isObject */ @@ -12931,14 +10021,14 @@ declare namespace _ { isObjectLike(value?: any): boolean; } - interface LoDashImplicitWrapperBase { + interface LoDashImplicitWrapper { /** * see _.isObjectLike */ isObjectLike(): boolean; } - interface LoDashExplicitWrapperBase { + interface LoDashExplicitWrapper { /** * see _.isObjectLike */ @@ -12959,14 +10049,14 @@ declare namespace _ { isPlainObject(value?: any): boolean; } - interface LoDashImplicitWrapperBase { + interface LoDashImplicitWrapper { /** * see _.isPlainObject */ isPlainObject(): boolean; } - interface LoDashExplicitWrapperBase { + interface LoDashExplicitWrapper { /** * see _.isPlainObject */ @@ -12984,14 +10074,14 @@ declare namespace _ { isRegExp(value?: any): value is RegExp; } - interface LoDashImplicitWrapperBase { + interface LoDashImplicitWrapper { /** * see _.isRegExp */ isRegExp(): boolean; } - interface LoDashExplicitWrapperBase { + interface LoDashExplicitWrapper { /** * see _.isRegExp */ @@ -13028,14 +10118,14 @@ declare namespace _ { isSafeInteger(value: any): boolean; } - interface LoDashImplicitWrapperBase { + interface LoDashImplicitWrapper { /** * see _.isSafeInteger */ isSafeInteger(): boolean; } - interface LoDashExplicitWrapperBase { + interface LoDashExplicitWrapper { /** * see _.isSafeInteger */ @@ -13050,17 +10140,17 @@ declare namespace _ { * @param value The value to check. * @returns Returns true if value is correctly classified, else false. */ - isSet(value?: any): value is Set; + isSet(value?: any): value is Set; } - interface LoDashImplicitWrapperBase { + interface LoDashImplicitWrapper { /** * @see _.isSet */ isSet(): boolean; } - interface LoDashExplicitWrapperBase { + interface LoDashExplicitWrapper { /** * @see _.isSet */ @@ -13078,14 +10168,14 @@ declare namespace _ { isString(value?: any): value is string; } - interface LoDashImplicitWrapperBase { + interface LoDashImplicitWrapper { /** * see _.isString */ isString(): boolean; } - interface LoDashExplicitWrapperBase { + interface LoDashExplicitWrapper { /** * see _.isString */ @@ -13113,14 +10203,14 @@ declare namespace _ { isSymbol(value: any): boolean; } - interface LoDashImplicitWrapperBase { + interface LoDashImplicitWrapper { /** * see _.isSymbol */ isSymbol(): boolean; } - interface LoDashExplicitWrapperBase { + interface LoDashExplicitWrapper { /** * see _.isSymbol */ @@ -13138,14 +10228,14 @@ declare namespace _ { isTypedArray(value: any): boolean; } - interface LoDashImplicitWrapperBase { + interface LoDashImplicitWrapper { /** * see _.isTypedArray */ isTypedArray(): boolean; } - interface LoDashExplicitWrapperBase { + interface LoDashExplicitWrapper { /** * see _.isTypedArray */ @@ -13163,14 +10253,14 @@ declare namespace _ { isUndefined(value: any): value is undefined; } - interface LoDashImplicitWrapperBase { + interface LoDashImplicitWrapper { /** * see _.isUndefined */ isUndefined(): boolean; } - interface LoDashExplicitWrapperBase { + interface LoDashExplicitWrapper { /** * see _.isUndefined */ @@ -13185,17 +10275,17 @@ declare namespace _ { * @param value The value to check. * @returns Returns true if value is correctly classified, else false. */ - isWeakMap(value?: any): value is WeakMap; + isWeakMap(value?: any): value is WeakMap; } - interface LoDashImplicitWrapperBase { + interface LoDashImplicitWrapper { /** * @see _.isSet */ isWeakMap(): boolean; } - interface LoDashExplicitWrapperBase { + interface LoDashExplicitWrapper { /** * @see _.isSet */ @@ -13213,14 +10303,14 @@ declare namespace _ { isWeakSet(value?: any): value is WeakSet; } - interface LoDashImplicitWrapperBase { + interface LoDashImplicitWrapper { /** * @see _.isWeakSet */ isWeakSet(): boolean; } - interface LoDashExplicitWrapperBase { + interface LoDashExplicitWrapper { /** * @see _.isWeakSet */ @@ -13242,14 +10332,14 @@ declare namespace _ { ): boolean; } - interface LoDashImplicitWrapperBase { + interface LoDashImplicitWrapper { /** * @see _.lt */ lt(other: any): boolean; } - interface LoDashExplicitWrapperBase { + interface LoDashExplicitWrapper { /** * @see _.lt */ @@ -13271,14 +10361,14 @@ declare namespace _ { ): boolean; } - interface LoDashImplicitWrapperBase { + interface LoDashImplicitWrapper { /** * @see _.lte */ lte(other: any): boolean; } - interface LoDashExplicitWrapperBase { + interface LoDashExplicitWrapper { /** * @see _.lte */ @@ -13293,59 +10383,41 @@ declare namespace _ { * @param value The value to convert. * @return Returns the converted array. */ - toArray(value: List|Dictionary|NumericDictionary): T[]; + toArray(value: List | Dictionary | NumericDictionary | null | undefined): T[]; /** * @see _.toArray */ - toArray(value: TValue): TResult[]; + toArray(value: T): Array; /** * @see _.toArray */ - toArray(value?: any): TResult[]; + toArray(): any[]; } - interface LoDashImplicitWrapper { + interface LoDashImplicitWrapper { /** * @see _.toArray */ - toArray(): LoDashImplicitArrayWrapper; + toArray(this: LoDashImplicitWrapper | Dictionary | NumericDictionary | null | undefined>): LoDashImplicitWrapper; + + /** + * @see _.toArray + */ + toArray(): LoDashImplicitWrapper>; } - interface LoDashImplicitArrayWrapperBase { + interface LoDashExplicitWrapper { /** * @see _.toArray */ - toArray(): LoDashImplicitArrayWrapper; - } + toArray(this: LoDashExplicitWrapper | Dictionary | NumericDictionary | null | undefined>): LoDashExplicitWrapper; - interface LoDashImplicitObjectWrapperBase { /** * @see _.toArray */ - toArray(): LoDashImplicitArrayWrapper; - } - - interface LoDashExplicitWrapper { - /** - * @see _.toArray - */ - toArray(): LoDashExplicitArrayWrapper; - } - - interface LoDashExplicitArrayWrapperBase { - /** - * @see _.toArray - */ - toArray(): LoDashExplicitArrayWrapper; - } - - interface LoDashExplicitObjectWrapperBase { - /** - * @see _.toArray - */ - toArray(): LoDashExplicitArrayWrapper; + toArray(): LoDashExplicitWrapper>; } //_.toPlainObject @@ -13357,14 +10429,21 @@ declare namespace _ { * @param value The value to convert. * @return Returns the converted plain object. */ - toPlainObject(value?: any): TResult; + toPlainObject(value?: any): any; } - interface LoDashImplicitWrapperBase { + interface LoDashImplicitWrapper { /** * @see _.toPlainObject */ - toPlainObject(): LoDashImplicitObjectWrapper; + toPlainObject(): LoDashImplicitWrapper; + } + + interface LoDashExplicitWrapper { + /** + * @see _.toPlainObject + */ + toPlainObject(): LoDashExplicitWrapper; } //_.toFinite @@ -13395,14 +10474,14 @@ declare namespace _ { toFinite(value: any): number; } - interface LoDashImplicitWrapperBase { + interface LoDashImplicitWrapper { /** * @see _.toFinite */ - toFinite(): LoDashImplicitWrapper; + toFinite(): number; } - interface LoDashExplicitWrapperBase { + interface LoDashExplicitWrapper { /** * @see _.toFinite */ @@ -13438,14 +10517,14 @@ declare namespace _ { toInteger(value: any): number; } - interface LoDashImplicitWrapperBase { + interface LoDashImplicitWrapper { /** * @see _.toInteger */ - toInteger(): LoDashImplicitWrapper; + toInteger(): number; } - interface LoDashExplicitWrapperBase { + interface LoDashExplicitWrapper { /** * @see _.toInteger */ @@ -13482,14 +10561,14 @@ declare namespace _ { toLength(value: any): number; } - interface LoDashImplicitWrapperBase { + interface LoDashImplicitWrapper { /** * @see _.toLength */ - toLength(): LoDashImplicitWrapper; + toLength(): number; } - interface LoDashExplicitWrapperBase { + interface LoDashExplicitWrapper { /** * @see _.toLength */ @@ -13523,14 +10602,14 @@ declare namespace _ { toNumber(value: any): number; } - interface LoDashImplicitWrapperBase { + interface LoDashImplicitWrapper { /** * @see _.toNumber */ - toNumber(): LoDashImplicitWrapper; + toNumber(): number; } - interface LoDashExplicitWrapperBase { + interface LoDashExplicitWrapper { /** * @see _.toNumber */ @@ -13565,21 +10644,21 @@ declare namespace _ { toSafeInteger(value: any): number; } - interface LoDashImplicitWrapperBase { + interface LoDashImplicitWrapper { /** * @see _.toSafeInteger */ - toSafeInteger(): LoDashImplicitWrapper; + toSafeInteger(): number; } - interface LoDashExplicitWrapperBase { + interface LoDashExplicitWrapper { /** * @see _.toSafeInteger */ toSafeInteger(): LoDashExplicitWrapper; } - //_.toString DUMMY + //_.toString interface LoDashStatic { /** * Converts `value` to a string if it's not one. An empty string is returned @@ -13623,14 +10702,14 @@ declare namespace _ { ): number; } - interface LoDashImplicitWrapper { + interface LoDashImplicitWrapper { /** * @see _.add */ add(addend: number): number; } - interface LoDashExplicitWrapper { + interface LoDashExplicitWrapper { /** * @see _.add */ @@ -13652,14 +10731,14 @@ declare namespace _ { ): number; } - interface LoDashImplicitWrapper { + interface LoDashImplicitWrapper { /** * @see _.ceil */ ceil(precision?: number): number; } - interface LoDashExplicitWrapper { + interface LoDashExplicitWrapper { /** * @see _.ceil */ @@ -13681,14 +10760,14 @@ declare namespace _ { ): number; } - interface LoDashImplicitWrapper { + interface LoDashImplicitWrapper { /** * @see _.divide */ divide(divisor: number): number; } - interface LoDashExplicitWrapper { + interface LoDashExplicitWrapper { /** * @see _.divide */ @@ -13710,14 +10789,14 @@ declare namespace _ { ): number; } - interface LoDashImplicitWrapper { + interface LoDashImplicitWrapper { /** * @see _.floor */ floor(precision?: number): number; } - interface LoDashExplicitWrapper { + interface LoDashExplicitWrapper { /** * @see _.floor */ @@ -13741,18 +10820,18 @@ declare namespace _ { ): T | undefined; } - interface LoDashImplicitArrayWrapperBase { + interface LoDashImplicitWrapper { /** * @see _.max */ - max(): T | undefined; + max(this: LoDashImplicitWrapper | null | undefined>): T | undefined; } - interface LoDashImplicitObjectWrapperBase { + interface LoDashExplicitWrapper { /** * @see _.max */ - max(): T | undefined; + max(this: LoDashExplicitWrapper | null | undefined>): LoDashExplicitWrapper; } //_.maxBy @@ -13781,78 +10860,28 @@ declare namespace _ { */ maxBy( collection: List | null | undefined, - iteratee?: ListIterator - ): T | undefined; - - /** - * @see _.maxBy - */ - maxBy( - collection: Dictionary | null | undefined, - iteratee?: DictionaryIterator - ): T | undefined; - - /** - * @see _.maxBy - */ - maxBy( - collection: List|Dictionary | null | undefined, - iteratee?: string - ): T | undefined; - - /** - * @see _.maxBy - */ - maxBy( - collection: List|Dictionary | null | undefined, - whereValue?: TObject + iteratee?: ListIteratee ): T | undefined; } - interface LoDashImplicitArrayWrapperBase { + interface LoDashImplicitWrapper { /** * @see _.maxBy */ - maxBy( - iteratee?: ListIterator - ): T | undefined; - - /** - * @see _.maxBy - */ - maxBy( - iteratee?: string - ): T | undefined; - - /** - * @see _.maxBy - */ - maxBy( - whereValue?: TObject + maxBy( + this: LoDashImplicitWrapper | null | undefined>, + iteratee?: ListIteratee ): T | undefined; } - interface LoDashImplicitObjectWrapperBase { + interface LoDashExplicitWrapper { /** * @see _.maxBy */ maxBy( - iteratee?: ListIterator|DictionaryIterator - ): T | undefined; - - /** - * @see _.maxBy - */ - maxBy( - iteratee?: string - ): T | undefined; - - /** - * @see _.maxBy - */ - maxBy( - whereValue?: TObject - ): T | undefined; + this: LoDashExplicitWrapper | null | undefined>, + iteratee?: ListIteratee + ): LoDashExplicitWrapper; } //_.mean @@ -13870,11 +10899,25 @@ declare namespace _ { * _.mean([4, 2, 8, 6]); * // => 5 */ - mean( - collection: List | null | undefined + mean( + collection: List | null | undefined ): number; } + interface LoDashImplicitWrapper { + /** + * @see _.mean + */ + mean(): number; + } + + interface LoDashExplicitWrapper { + /** + * @see _.mean + */ + mean(): LoDashExplicitWrapper; + } + //_.meanBy interface LoDashStatic { /** @@ -13891,27 +10934,30 @@ declare namespace _ { * _.mean([{ 'n': 4 }, { 'n': 2 }, { 'n': 8 }, { 'n': 6 }], 'n'); * // => 5 */ - meanBy( - collection: List | null | undefined, - iteratee?: ListIterator | string - ): number; - - meanBy( - collection: Dictionary | null | undefined, - iteratee?: DictionaryIterator | string - ): number; + meanBy( + collection: List | null | undefined, + iteratee?: ListIteratee + ): number; } - interface LoDashImplicitArrayWrapperBase { + interface LoDashImplicitWrapper { /** - * @see _.mean + * @see _.meanBy */ - mean(): number; + meanBy( + this: LoDashImplicitWrapper | null | undefined>, + iteratee?: ListIteratee + ): number; + } + interface LoDashExplicitWrapper { /** - * @see _.mean + * @see _.meanBy */ - mean(): number; + meanBy( + this: LoDashExplicitWrapper | null | undefined>, + iteratee?: ListIteratee + ): LoDashExplicitWrapper; } //_.min @@ -13931,18 +10977,18 @@ declare namespace _ { ): T | undefined; } - interface LoDashImplicitArrayWrapperBase { + interface LoDashImplicitWrapper { /** * @see _.min */ - min(): T | undefined; + min(this: LoDashImplicitWrapper | null | undefined>): T | undefined; } - interface LoDashImplicitObjectWrapperBase { + interface LoDashExplicitWrapper { /** * @see _.min */ - min(): T | undefined; + min(this: LoDashExplicitWrapper | null | undefined>): LoDashExplicitWrapper; } //_.minBy @@ -13971,78 +11017,28 @@ declare namespace _ { */ minBy( collection: List | null | undefined, - iteratee?: ListIterator - ): T | undefined; - - /** - * @see _.minBy - */ - minBy( - collection: Dictionary | null | undefined, - iteratee?: DictionaryIterator - ): T | undefined; - - /** - * @see _.minBy - */ - minBy( - collection: List|Dictionary | null | undefined, - iteratee?: string - ): T | undefined; - - /** - * @see _.minBy - */ - minBy( - collection: List|Dictionary | null | undefined, - whereValue?: TObject + iteratee?: ListIteratee ): T | undefined; } - interface LoDashImplicitArrayWrapperBase { + interface LoDashImplicitWrapper { /** * @see _.minBy */ - minBy( - iteratee?: ListIterator - ): T | undefined; - - /** - * @see _.minBy - */ - minBy( - iteratee?: string - ): T | undefined; - - /** - * @see _.minBy - */ - minBy( - whereValue?: TObject + minBy( + this: LoDashImplicitWrapper | null | undefined>, + iteratee?: ListIteratee ): T | undefined; } - interface LoDashImplicitObjectWrapperBase { + interface LoDashExplicitWrapper { /** * @see _.minBy */ minBy( - iteratee?: ListIterator|DictionaryIterator - ): T | undefined; - - /** - * @see _.minBy - */ - minBy( - iteratee?: string - ): T | undefined; - - /** - * @see _.minBy - */ - minBy( - whereValue?: TObject - ): T | undefined; + this: LoDashExplicitWrapper | null | undefined>, + iteratee?: ListIteratee + ): LoDashExplicitWrapper; } //_.multiply @@ -14059,14 +11055,14 @@ declare namespace _ { ): number; } - interface LoDashImplicitWrapper { + interface LoDashImplicitWrapper { /** * @see _.multiply */ multiply(multiplicand: number): number; } - interface LoDashExplicitWrapper { + interface LoDashExplicitWrapper { /** * @see _.multiply */ @@ -14088,14 +11084,14 @@ declare namespace _ { ): number; } - interface LoDashImplicitWrapper { + interface LoDashImplicitWrapper { /** * @see _.round */ round(precision?: number): number; } - interface LoDashExplicitWrapper { + interface LoDashExplicitWrapper { /** * @see _.round */ @@ -14117,46 +11113,17 @@ declare namespace _ { * _.sum([4, 2, 8, 6]); * // => 20 */ - sum(collection: List | null | undefined): number; - - /** - * @see _.sum - */ - sum(collection: List|Dictionary | null | undefined): number; + sum(collection: List | null | undefined): number; } - interface LoDashImplicitArrayWrapperBase { + interface LoDashImplicitWrapper { /** * @see _.sum */ sum(): number; } - interface LoDashImplicitObjectWrapperBase { - /** - * @see _.sum - **/ - sum(): number; - - /** - * @see _.sum - */ - sum(): number; - } - - interface LoDashExplicitArrayWrapperBase { - /** - * @see _.sum - */ - sum(): LoDashExplicitWrapper; - } - - interface LoDashExplicitObjectWrapperBase { - /** - * @see _.sum - */ - sum(): LoDashExplicitWrapper; - + interface LoDashExplicitWrapper { /** * @see _.sum */ @@ -14189,112 +11156,28 @@ declare namespace _ { */ sumBy( collection: List | null | undefined, - iteratee: ListIterator - ): number; - - /** - * @see _.sumBy - */ - sumBy( - collection: List<{}> | null | undefined, - iteratee: string - ): number; - - /** - * @see _.sumBy - */ - sumBy( - collection: List | null | undefined - ): number; - - /** - * @see _.sumBy - */ - sumBy( - collection: List<{}> | null | undefined, - iteratee: Dictionary<{}> + iteratee?: ((value: T) => number) | string ): number; } - interface LoDashImplicitArrayWrapperBase { + interface LoDashImplicitWrapper { /** * @see _.sumBy */ - sumBy( - iteratee: ListIterator + sumBy( + this: LoDashImplicitWrapper | null | undefined>, + iteratee?: ((value: T) => number) | string ): number; - - /** - * @see _.sumBy - */ - sumBy(iteratee: string): number; - - /** - * @see _.sumBy - */ - sumBy(iteratee: Dictionary<{}>): number; } - interface LoDashImplicitObjectWrapperBase { + interface LoDashExplicitWrapper { /** * @see _.sumBy */ - sumBy( - iteratee: ListIterator - ): number; - - /** - * @see _.sumBy - */ - sumBy(iteratee: string): number; - - /** - * @see _.sumBy - */ - sumBy(iteratee: Dictionary<{}>): number; - } - - interface LoDashExplicitArrayWrapperBase { - /** - * @see _.sumBy - */ - sumBy( - iteratee: ListIterator + sumBy( + this: LoDashExplicitWrapper | null | undefined>, + iteratee?: ((value: T) => number) | string ): LoDashExplicitWrapper; - - /** - * @see _.sumBy - */ - sumBy(iteratee: string): LoDashExplicitWrapper; - - /** - * @see _.sumBy - */ - sumBy(): LoDashExplicitWrapper; - - /** - * @see _.sumBy - */ - sumBy(iteratee: Dictionary<{}>): LoDashExplicitWrapper; - } - - interface LoDashExplicitObjectWrapperBase { - /** - * @see _.sumBy - */ - sumBy( - iteratee: ListIterator - ): LoDashExplicitWrapper; - - /** - * @see _.sumBy - */ - sumBy(iteratee: string): LoDashExplicitWrapper; - - /** - * @see _.sumBy - */ - sumBy(iteratee: Dictionary<{}>): LoDashExplicitWrapper; } /********** @@ -14323,7 +11206,7 @@ declare namespace _ { ): number; } - interface LoDashImplicitWrapper { + interface LoDashImplicitWrapper { /** * @see _.subtract */ @@ -14332,7 +11215,7 @@ declare namespace _ { ): number; } - interface LoDashExplicitWrapper { + interface LoDashExplicitWrapper { /** * @see _.subtract */ @@ -14368,7 +11251,7 @@ declare namespace _ { ): number; } - interface LoDashImplicitWrapper { + interface LoDashImplicitWrapper { /** * @see _.clamp */ @@ -14378,7 +11261,7 @@ declare namespace _ { ): number; } - interface LoDashExplicitWrapper { + interface LoDashExplicitWrapper { /** * @see _.clamp */ @@ -14402,46 +11285,28 @@ declare namespace _ { inRange( n: number, start: number, - end: number - ): boolean; - - /** - * @see _.inRange - */ - inRange( - n: number, - end: number + end?: number ): boolean; } - interface LoDashImplicitWrapper { + interface LoDashImplicitWrapper { /** * @see _.inRange */ inRange( start: number, - end: number + end?: number ): boolean; - - /** - * @see _.inRange - */ - inRange(end: number): boolean; } - interface LoDashExplicitWrapper { + interface LoDashExplicitWrapper { /** * @see _.inRange */ inRange( start: number, - end: number + end?: number ): LoDashExplicitWrapper; - - /** - * @see _.inRange - */ - inRange(end: number): LoDashExplicitWrapper; } //_.random @@ -14476,7 +11341,7 @@ declare namespace _ { random(floating?: boolean): number; } - interface LoDashImplicitWrapper { + interface LoDashImplicitWrapper { /** * @see _.random */ @@ -14491,7 +11356,7 @@ declare namespace _ { random(floating?: boolean): number; } - interface LoDashExplicitWrapper { + interface LoDashExplicitWrapper { /** * @see _.random */ @@ -14585,19 +11450,19 @@ declare namespace _ { /** * @see _.assign */ - assign( + assign( object: any, ...otherArgs: any[] - ): TResult; + ): any; } - interface LoDashImplicitObjectWrapper { + interface LoDashImplicitWrapper { /** * @see _.assign */ assign( source: TSource - ): LoDashImplicitObjectWrapper; + ): LoDashImplicitWrapper; /** * @see assign @@ -14605,7 +11470,7 @@ declare namespace _ { assign( source1: TSource1, source2: TSource2 - ): LoDashImplicitObjectWrapper; + ): LoDashImplicitWrapper; /** * @see assign @@ -14614,7 +11479,7 @@ declare namespace _ { source1: TSource1, source2: TSource2, source3: TSource3 - ): LoDashImplicitObjectWrapper; + ): LoDashImplicitWrapper; /** * @see assign @@ -14624,26 +11489,26 @@ declare namespace _ { source2: TSource2, source3: TSource3, source4: TSource4 - ): LoDashImplicitObjectWrapper; + ): LoDashImplicitWrapper; /** * @see _.assign */ - assign(): LoDashImplicitObjectWrapper; + assign(): LoDashImplicitWrapper; /** * @see _.assign */ - assign(...otherArgs: any[]): LoDashImplicitObjectWrapper; + assign(...otherArgs: any[]): LoDashImplicitWrapper; } - interface LoDashExplicitObjectWrapper { + interface LoDashExplicitWrapper { /** * @see _.assign */ assign( source: TSource - ): LoDashExplicitObjectWrapper; + ): LoDashExplicitWrapper; /** * @see assign @@ -14651,7 +11516,7 @@ declare namespace _ { assign( source1: TSource1, source2: TSource2 - ): LoDashExplicitObjectWrapper; + ): LoDashExplicitWrapper; /** * @see assign @@ -14660,7 +11525,7 @@ declare namespace _ { source1: TSource1, source2: TSource2, source3: TSource3 - ): LoDashExplicitObjectWrapper; + ): LoDashExplicitWrapper; /** * @see assign @@ -14670,17 +11535,17 @@ declare namespace _ { source2: TSource2, source3: TSource3, source4: TSource4 - ): LoDashExplicitObjectWrapper; + ): LoDashExplicitWrapper; /** * @see _.assign */ - assign(): LoDashExplicitObjectWrapper; + assign(): LoDashExplicitWrapper; /** * @see _.assign */ - assign(...otherArgs: any[]): LoDashExplicitObjectWrapper; + assign(...otherArgs: any[]): LoDashExplicitWrapper; } interface LoDashStatic { @@ -14763,14 +11628,14 @@ declare namespace _ { ): TResult; } - interface LoDashImplicitObjectWrapper { + interface LoDashImplicitWrapper { /** * @see _.assignWith */ assignWith( source: TSource, customizer: AssignCustomizer - ): LoDashImplicitObjectWrapper; + ): LoDashImplicitWrapper; /** * @see assignWith @@ -14779,7 +11644,7 @@ declare namespace _ { source1: TSource1, source2: TSource2, customizer: AssignCustomizer - ): LoDashImplicitObjectWrapper; + ): LoDashImplicitWrapper; /** * @see assignWith @@ -14789,7 +11654,7 @@ declare namespace _ { source2: TSource2, source3: TSource3, customizer: AssignCustomizer - ): LoDashImplicitObjectWrapper; + ): LoDashImplicitWrapper; /** * @see assignWith @@ -14800,27 +11665,27 @@ declare namespace _ { source3: TSource3, source4: TSource4, customizer: AssignCustomizer - ): LoDashImplicitObjectWrapper; + ): LoDashImplicitWrapper; /** * @see _.assignWith */ - assignWith(): LoDashImplicitObjectWrapper; + assignWith(): LoDashImplicitWrapper; /** * @see _.assignWith */ - assignWith(...otherArgs: any[]): LoDashImplicitObjectWrapper; + assignWith(...otherArgs: any[]): LoDashImplicitWrapper; } - interface LoDashExplicitObjectWrapper { + interface LoDashExplicitWrapper { /** * @see _.assignWith */ assignWith( source: TSource, customizer: AssignCustomizer - ): LoDashExplicitObjectWrapper; + ): LoDashExplicitWrapper; /** * @see assignWith @@ -14829,7 +11694,7 @@ declare namespace _ { source1: TSource1, source2: TSource2, customizer: AssignCustomizer - ): LoDashExplicitObjectWrapper; + ): LoDashExplicitWrapper; /** * @see assignWith @@ -14839,7 +11704,7 @@ declare namespace _ { source2: TSource2, source3: TSource3, customizer: AssignCustomizer - ): LoDashExplicitObjectWrapper; + ): LoDashExplicitWrapper; /** * @see assignWith @@ -14850,17 +11715,17 @@ declare namespace _ { source3: TSource3, source4: TSource4, customizer: AssignCustomizer - ): LoDashExplicitObjectWrapper; + ): LoDashExplicitWrapper; /** * @see _.assignWith */ - assignWith(): LoDashExplicitObjectWrapper; + assignWith(): LoDashExplicitWrapper; /** * @see _.assignWith */ - assignWith(...otherArgs: any[]): LoDashExplicitObjectWrapper; + assignWith(...otherArgs: any[]): LoDashExplicitWrapper; } //_.assignIn @@ -14943,13 +11808,13 @@ declare namespace _ { ): TResult; } - interface LoDashImplicitObjectWrapper { + interface LoDashImplicitWrapper { /** * @see _.assignIn */ assignIn( source: TSource - ): LoDashImplicitObjectWrapper; + ): LoDashImplicitWrapper; /** * @see assignIn @@ -14957,7 +11822,7 @@ declare namespace _ { assignIn( source1: TSource1, source2: TSource2 - ): LoDashImplicitObjectWrapper; + ): LoDashImplicitWrapper; /** * @see assignIn @@ -14966,7 +11831,7 @@ declare namespace _ { source1: TSource1, source2: TSource2, source3: TSource3 - ): LoDashImplicitObjectWrapper; + ): LoDashImplicitWrapper; /** * @see assignIn @@ -14976,26 +11841,26 @@ declare namespace _ { source2: TSource2, source3: TSource3, source4: TSource4 - ): LoDashImplicitObjectWrapper; + ): LoDashImplicitWrapper; /** * @see _.assignIn */ - assignIn(): LoDashImplicitObjectWrapper; + assignIn(): LoDashImplicitWrapper; /** * @see _.assignIn */ - assignIn(...otherArgs: any[]): LoDashImplicitObjectWrapper; + assignIn(...otherArgs: any[]): LoDashImplicitWrapper; } - interface LoDashExplicitObjectWrapper { + interface LoDashExplicitWrapper { /** * @see _.assignIn */ assignIn( source: TSource - ): LoDashExplicitObjectWrapper; + ): LoDashExplicitWrapper; /** * @see assignIn @@ -15003,7 +11868,7 @@ declare namespace _ { assignIn( source1: TSource1, source2: TSource2 - ): LoDashExplicitObjectWrapper; + ): LoDashExplicitWrapper; /** * @see assignIn @@ -15012,7 +11877,7 @@ declare namespace _ { source1: TSource1, source2: TSource2, source3: TSource3 - ): LoDashExplicitObjectWrapper; + ): LoDashExplicitWrapper; /** * @see assignIn @@ -15022,17 +11887,17 @@ declare namespace _ { source2: TSource2, source3: TSource3, source4: TSource4 - ): LoDashExplicitObjectWrapper; + ): LoDashExplicitWrapper; /** * @see _.assignIn */ - assignIn(): LoDashExplicitObjectWrapper; + assignIn(): LoDashExplicitWrapper; /** * @see _.assignIn */ - assignIn(...otherArgs: any[]): LoDashExplicitObjectWrapper; + assignIn(...otherArgs: any[]): LoDashExplicitWrapper; } //_.assignInWith @@ -15119,14 +11984,14 @@ declare namespace _ { ): TResult; } - interface LoDashImplicitObjectWrapper { + interface LoDashImplicitWrapper { /** * @see _.assignInWith */ assignInWith( source: TSource, customizer: AssignCustomizer - ): LoDashImplicitObjectWrapper; + ): LoDashImplicitWrapper; /** * @see assignInWith @@ -15135,7 +12000,7 @@ declare namespace _ { source1: TSource1, source2: TSource2, customizer: AssignCustomizer - ): LoDashImplicitObjectWrapper; + ): LoDashImplicitWrapper; /** * @see assignInWith @@ -15145,7 +12010,7 @@ declare namespace _ { source2: TSource2, source3: TSource3, customizer: AssignCustomizer - ): LoDashImplicitObjectWrapper; + ): LoDashImplicitWrapper; /** * @see assignInWith @@ -15156,27 +12021,27 @@ declare namespace _ { source3: TSource3, source4: TSource4, customizer: AssignCustomizer - ): LoDashImplicitObjectWrapper; + ): LoDashImplicitWrapper; /** * @see _.assignInWith */ - assignInWith(): LoDashImplicitObjectWrapper; + assignInWith(): LoDashImplicitWrapper; /** * @see _.assignInWith */ - assignInWith(...otherArgs: any[]): LoDashImplicitObjectWrapper; + assignInWith(...otherArgs: any[]): LoDashImplicitWrapper; } - interface LoDashExplicitObjectWrapper { + interface LoDashExplicitWrapper { /** * @see _.assignInWith */ assignInWith( source: TSource, customizer: AssignCustomizer - ): LoDashExplicitObjectWrapper; + ): LoDashExplicitWrapper; /** * @see assignInWith @@ -15185,7 +12050,7 @@ declare namespace _ { source1: TSource1, source2: TSource2, customizer: AssignCustomizer - ): LoDashExplicitObjectWrapper; + ): LoDashExplicitWrapper; /** * @see assignInWith @@ -15195,7 +12060,7 @@ declare namespace _ { source2: TSource2, source3: TSource3, customizer: AssignCustomizer - ): LoDashExplicitObjectWrapper; + ): LoDashExplicitWrapper; /** * @see assignInWith @@ -15206,17 +12071,17 @@ declare namespace _ { source3: TSource3, source4: TSource4, customizer: AssignCustomizer - ): LoDashExplicitObjectWrapper; + ): LoDashExplicitWrapper; /** * @see _.assignInWith */ - assignInWith(): LoDashExplicitObjectWrapper; + assignInWith(): LoDashExplicitWrapper; /** * @see _.assignInWith */ - assignInWith(...otherArgs: any[]): LoDashExplicitObjectWrapper; + assignInWith(...otherArgs: any[]): LoDashExplicitWrapper; } //_.create @@ -15229,24 +12094,24 @@ declare namespace _ { * @param properties The properties to assign to the object. * @return Returns the new object. */ - create( + create( prototype: T, properties?: U ): T & U; } - interface LoDashImplicitObjectWrapper { + interface LoDashImplicitWrapper { /** * @see _.create */ - create(properties?: U): LoDashImplicitObjectWrapper; + create(properties?: U): LoDashImplicitWrapper; } - interface LoDashExplicitObjectWrapper { + interface LoDashExplicitWrapper { /** * @see _.create */ - create(properties?: U): LoDashExplicitObjectWrapper; + create(properties?: U): LoDashExplicitWrapper; } //_.defaults @@ -15305,19 +12170,19 @@ declare namespace _ { /** * @see _.defaults */ - defaults( + defaults( object: any, ...sources: any[] - ): TResult; + ): any; } - interface LoDashImplicitObjectWrapper { + interface LoDashImplicitWrapper { /** * @see _.defaults */ defaults( source: TSource - ): LoDashImplicitObjectWrapper; + ): LoDashImplicitWrapper; /** * @see _.defaults @@ -15325,7 +12190,7 @@ declare namespace _ { defaults( source1: TSource1, source2: TSource2 - ): LoDashImplicitObjectWrapper; + ): LoDashImplicitWrapper; /** * @see _.defaults @@ -15334,7 +12199,7 @@ declare namespace _ { source1: TSource1, source2: TSource2, source3: TSource3 - ): LoDashImplicitObjectWrapper; + ): LoDashImplicitWrapper; /** * @see _.defaults @@ -15344,26 +12209,26 @@ declare namespace _ { source2: TSource2, source3: TSource3, source4: TSource4 - ): LoDashImplicitObjectWrapper; + ): LoDashImplicitWrapper; /** * @see _.defaults */ - defaults(): LoDashImplicitObjectWrapper; + defaults(): LoDashImplicitWrapper; /** * @see _.defaults */ - defaults(...sources: any[]): LoDashImplicitObjectWrapper; + defaults(...sources: any[]): LoDashImplicitWrapper; } - interface LoDashExplicitObjectWrapper { + interface LoDashExplicitWrapper { /** * @see _.defaults */ defaults( source: TSource - ): LoDashExplicitObjectWrapper; + ): LoDashExplicitWrapper; /** * @see _.defaults @@ -15371,7 +12236,7 @@ declare namespace _ { defaults( source1: TSource1, source2: TSource2 - ): LoDashExplicitObjectWrapper; + ): LoDashExplicitWrapper; /** * @see _.defaults @@ -15380,7 +12245,7 @@ declare namespace _ { source1: TSource1, source2: TSource2, source3: TSource3 - ): LoDashExplicitObjectWrapper; + ): LoDashExplicitWrapper; /** * @see _.defaults @@ -15390,17 +12255,17 @@ declare namespace _ { source2: TSource2, source3: TSource3, source4: TSource4 - ): LoDashExplicitObjectWrapper; + ): LoDashExplicitWrapper; /** * @see _.defaults */ - defaults(): LoDashExplicitObjectWrapper; + defaults(): LoDashExplicitWrapper; /** * @see _.defaults */ - defaults(...sources: any[]): LoDashExplicitObjectWrapper; + defaults(...sources: any[]): LoDashExplicitWrapper; } //_.defaultsDeep @@ -15411,16 +12276,23 @@ declare namespace _ { * @param sources The source objects. * @return Returns object. **/ - defaultsDeep( - object: T, - ...sources: any[]): TResult; + defaultsDeep( + object: any, + ...sources: any[]): any; } - interface LoDashImplicitObjectWrapper { + interface LoDashImplicitWrapper { /** * @see _.defaultsDeep **/ - defaultsDeep(...sources: any[]): LoDashImplicitObjectWrapper; + defaultsDeep(...sources: any[]): LoDashImplicitWrapper; + } + + interface LoDashExplicitWrapper { + /** + * @see _.defaultsDeep + **/ + defaultsDeep(...sources: any[]): LoDashExplicitWrapper; } //_.entries @@ -15428,23 +12300,36 @@ declare namespace _ { /** * @see _.toPairs */ - entries(object?: T): [string, any][]; + entries(object?: Dictionary): Array<[string, T]>; - entries(object?: T): [string, TResult][]; - } - - interface LoDashImplicitObjectWrapper { /** * @see _.toPairs */ - entries(): LoDashImplicitArrayWrapper<[string, TResult]>; + entries(object?: object): Array<[string, any]>; } - interface LoDashExplicitObjectWrapper { + interface LoDashImplicitWrapper { /** * @see _.toPairs */ - entries(): LoDashExplicitArrayWrapper<[string, TResult]>; + entries(this: LoDashImplicitWrapper>): LoDashImplicitWrapper>; + + /** + * @see _.toPairs + */ + entries(): LoDashImplicitWrapper>; + } + + interface LoDashExplicitWrapper { + /** + * @see _.toPairs + */ + entries(this: LoDashExplicitWrapper>): LoDashExplicitWrapper>; + + /** + * @see _.toPairs + */ + entries(): LoDashExplicitWrapper>; } //_.entriesIn @@ -15452,23 +12337,36 @@ declare namespace _ { /** * @see _.toPairsIn */ - entriesIn(object?: T): [string, any][]; + entriesIn(object?: Dictionary): Array<[string, T]>; - entriesIn(object?: T): [string, TResult][]; - } - - interface LoDashImplicitObjectWrapper { /** * @see _.toPairsIn */ - entriesIn(): LoDashImplicitArrayWrapper<[string, TResult]>; + entriesIn(object?: object): Array<[string, any]>; } - interface LoDashExplicitObjectWrapper { + interface LoDashImplicitWrapper { /** * @see _.toPairsIn */ - entriesIn(): LoDashExplicitArrayWrapper<[string, TResult]>; + entriesIn(this: LoDashImplicitWrapper>): LoDashImplicitWrapper>; + + /** + * @see _.toPairsIn + */ + entriesIn(): LoDashImplicitWrapper>; + } + + interface LoDashExplicitWrapper { + /** + * @see _.toPairsIn + */ + entriesIn(this: LoDashExplicitWrapper>): LoDashExplicitWrapper>; + + /** + * @see _.toPairsIn + */ + entriesIn(): LoDashExplicitWrapper>; } // _.extend @@ -15525,13 +12423,13 @@ declare namespace _ { ): TResult; } - interface LoDashImplicitObjectWrapper { + interface LoDashImplicitWrapper { /** * @see _.assignIn */ extend( source: TSource - ): LoDashImplicitObjectWrapper; + ): LoDashImplicitWrapper; /** * @see _.assignIn @@ -15539,7 +12437,7 @@ declare namespace _ { extend( source1: TSource1, source2: TSource2 - ): LoDashImplicitObjectWrapper; + ): LoDashImplicitWrapper; /** * @see _.assignIn @@ -15548,7 +12446,7 @@ declare namespace _ { source1: TSource1, source2: TSource2, source3: TSource3 - ): LoDashImplicitObjectWrapper; + ): LoDashImplicitWrapper; /** * @see _.assignIn @@ -15558,26 +12456,26 @@ declare namespace _ { source2: TSource2, source3: TSource3, source4: TSource4 - ): LoDashImplicitObjectWrapper; + ): LoDashImplicitWrapper; /** * @see _.assignIn */ - extend(): LoDashImplicitObjectWrapper; + extend(): LoDashImplicitWrapper; /** * @see _.assignIn */ - extend(...otherArgs: any[]): LoDashImplicitObjectWrapper; + extend(...otherArgs: any[]): LoDashImplicitWrapper; } - interface LoDashExplicitObjectWrapper { + interface LoDashExplicitWrapper { /** * @see _.assignIn */ extend( source: TSource - ): LoDashExplicitObjectWrapper; + ): LoDashExplicitWrapper; /** * @see _.assignIn @@ -15585,7 +12483,7 @@ declare namespace _ { extend( source1: TSource1, source2: TSource2 - ): LoDashExplicitObjectWrapper; + ): LoDashExplicitWrapper; /** * @see _.assignIn @@ -15594,7 +12492,7 @@ declare namespace _ { source1: TSource1, source2: TSource2, source3: TSource3 - ): LoDashExplicitObjectWrapper; + ): LoDashExplicitWrapper; /** * @see _.assignIn @@ -15604,17 +12502,17 @@ declare namespace _ { source2: TSource2, source3: TSource3, source4: TSource4 - ): LoDashExplicitObjectWrapper; + ): LoDashExplicitWrapper; /** * @see _.assignIn */ - extend(): LoDashExplicitObjectWrapper; + extend(): LoDashExplicitWrapper; /** * @see _.assignIn */ - extend(...otherArgs: any[]): LoDashExplicitObjectWrapper; + extend(...otherArgs: any[]): LoDashExplicitWrapper; } interface LoDashStatic { @@ -15674,14 +12572,14 @@ declare namespace _ { ): TResult; } - interface LoDashImplicitObjectWrapper { + interface LoDashImplicitWrapper { /** * @see _.assignInWith */ extendWith( source: TSource, customizer: AssignCustomizer - ): LoDashImplicitObjectWrapper; + ): LoDashImplicitWrapper; /** * @see _.assignInWith @@ -15690,7 +12588,7 @@ declare namespace _ { source1: TSource1, source2: TSource2, customizer: AssignCustomizer - ): LoDashImplicitObjectWrapper; + ): LoDashImplicitWrapper; /** * @see _.assignInWith @@ -15700,7 +12598,7 @@ declare namespace _ { source2: TSource2, source3: TSource3, customizer: AssignCustomizer - ): LoDashImplicitObjectWrapper; + ): LoDashImplicitWrapper; /** * @see _.assignInWith @@ -15711,27 +12609,27 @@ declare namespace _ { source3: TSource3, source4: TSource4, customizer: AssignCustomizer - ): LoDashImplicitObjectWrapper; + ): LoDashImplicitWrapper; /** * @see _.assignInWith */ - extendWith(): LoDashImplicitObjectWrapper; + extendWith(): LoDashImplicitWrapper; /** * @see _.assignInWith */ - extendWith(...otherArgs: any[]): LoDashImplicitObjectWrapper; + extendWith(...otherArgs: any[]): LoDashImplicitWrapper; } - interface LoDashExplicitObjectWrapper { + interface LoDashExplicitWrapper { /** * @see _.assignInWith */ extendWith( source: TSource, customizer: AssignCustomizer - ): LoDashExplicitObjectWrapper; + ): LoDashExplicitWrapper; /** * @see _.assignInWith @@ -15740,7 +12638,7 @@ declare namespace _ { source1: TSource1, source2: TSource2, customizer: AssignCustomizer - ): LoDashExplicitObjectWrapper; + ): LoDashExplicitWrapper; /** * @see _.assignInWith @@ -15750,7 +12648,7 @@ declare namespace _ { source2: TSource2, source3: TSource3, customizer: AssignCustomizer - ): LoDashExplicitObjectWrapper; + ): LoDashExplicitWrapper; /** * @see _.assignInWith @@ -15761,17 +12659,17 @@ declare namespace _ { source3: TSource3, source4: TSource4, customizer: AssignCustomizer - ): LoDashExplicitObjectWrapper; + ): LoDashExplicitWrapper; /** * @see _.assignInWith */ - extendWith(): LoDashExplicitObjectWrapper; + extendWith(): LoDashExplicitWrapper; /** * @see _.assignInWith */ - extendWith(...otherArgs: any[]): LoDashExplicitObjectWrapper; + extendWith(...otherArgs: any[]): LoDashExplicitWrapper; } //_.findKey @@ -15794,93 +12692,29 @@ declare namespace _ { * @param thisArg The this binding of predicate. * @return Returns the key of the matched element, else undefined. */ - findKey( - object: TObject, - predicate?: DictionaryIterator - ): string | undefined; - - /** - * @see _.findKey - */ - findKey( - object: TObject, - predicate?: ObjectIterator - ): string | undefined; - - /** - * @see _.findKey - */ - findKey( - object: TObject, - predicate?: string - ): string | undefined; - - /** - * @see _.findKey - */ - findKey, TObject>( - object: TObject, - predicate?: TWhere + findKey( + object: T | null | undefined, + predicate?: ObjectIteratee ): string | undefined; } - interface LoDashImplicitObjectWrapperBase { + interface LoDashImplicitWrapper { /** * @see _.findKey */ - findKey( - predicate?: DictionaryIterator - ): string | undefined; - - /** - * @see _.findKey - */ - findKey( - predicate?: ObjectIterator - ): string | undefined; - - /** - * @see _.findKey - */ - findKey( - predicate?: string - ): string | undefined; - - /** - * @see _.findKey - */ - findKey>( - predicate?: TWhere + findKey( + this: LoDashImplicitWrapper, + predicate?: ObjectIteratee ): string | undefined; } - interface LoDashExplicitObjectWrapperBase { + interface LoDashExplicitWrapper { /** * @see _.findKey */ - findKey( - predicate?: DictionaryIterator - ): LoDashExplicitWrapper; - - /** - * @see _.findKey - */ - findKey( - predicate?: ObjectIterator - ): LoDashExplicitWrapper; - - /** - * @see _.findKey - */ - findKey( - predicate?: string - ): LoDashExplicitWrapper; - - /** - * @see _.findKey - */ - findKey>( - predicate?: TWhere + findKey( + this: LoDashExplicitWrapper, + predicate?: ObjectIteratee ): LoDashExplicitWrapper; } @@ -15903,93 +12737,29 @@ declare namespace _ { * @param thisArg The this binding of predicate. * @return Returns the key of the matched element, else undefined. */ - findLastKey( - object: TObject, - predicate?: DictionaryIterator - ): string | undefined; - - /** - * @see _.findLastKey - */ - findLastKey( - object: TObject, - predicate?: ObjectIterator - ): string | undefined; - - /** - * @see _.findLastKey - */ - findLastKey( - object: TObject, - predicate?: string - ): string; - - /** - * @see _.findLastKey - */ - findLastKey, TObject>( - object: TObject, - predicate?: TWhere + findLastKey( + object: T | null | undefined, + predicate?: ObjectIteratee ): string | undefined; } - interface LoDashImplicitObjectWrapperBase { + interface LoDashImplicitWrapper { /** * @see _.findLastKey */ - findLastKey( - predicate?: DictionaryIterator - ): string; - - /** - * @see _.findLastKey - */ - findLastKey( - predicate?: ObjectIterator - ): string | undefined; - - /** - * @see _.findLastKey - */ - findLastKey( - predicate?: string - ): string | undefined; - - /** - * @see _.findLastKey - */ - findLastKey>( - predicate?: TWhere + findLastKey( + this: LoDashImplicitWrapper, + predicate?: ObjectIteratee ): string | undefined; } - interface LoDashExplicitObjectWrapperBase { + interface LoDashExplicitWrapper { /** * @see _.findLastKey */ - findLastKey( - predicate?: DictionaryIterator - ): LoDashExplicitWrapper; - - /** - * @see _.findLastKey - */ - findLastKey( - predicate?: ObjectIterator - ): LoDashExplicitWrapper; - - /** - * @see _.findLastKey - */ - findLastKey( - predicate?: string - ): LoDashExplicitWrapper; - - /** - * @see _.findLastKey - */ - findLastKey>( - predicate?: TWhere + findLastKey( + this: LoDashExplicitWrapper, + predicate?: ObjectIteratee ): LoDashExplicitWrapper; } @@ -16006,43 +12776,27 @@ declare namespace _ { * @return Returns object. */ forIn( - object: Dictionary, - iteratee?: DictionaryIterator - ): Dictionary; + object: T, + iteratee?: ObjectIterator + ): T; /** * @see _.forIn */ forIn( - object: Dictionary | null | undefined, - iteratee?: DictionaryIterator - ): Dictionary | null | undefined; - - /** - * @see _.forIn - */ - forIn( - object: T, - iteratee?: ObjectIterator - ): T; + object: T | null | undefined, + iteratee?: ObjectIterator + ): T | null | undefined; } - interface LoDashImplicitObjectWrapperBase { + interface LoDashWrapper { /** * @see _.forIn */ - forIn( - iteratee?: DictionaryIterator - ): TWrapper; - } - - interface LoDashExplicitObjectWrapperBase { - /** - * @see _.forIn - */ - forIn( - iteratee?: DictionaryIterator - ): TWrapper; + forIn( + this: LoDashWrapper, + iteratee?: ObjectIterator + ): this; } //_.forInRight @@ -16056,43 +12810,27 @@ declare namespace _ { * @return Returns object. */ forInRight( - object: Dictionary, - iteratee?: DictionaryIterator - ): Dictionary; + object: T, + iteratee?: ObjectIterator + ): T; /** * @see _.forInRight */ forInRight( - object: Dictionary | null | undefined, - iteratee?: DictionaryIterator - ): Dictionary | null | undefined; - - /** - * @see _.forInRight - */ - forInRight( - object: T, - iteratee?: ObjectIterator - ): T; + object: T | null | undefined, + iteratee?: ObjectIterator + ): T | null | undefined; } - interface LoDashImplicitObjectWrapperBase { + interface LoDashWrapper { /** * @see _.forInRight */ - forInRight( - iteratee?: DictionaryIterator - ): TWrapper; - } - - interface LoDashExplicitObjectWrapperBase { - /** - * @see _.forInRight - */ - forInRight( - iteratee?: DictionaryIterator - ): TWrapper; + forInRight( + this: LoDashWrapper, + iteratee?: ObjectIterator + ): this; } //_.forOwn @@ -16108,43 +12846,27 @@ declare namespace _ { * @return Returns object. */ forOwn( - object: Dictionary, - iteratee?: DictionaryIterator - ): Dictionary; + object: T, + iteratee?: ObjectIterator + ): T; /** * @see _.forOwn */ forOwn( - object: Dictionary | null | undefined, - iteratee?: DictionaryIterator - ): Dictionary | null | undefined; - - /** - * @see _.forOwn - */ - forOwn( - object: T, - iteratee?: ObjectIterator - ): T; + object: T | null | undefined, + iteratee?: ObjectIterator + ): T | null | undefined; } - interface LoDashImplicitObjectWrapperBase { + interface LoDashWrapper { /** * @see _.forOwn */ - forOwn( - iteratee?: DictionaryIterator - ): TWrapper; - } - - interface LoDashExplicitObjectWrapperBase { - /** - * @see _.forOwn - */ - forOwn( - iteratee?: DictionaryIterator - ): TWrapper; + forOwn( + this: LoDashWrapper, + iteratee?: ObjectIterator + ): this; } //_.forOwnRight @@ -16158,43 +12880,27 @@ declare namespace _ { * @return Returns object. */ forOwnRight( - object: Dictionary, - iteratee?: DictionaryIterator - ): Dictionary; + object: T, + iteratee?: ObjectIterator + ): T; /** * @see _.forOwnRight */ forOwnRight( - object: Dictionary | null | undefined, - iteratee?: DictionaryIterator - ): Dictionary | null | undefined; - - /** - * @see _.forOwnRight - */ - forOwnRight( - object: T, - iteratee?: ObjectIterator - ): T; + object: T | null | undefined, + iteratee?: ObjectIterator + ): T | null | undefined; } - interface LoDashImplicitObjectWrapperBase { + interface LoDashWrapper { /** * @see _.forOwnRight */ - forOwnRight( - iteratee?: DictionaryIterator - ): TWrapper; - } - - interface LoDashExplicitObjectWrapperBase { - /** - * @see _.forOwnRight - */ - forOwnRight( - iteratee?: DictionaryIterator - ): TWrapper; + forOwnRight( + this: LoDashWrapper, + iteratee?: ObjectIterator + ): this; } //_.functions @@ -16220,21 +12926,21 @@ declare namespace _ { * _.functions(new Foo); * // => ['a', 'b'] */ - functions(object: any): string[]; + functions(object: any): string[]; } - interface LoDashImplicitObjectWrapper { + interface LoDashImplicitWrapper { /** * @see _.functions */ - functions(): _.LoDashImplicitArrayWrapper; + functions(): LoDashImplicitWrapper; } - interface LoDashExplicitObjectWrapper { + interface LoDashExplicitWrapper { /** * @see _.functions */ - functions(): _.LoDashExplicitArrayWrapper; + functions(): LoDashExplicitWrapper; } //_.functionsIn @@ -16263,18 +12969,18 @@ declare namespace _ { functionsIn(object: any): string[]; } - interface LoDashImplicitObjectWrapper { + interface LoDashImplicitWrapper { /** * @see _.functionsIn */ - functionsIn(): _.LoDashImplicitArrayWrapper; + functionsIn(): LoDashImplicitWrapper; } - interface LoDashExplicitObjectWrapper { + interface LoDashExplicitWrapper { /** * @see _.functionsIn */ - functionsIn(): _.LoDashExplicitArrayWrapper; + functionsIn(): LoDashExplicitWrapper; } //_.get @@ -16288,80 +12994,155 @@ declare namespace _ { * @param defaultValue The value returned if the resolved value is undefined. * @return Returns the resolved value. */ - get( + get( object: TObject, - path: Many, - defaultValue?: TResult - ): TResult; + path: TKey | [TKey] + ): TObject[TKey]; /** * @see _.get */ - get( + get( + object: TObject | null | undefined, + path: TKey | [TKey] + ): TObject[TKey] | undefined; + + /** + * @see _.get + */ + get( + object: TObject | null | undefined, + path: TKey | [TKey], + defaultValue: TDefault + ): TObject[TKey] | TDefault; + + /** + * @see _.get + */ + get( + object: null | undefined, + path: Many, + defaultValue: TDefault + ): TDefault; + + /** + * @see _.get + */ + get( + object: null | undefined, + path: Many + ): undefined; + + /** + * @see _.get + */ + get( object: any, path: Many, - defaultValue?: TResult - ): TResult; + defaultValue?: any + ): any; } - interface LoDashImplicitWrapper { + interface LoDashImplicitWrapper { + /** + * @see _.get + */ + get( + path: TKey | [TKey] + ): TValue[TKey]; + + /** + * @see _.get + */ + get( + this: LoDashImplicitWrapper, + path: TKey | [TKey], + ): TObject[TKey] | undefined; + + /** + * @see _.get + */ + get( + this: LoDashImplicitWrapper, + path: TKey | [TKey], + defaultValue: TDefault + ): TObject[TKey] | TDefault; + + /** + * @see _.get + */ + get( + this: LoDashImplicitWrapper, + path: Many, + defaultValue: TDefault + ): TDefault; + + /** + * @see _.get + */ + get( + this: LoDashImplicitWrapper, + path: Many + ): undefined; + /** * @see _.get */ get( path: Many, - defaultValue?: TResult - ): TResult; + defaultValue?: any + ): any; } - interface LoDashImplicitArrayWrapperBase { + interface LoDashExplicitWrapper { /** * @see _.get */ - get( + get( + path: TKey | [TKey] + ): LoDashExplicitWrapper; + + /** + * @see _.get + */ + get( + this: LoDashExplicitWrapper, + path: TKey | [TKey], + ): LoDashExplicitWrapper; + + /** + * @see _.get + */ + get( + this: LoDashExplicitWrapper, + path: TKey | [TKey], + defaultValue: TDefault + ): LoDashExplicitWrapper; + + /** + * @see _.get + */ + get( + this: LoDashExplicitWrapper, path: Many, - defaultValue?: TResult - ): TResult; - } + defaultValue: TDefault + ): LoDashExplicitWrapper; - interface LoDashImplicitObjectWrapperBase { /** * @see _.get */ - get( - path: Many, - defaultValue?: TResult - ): TResult; - } + get( + this: LoDashExplicitWrapper, + path: Many + ): LoDashExplicitWrapper; - interface LoDashExplicitWrapper { /** * @see _.get */ - get( + get( path: Many, defaultValue?: any - ): TResultWrapper; - } - - interface LoDashExplicitArrayWrapperBase { - /** - * @see _.get - */ - get( - path: Many, - defaultValue?: any - ): TResultWrapper; - } - - interface LoDashExplicitObjectWrapperBase { - /** - * @see _.get - */ - get( - path: Many, - defaultValue?: any - ): TResultWrapper; + ): LoDashExplicitWrapper; } //_.has @@ -16392,20 +13173,20 @@ declare namespace _ { * _.has(other, 'a'); * // => false */ - has( + has( object: T, path: Many ): boolean; } - interface LoDashImplicitObjectWrapperBase { + interface LoDashImplicitWrapper { /** * @see _.has */ has(path: Many): boolean; } - interface LoDashExplicitObjectWrapperBase { + interface LoDashExplicitWrapper { /** * @see _.has */ @@ -16439,20 +13220,20 @@ declare namespace _ { * _.hasIn(object, 'b'); * // => false */ - hasIn( + hasIn( object: T, path: Many ): boolean; } - interface LoDashImplicitObjectWrapperBase { + interface LoDashImplicitWrapper { /** * @see _.hasIn */ hasIn(path: Many): boolean; } - interface LoDashExplicitObjectWrapperBase { + interface LoDashExplicitWrapper { /** * @see _.hasIn */ @@ -16469,37 +13250,26 @@ declare namespace _ { * @param multiValue Allow multiple values per key. * @return Returns the new inverted object. */ - invert( - object: T, - multiValue?: boolean - ): TResult; + invert( + object: object + ): Dictionary; + } + interface LoDashImplicitWrapper { /** * @see _.invert */ - invert( - object: Object, - multiValue?: boolean - ): TResult; + invert(): LoDashImplicitWrapper>; } - interface LoDashImplicitObjectWrapper { + interface LoDashExplicitWrapper { /** * @see _.invert */ - invert(multiValue?: boolean): LoDashImplicitObjectWrapper; + invert(): LoDashExplicitWrapper>; } - interface LoDashExplicitObjectWrapper { - /** - * @see _.invert - */ - invert(multiValue?: boolean): LoDashExplicitObjectWrapper; - } - - //_.inverBy - type InvertByIterator = (value: T) => any; - + //_.invertBy interface LoDashStatic { /** * This method is like _.invert except that the inverted object is generated from the results of running each @@ -16510,116 +13280,54 @@ declare namespace _ { * @param interatee The iteratee invoked per element. * @return Returns the new inverted object. */ - invertBy( - object: Object, - interatee?: InvertByIterator|string + invertBy( + object: List | Dictionary | NumericDictionary | null | undefined, + interatee?: ValueIteratee ): Dictionary; + /** + * @see _.invertBy + */ + invertBy( + object: T | null | undefined, + interatee?: ValueIteratee + ): Dictionary; + } + + interface LoDashImplicitWrapper { /** * @see _.invertBy */ invertBy( - object: _.Dictionary|_.NumericDictionary, - interatee?: InvertByIterator|string - ): Dictionary; + this: LoDashImplicitWrapper | Dictionary | NumericDictionary | null | undefined>, + interatee?: ValueIteratee + ): LoDashImplicitWrapper>; /** * @see _.invertBy */ - invertBy( - object: Object, - interatee?: W - ): Dictionary; - - /** - * @see _.invertBy - */ - invertBy( - object: _.Dictionary, - interatee?: W - ): Dictionary; + invertBy( + this: LoDashImplicitWrapper, + interatee?: ValueIteratee + ): LoDashImplicitWrapper>; } - interface LoDashImplicitWrapper { + interface LoDashExplicitWrapper { /** * @see _.invertBy */ - invertBy( - interatee?: InvertByIterator - ): LoDashImplicitObjectWrapper>; - } - - interface LoDashImplicitArrayWrapper { - /** - * @see _.invertBy - */ - invertBy( - interatee?: InvertByIterator|string - ): LoDashImplicitObjectWrapper>; + invertBy( + this: LoDashExplicitWrapper | Dictionary | NumericDictionary | null | undefined>, + interatee?: ValueIteratee + ): LoDashExplicitWrapper>; /** * @see _.invertBy */ - invertBy( - interatee?: W - ): LoDashImplicitObjectWrapper>; - } - - interface LoDashImplicitObjectWrapper { - /** - * @see _.invertBy - */ - invertBy( - interatee?: InvertByIterator|string - ): LoDashImplicitObjectWrapper>; - - /** - * @see _.invertBy - */ - invertBy( - interatee?: W - ): LoDashImplicitObjectWrapper>; - } - - interface LoDashExplicitWrapper { - /** - * @see _.invertBy - */ - invertBy( - interatee?: InvertByIterator - ): LoDashExplicitObjectWrapper>; - } - - interface LoDashExplicitArrayWrapper { - /** - * @see _.invertBy - */ - invertBy( - interatee?: InvertByIterator|string - ): LoDashExplicitObjectWrapper>; - - /** - * @see _.invertBy - */ - invertBy( - interatee?: W - ): LoDashExplicitObjectWrapper>; - } - - interface LoDashExplicitObjectWrapper { - /** - * @see _.invertBy - */ - invertBy( - interatee?: InvertByIterator|string - ): LoDashExplicitObjectWrapper>; - - /** - * @see _.invertBy - */ - invertBy( - interatee?: W - ): LoDashExplicitObjectWrapper>; + invertBy( + this: LoDashExplicitWrapper, + interatee?: ValueIteratee + ): LoDashExplicitWrapper>; } //_.keys @@ -16635,18 +13343,18 @@ declare namespace _ { keys(object?: any): string[]; } - interface LoDashImplicitObjectWrapperBase { + interface LoDashImplicitWrapper { /** * @see _.keys */ - keys(): LoDashImplicitArrayWrapper; + keys(): LoDashImplicitWrapper; } - interface LoDashExplicitObjectWrapperBase { + interface LoDashExplicitWrapper { /** * @see _.keys */ - keys(): LoDashExplicitArrayWrapper; + keys(): LoDashExplicitWrapper; } //_.keysIn @@ -16662,18 +13370,18 @@ declare namespace _ { keysIn(object?: any): string[]; } - interface LoDashImplicitObjectWrapperBase { + interface LoDashImplicitWrapper { /** * @see _.keysIn */ - keysIn(): LoDashImplicitArrayWrapper; + keysIn(): LoDashImplicitWrapper; } - interface LoDashExplicitObjectWrapperBase { + interface LoDashExplicitWrapper { /** * @see _.keysIn */ - keysIn(): LoDashExplicitArrayWrapper; + keysIn(): LoDashExplicitWrapper; } //_.mapKeys @@ -16687,126 +13395,78 @@ declare namespace _ { * @param thisArg The this binding of iteratee. * @return Returns the new mapped object. */ - mapKeys( + mapKeys( object: List | null | undefined, - iteratee?: ListIterator - ): Dictionary; - - /** - * @see _.mapKeys - */ - mapKeys( - object: Dictionary | null | undefined, - iteratee?: DictionaryIterator - ): Dictionary; - - /** - * @see _.mapKeys - */ - mapKeys( - object: List|Dictionary | null | undefined, - iteratee?: TObject + iteratee?: ListIteratee ): Dictionary; /** * @see _.mapKeys */ mapKeys( - object: List|Dictionary | null | undefined, - iteratee?: string + object: Dictionary | null | undefined, + iteratee?: DictionaryIteratee ): Dictionary; - } - - interface LoDashImplicitArrayWrapperBase { - /** - * @see _.mapKeys - */ - mapKeys( - iteratee?: ListIterator - ): LoDashImplicitObjectWrapper>; - - /** - * @see _.mapKeys - */ - mapKeys( - iteratee?: TObject - ): LoDashImplicitObjectWrapper>; /** * @see _.mapKeys */ mapKeys( - iteratee?: string - ): LoDashImplicitObjectWrapper>; + object: object | null | undefined, + iteratee?: ObjectIteratee + ): Dictionary; } - interface LoDashImplicitObjectWrapperBase { + interface LoDashImplicitWrapper { /** * @see _.mapKeys */ - mapKeys( - iteratee?: ListIterator|DictionaryIterator - ): LoDashImplicitObjectWrapper>; + mapKeys( + this: LoDashImplicitWrapper | null | undefined>, + iteratee?: ListIteratee + ): LoDashImplicitWrapper>; /** * @see _.mapKeys */ - mapKeys( - iteratee?: TObject - ): LoDashImplicitObjectWrapper>; - - /** - * @see _.mapKeys - */ - mapKeys( - iteratee?: string - ): LoDashImplicitObjectWrapper>; - } - - interface LoDashExplicitArrayWrapperBase { - /** - * @see _.mapKeys - */ - mapKeys( - iteratee?: ListIterator - ): LoDashExplicitObjectWrapper>; - - /** - * @see _.mapKeys - */ - mapKeys( - iteratee?: TObject - ): LoDashExplicitObjectWrapper>; + mapKeys( + this: LoDashImplicitWrapper | null | undefined>, + iteratee?: DictionaryIteratee + ): LoDashImplicitWrapper>; /** * @see _.mapKeys */ mapKeys( - iteratee?: string - ): LoDashExplicitObjectWrapper>; + this: LoDashImplicitWrapper, + iteratee?: ObjectIteratee + ): LoDashImplicitWrapper>; } - interface LoDashExplicitObjectWrapperBase { + interface LoDashExplicitWrapper { /** * @see _.mapKeys */ - mapKeys( - iteratee?: ListIterator|DictionaryIterator - ): LoDashExplicitObjectWrapper>; + mapKeys( + this: LoDashExplicitWrapper | null | undefined>, + iteratee?: ListIteratee + ): LoDashExplicitWrapper>; /** * @see _.mapKeys */ - mapKeys( - iteratee?: TObject - ): LoDashExplicitObjectWrapper>; + mapKeys( + this: LoDashExplicitWrapper | null | undefined>, + iteratee?: DictionaryIteratee + ): LoDashExplicitWrapper>; /** * @see _.mapKeys */ - mapKeys( - iteratee?: string - ): LoDashExplicitObjectWrapper>; + mapKeys( + this: LoDashExplicitWrapper, + iteratee?: ObjectIteratee + ): LoDashExplicitWrapper>; } //_.mapValues @@ -16830,56 +13490,171 @@ declare namespace _ { * @param {Object} [thisArg] The `this` binding of `iteratee`. * @return {Object} Returns the new mapped object. */ - mapValues(obj: Dictionary | null | undefined, callback: ObjectIterator): Dictionary; - mapValues(obj: Dictionary | null | undefined, where: Dictionary): Dictionary; - mapValues(obj: T | null | undefined, pluck?: string): TMapped; - mapValues(obj: T | null | undefined, callback: ObjectIterator): T; + mapValues(obj: T | null | undefined, callback: ObjectIterator): { [P in keyof T]: TResult }; + + /** + * @see _.mapValues + */ + mapValues(obj: T | null | undefined, iteratee: object): { [P in keyof T]: boolean }; + + /** + * @see _.mapValues + */ + mapValues(obj: Dictionary | null | undefined, iteratee: TKey): Dictionary; + + /** + * @see _.mapValues + */ + mapValues(obj: T | null | undefined, iteratee: string): { [P in keyof T]: any }; + + /** + * @see _.mapValues + */ + mapValues(obj: string | null | undefined, callback: StringIterator): NumericDictionary; + + /** + * @see _.mapValues + */ + mapValues(obj: Dictionary | null | undefined): Dictionary; + + /** + * @see _.mapValues + */ + mapValues(obj: T): T; + + /** + * @see _.mapValues + */ + mapValues(obj: T | null | undefined): T | {}; + + /** + * @see _.mapValues + */ + mapValues(obj: string | null | undefined): NumericDictionary; } - interface LoDashImplicitObjectWrapperBase { + interface LoDashImplicitWrapper { /** * @see _.mapValues - * TValue is the type of the property values of T. - * TResult is the type output by the ObjectIterator function */ - mapValues(callback: ObjectIterator): LoDashImplicitObjectWrapper>; + mapValues( + this: LoDashImplicitWrapper, + callback: ObjectIterator + ): LoDashImplicitWrapper<{ [P in keyof T]: TResult }>; /** * @see _.mapValues - * TResult is the type of the property specified by pluck. - * T should be a Dictionary> */ - mapValues(pluck?: string): LoDashImplicitObjectWrapper>; + mapValues( + this: LoDashImplicitWrapper, + iteratee: object + ): LoDashImplicitWrapper<{ [P in keyof T]: boolean }>; /** * @see _.mapValues - * TResult is the type of the properties of each object in the values of T - * T should be a Dictionary> */ - mapValues(where: Dictionary): LoDashImplicitArrayWrapper; + mapValues( + this: LoDashImplicitWrapper | null | undefined>, + iteratee: TKey + ): LoDashImplicitWrapper>; + + /** + * @see _.mapValues + */ + mapValues( + this: LoDashImplicitWrapper, + iteratee: string + ): LoDashImplicitWrapper<{ [P in keyof T]: any }>; + + /** + * @see _.mapValues + */ + mapValues( + this: LoDashImplicitWrapper, + callback: StringIterator + ): LoDashImplicitWrapper>; + + /** + * @see _.mapValues + */ + mapValues(this: LoDashImplicitWrapper | null | undefined>): LoDashImplicitWrapper>; + + /** + * @see _.mapValues + */ + mapValues(this: LoDashImplicitWrapper): LoDashImplicitWrapper; + + /** + * @see _.mapValues + */ + mapValues(this: LoDashImplicitWrapper): LoDashImplicitWrapper; + + /** + * @see _.mapValues + */ + mapValues(this: LoDashImplicitWrapper): LoDashImplicitWrapper>; } - interface LoDashExplicitObjectWrapperBase { + interface LoDashExplicitWrapper { /** * @see _.mapValues - * TValue is the type of the property values of T. - * TResult is the type output by the ObjectIterator function */ - mapValues(callback: ObjectIterator): LoDashExplicitObjectWrapper>; + mapValues( + this: LoDashExplicitWrapper, + callback: ObjectIterator + ): LoDashExplicitWrapper<{ [P in keyof T]: TResult }>; /** * @see _.mapValues - * TResult is the type of the property specified by pluck. - * T should be a Dictionary> */ - mapValues(pluck?: string): LoDashExplicitObjectWrapper>; + mapValues( + this: LoDashExplicitWrapper, + iteratee: object + ): LoDashExplicitWrapper<{ [P in keyof T]: boolean }>; /** * @see _.mapValues - * TResult is the type of the properties of each object in the values of T - * T should be a Dictionary> */ - mapValues(where: Dictionary): LoDashExplicitObjectWrapper; + mapValues( + this: LoDashExplicitWrapper | null | undefined>, + iteratee: TKey + ): LoDashExplicitWrapper>; + + /** + * @see _.mapValues + */ + mapValues( + this: LoDashExplicitWrapper, + iteratee: string + ): LoDashExplicitWrapper<{ [P in keyof T]: any }>; + + /** + * @see _.mapValues + */ + mapValues( + this: LoDashExplicitWrapper, + callback: StringIterator + ): LoDashExplicitWrapper>; + + /** + * @see _.mapValues + */ + mapValues(this: LoDashExplicitWrapper | null | undefined>): LoDashExplicitWrapper>; + + /** + * @see _.mapValues + */ + mapValues(this: LoDashExplicitWrapper): LoDashExplicitWrapper; + + /** + * @see _.mapValues + */ + mapValues(this: LoDashExplicitWrapper): LoDashExplicitWrapper; + + /** + * @see _.mapValues + */ + mapValues(this: LoDashExplicitWrapper): LoDashExplicitWrapper>; } //_.merge @@ -16951,19 +13726,19 @@ declare namespace _ { /** * @see _.merge */ - merge( + merge( object: any, ...otherArgs: any[] - ): TResult; + ): any; } - interface LoDashImplicitObjectWrapper { + interface LoDashImplicitWrapper { /** * @see _.merge */ merge( source: TSource - ): LoDashImplicitObjectWrapper; + ): LoDashImplicitWrapper; /** * @see _.merge @@ -16971,7 +13746,7 @@ declare namespace _ { merge( source1: TSource1, source2: TSource2 - ): LoDashImplicitObjectWrapper; + ): LoDashImplicitWrapper; /** * @see _.merge @@ -16980,7 +13755,7 @@ declare namespace _ { source1: TSource1, source2: TSource2, source3: TSource3 - ): LoDashImplicitObjectWrapper; + ): LoDashImplicitWrapper; /** * @see _.merge @@ -16990,23 +13765,23 @@ declare namespace _ { source2: TSource2, source3: TSource3, source4: TSource4 - ): LoDashImplicitObjectWrapper; + ): LoDashImplicitWrapper; /** * @see _.merge */ - merge( + merge( ...otherArgs: any[] - ): LoDashImplicitObjectWrapper; + ): LoDashImplicitWrapper; } - interface LoDashExplicitObjectWrapper { + interface LoDashExplicitWrapper { /** * @see _.merge */ merge( source: TSource - ): LoDashExplicitObjectWrapper; + ): LoDashExplicitWrapper; /** * @see _.merge @@ -17014,7 +13789,7 @@ declare namespace _ { merge( source1: TSource1, source2: TSource2 - ): LoDashExplicitObjectWrapper; + ): LoDashExplicitWrapper; /** * @see _.merge @@ -17023,20 +13798,20 @@ declare namespace _ { source1: TSource1, source2: TSource2, source3: TSource3 - ): LoDashExplicitObjectWrapper; + ): LoDashExplicitWrapper; /** * @see _.merge */ merge( - ): LoDashExplicitObjectWrapper; + ): LoDashExplicitWrapper; /** * @see _.merge */ - merge( + merge( ...otherArgs: any[] - ): LoDashExplicitObjectWrapper; + ): LoDashExplicitWrapper; } //_.mergeWith @@ -17120,20 +13895,20 @@ declare namespace _ { /** * @see _.mergeWith */ - mergeWith( + mergeWith( object: any, ...otherArgs: any[] - ): TResult; + ): any; } - interface LoDashImplicitObjectWrapper { + interface LoDashImplicitWrapper { /** * @see _.mergeWith */ mergeWith( source: TSource, customizer: MergeWithCustomizer - ): LoDashImplicitObjectWrapper; + ): LoDashImplicitWrapper; /** * @see _.mergeWith @@ -17142,7 +13917,7 @@ declare namespace _ { source1: TSource1, source2: TSource2, customizer: MergeWithCustomizer - ): LoDashImplicitObjectWrapper; + ): LoDashImplicitWrapper; /** * @see _.mergeWith @@ -17152,7 +13927,7 @@ declare namespace _ { source2: TSource2, source3: TSource3, customizer: MergeWithCustomizer - ): LoDashImplicitObjectWrapper; + ): LoDashImplicitWrapper; /** * @see _.mergeWith @@ -17163,14 +13938,14 @@ declare namespace _ { source3: TSource3, source4: TSource4, customizer: MergeWithCustomizer - ): LoDashImplicitObjectWrapper; + ): LoDashImplicitWrapper; /** * @see _.mergeWith */ - mergeWith( + mergeWith( ...otherArgs: any[] - ): LoDashImplicitObjectWrapper; + ): LoDashImplicitWrapper; } //_.omit @@ -17194,28 +13969,30 @@ declare namespace _ { * // => { 'b': '2' } */ - omit( + omit( object: T | null | undefined, - ...predicate: Array> - ): TResult; + ...props: Array> + ): PartialObject; } - interface LoDashImplicitObjectWrapperBase { + interface LoDashImplicitWrapper { /** * @see _.omit */ - omit( - ...predicate: Array> - ): LoDashImplicitObjectWrapper; + omit( + this: LoDashImplicitWrapper, + ...props: Array> + ): LoDashImplicitWrapper>; } - interface LoDashExplicitObjectWrapperBase { + interface LoDashExplicitWrapper { /** * @see _.omit */ - omit( + omit( + this: LoDashExplicitWrapper, ...predicate: Array> - ): LoDashExplicitObjectWrapper; + ): LoDashExplicitWrapper>; } //_.omitBy @@ -17238,28 +14015,30 @@ declare namespace _ { * _.omitBy(object, _.isNumber); * // => { 'b': '2' } */ - omitBy( + omitBy( object: T | null | undefined, - predicate: ObjectIterator - ): TResult; + predicate: ValueKeyIteratee + ): PartialObject; } - interface LoDashImplicitObjectWrapperBase { + interface LoDashImplicitWrapper { /** * @see _.omitBy */ - omitBy( - predicate: ObjectIterator - ): LoDashImplicitObjectWrapper; + omitBy( + this: LoDashImplicitWrapper, + predicate: ValueKeyIteratee + ): LoDashImplicitWrapper>; } - interface LoDashExplicitObjectWrapperBase { + interface LoDashExplicitWrapper { /** * @see _.omitBy */ - omitBy( - predicate: ObjectIterator - ): LoDashExplicitObjectWrapper; + omitBy( + this: LoDashExplicitWrapper, + predicate: ValueKeyIteratee + ): LoDashExplicitWrapper>; } //_.pick @@ -17281,35 +14060,37 @@ declare namespace _ { * _.pick(object, ['a', 'c']); * // => { 'a': 1, 'c': 3 } */ - pick( + pick( object: T | null | undefined, ...predicate: Array> - ): TResult; + ): PartialObject; } - interface LoDashImplicitObjectWrapperBase { + interface LoDashImplicitWrapper { /** * @see _.pick */ - pick( + pick( + this: LoDashImplicitWrapper, ...predicate: Array> - ): LoDashImplicitObjectWrapper; + ): LoDashImplicitWrapper>; } - interface LoDashExplicitObjectWrapperBase { + interface LoDashExplicitWrapper { /** * @see _.pick */ - pick( + pick( + this: LoDashExplicitWrapper, ...predicate: Array> - ): LoDashExplicitObjectWrapper; + ): LoDashExplicitWrapper>; } //_.pickBy interface LoDashStatic { /** * Creates an object composed of the `object` properties `predicate` returns - * truthy for. The predicate is invoked with one argument: (value). + * truthy for. The predicate is invoked with two arguments: (value, key). * * @static * @memberOf _ @@ -17324,28 +14105,30 @@ declare namespace _ { * _.pickBy(object, _.isNumber); * // => { 'a': 1, 'c': 3 } */ - pickBy( + pickBy( object: T | null | undefined, - predicate?: ObjectIterator - ): TResult; + predicate?: ValueKeyIteratee + ): PartialObject; } - interface LoDashImplicitObjectWrapperBase { + interface LoDashImplicitWrapper { /** * @see _.pickBy */ - pickBy( - predicate?: ObjectIterator - ): LoDashImplicitObjectWrapper; + pickBy( + this: LoDashImplicitWrapper, + predicate?: ValueKeyIteratee + ): LoDashImplicitWrapper>; } - interface LoDashExplicitObjectWrapperBase { + interface LoDashExplicitWrapper { /** * @see _.pickBy */ - pickBy( - predicate?: ObjectIterator - ): LoDashExplicitObjectWrapper; + pickBy( + this: LoDashExplicitWrapper, + predicate?: ValueKeyIteratee + ): LoDashExplicitWrapper>; } //_.result @@ -17359,15 +14142,6 @@ declare namespace _ { * @param defaultValue The value returned if the resolved value is undefined. * @return Returns the resolved value. */ - result( - object: TObject, - path: Many, - defaultValue?: TResult|((...args: any[]) => TResult) - ): TResult; - - /** - * @see _.result - */ result( object: any, path: Many, @@ -17375,7 +14149,7 @@ declare namespace _ { ): TResult; } - interface LoDashImplicitWrapper { + interface LoDashImplicitWrapper { /** * @see _.result */ @@ -17385,54 +14159,14 @@ declare namespace _ { ): TResult; } - interface LoDashImplicitArrayWrapperBase { + interface LoDashExplicitWrapper { /** * @see _.result */ result( path: Many, defaultValue?: TResult|((...args: any[]) => TResult) - ): TResult; - } - - interface LoDashImplicitObjectWrapperBase { - /** - * @see _.result - */ - result( - path: Many, - defaultValue?: TResult|((...args: any[]) => TResult) - ): TResult; - } - - interface LoDashExplicitWrapper { - /** - * @see _.result - */ - result( - path: Many, - defaultValue?: any - ): TResultWrapper; - } - - interface LoDashExplicitArrayWrapperBase { - /** - * @see _.result - */ - result( - path: Many, - defaultValue?: any - ): TResultWrapper; - } - - interface LoDashExplicitObjectWrapper { - /** - * @see _.result - */ - result( - path: Many, - defaultValue?: any - ): TResultWrapper; + ): LoDashExplicitWrapper; } //_.set @@ -17447,65 +14181,56 @@ declare namespace _ { * @param value The value to set. * @return Returns object. */ - set( - object: Object, + set( + object: T, path: Many, value: any - ): TResult; + ): T; /** * @see _.set */ - set( - object: Object, + set( + object: object, path: Many, - value: V - ): TResult; - - /** - * @see _.set - */ - set( - object: O, - path: Many, - value: V + value: any ): TResult; } - interface LoDashImplicitObjectWrapper { + interface LoDashImplicitWrapper { + /** + * @see _.set + */ + set( + path: Many, + value: any + ): this; + /** * @see _.set */ set( path: Many, value: any - ): LoDashImplicitObjectWrapper; - - /** - * @see _.set - */ - set( - path: Many, - value: V - ): LoDashImplicitObjectWrapper; + ): LoDashImplicitWrapper; } - interface LoDashExplicitObjectWrapper { + interface LoDashExplicitWrapper { + /** + * @see _.set + */ + set( + path: Many, + value: any + ): this; + /** * @see _.set */ set( path: Many, value: any - ): LoDashExplicitObjectWrapper; - - /** - * @see _.set - */ - set( - path: Many, - value: V - ): LoDashExplicitObjectWrapper; + ): LoDashExplicitWrapper; } //_.setWith @@ -17523,72 +14248,59 @@ declare namespace _ { * @parem customizer The function to customize assigned values. * @return Returns object. */ - setWith( - object: O, - path: Many, - value: V, - customizer?: SetWithCustomizer - ): TResult; - - /** - * @see _.setWith - */ - setWith( - object: any, + setWith( + object: T, path: Many, value: any, - customizer?: SetWithCustomizer - ): TResult; + customizer?: SetWithCustomizer + ): T; - /** - * @see _.setWith - */ - setWith( - object: any, + setWith( + object: T, path: Many, - value: V, - customizer?: SetWithCustomizer + value: any, + customizer?: SetWithCustomizer ): TResult; } - interface LoDashImplicitObjectWrapper { + interface LoDashImplicitWrapper { + /** + * @see _.setWith + */ + setWith( + path: Many, + value: any, + customizer?: SetWithCustomizer + ): this; + /** * @see _.setWith */ setWith( path: Many, value: any, - customizer?: SetWithCustomizer - ): LoDashImplicitObjectWrapper; - - /** - * @see _.setWith - */ - setWith( - path: Many, - value: V, - customizer?: SetWithCustomizer - ): LoDashImplicitObjectWrapper; + customizer?: SetWithCustomizer + ): LoDashImplicitWrapper; } - interface LoDashExplicitObjectWrapper { + interface LoDashExplicitWrapper { + /** + * @see _.setWith + */ + setWith( + path: Many, + value: any, + customizer?: SetWithCustomizer + ): this; + /** * @see _.setWith */ setWith( path: Many, value: any, - customizer?: SetWithCustomizer - ): LoDashExplicitObjectWrapper; - - /** - * @see _.setWith - */ - setWith( - path: Many, - value: V, - customizer?: SetWithCustomizer - ): LoDashExplicitObjectWrapper; + customizer?: SetWithCustomizer + ): LoDashExplicitWrapper; } //_.toPairs @@ -17599,23 +14311,36 @@ declare namespace _ { * @param object The object to query. * @return Returns the new array of key-value pairs. */ - toPairs(object?: T): [string, any][]; + toPairs(object?: Dictionary): Array<[string, T]>; - toPairs(object?: T): [string, TResult][]; - } - - interface LoDashImplicitObjectWrapper { /** * @see _.toPairs */ - toPairs(): LoDashImplicitArrayWrapper<[string, TResult]>; + toPairs(object?: object): Array<[string, any]>; } - interface LoDashExplicitObjectWrapper { + interface LoDashImplicitWrapper { /** * @see _.toPairs */ - toPairs(): LoDashExplicitArrayWrapper<[string, TResult]>; + toPairs(this: LoDashImplicitWrapper>): LoDashImplicitWrapper>; + + /** + * @see _.toPairs + */ + toPairs(): LoDashImplicitWrapper>; + } + + interface LoDashExplicitWrapper { + /** + * @see _.toPairs + */ + toPairs(this: LoDashExplicitWrapper>): LoDashExplicitWrapper>; + + /** + * @see _.toPairs + */ + toPairs(): LoDashExplicitWrapper>; } //_.toPairsIn @@ -17626,23 +14351,36 @@ declare namespace _ { * @param object The object to query. * @return Returns the new array of key-value pairs. */ - toPairsIn(object?: T): [string, any][]; + toPairsIn(object?: Dictionary): Array<[string, T]>; - toPairsIn(object?: T): [string, TResult][]; - } - - interface LoDashImplicitObjectWrapper { /** * @see _.toPairsIn */ - toPairsIn(): LoDashImplicitArrayWrapper<[string, TResult]>; + toPairsIn(object?: object): Array<[string, any]>; } - interface LoDashExplicitObjectWrapper { + interface LoDashImplicitWrapper { /** * @see _.toPairsIn */ - toPairsIn(): LoDashExplicitArrayWrapper<[string, TResult]>; + toPairsIn(this: LoDashImplicitWrapper>): LoDashImplicitWrapper>; + + /** + * @see _.toPairsIn + */ + toPairsIn(): LoDashImplicitWrapper>; + } + + interface LoDashExplicitWrapper { + /** + * @see _.toPairsIn + */ + toPairsIn(this: LoDashExplicitWrapper>): LoDashExplicitWrapper>; + + /** + * @see _.toPairsIn + */ + toPairsIn(): LoDashExplicitWrapper>; } //_.transform @@ -17661,7 +14399,7 @@ declare namespace _ { */ transform( object: T[], - iteratee?: MemoVoidArrayIterator, + iteratee: MemoVoidArrayIterator, accumulator?: TResult[] ): TResult[]; @@ -17670,7 +14408,16 @@ declare namespace _ { */ transform( object: T[], - iteratee?: MemoVoidArrayIterator>, + iteratee: MemoVoidArrayIterator>, + accumulator: Dictionary + ): Dictionary; + + /** + * @see _.transform + */ + transform( + object: Dictionary, + iteratee: MemoVoidDictionaryIterator>, accumulator?: Dictionary ): Dictionary; @@ -17679,54 +14426,123 @@ declare namespace _ { */ transform( object: Dictionary, - iteratee?: MemoVoidDictionaryIterator>, - accumulator?: Dictionary - ): Dictionary; - - /** - * @see _.transform - */ - transform( - object: Dictionary, - iteratee?: MemoVoidDictionaryIterator, - accumulator?: TResult[] + iteratee: MemoVoidDictionaryIterator, + accumulator: TResult[] ): TResult[]; - } - - interface LoDashImplicitArrayWrapper { - /** - * @see _.transform - */ - transform( - iteratee?: MemoVoidArrayIterator, - accumulator?: TResult[] - ): LoDashImplicitArrayWrapper; /** * @see _.transform */ - transform( - iteratee?: MemoVoidArrayIterator>, - accumulator?: Dictionary - ): LoDashImplicitObjectWrapper>; + transform( + object: any[], + ): any[]; + + /** + * @see _.transform + */ + transform( + object: object, + ): Dictionary; } - interface LoDashImplicitObjectWrapper { + interface LoDashImplicitWrapper { /** * @see _.transform */ transform( - iteratee?: MemoVoidDictionaryIterator>, - accumulator?: Dictionary - ): LoDashImplicitObjectWrapper>; + this: LoDashImplicitWrapper, + iteratee: MemoVoidArrayIterator, + accumulator?: TResult[] + ): LoDashImplicitWrapper; /** * @see _.transform */ transform( - iteratee?: MemoVoidDictionaryIterator, + this: LoDashImplicitWrapper, + iteratee: MemoVoidArrayIterator>, + accumulator: Dictionary + ): LoDashImplicitWrapper>; + + /** + * @see _.transform + */ + transform( + this: LoDashImplicitWrapper>, + iteratee: MemoVoidDictionaryIterator>, + accumulator?: Dictionary + ): LoDashImplicitWrapper>; + + /** + * @see _.transform + */ + transform( + this: LoDashImplicitWrapper>, + iteratee: MemoVoidDictionaryIterator, + accumulator: TResult[] + ): LoDashImplicitWrapper; + + /** + * @see _.transform + */ + transform( + this: LoDashImplicitWrapper, + ): LoDashImplicitWrapper; + + /** + * @see _.transform + */ + transform(): LoDashImplicitWrapper>; + } + + interface LoDashExplicitWrapper { + /** + * @see _.transform + */ + transform( + this: LoDashExplicitWrapper, + iteratee: MemoVoidArrayIterator, accumulator?: TResult[] - ): LoDashImplicitArrayWrapper; + ): LoDashExplicitWrapper; + + /** + * @see _.transform + */ + transform( + this: LoDashExplicitWrapper, + iteratee: MemoVoidArrayIterator>, + accumulator?: Dictionary + ): LoDashExplicitWrapper>; + + /** + * @see _.transform + */ + transform( + this: LoDashExplicitWrapper>, + iteratee: MemoVoidDictionaryIterator>, + accumulator?: Dictionary + ): LoDashExplicitWrapper>; + + /** + * @see _.transform + */ + transform( + this: LoDashExplicitWrapper>, + iteratee: MemoVoidDictionaryIterator, + accumulator?: TResult[] + ): LoDashExplicitWrapper; + + /** + * @see _.transform + */ + transform( + this: LoDashExplicitWrapper, + ): LoDashExplicitWrapper; + + /** + * @see _.transform + */ + transform(): LoDashExplicitWrapper>; } //_.unset @@ -17740,20 +14556,20 @@ declare namespace _ { * @param path The path of the property to unset. * @return Returns true if the property is deleted, else false. */ - unset( - object: T, + unset( + object: any, path: Many ): boolean; } - interface LoDashImplicitObjectWrapper { + interface LoDashImplicitWrapper { /** * @see _.unset */ unset(path: Many): LoDashImplicitWrapper; } - interface LoDashExplicitObjectWrapper { + interface LoDashExplicitWrapper { /** * @see _.unset */ @@ -17771,74 +14587,31 @@ declare namespace _ { * @param updater The function to produce the updated value. * @return Returns object. */ - update( - object: Object, + update( + object: object, path: Many, - updater: Function - ): TResult; - - /** - * @see _.update - */ - update( - object: Object, - path: Many, - updater: U - ): TResult; - - /** - * @see _.update - */ - update( - object: O, - path: Many, - updater: Function - ): TResult; - - /** - * @see _.update - */ - update( - object: O, - path: Many, - updater: U - ): TResult; + updater: (value: any) => any + ): any; } - interface LoDashImplicitObjectWrapper { + interface LoDashImplicitWrapper { /** * @see _.update */ - update( + update( path: Many, - updater: any - ): LoDashImplicitObjectWrapper; - - /** - * @see _.update - */ - update( - path: Many, - updater: U - ): LoDashImplicitObjectWrapper; + updater: (value: any) => any + ): LoDashImplicitWrapper; } - interface LoDashExplicitObjectWrapper { + interface LoDashExplicitWrapper { /** * @see _.update */ - update( + update( path: Many, - updater: any - ): LoDashExplicitObjectWrapper; - - /** - * @see _.update - */ - update( - path: Many, - updater: U - ): LoDashExplicitObjectWrapper; + updater: (value: any) => any + ): LoDashExplicitWrapper; } //_.updateWith @@ -17867,44 +14640,62 @@ declare namespace _ { * _.updateWith(object, '[0][1]', _.constant('a'), Object); * // => { '0': { '1': 'a' } } */ - updateWith( - object: O, - path: Many, - updater: (oldValue: any) => any, - customizer?: SetWithCustomizer - ): TResult; - - /** - * @see _.updateWith - */ - updateWith( - object: any, - path: Many, - updater: (oldValue: any) => any, - customizer?: SetWithCustomizer - ): TResult; - } - - interface LoDashImplicitObjectWrapper { - /** - * @see _.updateWith - */ - updateWith( + updateWith( + object: T, path: Many, updater: (oldValue: any) => any, customizer?: SetWithCustomizer - ): LoDashImplicitObjectWrapper; + ): T; + + /** + * @see _.updateWith + */ + updateWith( + object: T, + path: Many, + updater: (oldValue: any) => any, + customizer?: SetWithCustomizer + ): TResult; } - interface LoDashExplicitObjectWrapper { + interface LoDashImplicitWrapper { + /** + * @see _.updateWith + */ + updateWith( + path: Many, + updater: (oldValue: any) => any, + customizer?: SetWithCustomizer + ): this; + /** * @see _.updateWith */ updateWith( path: Many, updater: (oldValue: any) => any, - customizer?: SetWithCustomizer - ): LoDashExplicitObjectWrapper; + customizer?: SetWithCustomizer + ): LoDashImplicitWrapper; + } + + interface LoDashExplicitWrapper { + /** + * @see _.updateWith + */ + updateWith( + path: Many, + updater: (oldValue: any) => any, + customizer?: SetWithCustomizer + ): this; + + /** + * @see _.updateWith + */ + updateWith( + path: Many, + updater: (oldValue: any) => any, + customizer?: SetWithCustomizer + ): LoDashExplicitWrapper; } //_.values @@ -17915,61 +14706,51 @@ declare namespace _ { * @param object The object to query. * @return Returns an array of property values. */ - values(object?: Dictionary|NumericDictionary|List | null | undefined): T[]; + values(object: Dictionary|NumericDictionary|List | null | undefined): T[]; /** * @see _.values */ - values(object?: any): T[]; + values(object: T | null | undefined): Array; + + /** + * @see _.values + */ + values(object: any): any[]; } - interface LoDashImplicitStringWrapper { + interface LoDashImplicitWrapper { /** * @see _.values */ - values(): LoDashImplicitArrayWrapper; + values(this: LoDashImplicitWrapper | NumericDictionary | List | null | undefined>): LoDashImplicitWrapper; + + /** + * @see _.values + */ + values(this: LoDashImplicitWrapper): LoDashImplicitWrapper>; + + /** + * @see _.values + */ + values(): LoDashImplicitWrapper; } - interface LoDashImplicitWrapper { + interface LoDashExplicitWrapper { /** * @see _.values */ - values(): LoDashImplicitArrayWrapper; - } + values(this: LoDashExplicitWrapper | NumericDictionary | List | null | undefined>): LoDashExplicitWrapper; - interface LoDashImplicitArrayWrapperBase { /** * @see _.values */ - values(): LoDashImplicitArrayWrapper; - } + values(this: LoDashExplicitWrapper): LoDashExplicitWrapper>; - interface LoDashImplicitObjectWrapperBase { /** * @see _.values */ - values(): LoDashImplicitArrayWrapper; - } - - interface LoDashExplicitWrapper { - /** - * @see _.values - */ - values(): LoDashExplicitArrayWrapper; - } - - interface LoDashExplicitArrayWrapperBase { - /** - * @see _.values - */ - values(): LoDashExplicitArrayWrapper; - } - - interface LoDashExplicitObjectWrapperBase { - /** - * @see _.values - */ - values(): LoDashExplicitArrayWrapper; + values(): LoDashExplicitWrapper; } //_.valuesIn @@ -17980,26 +14761,36 @@ declare namespace _ { * @param object The object to query. * @return Returns the array of property values. */ - valuesIn(object?: Dictionary): T[]; + valuesIn(object: Dictionary|NumericDictionary|List | null | undefined): T[]; /** * @see _.valuesIn */ - valuesIn(object?: any): T[]; + valuesIn(object: T | null | undefined): Array; } - interface LoDashImplicitObjectWrapperBase { + interface LoDashImplicitWrapper { /** * @see _.valuesIn */ - valuesIn(): LoDashImplicitArrayWrapper; + valuesIn(this: LoDashImplicitWrapper | NumericDictionary | List | null | undefined>): LoDashImplicitWrapper; + + /** + * @see _.valuesIn + */ + valuesIn(this: LoDashImplicitWrapper): LoDashImplicitWrapper>; } - interface LoDashExplicitObjectWrapperBase { + interface LoDashExplicitWrapper { /** * @see _.valuesIn */ - valuesIn(): LoDashExplicitArrayWrapper; + valuesIn(this: LoDashExplicitWrapper | NumericDictionary | List | null | undefined>): LoDashExplicitWrapper; + + /** + * @see _.valuesIn + */ + valuesIn(this: LoDashExplicitWrapper): LoDashExplicitWrapper>; } /********** @@ -18017,14 +14808,14 @@ declare namespace _ { camelCase(string?: string): string; } - interface LoDashImplicitWrapper { + interface LoDashImplicitWrapper { /** * @see _.camelCase */ camelCase(): string; } - interface LoDashExplicitWrapper { + interface LoDashExplicitWrapper { /** * @see _.camelCase */ @@ -18042,14 +14833,14 @@ declare namespace _ { capitalize(string?: string): string; } - interface LoDashImplicitWrapper { + interface LoDashImplicitWrapper { /** * @see _.capitalize */ capitalize(): string; } - interface LoDashExplicitWrapper { + interface LoDashExplicitWrapper { /** * @see _.capitalize */ @@ -18068,14 +14859,14 @@ declare namespace _ { deburr(string?: string): string; } - interface LoDashImplicitWrapper { + interface LoDashImplicitWrapper { /** * @see _.deburr */ deburr(): string; } - interface LoDashExplicitWrapper { + interface LoDashExplicitWrapper { /** * @see _.deburr */ @@ -18099,7 +14890,7 @@ declare namespace _ { ): boolean; } - interface LoDashImplicitWrapper { + interface LoDashImplicitWrapper { /** * @see _.endsWith */ @@ -18109,7 +14900,7 @@ declare namespace _ { ): boolean; } - interface LoDashExplicitWrapper { + interface LoDashExplicitWrapper { /** * @see _.endsWith */ @@ -18141,14 +14932,14 @@ declare namespace _ { escape(string?: string): string; } - interface LoDashImplicitWrapper { + interface LoDashImplicitWrapper { /** * @see _.escape */ escape(): string; } - interface LoDashExplicitWrapper { + interface LoDashExplicitWrapper { /** * @see _.escape */ @@ -18167,14 +14958,14 @@ declare namespace _ { escapeRegExp(string?: string): string; } - interface LoDashImplicitWrapper { + interface LoDashImplicitWrapper { /** * @see _.escapeRegExp */ escapeRegExp(): string; } - interface LoDashExplicitWrapper { + interface LoDashExplicitWrapper { /** * @see _.escapeRegExp */ @@ -18192,14 +14983,14 @@ declare namespace _ { kebabCase(string?: string): string; } - interface LoDashImplicitWrapper { + interface LoDashImplicitWrapper { /** * @see _.kebabCase */ kebabCase(): string; } - interface LoDashExplicitWrapper { + interface LoDashExplicitWrapper { /** * @see _.kebabCase */ @@ -18217,14 +15008,14 @@ declare namespace _ { lowerCase(string?: string): string; } - interface LoDashImplicitWrapper { + interface LoDashImplicitWrapper { /** * @see _.lowerCase */ lowerCase(): string; } - interface LoDashExplicitWrapper { + interface LoDashExplicitWrapper { /** * @see _.lowerCase */ @@ -18242,14 +15033,14 @@ declare namespace _ { lowerFirst(string?: string): string; } - interface LoDashImplicitWrapper { + interface LoDashImplicitWrapper { /** * @see _.lowerFirst */ lowerFirst(): string; } - interface LoDashExplicitWrapper { + interface LoDashExplicitWrapper { /** * @see _.lowerFirst */ @@ -18274,7 +15065,7 @@ declare namespace _ { ): string; } - interface LoDashImplicitWrapper { + interface LoDashImplicitWrapper { /** * @see _.pad */ @@ -18284,7 +15075,7 @@ declare namespace _ { ): string; } - interface LoDashExplicitWrapper { + interface LoDashExplicitWrapper { /** * @see _.pad */ @@ -18312,7 +15103,7 @@ declare namespace _ { ): string; } - interface LoDashImplicitWrapper { + interface LoDashImplicitWrapper { /** * @see _.padEnd */ @@ -18322,7 +15113,7 @@ declare namespace _ { ): string; } - interface LoDashExplicitWrapper { + interface LoDashExplicitWrapper { /** * @see _.padEnd */ @@ -18350,7 +15141,7 @@ declare namespace _ { ): string; } - interface LoDashImplicitWrapper { + interface LoDashImplicitWrapper { /** * @see _.padStart */ @@ -18360,7 +15151,7 @@ declare namespace _ { ): string; } - interface LoDashExplicitWrapper { + interface LoDashExplicitWrapper { /** * @see _.padStart */ @@ -18388,14 +15179,14 @@ declare namespace _ { ): number; } - interface LoDashImplicitWrapper { + interface LoDashImplicitWrapper { /** * @see _.parseInt */ parseInt(radix?: number): number; } - interface LoDashExplicitWrapper { + interface LoDashExplicitWrapper { /** * @see _.parseInt */ @@ -18417,20 +15208,22 @@ declare namespace _ { ): string; } - interface LoDashImplicitWrapper { + interface LoDashImplicitWrapper { /** * @see _.repeat */ repeat(n?: number): string; } - interface LoDashExplicitWrapper { + interface LoDashExplicitWrapper { /** * @see _.repeat */ repeat(n?: number): LoDashExplicitWrapper; } + type ReplaceFunction = (match: string, ...args: any[]) => string; + //_.replace interface LoDashStatic { /** @@ -18445,84 +15238,50 @@ declare namespace _ { */ replace( string: string, + pattern: RegExp | string, + replacement: ReplaceFunction | string + ): string; + + /** + * @see _.replace + */ + replace( + pattern: RegExp | string, + replacement: ReplaceFunction | string + ): string; + } + + interface LoDashImplicitWrapper { + /** + * @see _.replace + */ + replace( pattern: RegExp|string, - replacement: Function|string + replacement: ReplaceFunction | string ): string; /** * @see _.replace */ replace( - pattern?: RegExp|string, - replacement?: Function|string + replacement: ReplaceFunction | string ): string; } - interface LoDashImplicitWrapper { + interface LoDashExplicitWrapper { /** * @see _.replace */ replace( - pattern?: RegExp|string, - replacement?: Function|string - ): string; - - /** - * @see _.replace - */ - replace( - replacement?: Function|string - ): string; - } - - interface LoDashImplicitObjectWrapper { - /** - * @see _.replace - */ - replace( - pattern?: RegExp|string, - replacement?: Function|string - ): string; - - /** - * @see _.replace - */ - replace( - replacement?: Function|string - ): string; - } - - interface LoDashExplicitWrapper { - /** - * @see _.replace - */ - replace( - pattern?: RegExp|string, - replacement?: Function|string + pattern: RegExp | string, + replacement: ReplaceFunction | string ): LoDashExplicitWrapper; /** * @see _.replace */ replace( - replacement?: Function|string - ): LoDashExplicitWrapper; - } - - interface LoDashExplicitObjectWrapper { - /** - * @see _.replace - */ - replace( - pattern?: RegExp|string, - replacement?: Function|string - ): LoDashExplicitWrapper; - - /** - * @see _.replace - */ - replace( - replacement?: Function|string + replacement: ReplaceFunction | string ): LoDashExplicitWrapper; } @@ -18537,14 +15296,14 @@ declare namespace _ { snakeCase(string?: string): string; } - interface LoDashImplicitWrapper { + interface LoDashImplicitWrapper { /** * @see _.snakeCase */ snakeCase(): string; } - interface LoDashExplicitWrapper { + interface LoDashExplicitWrapper { /** * @see _.snakeCase */ @@ -18570,24 +15329,24 @@ declare namespace _ { ): string[]; } - interface LoDashImplicitWrapper { + interface LoDashImplicitWrapper { /** * @see _.split */ split( separator?: RegExp|string, limit?: number - ): LoDashImplicitArrayWrapper; + ): LoDashImplicitWrapper; } - interface LoDashExplicitWrapper { + interface LoDashExplicitWrapper { /** * @see _.split */ split( separator?: RegExp|string, limit?: number - ): LoDashExplicitArrayWrapper; + ): LoDashExplicitWrapper; } //_.startCase @@ -18601,14 +15360,14 @@ declare namespace _ { startCase(string?: string): string; } - interface LoDashImplicitWrapper { + interface LoDashImplicitWrapper { /** * @see _.startCase */ startCase(): string; } - interface LoDashExplicitWrapper { + interface LoDashExplicitWrapper { /** * @see _.startCase */ @@ -18632,7 +15391,7 @@ declare namespace _ { ): boolean; } - interface LoDashImplicitWrapper { + interface LoDashImplicitWrapper { /** * @see _.startsWith */ @@ -18642,7 +15401,7 @@ declare namespace _ { ): boolean; } - interface LoDashExplicitWrapper { + interface LoDashExplicitWrapper { /** * @see _.startsWith */ @@ -18661,7 +15420,7 @@ declare namespace _ { } interface TemplateExecutor { - (data?: Object): string; + (data?: object): string; source: string; } @@ -18693,23 +15452,23 @@ declare namespace _ { * @return Returns the compiled template function. */ template( - string: string, + string?: string, options?: TemplateOptions ): TemplateExecutor; } - interface LoDashImplicitWrapper { + interface LoDashImplicitWrapper { /** * @see _.template */ template(options?: TemplateOptions): TemplateExecutor; } - interface LoDashExplicitWrapper { + interface LoDashExplicitWrapper { /** * @see _.template */ - template(options?: TemplateOptions): LoDashExplicitObjectWrapper; + template(options?: TemplateOptions): LoDashExplicitWrapper; } //_.toLower @@ -18723,14 +15482,14 @@ declare namespace _ { toLower(string?: string): string; } - interface LoDashImplicitWrapper { + interface LoDashImplicitWrapper { /** * @see _.toLower */ toLower(): string; } - interface LoDashExplicitWrapper { + interface LoDashExplicitWrapper { /** * @see _.toLower */ @@ -18748,14 +15507,14 @@ declare namespace _ { toUpper(string?: string): string; } - interface LoDashImplicitWrapper { + interface LoDashImplicitWrapper { /** * @see _.toUpper */ toUpper(): string; } - interface LoDashExplicitWrapper { + interface LoDashExplicitWrapper { /** * @see _.toUpper */ @@ -18777,14 +15536,14 @@ declare namespace _ { ): string; } - interface LoDashImplicitWrapper { + interface LoDashImplicitWrapper { /** * @see _.trim */ trim(chars?: string): string; } - interface LoDashExplicitWrapper { + interface LoDashExplicitWrapper { /** * @see _.trim */ @@ -18806,14 +15565,14 @@ declare namespace _ { ): string; } - interface LoDashImplicitWrapper { + interface LoDashImplicitWrapper { /** * @see _.trimEnd */ trimEnd(chars?: string): string; } - interface LoDashExplicitWrapper { + interface LoDashExplicitWrapper { /** * @see _.trimEnd */ @@ -18835,14 +15594,14 @@ declare namespace _ { ): string; } - interface LoDashImplicitWrapper { + interface LoDashImplicitWrapper { /** * @see _.trimStart */ trimStart(chars?: string): string; } - interface LoDashExplicitWrapper { + interface LoDashExplicitWrapper { /** * @see _.trimStart */ @@ -18874,14 +15633,14 @@ declare namespace _ { ): string; } - interface LoDashImplicitWrapper { + interface LoDashImplicitWrapper { /** * @see _.truncate */ truncate(options?: TruncateOptions): string; } - interface LoDashExplicitWrapper { + interface LoDashExplicitWrapper { /** * @see _.truncate */ @@ -18903,14 +15662,14 @@ declare namespace _ { unescape(string?: string): string; } - interface LoDashImplicitWrapper { + interface LoDashImplicitWrapper { /** * @see _.unescape */ unescape(): string; } - interface LoDashExplicitWrapper { + interface LoDashExplicitWrapper { /** * @see _.unescape */ @@ -18928,14 +15687,14 @@ declare namespace _ { upperCase(string?: string): string; } - interface LoDashImplicitWrapper { + interface LoDashImplicitWrapper { /** * @see _.upperCase */ upperCase(): string; } - interface LoDashExplicitWrapper { + interface LoDashExplicitWrapper { /** * @see _.upperCase */ @@ -18953,14 +15712,14 @@ declare namespace _ { upperFirst(string?: string): string; } - interface LoDashImplicitWrapper { + interface LoDashImplicitWrapper { /** * @see _.upperFirst */ upperFirst(): string; } - interface LoDashExplicitWrapper { + interface LoDashExplicitWrapper { /** * @see _.upperFirst */ @@ -18982,18 +15741,18 @@ declare namespace _ { ): string[]; } - interface LoDashImplicitWrapper { + interface LoDashImplicitWrapper { /** * @see _.words */ words(pattern?: string|RegExp): string[]; } - interface LoDashExplicitWrapper { + interface LoDashExplicitWrapper { /** * @see _.words */ - words(pattern?: string|RegExp): LoDashExplicitArrayWrapper; + words(pattern?: string|RegExp): LoDashExplicitWrapper; } /*********** @@ -19012,18 +15771,18 @@ declare namespace _ { attempt(func: (...args: any[]) => TResult, ...args: any[]): TResult|Error; } - interface LoDashImplicitObjectWrapper { + interface LoDashImplicitWrapper { /** * @see _.attempt */ attempt(...args: any[]): TResult|Error; } - interface LoDashExplicitObjectWrapper { + interface LoDashExplicitWrapper { /** * @see _.attempt */ - attempt(...args: any[]): LoDashExplicitObjectWrapper; + attempt(...args: any[]): LoDashExplicitWrapper; } //_.constant @@ -19037,18 +15796,18 @@ declare namespace _ { constant(value: T): () => T; } - interface LoDashImplicitWrapperBase { + interface LoDashImplicitWrapper { /** * @see _.constant */ - constant(): LoDashImplicitObjectWrapper<() => TResult>; + constant(): LoDashImplicitWrapper<() => TValue>; } - interface LoDashExplicitWrapperBase { + interface LoDashExplicitWrapper { /** * @see _.constant */ - constant(): LoDashExplicitObjectWrapper<() => TResult>; + constant(): LoDashExplicitWrapper<() => TValue>; } //_.defaultTo @@ -19063,20 +15822,44 @@ declare namespace _ { * @returns Returns the resolved value. */ defaultTo(value: T | null | undefined, defaultValue: T): T; - } - interface LoDashImplicitWrapperBase { /** * @see _.defaultTo */ - defaultTo(value: TResult): LoDashImplicitObjectWrapper; + defaultTo( + value: T | null | undefined, + defaultValue: TDefault + ): T | TDefault; } - interface LoDashExplicitWrapperBase { + interface LoDashImplicitWrapper { /** * @see _.defaultTo */ - defaultTo(value: TResult): LoDashExplicitObjectWrapper; + defaultTo(this: LoDashImplicitWrapper, defaultValue: T): T; + + /** + * @see _.defaultTo + */ + defaultTo( + this: LoDashImplicitWrapper, + defaultValue: TDefault + ): T | TDefault; + } + + interface LoDashExplicitWrapper { + /** + * @see _.defaultTo + */ + defaultTo(this: LoDashExplicitWrapper, defaultValue: T): LoDashExplicitWrapper; + + /** + * @see _.defaultTo + */ + defaultTo( + this: LoDashExplicitWrapper, + defaultValue: TDefault + ): LoDashExplicitWrapper; } //_.identity @@ -19095,46 +15878,18 @@ declare namespace _ { identity(): undefined; } - interface LoDashImplicitWrapper { + interface LoDashImplicitWrapper { /** * @see _.identity */ - identity(): T; + identity(): TValue; } - interface LoDashImplicitArrayWrapperBase { + interface LoDashExplicitWrapper { /** * @see _.identity */ - identity(): TArray; - } - - interface LoDashImplicitObjectWrapperBase { - /** - * @see _.identity - */ - identity(): TObject; - } - - interface LoDashExplicitWrapper { - /** - * @see _.identity - */ - identity(): LoDashExplicitWrapper; - } - - interface LoDashExplicitArrayWrapperBase { - /** - * @see _.identity - */ - identity(): TWrapper; - } - - interface LoDashExplicitObjectWrapperBase { - /** - * @see _.identity - */ - identity(): TWrapper; + identity(): this; } //_.iteratee @@ -19168,66 +15923,32 @@ declare namespace _ { * _.filter(users, 'age > 36'); * // => [{ 'user': 'fred', 'age': 40 }] */ - iteratee( - func: TFunction + iteratee any>( + func: TFunction | string | object ): TFunction; /** * @see _.iteratee */ - iteratee( - func: string - ): (object: any) => TResult; - - /** - * @see _.iteratee - */ - iteratee( - func: Object - ): (object: any) => boolean; - - /** - * @see _.iteratee - */ - iteratee(): (value: TResult) => TResult; + iteratee(): typeof _.identity; // tslint:disable-line:no-unnecessary-qualifier } - interface LoDashImplicitWrapper { + interface LoDashImplicitWrapper { /** * @see _.iteratee */ - iteratee(): LoDashImplicitObjectWrapper<(object: any) => TResult>; + iteratee any>( + this: LoDashImplicitWrapper + ): LoDashImplicitWrapper; } - interface LoDashImplicitObjectWrapper { + interface LoDashExplicitWrapper { /** * @see _.iteratee */ - iteratee(): LoDashImplicitObjectWrapper<(object: any) => boolean>; - - /** - * @see _.iteratee - */ - iteratee(): LoDashImplicitObjectWrapper<(...args: any[]) => TResult>; - } - - interface LoDashExplicitWrapper { - /** - * @see _.iteratee - */ - iteratee(): LoDashExplicitObjectWrapper<(object: any) => TResult>; - } - - interface LoDashExplicitObjectWrapper { - /** - * @see _.iteratee - */ - iteratee(): LoDashExplicitObjectWrapper<(object: any) => boolean>; - - /** - * @see _.iteratee - */ - iteratee(): LoDashExplicitObjectWrapper<(...args: any[]) => TResult>; + iteratee any>( + this: LoDashExplicitWrapper + ): LoDashExplicitWrapper; } //_.matches @@ -19251,18 +15972,18 @@ declare namespace _ { matches(source: T): (value: V) => boolean; } - interface LoDashImplicitWrapperBase { + interface LoDashImplicitWrapper { /** * @see _.matches */ - matches(): LoDashImplicitObjectWrapper<(value: V) => boolean>; + matches(): LoDashImplicitWrapper<(value: V) => boolean>; } - interface LoDashExplicitWrapperBase { + interface LoDashExplicitWrapper { /** * @see _.matches */ - matches(): LoDashExplicitObjectWrapper<(value: V) => boolean>; + matches(): LoDashExplicitWrapper<(value: V) => boolean>; } //_.matchesProperty @@ -19291,36 +16012,36 @@ declare namespace _ { ): (value: V) => boolean; } - interface LoDashImplicitWrapperBase { + interface LoDashImplicitWrapper { /** * @see _.matchesProperty */ matchesProperty( srcValue: SrcValue - ): LoDashImplicitObjectWrapper<(value: any) => boolean>; + ): LoDashImplicitWrapper<(value: any) => boolean>; /** * @see _.matchesProperty */ matchesProperty( srcValue: SrcValue - ): LoDashImplicitObjectWrapper<(value: Value) => boolean>; + ): LoDashImplicitWrapper<(value: Value) => boolean>; } - interface LoDashExplicitWrapperBase { + interface LoDashExplicitWrapper { /** * @see _.matchesProperty */ matchesProperty( srcValue: SrcValue - ): LoDashExplicitObjectWrapper<(value: any) => boolean>; + ): LoDashExplicitWrapper<(value: any) => boolean>; /** * @see _.matchesProperty */ matchesProperty( srcValue: SrcValue - ): LoDashExplicitObjectWrapper<(value: Value) => boolean>; + ): LoDashExplicitWrapper<(value: Value) => boolean>; } //_.method @@ -19333,66 +16054,24 @@ declare namespace _ { * @param args The arguments to invoke the method with. * @return Returns the new function. */ - method( + method( path: string|StringRepresentable[], ...args: any[] - ): (object: TObject) => TResult; - - /** - * @see _.method - */ - method( - path: string|StringRepresentable[], - ...args: any[] - ): (object: any) => TResult; + ): (object: any) => any; } - interface LoDashImplicitWrapper { + interface LoDashImplicitWrapper { /** * @see _.method */ - method(...args: any[]): LoDashImplicitObjectWrapper<(object: TObject) => TResult>; - - /** - * @see _.method - */ - method(...args: any[]): LoDashImplicitObjectWrapper<(object: any) => TResult>; + method(...args: any[]): LoDashImplicitWrapper<(object: any) => any>; } - interface LoDashImplicitArrayWrapper { + interface LoDashExplicitWrapper { /** * @see _.method */ - method(...args: any[]): LoDashImplicitObjectWrapper<(object: TObject) => TResult>; - - /** - * @see _.method - */ - method(...args: any[]): LoDashImplicitObjectWrapper<(object: any) => TResult>; - } - - interface LoDashExplicitWrapper { - /** - * @see _.method - */ - method(...args: any[]): LoDashExplicitObjectWrapper<(object: TObject) => TResult>; - - /** - * @see _.method - */ - method(...args: any[]): LoDashExplicitObjectWrapper<(object: any) => TResult>; - } - - interface LoDashExplicitArrayWrapper { - /** - * @see _.method - */ - method(...args: any[]): LoDashExplicitObjectWrapper<(object: TObject) => TResult>; - - /** - * @see _.method - */ - method(...args: any[]): LoDashExplicitObjectWrapper<(object: any) => TResult>; + method(...args: any[]): LoDashExplicitWrapper<(object: any) => any>; } //_.methodOf @@ -19405,36 +16084,28 @@ declare namespace _ { * @param args The arguments to invoke the method with. * @return Returns the new function. */ - methodOf( - object: TObject, + methodOf( + object: object, ...args: any[] - ): (path: Many) => TResult; - - /** - * @see _.methodOf - */ - methodOf( - object: {}, - ...args: any[] - ): (path: Many) => TResult; + ): (path: Many) => any; } - interface LoDashImplicitObjectWrapper { + interface LoDashImplicitWrapper { /** * @see _.methodOf */ - methodOf( + methodOf( ...args: any[] - ): LoDashImplicitObjectWrapper<(path: Many) => TResult>; + ): LoDashImplicitWrapper<(path: Many) => any>; } - interface LoDashExplicitObjectWrapper { + interface LoDashExplicitWrapper { /** * @see _.methodOf */ - methodOf( + methodOf( ...args: any[] - ): LoDashExplicitObjectWrapper<(path: Many) => TResult>; + ): LoDashExplicitWrapper<(path: Many) => any>; } //_.mixin @@ -19456,53 +16127,53 @@ declare namespace _ { * @param options.chain Specify whether the functions added are chainable. * @return Returns object. */ - mixin( + mixin( object: TObject, - source: Dictionary, + source: Dictionary<(...args: any[]) => any>, options?: MixinOptions - ): TResult; + ): TObject; /** * @see _.mixin */ mixin( - source: Dictionary, + source: Dictionary<(...args: any[]) => any>, options?: MixinOptions - ): TResult; + ): LoDashStatic; } - interface LoDashImplicitObjectWrapper { + interface LoDashImplicitWrapper { /** * @see _.mixin */ - mixin( - source: Dictionary, + mixin( + source: Dictionary<(...args: any[]) => any>, options?: MixinOptions - ): LoDashImplicitObjectWrapper; + ): this; /** * @see _.mixin */ - mixin( + mixin( options?: MixinOptions - ): LoDashImplicitObjectWrapper; + ): LoDashImplicitWrapper; } - interface LoDashExplicitObjectWrapper { + interface LoDashExplicitWrapper { /** * @see _.mixin */ - mixin( - source: Dictionary, + mixin( + source: Dictionary<(...args: any[]) => any>, options?: MixinOptions - ): LoDashExplicitObjectWrapper; + ): this; /** * @see _.mixin */ - mixin( + mixin( options?: MixinOptions - ): LoDashExplicitObjectWrapper; + ): LoDashExplicitWrapper; } //_.noConflict @@ -19515,18 +16186,18 @@ declare namespace _ { noConflict(): typeof _; } - interface LoDashImplicitWrapperBase { + interface LoDashImplicitWrapper { /** * @see _.noConflict */ noConflict(): typeof _; } - interface LoDashExplicitWrapperBase { + interface LoDashExplicitWrapper { /** * @see _.noConflict */ - noConflict(): LoDashExplicitObjectWrapper; + noConflict(): LoDashExplicitWrapper; } //_.noop @@ -19539,18 +16210,18 @@ declare namespace _ { noop(...args: any[]): void; } - interface LoDashImplicitWrapperBase { + interface LoDashImplicitWrapper { /** * @see _.noop */ noop(...args: any[]): void; } - interface LoDashExplicitWrapperBase { + interface LoDashExplicitWrapper { /** * @see _.noop */ - noop(...args: any[]): _.LoDashExplicitWrapper; + noop(...args: any[]): LoDashExplicitWrapper; } //_.nthArg @@ -19561,21 +16232,21 @@ declare namespace _ { * @param n The index of the argument to return. * @return Returns the new function. */ - nthArg(n?: number): TResult; + nthArg(n?: number): (...args: any[]) => any; } - interface LoDashImplicitWrapper { + interface LoDashImplicitWrapper { /** * @see _.nthArg */ - nthArg(): LoDashImplicitObjectWrapper; + nthArg(): LoDashImplicitWrapper<(...args: any[]) => any>; } - interface LoDashExplicitWrapper { + interface LoDashExplicitWrapper { /** * @see _.nthArg */ - nthArg(): LoDashExplicitObjectWrapper; + nthArg(): LoDashExplicitWrapper<(...args: any[]) => any>; } //_.over @@ -19587,35 +16258,27 @@ declare namespace _ { * @param iteratees The iteratees to invoke. * @return Returns the new function. */ - over(...iteratees: Array>): (...args: any[]) => TResult[]; + over(...iteratees: Array TResult>>): (...args: any[]) => TResult[]; } - interface LoDashImplicitArrayWrapper { + interface LoDashImplicitWrapper { /** * @see _.over */ - over(...iteratees: Array>): LoDashImplicitObjectWrapper<(...args: any[]) => TResult[]>; + over( + this: LoDashImplicitWrapper TResult>>, + ...iteratees: Array TResult>> + ): LoDashImplicitWrapper<(...args: any[]) => TResult[]>; } - interface LoDashImplicitObjectWrapper { + interface LoDashExplicitWrapper { /** * @see _.over */ - over(...iteratees: Array>): LoDashImplicitObjectWrapper<(...args: any[]) => TResult[]>; - } - - interface LoDashExplicitArrayWrapper { - /** - * @see _.over - */ - over(...iteratees: Array>): LoDashExplicitObjectWrapper<(...args: any[]) => TResult[]>; - } - - interface LoDashExplicitObjectWrapper { - /** - * @see _.over - */ - over(...iteratees: Array>): LoDashExplicitObjectWrapper<(...args: any[]) => TResult[]>; + over( + this: LoDashExplicitWrapper TResult>>, + ...iteratees: Array TResult>> + ): LoDashExplicitWrapper<(...args: any[]) => TResult[]>; } //_.overEvery @@ -19627,35 +16290,21 @@ declare namespace _ { * @param predicates The predicates to check. * @return Returns the new function. */ - overEvery(...predicates: Array>): (...args: any[]) => boolean; + overEvery(...predicates: Array any>>): (...args: any[]) => boolean; } - interface LoDashImplicitArrayWrapper { + interface LoDashImplicitWrapper { /** * @see _.overEvery */ - overEvery(...predicates: Array>): LoDashImplicitObjectWrapper<(...args: any[]) => boolean>; + overEvery(...predicates: Array any>>): LoDashImplicitWrapper<(...args: any[]) => boolean>; } - interface LoDashImplicitObjectWrapper { + interface LoDashExplicitWrapper { /** * @see _.overEvery */ - overEvery(...predicates: Array>): LoDashImplicitObjectWrapper<(...args: any[]) => boolean>; - } - - interface LoDashExplicitArrayWrapper { - /** - * @see _.overEvery - */ - overEvery(...predicates: Array>): LoDashExplicitObjectWrapper<(...args: any[]) => boolean>; - } - - interface LoDashExplicitObjectWrapper { - /** - * @see _.overEvery - */ - overEvery(...predicates: Array>): LoDashExplicitObjectWrapper<(...args: any[]) => boolean>; + overEvery(...predicates: Array any>>): LoDashExplicitWrapper<(...args: any[]) => boolean>; } //_.overSome @@ -19667,35 +16316,21 @@ declare namespace _ { * @param predicates The predicates to check. * @return Returns the new function. */ - overSome(...predicates: Array>): (...args: any[]) => boolean; + overSome(...predicates: Array any>>): (...args: any[]) => boolean; } - interface LoDashImplicitArrayWrapper { + interface LoDashImplicitWrapper { /** * @see _.overSome */ - overSome(...predicates: Array>): LoDashImplicitObjectWrapper<(...args: any[]) => boolean>; + overSome(...predicates: Array any>>): LoDashImplicitWrapper<(...args: any[]) => boolean>; } - interface LoDashImplicitObjectWrapper { + interface LoDashExplicitWrapper { /** * @see _.overSome */ - overSome(...predicates: Array>): LoDashImplicitObjectWrapper<(...args: any[]) => boolean>; - } - - interface LoDashExplicitArrayWrapper { - /** - * @see _.overSome - */ - overSome(...predicates: Array>): LoDashExplicitObjectWrapper<(...args: any[]) => boolean>; - } - - interface LoDashExplicitObjectWrapper { - /** - * @see _.overSome - */ - overSome(...predicates: Array>): LoDashExplicitObjectWrapper<(...args: any[]) => boolean>; + overSome(...predicates: Array any>>): LoDashExplicitWrapper<(...args: any[]) => boolean>; } //_.property @@ -19709,32 +16344,18 @@ declare namespace _ { property(path: Many): (obj: TObj) => TResult; } - interface LoDashImplicitWrapper { + interface LoDashImplicitWrapper { /** * @see _.property */ - property(): LoDashImplicitObjectWrapper<(obj: TObj) => TResult>; + property(): LoDashImplicitWrapper<(obj: TObj) => TResult>; } - interface LoDashImplicitArrayWrapper { + interface LoDashExplicitWrapper { /** * @see _.property */ - property(): LoDashImplicitObjectWrapper<(obj: TObj) => TResult>; - } - - interface LoDashExplicitWrapper { - /** - * @see _.property - */ - property(): LoDashExplicitObjectWrapper<(obj: TObj) => TResult>; - } - - interface LoDashExplicitArrayWrapper { - /** - * @see _.property - */ - property(): LoDashExplicitObjectWrapper<(obj: TObj) => TResult>; + property(): LoDashExplicitWrapper<(obj: TObj) => TResult>; } //_.propertyOf @@ -19749,18 +16370,18 @@ declare namespace _ { propertyOf(object: T): (path: Many) => any; } - interface LoDashImplicitObjectWrapper { + interface LoDashImplicitWrapper { /** * @see _.propertyOf */ - propertyOf(): LoDashImplicitObjectWrapper<(path: Many) => any>; + propertyOf(): LoDashImplicitWrapper<(path: Many) => any>; } - interface LoDashExplicitObjectWrapper { + interface LoDashExplicitWrapper { /** * @see _.propertyOf */ - propertyOf(): LoDashExplicitObjectWrapper<(path: Many) => any>; + propertyOf(): LoDashExplicitWrapper<(path: Many) => any>; } //_.range @@ -19777,37 +16398,29 @@ declare namespace _ { */ range( start: number, - end: number, - step?: number - ): number[]; - - /** - * @see _.range - */ - range( - end: number, + end?: number, step?: number ): number[]; } - interface LoDashImplicitWrapper { + interface LoDashImplicitWrapper { /** * @see _.range */ range( end?: number, step?: number - ): LoDashImplicitArrayWrapper; + ): LoDashImplicitWrapper; } - interface LoDashExplicitWrapper { + interface LoDashExplicitWrapper { /** * @see _.range */ range( end?: number, step?: number - ): LoDashExplicitArrayWrapper; + ): LoDashExplicitWrapper; } //_.rangeRight @@ -19848,37 +16461,29 @@ declare namespace _ { */ rangeRight( start: number, - end: number, - step?: number - ): number[]; - - /** - * @see _.rangeRight - */ - rangeRight( - end: number, + end?: number, step?: number ): number[]; } - interface LoDashImplicitWrapper { + interface LoDashImplicitWrapper { /** * @see _.rangeRight */ rangeRight( end?: number, step?: number - ): LoDashImplicitArrayWrapper; + ): LoDashImplicitWrapper; } - interface LoDashExplicitWrapper { + interface LoDashExplicitWrapper { /** * @see _.rangeRight */ rangeRight( end?: number, step?: number - ): LoDashExplicitArrayWrapper; + ): LoDashExplicitWrapper; } //_.runInContext @@ -19889,10 +16494,10 @@ declare namespace _ { * @param context The context object. * @return Returns a new lodash function. */ - runInContext(context?: Object): typeof _; + runInContext(context?: object): typeof _; } - interface LoDashImplicitObjectWrapper { + interface LoDashImplicitWrapper { /** * @see _.runInContext */ @@ -19909,18 +16514,18 @@ declare namespace _ { stubArray(): any[]; } - interface LoDashImplicitWrapperBase { + interface LoDashImplicitWrapper { /** * @see _.stubArray */ stubArray(): any[]; } - interface LoDashExplicitWrapperBase { + interface LoDashExplicitWrapper { /** * @see _.stubArray */ - stubArray(): _.LoDashExplicitArrayWrapper; + stubArray(): LoDashExplicitWrapper; } // _.stubFalse @@ -19933,18 +16538,18 @@ declare namespace _ { stubFalse(): boolean; } - interface LoDashImplicitWrapperBase { + interface LoDashImplicitWrapper { /** * @see _.stubFalse */ stubFalse(): boolean; } - interface LoDashExplicitWrapperBase { + interface LoDashExplicitWrapper { /** * @see _.stubFalse */ - stubFalse(): _.LoDashExplicitWrapper; + stubFalse(): LoDashExplicitWrapper; } interface LoDashStatic { @@ -19953,21 +16558,21 @@ declare namespace _ { * * @returns Returns the new empty object. */ - stubObject(): Object; + stubObject(): any; } - interface LoDashImplicitWrapperBase { + interface LoDashImplicitWrapper { /** * @see _.stubObject */ - stubObject(): Object; + stubObject(): any; } - interface LoDashExplicitWrapperBase { + interface LoDashExplicitWrapper { /** * @see _.stubObject */ - stubObject(): _.LoDashExplicitObjectWrapper; + stubObject(): LoDashExplicitWrapper; } interface LoDashStatic { @@ -19979,18 +16584,18 @@ declare namespace _ { stubString(): string; } - interface LoDashImplicitWrapperBase { + interface LoDashImplicitWrapper { /** * @see _.stubString */ stubString(): string; } - interface LoDashExplicitWrapperBase { + interface LoDashExplicitWrapper { /** * @see _.stubString */ - stubString(): _.LoDashExplicitWrapper; + stubString(): LoDashExplicitWrapper; } interface LoDashStatic { @@ -20002,18 +16607,18 @@ declare namespace _ { stubTrue(): boolean; } - interface LoDashImplicitWrapperBase { + interface LoDashImplicitWrapper { /** * @see _.stubTrue */ stubTrue(): boolean; } - interface LoDashExplicitWrapperBase { + interface LoDashExplicitWrapper { /** * @see _.stubTrue */ - stubTrue(): _.LoDashExplicitWrapper; + stubTrue(): LoDashExplicitWrapper; } //_.times @@ -20037,7 +16642,7 @@ declare namespace _ { times(n: number): number[]; } - interface LoDashImplicitWrapper { + interface LoDashImplicitWrapper { /** * @see _.times */ @@ -20051,18 +16656,18 @@ declare namespace _ { times(): number[]; } - interface LoDashExplicitWrapper { + interface LoDashExplicitWrapper { /** * @see _.times */ times( iteratee: (num: number) => TResult - ): LoDashExplicitArrayWrapper; + ): LoDashExplicitWrapper; /** * @see _.times */ - times(): LoDashExplicitArrayWrapper; + times(): LoDashExplicitWrapper; } //_.toPath @@ -20095,14 +16700,14 @@ declare namespace _ { toPath(value: any): string[]; } - interface LoDashImplicitWrapperBase { + interface LoDashImplicitWrapper { /** * @see _.toPath */ toPath(): LoDashImplicitWrapper; } - interface LoDashExplicitWrapperBase { + interface LoDashExplicitWrapper { /** * @see _.toPath */ @@ -20120,41 +16725,53 @@ declare namespace _ { uniqueId(prefix?: string): string; } - interface LoDashImplicitWrapper { + interface LoDashImplicitWrapper { /** * @see _.uniqueId */ uniqueId(): string; } - interface LoDashExplicitWrapper { + interface LoDashExplicitWrapper { /** * @see _.uniqueId */ uniqueId(): LoDashExplicitWrapper; } + type ArrayIterator = (value: T, index: number, collection: T[]) => TResult; type ListIterator = (value: T, index: number, collection: List) => TResult; - + type ListIteratee = ListIterator | string | [string, any] | PartialDeep; type ListIteratorTypeGuard = (value: T, index: number, collection: List) => value is S; - type DictionaryIterator = (value: T, key: string, collection: Dictionary) => TResult; + // Note: key should be string, not keyof T, because the actual object may contain extra properties that were not specified in the type. + type ObjectIterator = (value: TObject[keyof TObject], key: string, collection: TObject) => TResult; + type ObjectIteratee = ObjectIterator | string | [string, any] | PartialDeep; + type ObjectIteratorTypeGuard = (value: TObject[keyof TObject], key: string, collection: TObject) => value is S; - type DictionaryIteratorTypeGuard = (value: T, key: string, collection: Dictionary) => value is S; + type DictionaryIterator = ObjectIterator, TResult>; + type DictionaryIteratee = ObjectIteratee>; + type DictionaryIteratorTypeGuard = ObjectIteratorTypeGuard, S>; - type NumericDictionaryIterator = (value: T, key: number, collection: Dictionary) => TResult; - - type ObjectIterator = (element: T, key: string, collection: any) => TResult; + type NumericDictionaryIterator = (value: T, key: number, collection: NumericDictionary) => TResult; + type NumericDictionaryIteratee = NumericDictionaryIterator | string | [string, any] | PartialDeep; type StringIterator = (char: string, index: number, string: string) => TResult; type MemoVoidIterator = (prev: TResult, curr: T, indexOrKey: any, list: T[]) => void; + /** @deprecated Use MemoListIterator or MemoObjectIterator instead. */ type MemoIterator = (prev: TResult, curr: T, indexOrKey: any, list: T[]) => TResult; + type MemoListIterator = (prev: TResult, curr: T, index: number, list: TList) => TResult; + type MemoObjectIterator = (prev: TResult, curr: T, key: string, list: TList) => TResult; type MemoVoidArrayIterator = (acc: TResult, curr: T, index: number, arr: T[]) => void; type MemoVoidDictionaryIterator = (acc: TResult, curr: T, key: string, dict: Dictionary) => void; + type ValueIteratee = ((value: T) => any) | string | [string, any] | PartialDeep; + type ValueKeyIteratee = ((value: T, key: string) => any) | string | [string, any] | PartialDeep; + type Comparator = (a: T, b: T) => boolean; + /** Common interface between Arrays and jQuery objects */ type List = ArrayLike; @@ -20174,6 +16791,24 @@ declare namespace _ { cancel(): void; flush(): void; } + + type PartialDeep = { + [P in keyof T]?: PartialDeep; + }; + + // For backwards compatibility + type LoDashImplicitArrayWrapper = LoDashImplicitWrapper; + type LoDashImplicitNillableArrayWrapper = LoDashImplicitWrapper; + type LoDashImplicitObjectWrapper = LoDashImplicitWrapper; + type LoDashImplicitNillableObjectWrapper = LoDashImplicitWrapper; + type LoDashImplicitNumberArrayWrapper = LoDashImplicitWrapper; + type LoDashImplicitStringWrapper = LoDashImplicitWrapper; + type LoDashExplicitArrayWrapper = LoDashExplicitWrapper; + type LoDashExplicitNillableArrayWrapper = LoDashExplicitWrapper; + type LoDashExplicitObjectWrapper = LoDashExplicitWrapper; + type LoDashExplicitNillableObjectWrapper = LoDashExplicitWrapper; + type LoDashExplicitNumberArrayWrapper = LoDashExplicitWrapper; + type LoDashExplicitStringWrapper = LoDashExplicitWrapper; } // Backward compatibility with --target es5 diff --git a/types/lodash/lodash-tests.ts b/types/lodash/lodash-tests.ts index 7ebd31f2c7..19399ff23b 100644 --- a/types/lodash/lodash-tests.ts +++ b/types/lodash/lodash-tests.ts @@ -1,6 +1,4 @@ -declare const $: any, jQuery: any; - -let x = 0 +declare const $: any; interface IFoodOrganic { name: string; @@ -130,7 +128,7 @@ namespace TestWrapper { { let result: _.LoDashImplicitArrayWrapper; - result = _(['']); + result = _(['']); } { @@ -140,12 +138,12 @@ namespace TestWrapper { { let a: TResult[] = []; - _(a) // $ExpectType LoDashImplicitArrayWrapper + _(a); // $ExpectType LoDashImplicitWrapper } { let a: TResult[] | null | undefined = any; - _(a) // $ExpectType LoDashImplicitNillableArrayWrapper + _(a); // $ExpectType LoDashImplicitWrapper } } @@ -227,14 +225,14 @@ namespace TestCompact { { let result: _.LoDashImplicitArrayWrapper; - result = _(array).compact(); + result = _(array).compact(); result = _(list).compact(); } { let result: _.LoDashExplicitArrayWrapper; - result = _(array).chain().compact(); + result = _(array).chain().compact(); result = _(list).chain().compact(); } } @@ -300,181 +298,181 @@ namespace TestDifferenceBy { { let result: TResult[]; - result = _.differenceBy(array, array); - result = _.differenceBy(array, list, array); - result = _.differenceBy(array, array, list, array); - result = _.differenceBy(array, list, array, list, array); - result = _.differenceBy(array, array, list, array, list, array); - result = _.differenceBy(array, list, array, list, array, list, array); + result = _.differenceBy(array, arrayParam); + result = _.differenceBy(array, listParam, arrayParam); + result = _.differenceBy(array, arrayParam, listParam, arrayParam); + result = _.differenceBy(array, listParam, arrayParam, listParam, arrayParam); + result = _.differenceBy(array, arrayParam, listParam, arrayParam, listParam, arrayParam); + result = _.differenceBy(array, listParam, arrayParam, listParam, arrayParam, listParam, arrayParam); - result = _.differenceBy(array, array, iteratee); - result = _.differenceBy(array, list, array, iteratee); - result = _.differenceBy(array, array, list, array, iteratee); - result = _.differenceBy(array, list, array, list, array, iteratee); - result = _.differenceBy(array, array, list, array, list, array, iteratee); - result = _.differenceBy(array, list, array, list, array, list, array, iteratee); + result = _.differenceBy(array, arrayParam, iteratee); + result = _.differenceBy(array, listParam, arrayParam, iteratee); + result = _.differenceBy(array, arrayParam, listParam, arrayParam, iteratee); + result = _.differenceBy(array, listParam, arrayParam, listParam, arrayParam, iteratee); + result = _.differenceBy(array, arrayParam, listParam, arrayParam, listParam, arrayParam, iteratee); + result = _.differenceBy(array, listParam, arrayParam, listParam, arrayParam, listParam, arrayParam, iteratee); - result = _.differenceBy(array, array, 'a'); - result = _.differenceBy(array, list, array, 'a'); - result = _.differenceBy(array, array, list, array, 'a'); - result = _.differenceBy(array, list, array, list, array, 'a'); - result = _.differenceBy(array, array, list, array, list, array, 'a'); - result = _.differenceBy(array, list, array, list, array, list, array, 'a'); + result = _.differenceBy(array, arrayParam, 'a'); + result = _.differenceBy(array, listParam, arrayParam, 'a'); + result = _.differenceBy(array, arrayParam, listParam, arrayParam, 'a'); + result = _.differenceBy(array, listParam, arrayParam, listParam, arrayParam, 'a'); + result = _.differenceBy(array, arrayParam, listParam, arrayParam, listParam, arrayParam, 'a'); + result = _.differenceBy(array, listParam, arrayParam, listParam, arrayParam, listParam, arrayParam, 'a'); - result = _.differenceBy(array, arrayParam, {a: 1}); - result = _.differenceBy(array, listParam, arrayParam, {a: 1}); - result = _.differenceBy(array, arrayParam, listParam, arrayParam, {a: 1}); - result = _.differenceBy(array, listParam, arrayParam, listParam, arrayParam, {a: 1}); - result = _.differenceBy(array, arrayParam, listParam, arrayParam, listParam, arrayParam, {a: 1}); - result = _.differenceBy(array, list, array, list, array, list, array, {a: 1}); + result = _.differenceBy(array, arrayParam, {a: 1}); + result = _.differenceBy(array, listParam, arrayParam, {a: 1}); + result = _.differenceBy(array, arrayParam, listParam, arrayParam, {a: 1}); + result = _.differenceBy(array, listParam, arrayParam, listParam, arrayParam, {a: 1}); + result = _.differenceBy(array, arrayParam, listParam, arrayParam, listParam, arrayParam, {a: 1}); + result = _.differenceBy(array, listParam, arrayParam, listParam, arrayParam, listParam, arrayParam, {a: 1}); - result = _.differenceBy(list, list); - result = _.differenceBy(list, array, list); - result = _.differenceBy(list, list, array, list); - result = _.differenceBy(list, array, list, array, list); - result = _.differenceBy(list, list, array, list, array, list); - result = _.differenceBy(list, array, list, array, list, array, list); + result = _.differenceBy(list, listParam); + result = _.differenceBy(list, arrayParam, listParam); + result = _.differenceBy(list, listParam, arrayParam, listParam); + result = _.differenceBy(list, arrayParam, listParam, arrayParam, listParam); + result = _.differenceBy(list, listParam, arrayParam, listParam, arrayParam, listParam); + result = _.differenceBy(list, arrayParam, listParam, arrayParam, listParam, arrayParam, listParam); - result = _.differenceBy(list, list, iteratee); - result = _.differenceBy(list, array, list, iteratee); - result = _.differenceBy(list, list, array, list, iteratee); - result = _.differenceBy(list, array, list, array, list, iteratee); - result = _.differenceBy(list, list, array, list, array, list, iteratee); - result = _.differenceBy(list, array, list, array, list, array, list, iteratee); + result = _.differenceBy(list, listParam, iteratee); + result = _.differenceBy(list, arrayParam, listParam, iteratee); + result = _.differenceBy(list, listParam, arrayParam, listParam, iteratee); + result = _.differenceBy(list, arrayParam, listParam, arrayParam, listParam, iteratee); + result = _.differenceBy(list, listParam, arrayParam, listParam, arrayParam, listParam, iteratee); + result = _.differenceBy(list, arrayParam, listParam, arrayParam, listParam, arrayParam, listParam, iteratee); - result = _.differenceBy(list, list, 'a'); - result = _.differenceBy(list, array, list, 'a'); - result = _.differenceBy(list, list, array, list, 'a'); - result = _.differenceBy(list, array, list, array, list, 'a'); - result = _.differenceBy(list, list, array, list, array, list, 'a'); - result = _.differenceBy(list, array, list, array, list, array, list, 'a'); + result = _.differenceBy(list, listParam, 'a'); + result = _.differenceBy(list, arrayParam, listParam, 'a'); + result = _.differenceBy(list, listParam, arrayParam, listParam, 'a'); + result = _.differenceBy(list, arrayParam, listParam, arrayParam, listParam, 'a'); + result = _.differenceBy(list, listParam, arrayParam, listParam, arrayParam, listParam, 'a'); + result = _.differenceBy(list, arrayParam, listParam, arrayParam, listParam, arrayParam, listParam, 'a'); - result = _.differenceBy(list, listParam, {a: 1}); - result = _.differenceBy(list, arrayParam, listParam, {a: 1}); - result = _.differenceBy(list, listParam, arrayParam, listParam, {a: 1}); - result = _.differenceBy(list, arrayParam, listParam, arrayParam, listParam, {a: 1}); - result = _.differenceBy(list, listParam, arrayParam, listParam, arrayParam, listParam, {a: 1}); - result = _.differenceBy(list, array, list, array, list, array, list, {a: 1}); + result = _.differenceBy(list, listParam, {a: 1}); + result = _.differenceBy(list, arrayParam, listParam, {a: 1}); + result = _.differenceBy(list, listParam, arrayParam, listParam, {a: 1}); + result = _.differenceBy(list, arrayParam, listParam, arrayParam, listParam, {a: 1}); + result = _.differenceBy(list, listParam, arrayParam, listParam, arrayParam, listParam, {a: 1}); + result = _.differenceBy(list, arrayParam, listParam, arrayParam, listParam, arrayParam, listParam, {a: 1}); } { - let result: _.LoDashImplicitArrayWrapper; + let result: _.LoDashImplicitWrapper; - result = _(array).differenceBy(array); - result = _(array).differenceBy(list, array); - result = _(array).differenceBy(array, list, array); - result = _(array).differenceBy(list, array, list, array); - result = _(array).differenceBy(array, list, array, list, array); - result = _(array).differenceBy(list, array, list, array, list, array); + result = _(array).differenceBy(arrayParam); + result = _(array).differenceBy(listParam, arrayParam); + result = _(array).differenceBy(arrayParam, listParam, arrayParam); + result = _(array).differenceBy(listParam, arrayParam, listParam, arrayParam); + result = _(array).differenceBy(arrayParam, listParam, arrayParam, listParam, arrayParam); + result = _(array).differenceBy(listParam, arrayParam, listParam, arrayParam, listParam, arrayParam); - result = _(array).differenceBy(array, iteratee); - result = _(array).differenceBy(list, array, iteratee); - result = _(array).differenceBy(array, list, array, iteratee); - result = _(array).differenceBy(list, array, list, array, iteratee); - result = _(array).differenceBy(array, list, array, list, array, iteratee); - result = _(array).differenceBy(list, array, list, array, list, array, iteratee); + result = _(array).differenceBy(arrayParam, iteratee); + result = _(array).differenceBy(listParam, arrayParam, iteratee); + result = _(array).differenceBy(arrayParam, listParam, arrayParam, iteratee); + result = _(array).differenceBy(listParam, arrayParam, listParam, arrayParam, iteratee); + result = _(array).differenceBy(arrayParam, listParam, arrayParam, listParam, arrayParam, iteratee); + result = _(array).differenceBy(listParam, arrayParam, listParam, arrayParam, listParam, arrayParam, iteratee); - result = _(array).differenceBy(array, 'a'); - result = _(array).differenceBy(list, array, 'a'); - result = _(array).differenceBy(array, list, array, 'a'); - result = _(array).differenceBy(list, array, list, array, 'a'); - result = _(array).differenceBy(array, list, array, list, array, 'a'); - result = _(array).differenceBy(list, array, list, array, list, array, 'a'); + result = _(array).differenceBy(arrayParam, 'a'); + result = _(array).differenceBy(listParam, arrayParam, 'a'); + result = _(array).differenceBy(arrayParam, listParam, arrayParam, 'a'); + result = _(array).differenceBy(listParam, arrayParam, listParam, arrayParam, 'a'); + result = _(array).differenceBy(arrayParam, listParam, arrayParam, listParam, arrayParam, 'a'); + result = _(array).differenceBy(listParam, arrayParam, listParam, arrayParam, listParam, arrayParam, 'a'); - result = _(array).differenceBy(arrayParam, {a: 1}); - result = _(array).differenceBy(listParam, arrayParam, {a: 1}); - result = _(array).differenceBy(arrayParam, listParam, arrayParam, {a: 1}); - result = _(array).differenceBy(listParam, arrayParam, listParam, arrayParam, {a: 1}); - result = _(array).differenceBy(arrayParam, listParam, arrayParam, listParam, arrayParam, {a: 1}); - result = _(array).differenceBy(list, array, list, array, list, array, {a: 1}); + result = _(array).differenceBy(arrayParam, {a: 1}); + result = _(array).differenceBy(listParam, arrayParam, {a: 1}); + result = _(array).differenceBy(arrayParam, listParam, arrayParam, {a: 1}); + result = _(array).differenceBy(listParam, arrayParam, listParam, arrayParam, {a: 1}); + result = _(array).differenceBy(arrayParam, listParam, arrayParam, listParam, arrayParam, {a: 1}); + result = _(array).differenceBy(listParam, arrayParam, listParam, arrayParam, listParam, arrayParam, {a: 1}); - result = _(list).differenceBy(list); - result = _(list).differenceBy(array, list); - result = _(list).differenceBy(list, array, list); - result = _(list).differenceBy(array, list, array, list); - result = _(list).differenceBy(list, array, list, array, list); - result = _(list).differenceBy(array, list, array, list, array, list); + result = _(list).differenceBy(listParam); + result = _(list).differenceBy(arrayParam, listParam); + result = _(list).differenceBy(listParam, arrayParam, listParam); + result = _(list).differenceBy(arrayParam, listParam, arrayParam, listParam); + result = _(list).differenceBy(listParam, arrayParam, listParam, arrayParam, listParam); + result = _(list).differenceBy(arrayParam, listParam, arrayParam, listParam, arrayParam, listParam); - result = _(list).differenceBy(list, iteratee); - result = _(list).differenceBy(array, list, iteratee); - result = _(list).differenceBy(list, array, list, iteratee); - result = _(list).differenceBy(array, list, array, list, iteratee); - result = _(list).differenceBy(list, array, list, array, list, iteratee); - result = _(list).differenceBy(array, list, array, list, array, list, iteratee); + result = _(list).differenceBy(listParam, iteratee); + result = _(list).differenceBy(arrayParam, listParam, iteratee); + result = _(list).differenceBy(listParam, arrayParam, listParam, iteratee); + result = _(list).differenceBy(arrayParam, listParam, arrayParam, listParam, iteratee); + result = _(list).differenceBy(listParam, arrayParam, listParam, arrayParam, listParam, iteratee); + result = _(list).differenceBy(arrayParam, listParam, arrayParam, listParam, arrayParam, listParam, iteratee); - result = _(list).differenceBy(list, 'a'); - result = _(list).differenceBy(array, list, 'a'); - result = _(list).differenceBy(list, array, list, 'a'); - result = _(list).differenceBy(array, list, array, list, 'a'); - result = _(list).differenceBy(list, array, list, array, list, 'a'); - result = _(list).differenceBy(array, list, array, list, array, list, 'a'); + result = _(list).differenceBy(listParam, 'a'); + result = _(list).differenceBy(arrayParam, listParam, 'a'); + result = _(list).differenceBy(listParam, arrayParam, listParam, 'a'); + result = _(list).differenceBy(arrayParam, listParam, arrayParam, listParam, 'a'); + result = _(list).differenceBy(listParam, arrayParam, listParam, arrayParam, listParam, 'a'); + result = _(list).differenceBy(arrayParam, listParam, arrayParam, listParam, arrayParam, listParam, 'a'); - result = _(list).differenceBy(listParam, {a: 1}); - result = _(list).differenceBy(arrayParam, listParam, {a: 1}); - result = _(list).differenceBy(listParam, arrayParam, listParam, {a: 1}); - result = _(list).differenceBy(arrayParam, listParam, arrayParam, listParam, {a: 1}); - result = _(list).differenceBy(listParam, arrayParam, listParam, arrayParam, listParam, {a: 1}); - result = _(list).differenceBy(array, list, array, list, array, list, {a: 1}); + result = _(list).differenceBy(listParam, {a: 1}); + result = _(list).differenceBy(arrayParam, listParam, {a: 1}); + result = _(list).differenceBy(listParam, arrayParam, listParam, {a: 1}); + result = _(list).differenceBy(arrayParam, listParam, arrayParam, listParam, {a: 1}); + result = _(list).differenceBy(listParam, arrayParam, listParam, arrayParam, listParam, {a: 1}); + result = _(list).differenceBy(arrayParam, listParam, arrayParam, listParam, arrayParam, listParam, {a: 1}); } { - let result: _.LoDashExplicitArrayWrapper; + let result: _.LoDashExplicitWrapper; - result = _(array).chain().differenceBy(array); - result = _(array).chain().differenceBy(list, array); - result = _(array).chain().differenceBy(array, list, array); - result = _(array).chain().differenceBy(list, array, list, array); - result = _(array).chain().differenceBy(array, list, array, list, array); - result = _(array).chain().differenceBy(list, array, list, array, list, array); + result = _(array).chain().differenceBy(arrayParam); + result = _(array).chain().differenceBy(listParam, arrayParam); + result = _(array).chain().differenceBy(arrayParam, listParam, arrayParam); + result = _(array).chain().differenceBy(listParam, arrayParam, listParam, arrayParam); + result = _(array).chain().differenceBy(arrayParam, listParam, arrayParam, listParam, arrayParam); + result = _(array).chain().differenceBy(listParam, arrayParam, listParam, arrayParam, listParam, arrayParam); - result = _(array).chain().differenceBy(array, iteratee); - result = _(array).chain().differenceBy(list, array, iteratee); - result = _(array).chain().differenceBy(array, list, array, iteratee); - result = _(array).chain().differenceBy(list, array, list, array, iteratee); - result = _(array).chain().differenceBy(array, list, array, list, array, iteratee); - result = _(array).chain().differenceBy(list, array, list, array, list, array, iteratee); + result = _(array).chain().differenceBy(arrayParam, iteratee); + result = _(array).chain().differenceBy(listParam, arrayParam, iteratee); + result = _(array).chain().differenceBy(arrayParam, listParam, arrayParam, iteratee); + result = _(array).chain().differenceBy(listParam, arrayParam, listParam, arrayParam, iteratee); + result = _(array).chain().differenceBy(arrayParam, listParam, arrayParam, listParam, arrayParam, iteratee); + result = _(array).chain().differenceBy(listParam, arrayParam, listParam, arrayParam, listParam, arrayParam, iteratee); - result = _(array).chain().differenceBy(array, 'a'); - result = _(array).chain().differenceBy(list, array, 'a'); - result = _(array).chain().differenceBy(array, list, array, 'a'); - result = _(array).chain().differenceBy(list, array, list, array, 'a'); - result = _(array).chain().differenceBy(array, list, array, list, array, 'a'); - result = _(array).chain().differenceBy(list, array, list, array, list, array, 'a'); + result = _(array).chain().differenceBy(arrayParam, 'a'); + result = _(array).chain().differenceBy(listParam, arrayParam, 'a'); + result = _(array).chain().differenceBy(arrayParam, listParam, arrayParam, 'a'); + result = _(array).chain().differenceBy(listParam, arrayParam, listParam, arrayParam, 'a'); + result = _(array).chain().differenceBy(arrayParam, listParam, arrayParam, listParam, arrayParam, 'a'); + result = _(array).chain().differenceBy(listParam, arrayParam, listParam, arrayParam, listParam, arrayParam, 'a'); - result = _(array).chain().differenceBy(arrayParam, {a: 1}); - result = _(array).chain().differenceBy(listParam, arrayParam, {a: 1}); - result = _(array).chain().differenceBy(arrayParam, listParam, arrayParam, {a: 1}); - result = _(array).chain().differenceBy(listParam, arrayParam, listParam, arrayParam, {a: 1}); - result = _(array).chain().differenceBy(arrayParam, listParam, arrayParam, listParam, arrayParam, {a: 1}); - result = _(array).chain().differenceBy(list, array, list, array, list, array, {a: 1}); + result = _(array).chain().differenceBy(arrayParam, {a: 1}); + result = _(array).chain().differenceBy(listParam, arrayParam, {a: 1}); + result = _(array).chain().differenceBy(arrayParam, listParam, arrayParam, {a: 1}); + result = _(array).chain().differenceBy(listParam, arrayParam, listParam, arrayParam, {a: 1}); + result = _(array).chain().differenceBy(arrayParam, listParam, arrayParam, listParam, arrayParam, {a: 1}); + result = _(array).chain().differenceBy(listParam, arrayParam, listParam, arrayParam, listParam, arrayParam, {a: 1}); - result = _(list).chain().differenceBy(list); - result = _(list).chain().differenceBy(array, list); - result = _(list).chain().differenceBy(list, array, list); - result = _(list).chain().differenceBy(array, list, array, list); - result = _(list).chain().differenceBy(list, array, list, array, list); - result = _(list).chain().differenceBy(array, list, array, list, array, list); + result = _(list).chain().differenceBy(listParam); + result = _(list).chain().differenceBy(arrayParam, listParam); + result = _(list).chain().differenceBy(listParam, arrayParam, listParam); + result = _(list).chain().differenceBy(arrayParam, listParam, arrayParam, listParam); + result = _(list).chain().differenceBy(listParam, arrayParam, listParam, arrayParam, listParam); + result = _(list).chain().differenceBy(arrayParam, listParam, arrayParam, listParam, arrayParam, listParam); - result = _(list).chain().differenceBy(list, iteratee); - result = _(list).chain().differenceBy(array, list, iteratee); - result = _(list).chain().differenceBy(list, array, list, iteratee); - result = _(list).chain().differenceBy(array, list, array, list, iteratee); - result = _(list).chain().differenceBy(list, array, list, array, list, iteratee); - result = _(list).chain().differenceBy(array, list, array, list, array, list, iteratee); + result = _(list).chain().differenceBy(listParam, iteratee); + result = _(list).chain().differenceBy(arrayParam, listParam, iteratee); + result = _(list).chain().differenceBy(listParam, arrayParam, listParam, iteratee); + result = _(list).chain().differenceBy(arrayParam, listParam, arrayParam, listParam, iteratee); + result = _(list).chain().differenceBy(listParam, arrayParam, listParam, arrayParam, listParam, iteratee); + result = _(list).chain().differenceBy(arrayParam, listParam, arrayParam, listParam, arrayParam, listParam, iteratee); - result = _(list).chain().differenceBy(list, 'a'); - result = _(list).chain().differenceBy(array, list, 'a'); - result = _(list).chain().differenceBy(list, array, list, 'a'); - result = _(list).chain().differenceBy(array, list, array, list, 'a'); - result = _(list).chain().differenceBy(list, array, list, array, list, 'a'); - result = _(list).chain().differenceBy(array, list, array, list, array, list, 'a'); + result = _(list).chain().differenceBy(listParam, 'a'); + result = _(list).chain().differenceBy(arrayParam, listParam, 'a'); + result = _(list).chain().differenceBy(listParam, arrayParam, listParam, 'a'); + result = _(list).chain().differenceBy(arrayParam, listParam, arrayParam, listParam, 'a'); + result = _(list).chain().differenceBy(listParam, arrayParam, listParam, arrayParam, listParam, 'a'); + result = _(list).chain().differenceBy(arrayParam, listParam, arrayParam, listParam, arrayParam, listParam, 'a'); - result = _(list).chain().differenceBy(listParam, {a: 1}); - result = _(list).chain().differenceBy(arrayParam, listParam, {a: 1}); - result = _(list).chain().differenceBy(listParam, arrayParam, listParam, {a: 1}); - result = _(list).chain().differenceBy(arrayParam, listParam, arrayParam, listParam, {a: 1}); - result = _(list).chain().differenceBy(listParam, arrayParam, listParam, arrayParam, listParam, {a: 1}); - result = _(list).chain().differenceBy(array, list, array, list, array, list, {a: 1}); + result = _(list).chain().differenceBy(listParam, {a: 1}); + result = _(list).chain().differenceBy(arrayParam, listParam, {a: 1}); + result = _(list).chain().differenceBy(listParam, arrayParam, listParam, {a: 1}); + result = _(list).chain().differenceBy(arrayParam, listParam, arrayParam, listParam, {a: 1}); + result = _(list).chain().differenceBy(listParam, arrayParam, listParam, arrayParam, listParam, {a: 1}); + result = _(list).chain().differenceBy(arrayParam, listParam, arrayParam, listParam, arrayParam, listParam, {a: 1}); } } @@ -561,12 +559,12 @@ namespace TestDropRightWhile { result = _.dropRightWhile(array); result = _.dropRightWhile(array, predicateFn); result = _.dropRightWhile(array, ''); - result = _.dropRightWhile<{a: number;}, TResult>(array, {a: 42}); + result = _.dropRightWhile(array, {a: 42}); result = _.dropRightWhile(list); result = _.dropRightWhile(list, predicateFn); result = _.dropRightWhile(list, ''); - result = _.dropRightWhile<{a: number;}, TResult>(list, {a: 42}); + result = _.dropRightWhile(list, {a: 42}); } { @@ -575,12 +573,12 @@ namespace TestDropRightWhile { result = _(array).dropRightWhile(); result = _(array).dropRightWhile(predicateFn); result = _(array).dropRightWhile(''); - result = _(array).dropRightWhile<{a: number;}>({a: 42}); + result = _(array).dropRightWhile({a: 42}); result = _(list).dropRightWhile(); result = _(list).dropRightWhile(predicateFn); result = _(list).dropRightWhile(''); - result = _(list).dropRightWhile<{a: number;}, TResult>({a: 42}); + result = _(list).dropRightWhile({a: 42}); } { @@ -589,12 +587,12 @@ namespace TestDropRightWhile { result = _(array).chain().dropRightWhile(); result = _(array).chain().dropRightWhile(predicateFn); result = _(array).chain().dropRightWhile(''); - result = _(array).chain().dropRightWhile<{a: number;}>({a: 42}); + result = _(array).chain().dropRightWhile({a: 42}); result = _(list).chain().dropRightWhile(); result = _(list).chain().dropRightWhile(predicateFn); result = _(list).chain().dropRightWhile(''); - result = _(list).chain().dropRightWhile<{a: number;}, TResult>({a: 42}); + result = _(list).chain().dropRightWhile({a: 42}); } } @@ -610,12 +608,12 @@ namespace TestDropWhile { result = _.dropWhile(array); result = _.dropWhile(array, predicateFn); result = _.dropWhile(array, ''); - result = _.dropWhile<{a: number;}, TResult>(array, {a: 42}); + result = _.dropWhile(array, {a: 42}); result = _.dropWhile(list); result = _.dropWhile(list, predicateFn); result = _.dropWhile(list, ''); - result = _.dropWhile<{a: number;}, TResult>(list, {a: 42}); + result = _.dropWhile(list, {a: 42}); } { @@ -624,12 +622,12 @@ namespace TestDropWhile { result = _(array).dropWhile(); result = _(array).dropWhile(predicateFn); result = _(array).dropWhile(''); - result = _(array).dropWhile<{a: number;}>({a: 42}); + result = _(array).dropWhile({a: 42}); result = _(list).dropWhile(); result = _(list).dropWhile(predicateFn); result = _(list).dropWhile(''); - result = _(list).dropWhile<{a: number;}, TResult>({a: 42}); + result = _(list).dropWhile({a: 42}); } { @@ -638,66 +636,66 @@ namespace TestDropWhile { result = _(array).chain().dropWhile(); result = _(array).chain().dropWhile(predicateFn); result = _(array).chain().dropWhile(''); - result = _(array).chain().dropWhile<{a: number;}>({a: 42}); + result = _(array).chain().dropWhile({a: 42}); result = _(list).chain().dropWhile(); result = _(list).chain().dropWhile(predicateFn); result = _(list).chain().dropWhile(''); - result = _(list).chain().dropWhile<{a: number;}, TResult>({a: 42}); + result = _(list).chain().dropWhile({a: 42}); } } // _.fill namespace TestFill { - let array: TResult[] | null | undefined = [] as any; - let list: _.List | null | undefined = [] as any; + let array: number[] | null | undefined = [] as any; + let list: _.List | null | undefined = [] as any; { let result: number[]; result = _.fill(array, 42); - result = _.fill(array, 42, 0); - result = _.fill(array, 42, 0, 10); + result = _.fill(array, 42, 0); + result = _.fill(array, 42, 0, 10); } { let result: _.List; result = _.fill(list, 42); - result = _.fill(list, 42, 0); - result = _.fill(list, 42, 0, 10); + result = _.fill(list, 42, 0); + result = _.fill(list, 42, 0, 10); } { let result: _.LoDashImplicitArrayWrapper; result = _(array).fill(42); - result = _(array).fill(42, 0); - result = _(array).fill(42, 0, 10); + result = _(array).fill(42, 0); + result = _(array).fill(42, 0, 10); } { let result: _.LoDashImplicitObjectWrapper<_.List>; result = _(list).fill(42); - result = _(list).fill(42, 0); - result = _(list).fill(42, 0, 10); + result = _(list).fill(42, 0); + result = _(list).fill(42, 0, 10); } { let result: _.LoDashExplicitArrayWrapper; result = _(array).chain().fill(42); - result = _(array).chain().fill(42, 0); - result = _(array).chain().fill(42, 0, 10); + result = _(array).chain().fill(42, 0); + result = _(array).chain().fill(42, 0, 10); } { let result: _.LoDashExplicitObjectWrapper<_.List>; result = _(list).chain().fill(42); - result = _(list).chain().fill(42, 0); - result = _(list).chain().fill(42, 0, 10); + result = _(list).chain().fill(42, 0); + result = _(list).chain().fill(42, 0, 10); } } @@ -714,21 +712,21 @@ namespace TestFindIndex { result = _.findIndex(array); result = _.findIndex(array, predicateFn); result = _.findIndex(array, ''); - result = _.findIndex<{a: number}, TResult>(array, {a: 42}); + result = _.findIndex(array, {a: 42}); result = _.findIndex(array, predicateFn, fromIndex); result = _.findIndex(list); result = _.findIndex(list, predicateFn); result = _.findIndex(list, ''); - result = _.findIndex<{a: number}, TResult>(list, {a: 42}); + result = _.findIndex(list, {a: 42}); result = _.findIndex(list, predicateFn, fromIndex); result = _.findIndex([{ b: 5 }], ['b', 5]); - result = _(array).findIndex(); - result = _(array).findIndex(predicateFn); - result = _(array).findIndex(''); - result = _(array).findIndex<{a: number}>({a: 42}); - result = _(array).findIndex(predicateFn, fromIndex); + result = _(array).findIndex(); + result = _(array).findIndex(predicateFn); + result = _(array).findIndex(''); + result = _(array).findIndex<{a: number}>({a: 42}); + result = _(array).findIndex(predicateFn, fromIndex); result = _(list).findIndex(); result = _(list).findIndex(predicateFn); @@ -740,11 +738,11 @@ namespace TestFindIndex { { let result: _.LoDashExplicitWrapper; - result = _(array).chain().findIndex(); - result = _(array).chain().findIndex(predicateFn); - result = _(array).chain().findIndex(''); - result = _(array).chain().findIndex<{a: number}>({a: 42}); - result = _(array).chain().findIndex(predicateFn, fromIndex); + result = _(array).chain().findIndex(); + result = _(array).chain().findIndex(predicateFn); + result = _(array).chain().findIndex(''); + result = _(array).chain().findIndex<{a: number}>({a: 42}); + result = _(array).chain().findIndex(predicateFn, fromIndex); result = _(list).chain().findIndex(); result = _(list).chain().findIndex(predicateFn); @@ -768,21 +766,21 @@ namespace TestFindLastIndex { result = _.findLastIndex(array); result = _.findLastIndex(array, predicateFn); result = _.findLastIndex(array, ''); - result = _.findLastIndex<{a: number}, TResult>(array, {a: 42}); + result = _.findLastIndex(array, {a: 42}); result = _.findLastIndex(array, predicateFn, fromIndex); result = _.findLastIndex(list); result = _.findLastIndex(list, predicateFn); result = _.findLastIndex(list, ''); - result = _.findLastIndex<{a: number}, TResult>(list, {a: 42}); + result = _.findLastIndex(list, {a: 42}); result = _.findLastIndex(list, predicateFn, fromIndex); result = _.findLastIndex([{ b: 5 }], ['b', 5]); - result = _(array).findLastIndex(); - result = _(array).findLastIndex(predicateFn); - result = _(array).findLastIndex(''); - result = _(array).findLastIndex<{a: number}>({a: 42}); - result = _(array).findLastIndex(predicateFn, fromIndex); + result = _(array).findLastIndex(); + result = _(array).findLastIndex(predicateFn); + result = _(array).findLastIndex(''); + result = _(array).findLastIndex<{a: number}>({a: 42}); + result = _(array).findLastIndex(predicateFn, fromIndex); result = _(list).findLastIndex(); result = _(list).findLastIndex(predicateFn); @@ -794,11 +792,11 @@ namespace TestFindLastIndex { { let result: _.LoDashExplicitWrapper; - result = _(array).chain().findLastIndex(); - result = _(array).chain().findLastIndex(predicateFn); - result = _(array).chain().findLastIndex(''); - result = _(array).chain().findLastIndex<{a: number}>({a: 42}); - result = _(array).chain().findLastIndex(predicateFn, fromIndex); + result = _(array).chain().findLastIndex(); + result = _(array).chain().findLastIndex(predicateFn); + result = _(array).chain().findLastIndex(''); + result = _(array).chain().findLastIndex<{a: number}>({a: 42}); + result = _(array).chain().findLastIndex(predicateFn, fromIndex); result = _(list).chain().findLastIndex(); result = _(list).chain().findLastIndex(predicateFn); @@ -831,16 +829,16 @@ namespace TestFirst { } { - let result: _.LoDashExplicitWrapper; + let result: _.LoDashExplicitWrapper; result = _('abc').chain().first(); } { - let result: _.LoDashExplicitObjectWrapper; + let result: _.LoDashExplicitWrapper; - result = _(array).chain().first<_.LoDashExplicitObjectWrapper>(); - result = _(list).chain().first<_.LoDashExplicitObjectWrapper>(); + result = _(array).chain().first(); + result = _(list).chain().first(); } } @@ -876,11 +874,11 @@ namespace TestFlatten { { let result: _.RecursiveArray; - result = _.flatten([1, [2, [3]]]); - result = _.flatten([1, [2, [3]], [[4]]]); + result = _.flatten([1, [2, [3]]]); + result = _.flatten([1, [2, [3]], [[4]]]); - result = _.flatten({0: 1, 1: [2, [3]], length: 2}); - result = _.flatten({0: 1, 1: [2, [3]], 2: [[4]], length: 3}); + result = _.flatten({0: 1, 1: [2, [3]], length: 2}); + result = _.flatten({0: 1, 1: [2, [3]], 2: [[4]], length: 3}); } { @@ -1080,16 +1078,16 @@ namespace TestHead { } { - let result: _.LoDashExplicitWrapper; + let result: _.LoDashExplicitWrapper; result = _('abc').chain().head(); } { - let result: _.LoDashExplicitObjectWrapper; + let result: _.LoDashExplicitWrapper; - result = _(array).chain().head<_.LoDashExplicitObjectWrapper>(); - result = _(list).chain().head<_.LoDashExplicitObjectWrapper>(); + result = _(array).chain().head(); + result = _(list).chain().head(); } } @@ -1184,8 +1182,8 @@ namespace TestInitial { // _.intersection namespace TestIntersection { - let array: TResult[] | null | undefined = [] as any; - let list: _.List | null | undefined = [] as any; + let array: TResult[] = [] as any; + let list: _.List = [] as any; let arrayParam: TResult[] = [] as any; let listParam: _.List = [] as any; @@ -1281,21 +1279,21 @@ namespace TestLast { } { - let result: _.LoDashExplicitWrapper; + let result: _.LoDashExplicitWrapper; result = _('abc').chain().last(); } { - let result: _.LoDashExplicitObjectWrapper; + let result: _.LoDashExplicitWrapper; - result = _(array).chain().last<_.LoDashExplicitObjectWrapper>(); + result = _(array).chain().last(); } { - let result: _.LoDashExplicitObjectWrapper; + let result: _.LoDashExplicitWrapper; - result = _(list).chain().last<_.LoDashExplicitObjectWrapper>(); + result = _(list).chain().last(); } } @@ -1359,7 +1357,7 @@ namespace TestNth { } { - let result: _.LoDashExplicitWrapper; + let result: _.LoDashExplicitWrapper; result = _(array).chain().nth(); result = _(array).chain().nth(42); @@ -1442,6 +1440,10 @@ namespace TestPullAt { result = _.pullAt(array, 1); result = _.pullAt(array, [2, 3], 1); result = _.pullAt(array, 4, [2, 3], 1); + } + + { + let result: ArrayLike; result = _.pullAt(list); result = _.pullAt(list, 1); @@ -1456,11 +1458,15 @@ namespace TestPullAt { result = _(array).pullAt(1); result = _(array).pullAt([2, 3], 1); result = _(array).pullAt(4, [2, 3], 1); + } - result = _(list).pullAt(); - result = _(list).pullAt(1); - result = _(list).pullAt([2, 3], 1); - result = _(list).pullAt(4, [2, 3], 1); + { + let result: _.LoDashImplicitWrapper>; + + result = _(list).pullAt(); + result = _(list).pullAt(1); + result = _(list).pullAt([2, 3], 1); + result = _(list).pullAt(4, [2, 3], 1); } { @@ -1470,11 +1476,15 @@ namespace TestPullAt { result = _(array).chain().pullAt(1); result = _(array).chain().pullAt([2, 3], 1); result = _(array).chain().pullAt(4, [2, 3], 1); + } - result = _(list).chain().pullAt(); - result = _(list).chain().pullAt(1); - result = _(list).chain().pullAt([2, 3], 1); - result = _(list).chain().pullAt(4, [2, 3], 1); + { + let result: _.LoDashExplicitWrapper>; + + result = _(list).chain().pullAt(); + result = _(list).chain().pullAt(1); + result = _(list).chain().pullAt([2, 3], 1); + result = _(list).chain().pullAt(4, [2, 3], 1); } } @@ -1490,40 +1500,40 @@ namespace TestRemove { result = _.remove(array); result = _.remove(array, predicateFn); result = _.remove(array, ''); - result = _.remove<{a: number}, TResult>(array, {a: 42}); + result = _.remove(array, {a: 42}); result = _.remove(list); result = _.remove(list, predicateFn); result = _.remove(list, ''); - result = _.remove<{a: number}, TResult>(list, {a: 42}); + result = _.remove(list, {a: 42}); } { let result: _.LoDashImplicitArrayWrapper; - result = _(array).remove(); - result = _(array).remove(predicateFn); - result = _(array).remove(''); - result = _(array).remove<{a: number}>({a: 42}); + result = _(array).remove(); + result = _(array).remove(predicateFn); + result = _(array).remove(''); + result = _(array).remove({a: 42}); result = _(list).remove(); result = _(list).remove(predicateFn); result = _(list).remove(''); - result = _(list).remove<{a: number}, TResult>({a: 42}); + result = _(list).remove({a: 42}); } { let result: _.LoDashExplicitArrayWrapper; - result = _(array).chain().remove(); - result = _(array).chain().remove(predicateFn); - result = _(array).chain().remove(''); - result = _(array).chain().remove<{a: number}>({a: 42}); + result = _(array).chain().remove(); + result = _(array).chain().remove(predicateFn); + result = _(array).chain().remove(''); + result = _(array).chain().remove({a: 42}); result = _(list).chain().remove(); result = _(list).chain().remove(predicateFn); result = _(list).chain().remove(''); - result = _(list).chain().remove<{a: number}, TResult>({a: 42}); + result = _(list).chain().remove({a: 42}); } } @@ -1640,47 +1650,38 @@ namespace TestSortedIndexBy { let result: number; result = _.sortedIndexBy('', '', stringIterator); - result = _.sortedIndexBy('', '', stringIterator); result = _.sortedIndexBy(array, value, arrayIterator); result = _.sortedIndexBy(array, value, ''); result = _.sortedIndexBy(array, value, {a: 42}); - result = _.sortedIndexBy(array, value, arrayIterator); - result = _.sortedIndexBy<{a: number}, SampleType>(array, value, {a: 42}); result = _.sortedIndexBy(list, value, listIterator); result = _.sortedIndexBy(list, value, ''); result = _.sortedIndexBy(list, value, {a: 42}); - result = _.sortedIndexBy(list, value, listIterator); - result = _.sortedIndexBy<{a: number}, SampleType>(list, value, {a: 42}); - result = _('').sortedIndexBy('', stringIterator); + result = _('').sortedIndexBy('', stringIterator); - result = _(array).sortedIndexBy(value, arrayIterator); + result = _(array).sortedIndexBy(value, arrayIterator); result = _(array).sortedIndexBy(value, ''); - result = _(array).sortedIndexBy<{a: number}>(value, {a: 42}); + result = _(array).sortedIndexBy(value, {a: 42}); result = _(list).sortedIndexBy(value, listIterator); result = _(list).sortedIndexBy(value, ''); result = _(list).sortedIndexBy(value, {a: 42}); - result = _(list).sortedIndexBy(value, listIterator); - result = _(list).sortedIndexBy<{a: number}, SampleType>(value, {a: 42}); } { let result: _.LoDashExplicitWrapper; - result = _('').chain().sortedIndexBy('', stringIterator); + result = _('').chain().sortedIndexBy('', stringIterator); - result = _(array).chain().sortedIndexBy(value, arrayIterator); + result = _(array).chain().sortedIndexBy(value, arrayIterator); result = _(array).chain().sortedIndexBy(value, ''); - result = _(array).chain().sortedIndexBy<{a: number}>(value, {a: 42}); + result = _(array).chain().sortedIndexBy(value, {a: 42}); result = _(list).chain().sortedIndexBy(value, listIterator); result = _(list).chain().sortedIndexBy(value, ''); result = _(list).chain().sortedIndexBy(value, {a: 42}); - result = _(list).chain().sortedIndexBy(value, listIterator); - result = _(list).chain().sortedIndexBy<{a: number}, SampleType>(value, {a: 42}); } } @@ -1741,47 +1742,38 @@ namespace TestSortedLastIndexBy { let result: number; result = _.sortedLastIndexBy('', '', stringIterator); - result = _.sortedLastIndexBy('', '', stringIterator); result = _.sortedLastIndexBy(array, value, arrayIterator); result = _.sortedLastIndexBy(array, value, ''); result = _.sortedLastIndexBy(array, value, {a: 42}); - result = _.sortedLastIndexBy(array, value, arrayIterator); - result = _.sortedLastIndexBy<{a: number}, SampleType>(array, value, {a: 42}); result = _.sortedLastIndexBy(list, value, listIterator); result = _.sortedLastIndexBy(list, value, ''); result = _.sortedLastIndexBy(list, value, {a: 42}); - result = _.sortedLastIndexBy(list, value, listIterator); - result = _.sortedLastIndexBy<{a: number}, SampleType>(list, value, {a: 42}); - result = _('').sortedLastIndexBy('', stringIterator); + result = _('').sortedLastIndexBy('', stringIterator); - result = _(array).sortedLastIndexBy(value, arrayIterator); + result = _(array).sortedLastIndexBy(value, arrayIterator); result = _(array).sortedLastIndexBy(value, ''); - result = _(array).sortedLastIndexBy<{a: number}>(value, {a: 42}); + result = _(array).sortedLastIndexBy(value, {a: 42}); result = _(list).sortedLastIndexBy(value, listIterator); result = _(list).sortedLastIndexBy(value, ''); result = _(list).sortedLastIndexBy(value, {a: 42}); - result = _(list).sortedLastIndexBy(value, listIterator); - result = _(list).sortedLastIndexBy<{a: number}, SampleType>(value, {a: 42}); } { let result: _.LoDashExplicitWrapper; - result = _('').chain().sortedLastIndexBy('', stringIterator); + result = _('').chain().sortedLastIndexBy('', stringIterator); - result = _(array).chain().sortedLastIndexBy(value, arrayIterator); + result = _(array).chain().sortedLastIndexBy(value, arrayIterator); result = _(array).chain().sortedLastIndexBy(value, ''); - result = _(array).chain().sortedLastIndexBy<{a: number}>(value, {a: 42}); + result = _(array).chain().sortedLastIndexBy(value, {a: 42}); result = _(list).chain().sortedLastIndexBy(value, listIterator); result = _(list).chain().sortedLastIndexBy(value, ''); result = _(list).chain().sortedLastIndexBy(value, {a: 42}); - result = _(list).chain().sortedLastIndexBy(value, listIterator); - result = _(list).chain().sortedLastIndexBy<{a: number}, SampleType>(value, {a: 42}); } } @@ -1896,12 +1888,12 @@ namespace TestTakeRightWhile { result = _.takeRightWhile(array); result = _.takeRightWhile(array, predicateFn); result = _.takeRightWhile(array, ''); - result = _.takeRightWhile<{a: number;}, TResult>(array, {a: 42}); + result = _.takeRightWhile(array, {a: 42}); result = _.takeRightWhile(list); result = _.takeRightWhile(list, predicateFn); result = _.takeRightWhile(list, ''); - result = _.takeRightWhile<{a: number;}, TResult>(list, {a: 42}); + result = _.takeRightWhile(list, {a: 42}); } { @@ -1910,12 +1902,12 @@ namespace TestTakeRightWhile { result = _(array).takeRightWhile(); result = _(array).takeRightWhile(predicateFn); result = _(array).takeRightWhile(''); - result = _(array).takeRightWhile<{a: number;}>({a: 42}); + result = _(array).takeRightWhile({a: 42}); result = _(list).takeRightWhile(); result = _(list).takeRightWhile(predicateFn); result = _(list).takeRightWhile(''); - result = _(list).takeRightWhile<{a: number;}, TResult>({a: 42}); + result = _(list).takeRightWhile({a: 42}); } { @@ -1924,12 +1916,12 @@ namespace TestTakeRightWhile { result = _(array).chain().takeRightWhile(); result = _(array).chain().takeRightWhile(predicateFn); result = _(array).chain().takeRightWhile(''); - result = _(array).chain().takeRightWhile<{a: number;}>({a: 42}); + result = _(array).chain().takeRightWhile({a: 42}); result = _(list).chain().takeRightWhile(); result = _(list).chain().takeRightWhile(predicateFn); result = _(list).chain().takeRightWhile(''); - result = _(list).chain().takeRightWhile<{a: number;}, TResult>({a: 42}); + result = _(list).chain().takeRightWhile({a: 42}); } } @@ -1945,12 +1937,12 @@ namespace TestTakeWhile { result = _.takeWhile(array); result = _.takeWhile(array, predicateFn); result = _.takeWhile(array, ''); - result = _.takeWhile<{a: number;}, TResult>(array, {a: 42}); + result = _.takeWhile(array, {a: 42}); result = _.takeWhile(list); result = _.takeWhile(list, predicateFn); result = _.takeWhile(list, ''); - result = _.takeWhile<{a: number;}, TResult>(list, {a: 42}); + result = _.takeWhile(list, {a: 42}); } { @@ -1959,12 +1951,12 @@ namespace TestTakeWhile { result = _(array).takeWhile(); result = _(array).takeWhile(predicateFn); result = _(array).takeWhile(''); - result = _(array).takeWhile<{a: number;}>({a: 42}); + result = _(array).takeWhile({a: 42}); result = _(list).takeWhile(); result = _(list).takeWhile(predicateFn); result = _(list).takeWhile(''); - result = _(list).takeWhile<{a: number;}, TResult>({a: 42}); + result = _(list).takeWhile({a: 42}); } { @@ -1973,12 +1965,12 @@ namespace TestTakeWhile { result = _(array).chain().takeWhile(); result = _(array).chain().takeWhile(predicateFn); result = _(array).chain().takeWhile(''); - result = _(array).chain().takeWhile<{a: number;}>({a: 42}); + result = _(array).chain().takeWhile({a: 42}); result = _(list).chain().takeWhile(); result = _(list).chain().takeWhile(predicateFn); result = _(list).chain().takeWhile(''); - result = _(list).chain().takeWhile<{a: number;}, TResult>({a: 42}); + result = _(list).chain().takeWhile({a: 42}); } } @@ -2061,10 +2053,10 @@ namespace TestUnionBy { result = _.unionBy(array, list, array, list, array, 'a'); result = _.unionBy(array, array, list, array, list, array, 'a'); - result = _.unionBy(array, array, {a: 1}); - result = _.unionBy(array, list, array, {a: 1}); - result = _.unionBy(array, array, list, array, {a: 1}); - result = _.unionBy(array, list, array, list, array, {a: 1}); + result = _.unionBy(array, array, {a: 1}); + result = _.unionBy(array, list, array, {a: 1}); + result = _.unionBy(array, array, list, array, {a: 1}); + result = _.unionBy(array, list, array, list, array, {a: 1}); result = _.unionBy(array, list, array, list, array, list, {a: 1}); result = _.unionBy(list, list); @@ -2085,10 +2077,10 @@ namespace TestUnionBy { result = _.unionBy(list, array, list, array, list, 'a'); result = _.unionBy(list, list, array, list, array, list, 'a'); - result = _.unionBy(list, list, {a: 1}); - result = _.unionBy(list, array, list, {a: 1}); - result = _.unionBy(list, list, array, list, {a: 1}); - result = _.unionBy(list, array, list, array, list, {a: 1}); + result = _.unionBy(list, list, {a: 1}); + result = _.unionBy(list, array, list, {a: 1}); + result = _.unionBy(list, list, array, list, {a: 1}); + result = _.unionBy(list, array, list, array, list, {a: 1}); result = _.unionBy(list, array, list, array, list, array, {a: 1}); } @@ -2113,10 +2105,10 @@ namespace TestUnionBy { result = _(array).unionBy(list, array, list, array, 'a'); result = _(array).unionBy(array, list, array, list, array, 'a'); - result = _(array).unionBy(array, {a: 1}); - result = _(array).unionBy(list, array, {a: 1}); - result = _(array).unionBy(array, list, array, {a: 1}); - result = _(array).unionBy(list, array, list, array, {a: 1}); + result = _(array).unionBy(array, {a: 1}); + result = _(array).unionBy(list, array, {a: 1}); + result = _(array).unionBy(array, list, array, {a: 1}); + result = _(array).unionBy(list, array, list, array, {a: 1}); result = _(array).unionBy(list, array, list, array, list, {a: 1}); result = _(list).unionBy(list); @@ -2137,10 +2129,10 @@ namespace TestUnionBy { result = _(list).unionBy(array, list, array, list, 'a'); result = _(list).unionBy(list, array, list, array, list, 'a'); - result = _(list).unionBy(list, {a: 1}); - result = _(list).unionBy(array, list, {a: 1}); - result = _(list).unionBy(list, array, list, {a: 1}); - result = _(list).unionBy(array, list, array, list, {a: 1}); + result = _(list).unionBy(list, {a: 1}); + result = _(list).unionBy(array, list, {a: 1}); + result = _(list).unionBy(list, array, list, {a: 1}); + result = _(list).unionBy(array, list, array, list, {a: 1}); result = _(list).unionBy(array, list, array, list, array, {a: 1}); } @@ -2165,10 +2157,10 @@ namespace TestUnionBy { result = _(array).chain().unionBy(list, array, list, array, 'a'); result = _(array).chain().unionBy(array, list, array, list, array, 'a'); - result = _(array).chain().unionBy(array, {a: 1}); - result = _(array).chain().unionBy(list, array, {a: 1}); - result = _(array).chain().unionBy(array, list, array, {a: 1}); - result = _(array).chain().unionBy(list, array, list, array, {a: 1}); + result = _(array).chain().unionBy(array, {a: 1}); + result = _(array).chain().unionBy(list, array, {a: 1}); + result = _(array).chain().unionBy(array, list, array, {a: 1}); + result = _(array).chain().unionBy(list, array, list, array, {a: 1}); result = _(array).chain().unionBy(list, array, list, array, list, {a: 1}); result = _(list).chain().unionBy(list); @@ -2189,10 +2181,10 @@ namespace TestUnionBy { result = _(list).chain().unionBy(array, list, array, list, 'a'); result = _(list).chain().unionBy(list, array, list, array, list, 'a'); - result = _(list).chain().unionBy(list, {a: 1}); - result = _(list).chain().unionBy(array, list, {a: 1}); - result = _(list).chain().unionBy(list, array, list, {a: 1}); - result = _(list).chain().unionBy(array, list, array, list, {a: 1}); + result = _(list).chain().unionBy(list, {a: 1}); + result = _(list).chain().unionBy(array, list, {a: 1}); + result = _(list).chain().unionBy(list, array, list, {a: 1}); + result = _(list).chain().unionBy(array, list, array, list, {a: 1}); result = _(list).chain().unionBy(array, list, array, list, array, {a: 1}); } } @@ -2255,7 +2247,6 @@ namespace TestUniqBy { { let result: string[]; - result = _.uniqBy('abc', stringIterator); result = _.uniqBy('abc', stringIterator); } @@ -2263,16 +2254,12 @@ namespace TestUniqBy { let result: SampleObject[]; result = _.uniqBy(array, listIterator); - result = _.uniqBy(array, listIterator); result = _.uniqBy(array, 'a'); result = _.uniqBy(array, {a: 42}); - result = _.uniqBy<{a: number}, SampleObject>(array, {a: 42}); result = _.uniqBy(list, listIterator); - result = _.uniqBy(list, listIterator); result = _.uniqBy(list, 'a'); result = _.uniqBy(list, {a: 42}); - result = _.uniqBy<{a: number}, SampleObject>(list, {a: 42}); } { @@ -2284,15 +2271,13 @@ namespace TestUniqBy { { let result: _.LoDashImplicitArrayWrapper; - result = _(array).uniqBy(listIterator); + result = _(array).uniqBy(listIterator); result = _(array).uniqBy('a'); - result = _(array).uniqBy<{a: number}>({a: 42}); + result = _(array).uniqBy({a: 42}); result = _(list).uniqBy(listIterator); - result = _(list).uniqBy(listIterator); result = _(list).uniqBy('a'); result = _(list).uniqBy({a: 42}); - result = _(list).uniqBy<{a: number}, SampleObject>({a: 42}); } { @@ -2304,15 +2289,13 @@ namespace TestUniqBy { { let result: _.LoDashExplicitArrayWrapper; - result = _(array).chain().uniqBy(listIterator); + result = _(array).chain().uniqBy(listIterator); result = _(array).chain().uniqBy('a'); - result = _(array).chain().uniqBy<{a: number}>({a: 42}); + result = _(array).chain().uniqBy({a: 42}); result = _(list).chain().uniqBy(listIterator); - result = _(list).chain().uniqBy(listIterator); result = _(list).chain().uniqBy('a'); result = _(list).chain().uniqBy({a: 42}); - result = _(list).chain().uniqBy<{a: number}, SampleObject>({a: 42}); } } @@ -2370,7 +2353,6 @@ namespace TestSortedUniqBy { { let result: string[]; - result = _.sortedUniqBy('abc', stringIterator); result = _.sortedUniqBy('abc', stringIterator); } @@ -2378,16 +2360,12 @@ namespace TestSortedUniqBy { let result: SampleObject[]; result = _.sortedUniqBy(array, listIterator); - result = _.sortedUniqBy(array, listIterator); result = _.sortedUniqBy(array, 'a'); result = _.sortedUniqBy(array, {a: 42}); - result = _.sortedUniqBy<{a: number}, SampleObject>(array, {a: 42}); result = _.sortedUniqBy(list, listIterator); - result = _.sortedUniqBy(list, listIterator); result = _.sortedUniqBy(list, 'a'); result = _.sortedUniqBy(list, {a: 42}); - result = _.sortedUniqBy<{a: number}, SampleObject>(list, {a: 42}); } { @@ -2399,15 +2377,13 @@ namespace TestSortedUniqBy { { let result: _.LoDashImplicitArrayWrapper; - result = _(array).sortedUniqBy(listIterator); + result = _(array).sortedUniqBy(listIterator); result = _(array).sortedUniqBy('a'); - result = _(array).sortedUniqBy<{a: number}>({a: 42}); + result = _(array).sortedUniqBy({a: 42}); result = _(list).sortedUniqBy(listIterator); - result = _(list).sortedUniqBy(listIterator); result = _(list).sortedUniqBy('a'); result = _(list).sortedUniqBy({a: 42}); - result = _(list).sortedUniqBy<{a: number}, SampleObject>({a: 42}); } { @@ -2419,15 +2395,13 @@ namespace TestSortedUniqBy { { let result: _.LoDashExplicitArrayWrapper; - result = _(array).chain().sortedUniqBy(listIterator); + result = _(array).chain().sortedUniqBy(listIterator); result = _(array).chain().sortedUniqBy('a'); - result = _(array).chain().sortedUniqBy<{a: number}>({a: 42}); + result = _(array).chain().sortedUniqBy({a: 42}); result = _(list).chain().sortedUniqBy(listIterator); - result = _(list).chain().sortedUniqBy(listIterator); result = _(list).chain().sortedUniqBy('a'); result = _(list).chain().sortedUniqBy({a: 42}); - result = _(list).chain().sortedUniqBy<{a: number}, SampleObject>({a: 42}); } } @@ -2475,16 +2449,62 @@ namespace TestUnzip { // _.unzipWith { - let testUnzipWithArray: (number[]|_.List)[] | null | undefined = [] as any; + let testUnzipWithArray: Array> | null | undefined = [] as any; let testUnzipWithList: _.List> | null | undefined = [] as any; - let testUnzipWithIterator: {(prev: TResult, curr: number, index?: number, list?: number[]): TResult} = (prev: TResult, curr: number, index?: number, list?: number[]) => ({ a: 1, b: "", c: true }); - let result: TResult[]; - result = _.unzipWith(testUnzipWithArray); - result = _.unzipWith(testUnzipWithArray, testUnzipWithIterator); - result = _.unzipWith(testUnzipWithList); - result = _.unzipWith(testUnzipWithList, testUnzipWithIterator); - result = _(testUnzipWithArray).unzipWith(testUnzipWithIterator).value(); - result = _(testUnzipWithList).unzipWith(testUnzipWithIterator).value(); + + { + _.unzipWith(testUnzipWithArray); // $ExpectType number[][] + _.unzipWith(testUnzipWithList); // $ExpectType number[][] + _(testUnzipWithArray).unzipWith(); // $ExpectType LoDashImplicitWrapper + _(testUnzipWithList).unzipWith(); // $ExpectType LoDashImplicitWrapper + _.chain(testUnzipWithArray).unzipWith(); // $ExpectType LoDashExplicitWrapper + _.chain(testUnzipWithList).unzipWith(); // $ExpectType LoDashExplicitWrapper + } + + { + let result: TResult[]; + result = _.unzipWith(testUnzipWithArray, (...group) => { + group; // $ExpectType number[] + return any as TResult; + }); + result = _.unzipWith(testUnzipWithArray, (value1, value2, value3) => { + value1; // $ExpectType number + value2; // $ExpectType number + value3; // $ExpectType number + return any as TResult; + }); + result = _.unzipWith(testUnzipWithList, (...group) => { + group; // $ExpectType number[] + return any as TResult; + }); + result = _.unzipWith(testUnzipWithList, (value1, value2, value3) => { + value1; // $ExpectType number + value2; // $ExpectType number + value3; // $ExpectType number + return any as TResult; + }); + + result = _(testUnzipWithArray).unzipWith((...group): TResult => { + group; // $ExpectType number[] + return any as TResult; + }).value(); + result = _(testUnzipWithArray).unzipWith((value1, value2, value3) => { + value1; // $ExpectType number + value2; // $ExpectType number + value3; // $ExpectType number + return any as TResult; + }).value(); + result = _(testUnzipWithList).unzipWith((...group): TResult => { + group; // $ExpectType number[] + return any as TResult; + }).value(); + result = _(testUnzipWithList).unzipWith((value1, value2, value3) => { + value1; // $ExpectType number + value2; // $ExpectType number + value3; // $ExpectType number + return any as TResult; + }).value(); + } } // _.without @@ -2629,8 +2649,8 @@ namespace TestZipObject { { let result: _.Dictionary; - result = _.zipObject<_.Dictionary>(arrayOfKeys); - result = _.zipObject<_.Dictionary>(listOfKeys); + result = _.zipObject(arrayOfKeys); + result = _.zipObject(listOfKeys); } { @@ -2641,13 +2661,13 @@ namespace TestZipObject { result = _.zipObject<_.Dictionary>(listOfKeys, listOfValues); result = _.zipObject<_.Dictionary>(listOfKeys, arrayOfValues); - result = _.zipObject>(arrayOfKeys, arrayOfValues); - result = _.zipObject>(arrayOfKeys, listOfValues); - result = _.zipObject>(listOfKeys, listOfValues); - result = _.zipObject>(listOfKeys, arrayOfValues); + result = _.zipObject(arrayOfKeys, arrayOfValues); + result = _.zipObject(arrayOfKeys, listOfValues); + result = _.zipObject(listOfKeys, listOfValues); + result = _.zipObject(listOfKeys, arrayOfValues); - result = _.zipObject<_.Dictionary>(arrayOfKeyValuePairs); - result = _.zipObject<_.Dictionary>(listOfKeyValuePairs); + result = _.zipObject(arrayOfKeyValuePairs); + result = _.zipObject(listOfKeyValuePairs); } { @@ -2667,15 +2687,15 @@ namespace TestZipObject { result = _.zipObject(listOfKeys, arrayOfValues); result = _.zipObjectDeep(listOfKeys, arrayOfValues); - result = _.zipObject<_.Dictionary>(arrayOfKeyValuePairs); - result = _.zipObject<_.Dictionary>(listOfKeyValuePairs); + result = _.zipObject(arrayOfKeyValuePairs); + result = _.zipObject(listOfKeyValuePairs); } { let result: _.LoDashImplicitObjectWrapper<_.Dictionary>; - result = _(arrayOfKeys).zipObject<_.Dictionary>(); - result = _(listOfKeys).zipObject<_.Dictionary>(); + result = _(arrayOfKeys).zipObject(); + result = _(listOfKeys).zipObject(); } { @@ -2686,13 +2706,13 @@ namespace TestZipObject { result = _(listOfKeys).zipObject<_.Dictionary>(listOfValues); result = _(listOfKeys).zipObject<_.Dictionary>(arrayOfValues); - result = _(arrayOfKeys).zipObject>(arrayOfValues); - result = _(arrayOfKeys).zipObject>(listOfValues); - result = _(listOfKeys).zipObject>(listOfValues); - result = _(listOfKeys).zipObject>(arrayOfValues); + result = _(arrayOfKeys).zipObject(arrayOfValues); + result = _(arrayOfKeys).zipObject(listOfValues); + result = _(listOfKeys).zipObject(listOfValues); + result = _(listOfKeys).zipObject(arrayOfValues); - result = _(listOfKeys).zipObject<_.Dictionary>(arrayOfKeyValuePairs); - result = _(listOfKeys).zipObject<_.Dictionary>(listOfKeyValuePairs); + result = _(listOfKeys).zipObject(arrayOfKeyValuePairs); + result = _(listOfKeys).zipObject(listOfKeyValuePairs); } { @@ -2721,8 +2741,8 @@ namespace TestZipObject { { let result: _.LoDashExplicitObjectWrapper<_.Dictionary>; - result = _(arrayOfKeys).chain().zipObject<_.Dictionary>(); - result = _(listOfKeys).chain().zipObject<_.Dictionary>(); + result = _(arrayOfKeys).chain().zipObject(); + result = _(listOfKeys).chain().zipObject(); } { @@ -2733,13 +2753,13 @@ namespace TestZipObject { result = _(listOfKeys).chain().zipObject<_.Dictionary>(listOfValues); result = _(listOfKeys).chain().zipObject<_.Dictionary>(arrayOfValues); - result = _(arrayOfKeys).chain().zipObject>(arrayOfValues); - result = _(arrayOfKeys).chain().zipObject>(listOfValues); - result = _(listOfKeys).chain().zipObject>(listOfValues); - result = _(listOfKeys).chain().zipObject>(arrayOfValues); + result = _(arrayOfKeys).chain().zipObject(arrayOfValues); + result = _(arrayOfKeys).chain().zipObject(listOfValues); + result = _(listOfKeys).chain().zipObject(listOfValues); + result = _(listOfKeys).chain().zipObject(arrayOfValues); - result = _(listOfKeys).chain().zipObject<_.Dictionary>(arrayOfKeyValuePairs); - result = _(listOfKeys).chain().zipObject<_.Dictionary>(listOfKeyValuePairs); + result = _(listOfKeys).chain().zipObject(arrayOfKeyValuePairs); + result = _(listOfKeys).chain().zipObject(listOfKeyValuePairs); } { @@ -2767,18 +2787,157 @@ namespace TestZipObject { } // _.zipWith -interface TestZipWithFn { - (a1: number, a2: number): number; +namespace TestZipWith { + type TestZipWithFn = (a1: number, a2: number) => number; + + { + let result: number[][]; + result = _.zipWith([1, 2]); + result = _.zipWith([1, 2], [3, 4], [5, 6]); + result = _([1, 2]).zipWith().value(); + result = _([1, 2]).zipWith([3, 4], [5, 6]).value(); + result = _.chain([1, 2]).zipWith().value(); + result = _.chain([1, 2]).zipWith([3, 4], [5, 6]).value(); + } + { + let result: number[]; + + result = _.zipWith([1, 2], (value1) => { + value1; // $ExpectType number + return 1; + }); + result = _.zipWith([1, 2], [1, 2], (value1, value2) => { + value1; // $ExpectType number + value2; // $ExpectType number + return 1; + }); + result = _.zipWith([1, 2], [1, 2], [1, 2], (value1, value2, value3) => { + value1; // $ExpectType number + value2; // $ExpectType number + value3; // $ExpectType number + return 1; + }); + result = _.zipWith([1, 2], [1, 2], [1, 2], [1, 2], (value1, value2, value3, value4) => { + value1; // $ExpectType number + value2; // $ExpectType number + value3; // $ExpectType number + value4; // $ExpectType number + return 1; + }); + result = _.zipWith([1, 2], [1, 2], [1, 2], [1, 2], [1, 2], (value1, value2, value3, value4, value5) => { + value1; // $ExpectType number + value2; // $ExpectType number + value3; // $ExpectType number + value4; // $ExpectType number + value5; // $ExpectType number + return 1; + }); + result = _.zipWith([1, 2], [1, 2], [1, 2], [1, 2], [1, 2], [1, 2], (value1, value2, value3, value4, value5, value6) => { + value1; // $ExpectType number + value2; // $ExpectType number + value3; // $ExpectType number + value4; // $ExpectType number + value5; // $ExpectType number + value6; // $ExpectType number + return 1; + }); + result = _.zipWith([1, 2], [1, 2], [1, 2], (...group: number[]) => 1); + result = _.zipWith([1, 2], [1, 2], [1, 2], [1, 2], [1, 2], [1, 2], (...group) => { + group; // $ExpectType number[] + return 1; + }); + + result = _([1, 2]).zipWith((value1) => { + value1; // $ExpectType number + return 1; + }).value(); + result = _([1, 2]).zipWith([1, 2], (value1, value2) => { + value1; // $ExpectType number + value2; // $ExpectType number + return 1; + }).value(); + result = _([1, 2]).zipWith([1, 2], [1, 2], (value1, value2, value3) => { + value1; // $ExpectType number + value2; // $ExpectType number + value3; // $ExpectType number + return 1; + }).value(); + result = _([1, 2]).zipWith([1, 2], [1, 2], [1, 2], (value1, value2, value3, value4) => { + value1; // $ExpectType number + value2; // $ExpectType number + value3; // $ExpectType number + value4; // $ExpectType number + return 1; + }).value(); + result = _([1, 2]).zipWith([1, 2], [1, 2], [1, 2], [1, 2], (value1, value2, value3, value4, value5) => { + value1; // $ExpectType number + value2; // $ExpectType number + value3; // $ExpectType number + value4; // $ExpectType number + value5; // $ExpectType number + return 1; + }).value(); + result = _([1, 2]).zipWith([1, 2], [1, 2], [1, 2], [1, 2], [1, 2], (value1, value2, value3, value4, value5, value6) => { + value1; // $ExpectType number + value2; // $ExpectType number + value3; // $ExpectType number + value4; // $ExpectType number + value5; // $ExpectType number + value6; // $ExpectType number + return 1; + }).value(); + result = _([1, 2]).zipWith([1, 2], [1, 2], (...group: number[]) => 1).value(); + result = _([1, 2]).zipWith([1, 2], [1, 2], [1, 2], [1, 2], [1, 2], (...group) => { + group; // $ExpectType number[] + return 1; + }).value(); + + result = _.chain([1, 2]).zipWith((value1) => { + value1; // $ExpectType number + return 1; + }).value(); + result = _.chain([1, 2]).zipWith([1, 2], (value1, value2) => { + value1; // $ExpectType number + value2; // $ExpectType number + return 1; + }).value(); + result = _.chain([1, 2]).zipWith([1, 2], [1, 2], (value1, value2, value3) => { + value1; // $ExpectType number + value2; // $ExpectType number + value3; // $ExpectType number + return 1; + }).value(); + result = _.chain([1, 2]).zipWith([1, 2], [1, 2], [1, 2], (value1, value2, value3, value4) => { + value1; // $ExpectType number + value2; // $ExpectType number + value3; // $ExpectType number + value4; // $ExpectType number + return 1; + }).value(); + result = _.chain([1, 2]).zipWith([1, 2], [1, 2], [1, 2], [1, 2], (value1, value2, value3, value4, value5) => { + value1; // $ExpectType number + value2; // $ExpectType number + value3; // $ExpectType number + value4; // $ExpectType number + value5; // $ExpectType number + return 1; + }).value(); + result = _.chain([1, 2]).zipWith([1, 2], [1, 2], [1, 2], [1, 2], [1, 2], (value1, value2, value3, value4, value5, value6) => { + value1; // $ExpectType number + value2; // $ExpectType number + value3; // $ExpectType number + value4; // $ExpectType number + value5; // $ExpectType number + value6; // $ExpectType number + return 1; + }).value(); + result = _.chain([1, 2]).zipWith([1, 2], [1, 2], (...group: number[]) => 1).value(); + result = _.chain([1, 2]).zipWith([1, 2], [1, 2], [1, 2], [1, 2], [1, 2], (...group) => { + group; // $ExpectType number[] + return 1; + }).value(); + } } -let testZipWithFn: TestZipWithFn = (a1, a2) => 1; -result = _.zipWith([1, 2]); -result = _.zipWith([1, 2], testZipWithFn); -result = _.zipWith([1, 2], [1, 2], testZipWithFn); -result = _.zipWith([1, 2], [1, 2], [1, 2], [1, 2], [1, 2], [1, 2], testZipWithFn); -result = _([1, 2]).zipWith().value(); -result = _([1, 2]).zipWith(testZipWithFn).value(); -result = _([1, 2]).zipWith([1, 2], testZipWithFn).value(); -result = _([1, 2]).zipWith([1, 2], [1, 2], [1, 2], [1, 2], [1, 2], testZipWithFn).value(); /********* * Chain * @@ -2868,7 +3027,7 @@ namespace TestTap { { let interceptor = (value: {a: string}) => {}; - let result: _.LoDashImplicitObjectWrapper<{a: string}>; + let result: _.LoDashImplicitWrapper<{a: string}>; _.chain({a: ''}).tap(interceptor); @@ -2895,7 +3054,7 @@ namespace TestTap { { let interceptor = (value: {a: string}) => {}; - let result: _.LoDashExplicitObjectWrapper<{a: string}>; + let result: _.LoDashExplicitWrapper<{a: string}>; _.chain({a: ''}).tap(interceptor); @@ -2948,7 +3107,7 @@ namespace TestThru { let interceptor: Interceptor = (x) => x; let result: _.LoDashImplicitArrayWrapper; - result = _([1, 2, 3]).thru(interceptor); + result = _([1, 2, 3]).thru(interceptor); } { @@ -2983,7 +3142,7 @@ namespace TestThru { let interceptor: Interceptor = (x) => x; let result: _.LoDashExplicitArrayWrapper; - result = _([1, 2, 3]).chain().thru(interceptor); + result = _([1, 2, 3]).chain().thru(interceptor); } } @@ -3037,13 +3196,13 @@ namespace TestConcat { { let result: _.LoDashImplicitArrayWrapper; - result = _(['']).concat(['']); - result = _(['']).concat([''], ['']); - result = _(['']).concat([''], [''], ['']); + result = _(['']).concat(['']); + result = _(['']).concat([''], ['']); + result = _(['']).concat([''], [''], ['']); - result = _(['']).concat(['']); - result = _(['']).concat([''], ['']); - result = _(['']).concat([''], [''], ['']); + result = _(['']).concat(['']); + result = _(['']).concat([''], ['']); + result = _(['']).concat([''], [''], ['']); } { @@ -3073,13 +3232,13 @@ namespace TestConcat { { let result: _.LoDashExplicitArrayWrapper; - result = _(['']).chain().concat(['']); - result = _(['']).chain().concat([''], ['']); - result = _(['']).chain().concat([''], [''], ['']); + result = _(['']).chain().concat(['']); + result = _(['']).chain().concat([''], ['']); + result = _(['']).chain().concat([''], [''], ['']); - result = _(['']).chain().concat(['']); - result = _(['']).chain().concat([''], ['']); - result = _(['']).chain().concat([''], [''], ['']); + result = _(['']).chain().concat(['']); + result = _(['']).chain().concat([''], ['']); + result = _(['']).chain().concat([''], [''], ['']); } { @@ -3123,7 +3282,7 @@ namespace TestPlant { } { - let result: _.LoDashImplicitObjectWrapper<{}>; + let result: _.LoDashImplicitWrapper<{}>; result = _(any).plant<{}>({}); } @@ -3153,7 +3312,7 @@ namespace TestPlant { } { - let result: _.LoDashExplicitObjectWrapper<{}>; + let result: _.LoDashExplicitWrapper<{}>; result = _(any).chain().plant<{}>({}); } } @@ -3197,8 +3356,8 @@ namespace TestToJSON { { let result: string[]; - result = _([]).toJSON(); - result = _([]).chain().toJSON(); + result = _(['']).toJSON(); + result = _(['']).chain().toJSON(); } { @@ -3216,13 +3375,13 @@ namespace TestToString { result = _('').toString(); result = _(42).toString(); result = _(true).toString(); - result = _(['']).toString(); + result = _(['']).toString(); result = _({}).toString(); result = _('').chain().toString(); result = _(42).chain().toString(); result = _(true).chain().toString(); - result = _(['']).chain().toString(); + result = _(['']).chain().toString(); result = _({}).chain().toString(); } @@ -3252,8 +3411,8 @@ namespace TestValue { { let result: string[]; - result = _([]).value(); - result = _([]).chain().value(); + result = _(['']).value(); + result = _(['']).chain().value(); } { @@ -3290,8 +3449,8 @@ namespace TestValueOf { { let result: string[]; - result = _([]).valueOf(); - result = _([]).chain().valueOf(); + result = _(['']).valueOf(); + result = _(['']).chain().valueOf(); } { @@ -3345,7 +3504,7 @@ namespace TestCountBy { let dictionary: _.Dictionary | null | undefined = obj; let numericDictionary: _.NumericDictionary | null | undefined = obj; - let stringIterator: (value: string, index: number, collection: ArrayLike) => any = (value: string, index: number, collection: ArrayLike) => 1; + let stringIterator: (value: string, index: number, collection: string) => any = (value: string, index: number, collection: string) => 1; let listIterator: (value: TResult, index: number, collection: _.List) => any = (value: TResult, index: number, collection: _.List) => 1; let dictionaryIterator: (value: TResult, key: string, collection: _.Dictionary) => any = (value: TResult, key: string, collection: _.Dictionary) => 1; let numericDictionaryIterator: (value: TResult, key: number, collection: _.NumericDictionary) => any = (value: TResult, key: number, collection: _.NumericDictionary) => 1; @@ -3359,25 +3518,25 @@ namespace TestCountBy { result = _.countBy(array); result = _.countBy(array, listIterator); result = _.countBy(array, ''); - result = _.countBy<{a: number}, TResult>(array, {a: 42}); + result = _.countBy(array, {a: 42}); result = _.countBy(array, {a: 42}); result = _.countBy(list); result = _.countBy(list, listIterator); result = _.countBy(list, ''); - result = _.countBy<{a: number}, TResult>(list, {a: 42}); + result = _.countBy(list, {a: 42}); result = _.countBy(list, {a: 42}); result = _.countBy(dictionary); - result = _.countBy(dictionary, dictionaryIterator); + result = _.countBy(dictionary, dictionaryIterator); result = _.countBy(dictionary, ''); - result = _.countBy<{a: number}, TResult>(dictionary, {a: 42}); + result = _.countBy(dictionary, {a: 42}); result = _.countBy(dictionary, {a: 42}); result = _.countBy(numericDictionary); result = _.countBy(numericDictionary, numericDictionaryIterator); result = _.countBy(numericDictionary, ''); - result = _.countBy<{a: number}, TResult>(numericDictionary, {a: 42}); + result = _.countBy(numericDictionary, {a: 42}); result = _.countBy(numericDictionary, {a: 42}); } @@ -3400,7 +3559,7 @@ namespace TestCountBy { result = _(list).countBy({a: 42}); result = _(dictionary).countBy(); - result = _(dictionary).countBy(dictionaryIterator); + result = _(dictionary).countBy(dictionaryIterator); result = _(dictionary).countBy(''); result = _(dictionary).countBy<{a: number}>({a: 42}); result = _(dictionary).countBy({a: 42}); @@ -3431,7 +3590,7 @@ namespace TestCountBy { result = _(list).chain().countBy({a: 42}); result = _(dictionary).chain().countBy(); - result = _(dictionary).chain().countBy(dictionaryIterator); + result = _(dictionary).chain().countBy(dictionaryIterator); result = _(dictionary).chain().countBy(''); result = _(dictionary).chain().countBy<{a: number}>({a: 42}); result = _(dictionary).chain().countBy({a: 42}); @@ -3526,7 +3685,7 @@ namespace TestEach { { let result: _.LoDashImplicitObjectWrapper<_.Dictionary>; - result = _(dictionary).each(dictionaryIterator); + result = _(dictionary).each(dictionaryIterator); } { @@ -3550,7 +3709,7 @@ namespace TestEach { { let result: _.LoDashExplicitObjectWrapper<_.Dictionary>; - result = _(dictionary).chain().each(dictionaryIterator); + result = _(dictionary).chain().each(dictionaryIterator); } } @@ -3636,7 +3795,7 @@ namespace TestEachRight { { let result: _.LoDashImplicitObjectWrapper<_.Dictionary>; - result = _(dictionary).eachRight(dictionaryIterator); + result = _(dictionary).eachRight(dictionaryIterator); } { @@ -3660,7 +3819,7 @@ namespace TestEachRight { { let result: _.LoDashExplicitObjectWrapper<_.Dictionary>; - result = _(dictionary).chain().eachRight(dictionaryIterator); + result = _(dictionary).chain().eachRight(dictionaryIterator); } } @@ -3694,7 +3853,7 @@ namespace TestEvery { result = _.every(list, {a: 42}); result = _.every(dictionary); - result = _.every(dictionary, dictionaryIterator); + result = _.every(dictionary, dictionaryIterator); result = _.every(dictionary, 'a'); result = _.every(dictionary, ['a', 42]); result = _.every(dictionary, {a: 42}); @@ -3718,7 +3877,7 @@ namespace TestEvery { result = _(list).every({a: 42}); result = _(dictionary).every(); - result = _(dictionary).every(dictionaryIterator); + result = _(dictionary).every(dictionaryIterator); result = _(dictionary).every('a'); result = _(dictionary).every(['a', 42]); result = _(dictionary).every({a: 42}); @@ -3746,7 +3905,7 @@ namespace TestEvery { result = _(list).chain().every({a: 42}); result = _(dictionary).chain().every(); - result = _(dictionary).chain().every(dictionaryIterator); + result = _(dictionary).chain().every(dictionaryIterator); result = _(dictionary).chain().every('a'); result = _(dictionary).chain().every(['a', 42]); result = _(dictionary).chain().every({a: 42}); @@ -3781,21 +3940,18 @@ namespace TestFilter { result = _.filter(array, listIterator); result = _.filter(array, ''); - result = _.filter(array, /./); result = _.filter(array, {a: 42}); result = _.filter(array, ["a", 42]); result = _.filter(list, listIterator); result = _.filter(list, ''); - result = _.filter(list, /./); result = _.filter(list, {a: 42}); result = _.filter(list, ["a", 42]); - result = _.filter(dictionary, dictionaryIterator); - result = _.filter(dictionary, ''); - result = _.filter(dictionary, /./); - result = _.filter(dictionary, {a: 42}); - result = _.filter(dictionary, ["a", 42]); + result = _.filter(dictionary, dictionaryIterator); + result = _.filter(dictionary, ''); + result = _.filter(dictionary, {a: 42}); + result = _.filter(dictionary, ["a", 42]); } { @@ -3809,21 +3965,18 @@ namespace TestFilter { result = _(array).filter(listIterator); result = _(array).filter(''); - result = _(array).filter(/./); result = _(array).filter({a: 42}); result = _(array).filter(["a", 42]); result = _(list).filter(listIterator); result = _(list).filter(''); - result = _(list).filter(/./); result = _(list).filter({a: 42}); result = _(list).filter(["a", 42]); - result = _(dictionary).filter(dictionaryIterator); - result = _(dictionary).filter(''); - result = _(dictionary).filter(/./); - result = _(dictionary).filter({a: 42}); - result = _(dictionary).filter(["a", 42]); + result = _(dictionary).filter(dictionaryIterator); + result = _(dictionary).filter(''); + result = _(dictionary).filter({a: 42}); + result = _(dictionary).filter(["a", 42]); } { @@ -3837,21 +3990,18 @@ namespace TestFilter { result = _(array).chain().filter(listIterator); result = _(array).chain().filter(''); - result = _(array).chain().filter(/./); result = _(array).chain().filter({a: 42}); result = _(array).chain().filter(["a", 42]); result = _(list).chain().filter(listIterator); result = _(list).chain().filter(''); - result = _(list).chain().filter(/./); result = _(list).chain().filter({a: 42}); result = _(list).chain().filter(["a", 42]); - result = _(dictionary).chain().filter(dictionaryIterator); - result = _(dictionary).chain().filter(''); - result = _(dictionary).chain().filter(/./); - result = _(dictionary).chain().filter({a: 42}); - result = _(dictionary).chain().filter(["a", 42]); + result = _(dictionary).chain().filter(dictionaryIterator); + result = _(dictionary).chain().filter(''); + result = _(dictionary).chain().filter({a: 42}); + result = _(dictionary).chain().filter(["a", 42]); } { @@ -3861,10 +4011,10 @@ namespace TestFilter { _.filter(a2, (item: string | number): item is number => typeof item === "number"); // $ExpectType number[] _.filter(d2, (item: string | number): item is number => typeof item === "number"); // $ExpectType number[] - _(a2).filter((item: string | number): item is number => typeof item === "number"); // $ExpectType LoDashImplicitArrayWrapper - _(d2).filter((item: string | number): item is number => typeof item === "number"); // $ExpectType LoDashImplicitArrayWrapper - _(a2).chain().filter((item: string | number): item is number => typeof item === "number"); // $ExpectType LoDashExplicitArrayWrapper - _(d2).chain().filter((item: string | number): item is number => typeof item === "number"); // $ExpectType LoDashExplicitArrayWrapper + _(a2).filter((item: string | number): item is number => typeof item === "number"); // $ExpectType LoDashImplicitWrapper + _(d2).filter((item: string | number): item is number => typeof item === "number"); // $ExpectType LoDashImplicitWrapper + _(a2).chain().filter((item: string | number): item is number => typeof item === "number"); // $ExpectType LoDashExplicitWrapper + _(d2).chain().filter((item: string | number): item is number => typeof item === "number"); // $ExpectType LoDashExplicitWrapper } } @@ -3903,13 +4053,13 @@ namespace TestFind { result = _.find(list, ['a', 5], 1); result = _.find(dictionary); - result = _.find(dictionary); - result = _.find(dictionary, dictionaryIterator); - result = _.find(dictionary, dictionaryIterator, 1); - result = _.find(dictionary, ''); - result = _.find(dictionary, '', 1); - result = _.find(dictionary, {a: 42}); - result = _.find(dictionary, {a: 42}, 1); + result = _.find(dictionary); + result = _.find(dictionary, dictionaryIterator); + result = _.find(dictionary, dictionaryIterator, 1); + result = _.find(dictionary, ''); + result = _.find(dictionary, '', 1); + result = _.find(dictionary, {a: 42}); + result = _.find(dictionary, {a: 42}, 1); result = _.find(dictionary, ['a', 5]); result = _.find(dictionary, ['a', 5], 1); @@ -3933,15 +4083,15 @@ namespace TestFind { result = _(list).find(['a', 5]); result = _(list).find(['a', 5], 1); - result = _(dictionary).find(); - result = _(dictionary).find(dictionaryIterator); - result = _(dictionary).find(dictionaryIterator, 1); - result = _(dictionary).find(''); - result = _(dictionary).find('', 1); - result = _(dictionary).find({a: 42}); - result = _(dictionary).find({a: 42}, 1); - result = _(dictionary).find(['a', 5]); - result = _(dictionary).find(['a', 5], 1); + result = _(dictionary).find(); + result = _(dictionary).find(dictionaryIterator); + result = _(dictionary).find(dictionaryIterator, 1); + result = _(dictionary).find(''); + result = _(dictionary).find('', 1); + result = _(dictionary).find({a: 42}); + result = _(dictionary).find({a: 42}, 1); + result = _(dictionary).find(['a', 5]); + result = _(dictionary).find(['a', 5], 1); result = _.find([any as TResult, null, undefined], (value: TResult | null | undefined): value is TResult | undefined => value !== null); result = _([any as TResult, null, undefined]).find((value: TResult | null | undefined): value is TResult | undefined => value !== null); @@ -3982,13 +4132,13 @@ namespace TestFindLast { result = _.findLast(list, ['a', 5], 1); result = _.findLast(dictionary); - result = _.findLast(dictionary); - result = _.findLast(dictionary, dictionaryIterator); - result = _.findLast(dictionary, dictionaryIterator, 1); - result = _.findLast(dictionary, ''); - result = _.findLast(dictionary, '', 1); - result = _.findLast(dictionary, {a: 42}); - result = _.findLast(dictionary, {a: 42}, 1); + result = _.findLast(dictionary); + result = _.findLast(dictionary, dictionaryIterator); + result = _.findLast(dictionary, dictionaryIterator, 1); + result = _.findLast(dictionary, ''); + result = _.findLast(dictionary, '', 1); + result = _.findLast(dictionary, {a: 42}); + result = _.findLast(dictionary, {a: 42}, 1); result = _.findLast(dictionary, ['a', 5]); result = _.findLast(dictionary, ['a', 5], 1); @@ -4012,15 +4162,15 @@ namespace TestFindLast { result = _(list).findLast(['a', 5]); result = _(list).findLast(['a', 5], 1); - result = _(dictionary).findLast(); - result = _(dictionary).findLast(dictionaryIterator); - result = _(dictionary).findLast(dictionaryIterator, 1); - result = _(dictionary).findLast(''); - result = _(dictionary).findLast('', 1); - result = _(dictionary).findLast({a: 42}); - result = _(dictionary).findLast({a: 42}, 1); - result = _(dictionary).findLast(['a', 5]); - result = _(dictionary).findLast(['a', 5], 1); + result = _(dictionary).findLast(); + result = _(dictionary).findLast(dictionaryIterator); + result = _(dictionary).findLast(dictionaryIterator, 1); + result = _(dictionary).findLast(''); + result = _(dictionary).findLast('', 1); + result = _(dictionary).findLast({a: 42}); + result = _(dictionary).findLast({a: 42}, 1); + result = _(dictionary).findLast(['a', 5]); + result = _(dictionary).findLast(['a', 5], 1); result = _.findLast([any as TResult, null, undefined], (value: TResult | null | undefined): value is TResult | undefined => value !== null); result = _([any as TResult, null, undefined]).findLast((value: TResult | null | undefined): value is TResult | undefined => value !== null); @@ -4068,7 +4218,7 @@ namespace TestFlatMap { result = _.flatMap(numArray, listIterator); result = _.flatMap(numArray, listIterator); - result = _.flatMap(objArray, 'a'); + result = _.flatMap(objArray, 'a'); result = _.flatMap(numList); result = _.flatMap(numList); @@ -4076,15 +4226,14 @@ namespace TestFlatMap { result = _.flatMap(numList, listIterator); result = _.flatMap(numList, listIterator); - result = _.flatMap(objList, 'a'); + result = _.flatMap(objList, 'a'); result = _.flatMap(numDictionary); result = _.flatMap(numDictionary); result = _.flatMap(numDictionary, dictionaryIterator); - result = _.flatMap(numDictionary, dictionaryIterator); - result = _.flatMap(objDictionary, 'a'); + result = _.flatMap(objDictionary, 'a'); result = _.flatMap(numNumericDictionary); result = _.flatMap(numNumericDictionary); @@ -4092,7 +4241,7 @@ namespace TestFlatMap { result = _.flatMap(numNumericDictionary, numericDictionaryIterator); result = _.flatMap(numNumericDictionary, numericDictionaryIterator); - result = _.flatMap<_.NumericDictionary<{a: number}|{a: number}[]>, number>(objNumericDictionary, 'a'); + result = _.flatMap(objNumericDictionary, 'a'); } { @@ -4115,27 +4264,26 @@ namespace TestFlatMap { let result: _.LoDashImplicitArrayWrapper; result = _('abc').flatMap(); - result = _('abc').flatMap(stringIterator); } { let result: _.LoDashImplicitArrayWrapper; result = _(numArray).flatMap(); - result = _(numArray).flatMap(listIterator); - result = _(objArray).flatMap('a'); + result = _(numArray).flatMap(listIterator); + result = _(objArray).flatMap('a'); result = _(numList).flatMap(); result = _(numList).flatMap(listIterator); - result = _(objList).flatMap('a'); + result = _(objList).flatMap('a'); result = _(numDictionary).flatMap(); - result = _(numDictionary).flatMap(dictionaryIterator); - result = _(objDictionary).flatMap('a'); + result = _(numDictionary).flatMap(dictionaryIterator); + result = _(objDictionary).flatMap('a'); result = _(numNumericDictionary).flatMap(); result = _(numNumericDictionary).flatMap(numericDictionaryIterator); - result = _(objNumericDictionary).flatMap('a'); + result = _(objNumericDictionary).flatMap('a'); } { @@ -4158,27 +4306,26 @@ namespace TestFlatMap { let result: _.LoDashExplicitArrayWrapper; result = _('abc').chain().flatMap(); - result = _('abc').chain().flatMap(stringIterator); } { let result: _.LoDashExplicitArrayWrapper; result = _(numArray).chain().flatMap(); - result = _(numArray).chain().flatMap(listIterator); - result = _(objArray).chain().flatMap('a'); + result = _(numArray).chain().flatMap(listIterator); + result = _(objArray).chain().flatMap('a'); result = _(numList).chain().flatMap(); result = _(numList).chain().flatMap(listIterator); - result = _(objList).chain().flatMap('a'); + result = _(objList).chain().flatMap('a'); result = _(numDictionary).chain().flatMap(); - result = _(numDictionary).chain().flatMap(dictionaryIterator); - result = _(objDictionary).chain().flatMap('a'); + result = _(numDictionary).chain().flatMap(dictionaryIterator); + result = _(objDictionary).chain().flatMap('a'); result = _(numNumericDictionary).chain().flatMap(); result = _(numNumericDictionary).chain().flatMap(numericDictionaryIterator); - result = _(objNumericDictionary).chain().flatMap('a'); + result = _(objNumericDictionary).chain().flatMap('a'); } { @@ -4232,25 +4379,25 @@ namespace TestFlatMapDeep { { let result: number[]; - result = _.flatMapDeep(numArray); + result = _.flatMapDeep(numArray); result = _.flatMapDeep(numArray, listIterator); result = _.flatMapDeep(objArray, 'a'); - result = _.flatMapDeep(numList); + result = _.flatMapDeep(numList); result = _.flatMapDeep(numList, listIterator); result = _.flatMapDeep(objList, 'a'); - result = _.flatMapDeep(numDictionary); + result = _.flatMapDeep(numDictionary); result = _.flatMapDeep(numDictionary, dictionaryIterator); result = _.flatMapDeep(objDictionary, 'a'); - result = _.flatMapDeep(numNumericDictionary); + result = _.flatMapDeep(numNumericDictionary); result = _.flatMapDeep(numNumericDictionary, numericDictionaryIterator); @@ -4283,19 +4430,19 @@ namespace TestFlatMapDeep { { let result: _.LoDashImplicitArrayWrapper; - result = _(numArray).flatMapDeep(); + result = _(numArray).flatMapDeep(); result = _(numArray).flatMapDeep(listIterator); result = _(objArray).flatMapDeep('a'); - result = _(numList).flatMapDeep(); + result = _(numList).flatMapDeep(); result = _(numList).flatMapDeep(listIterator); result = _(objList).flatMapDeep('a'); - result = _(numDictionary).flatMapDeep(); + result = _(numDictionary).flatMapDeep(); result = _(numDictionary).flatMapDeep(dictionaryIterator); result = _(objDictionary).flatMapDeep('a'); - result = _(numNumericDictionary).flatMapDeep(); + result = _(numNumericDictionary).flatMapDeep(); result = _(numNumericDictionary).flatMapDeep(numericDictionaryIterator); result = _(objNumericDictionary).flatMapDeep('a'); } @@ -4326,19 +4473,19 @@ namespace TestFlatMapDeep { { let result: _.LoDashExplicitArrayWrapper; - result = _(numArray).chain().flatMapDeep(); + result = _(numArray).chain().flatMapDeep(); result = _(numArray).chain().flatMapDeep(listIterator); result = _(objArray).chain().flatMapDeep('a'); - result = _(numList).chain().flatMapDeep(); + result = _(numList).chain().flatMapDeep(); result = _(numList).chain().flatMapDeep(listIterator); result = _(objList).chain().flatMapDeep('a'); - result = _(numDictionary).chain().flatMapDeep(); + result = _(numDictionary).chain().flatMapDeep(); result = _(numDictionary).chain().flatMapDeep(dictionaryIterator); result = _(objDictionary).chain().flatMapDeep('a'); - result = _(numNumericDictionary).chain().flatMapDeep(); + result = _(numNumericDictionary).chain().flatMapDeep(); result = _(numNumericDictionary).chain().flatMapDeep(numericDictionaryIterator); result = _(objNumericDictionary).chain().flatMapDeep('a'); } @@ -4394,25 +4541,25 @@ namespace TestFlatMapDepth { { let result: number[]; - result = _.flatMapDepth(numArray); + result = _.flatMapDepth(numArray); result = _.flatMapDepth(numArray, listIterator, 1); result = _.flatMapDepth(objArray, 'a'); - result = _.flatMapDepth(numList); + result = _.flatMapDepth(numList); result = _.flatMapDepth(numList, listIterator, 1); result = _.flatMapDepth(objList, 'a', 1); - result = _.flatMapDepth(numDictionary); + result = _.flatMapDepth(numDictionary); result = _.flatMapDepth(numDictionary, dictionaryIterator, 1); result = _.flatMapDepth(objDictionary, 'a', 1); - result = _.flatMapDepth(numNumericDictionary); + result = _.flatMapDepth(numNumericDictionary); result = _.flatMapDepth(numNumericDictionary, numericDictionaryIterator, 1); @@ -4445,19 +4592,19 @@ namespace TestFlatMapDepth { { let result: _.LoDashImplicitArrayWrapper; - result = _(numArray).flatMapDepth(); + result = _(numArray).flatMapDepth(); result = _(numArray).flatMapDepth(listIterator, 1); result = _(objArray).flatMapDepth('a', 1); - result = _(numList).flatMapDepth(); + result = _(numList).flatMapDepth(); result = _(numList).flatMapDepth(listIterator, 1); result = _(objList).flatMapDepth('a', 1); - result = _(numDictionary).flatMapDepth(); + result = _(numDictionary).flatMapDepth(); result = _(numDictionary).flatMapDepth(dictionaryIterator, 1); result = _(objDictionary).flatMapDepth('a', 1); - result = _(numNumericDictionary).flatMapDepth(); + result = _(numNumericDictionary).flatMapDepth(); result = _(numNumericDictionary).flatMapDepth(numericDictionaryIterator, 1); result = _(objNumericDictionary).flatMapDepth('a', 1); } @@ -4488,19 +4635,19 @@ namespace TestFlatMapDepth { { let result: _.LoDashExplicitArrayWrapper; - result = _(numArray).chain().flatMapDepth(); + result = _(numArray).chain().flatMapDepth(); result = _(numArray).chain().flatMapDepth(listIterator, 1); result = _(objArray).chain().flatMapDepth('a', 1); - result = _(numList).chain().flatMapDepth(); + result = _(numList).chain().flatMapDepth(); result = _(numList).chain().flatMapDepth(listIterator, 1); result = _(objList).chain().flatMapDepth('a', 1); - result = _(numDictionary).chain().flatMapDepth(); + result = _(numDictionary).chain().flatMapDepth(); result = _(numDictionary).chain().flatMapDepth(dictionaryIterator, 1); result = _(objDictionary).chain().flatMapDepth('a', 1); - result = _(numNumericDictionary).chain().flatMapDepth(); + result = _(numNumericDictionary).chain().flatMapDepth(); result = _(numNumericDictionary).chain().flatMapDepth(numericDictionaryIterator, 1); result = _(objNumericDictionary).chain().flatMapDepth('a', 1); } @@ -4564,8 +4711,7 @@ namespace TestForEach { result = _.forEach(array, (value, index, collection) => { value; // $ExpectType TResult index; // $ExpectType number - // Note: ideally we'd like collection TResult[], but it seems the best we can get is List. - collection; // $ExpectType ArrayLike + collection; // $ExpectType TResult[] }); } @@ -4579,8 +4725,7 @@ namespace TestForEach { result = _.forEach(nilArray, (value, index, collection) => { value; // $ExpectType TResult index; // $ExpectType number - // Note: ideally we'd like collection TResult[], but it seems the best we can get is List. - collection; // $ExpectType ArrayLike + collection; // $ExpectType TResult[] }); } @@ -4648,7 +4793,7 @@ namespace TestForEach { result = _(array).forEach((value, index, collection) => { value; // $ExpectType TResult index; // $ExpectType number - collection; // $ExpectType ArrayLike + collection; // $ExpectType TResult[] }); } @@ -4658,7 +4803,7 @@ namespace TestForEach { result = _(nilArray).forEach((value, index, collection) => { value; // $ExpectType TResult index; // $ExpectType number - collection; // $ExpectType ArrayLike + collection; // $ExpectType TResult[] }); } @@ -4677,13 +4822,13 @@ namespace TestForEach { { let result: _.LoDashImplicitObjectWrapper<_.Dictionary>; - result = _(dictionary).forEach(dictionaryIterator); + result = _(dictionary).forEach(dictionaryIterator); } { let result: _.LoDashImplicitNillableObjectWrapper<_.Dictionary>; - result = _(nilDictionary).forEach(dictionaryIterator); + result = _(nilDictionary).forEach(dictionaryIterator); } { @@ -4702,7 +4847,7 @@ namespace TestForEach { result = _(array).chain().forEach((value, index, collection) => { value; // $ExpectType TResult index; // $ExpectType number - collection; // $ExpectType ArrayLike + collection; // $ExpectType TResult[] }); } @@ -4712,7 +4857,7 @@ namespace TestForEach { result = _(nilArray).chain().forEach((value, index, collection) => { value; // $ExpectType TResult index; // $ExpectType number - collection; // $ExpectType ArrayLike + collection; // $ExpectType TResult[] }); } @@ -4731,13 +4876,13 @@ namespace TestForEach { { let result: _.LoDashExplicitObjectWrapper<_.Dictionary>; - result = _(dictionary).chain().forEach(dictionaryIterator); + result = _(dictionary).chain().forEach(dictionaryIterator); } { let result: _.LoDashExplicitNillableObjectWrapper<_.Dictionary>; - result = _(nilDictionary).chain().forEach(dictionaryIterator); + result = _(nilDictionary).chain().forEach(dictionaryIterator); } } @@ -4779,7 +4924,7 @@ namespace TestForEachRight { result = _.forEachRight(array, (value, index, collection) => { value; // $ExpectType TResult index; // $ExpectType number - collection; // $ExpectType ArrayLike + collection; // $ExpectType TResult[] }); } @@ -4789,7 +4934,7 @@ namespace TestForEachRight { result = _.forEachRight(nilArray, (value, index, collection) => { value; // $ExpectType TResult index; // $ExpectType number - collection; // $ExpectType ArrayLike + collection; // $ExpectType TResult[] }); } @@ -4870,13 +5015,13 @@ namespace TestForEachRight { { let result: _.LoDashImplicitObjectWrapper<_.Dictionary>; - result = _(dictionary).forEachRight(dictionaryIterator); + result = _(dictionary).forEachRight(dictionaryIterator); } { let result: _.LoDashImplicitNillableObjectWrapper<_.Dictionary>; - result = _(nilDictionary).forEachRight(dictionaryIterator); + result = _(nilDictionary).forEachRight(dictionaryIterator); } { @@ -4895,7 +5040,7 @@ namespace TestForEachRight { result = _(array).chain().forEachRight((value, index, collection) => { value; // $ExpectType TResult index; // $ExpectType number - collection; // $ExpectType ArrayLike + collection; // $ExpectType TResult[] }); } @@ -4905,7 +5050,7 @@ namespace TestForEachRight { result = _(nilArray).chain().forEachRight((value, index, collection) => { value; // $ExpectType TResult index; // $ExpectType number - collection; // $ExpectType ArrayLike + collection; // $ExpectType TResult[] }); } @@ -4924,13 +5069,13 @@ namespace TestForEachRight { { let result: _.LoDashExplicitObjectWrapper<_.Dictionary>; - result = _(dictionary).chain().forEachRight(dictionaryIterator); + result = _(dictionary).chain().forEachRight(dictionaryIterator); } { let result: _.LoDashExplicitNillableObjectWrapper<_.Dictionary>; - result = _(nilDictionary).chain().forEachRight(dictionaryIterator); + result = _(nilDictionary).chain().forEachRight(dictionaryIterator); } } @@ -4952,7 +5097,6 @@ namespace TestGroupBy { result = _.groupBy(''); result = _.groupBy('', stringIterator); - result = _.groupBy('', stringIterator); } { @@ -4963,97 +5107,67 @@ namespace TestGroupBy { result = _.groupBy(array, ''); result = _.groupBy(array, {a: 42}); - result = _.groupBy(array, listIterator); - result = _.groupBy(array, ''); - result = _.groupBy<{a: number}, SampleType>(array, {a: 42}); - result = _.groupBy(list); result = _.groupBy(list, listIterator); result = _.groupBy(list, ''); result = _.groupBy(list, {a: 42}); - result = _.groupBy(list, listIterator); - result = _.groupBy(list, ''); - result = _.groupBy<{a: number}, SampleType>(list, {a: 42}); - - result = _.groupBy(dictionary); - result = _.groupBy(dictionary, dictionaryIterator); - result = _.groupBy(dictionary, ''); - result = _.groupBy(dictionary, {a: 42}); - - result = _.groupBy(dictionary, dictionaryIterator); - result = _.groupBy(dictionary, ''); - result = _.groupBy<{a: number}, SampleType>(dictionary, {a: 42}); + result = _.groupBy(dictionary); + result = _.groupBy(dictionary, dictionaryIterator); + result = _.groupBy(dictionary, ''); + result = _.groupBy(dictionary, {a: 42}); } { let result: _.LoDashImplicitObjectWrapper<_.Dictionary>; result = _('').groupBy(); - result = _('').groupBy((char: string, index: number, string: ArrayLike) => 0); + result = _('').groupBy((char: string, index: number, string: ArrayLike) => 0); } { let result: _.LoDashImplicitObjectWrapper<_.Dictionary>; result = _(array).groupBy(); - result = _(array).groupBy(listIterator); + result = _(array).groupBy(listIterator); result = _(array).groupBy(''); - result = _(array).groupBy(''); - result = _(array).groupBy<{a: number}>({a: 42}); + result = _(array).groupBy({a: 42}); result = _(list).groupBy(); result = _(list).groupBy(listIterator); result = _(list).groupBy(''); result = _(list).groupBy({a: 42}); - result = _(list).groupBy(listIterator); - result = _(list).groupBy(''); - result = _(list).groupBy<{a: number}, SampleType>({a: 42}); - result = _(dictionary).groupBy(); - result = _(dictionary).groupBy(dictionaryIterator); + result = _(dictionary).groupBy(dictionaryIterator); result = _(dictionary).groupBy(''); result = _(dictionary).groupBy({a: 42}); - - result = _(dictionary).groupBy(dictionaryIterator); - result = _(dictionary).groupBy(''); - result = _(dictionary).groupBy<{a: number}, SampleType>({a: 42}); } { let result: _.LoDashExplicitObjectWrapper<_.Dictionary>; result = _('').chain().groupBy(); - result = _('').chain().groupBy((char: string, index: number, string: ArrayLike) => 0); + result = _('').chain().groupBy((char: string, index: number, string: ArrayLike) => 0); } { let result: _.LoDashExplicitObjectWrapper<_.Dictionary>; result = _(array).chain().groupBy(); - result = _(array).chain().groupBy(listIterator); + result = _(array).chain().groupBy(listIterator); result = _(array).chain().groupBy(''); - result = _(array).chain().groupBy(''); - result = _(array).chain().groupBy<{a: number}>({a: 42}); + result = _(array).chain().groupBy({a: 42}); result = _(list).chain().groupBy(); result = _(list).chain().groupBy(listIterator); result = _(list).chain().groupBy(''); result = _(list).chain().groupBy({a: 42}); - result = _(list).chain().groupBy(listIterator); - result = _(list).chain().groupBy(''); - result = _(list).chain().groupBy<{a: number}, SampleType>({a: 42}); - result = _(dictionary).chain().groupBy(); - result = _(dictionary).chain().groupBy(dictionaryIterator); + result = _(dictionary).chain().groupBy(dictionaryIterator); result = _(dictionary).chain().groupBy(''); result = _(dictionary).chain().groupBy({a: 42}); - - result = _(dictionary).chain().groupBy(dictionaryIterator); - result = _(dictionary).chain().groupBy(''); - result = _(dictionary).chain().groupBy<{a: number}, SampleType>({a: 42}); } } @@ -5132,26 +5246,22 @@ namespace TestKeyBy { result = _.keyBy(array); result = _.keyBy(array, listIterator); result = _.keyBy(array, 'a'); - result = _.keyBy<{a: number}, SampleObject>(array, {a: 42}); result = _.keyBy(array, {a: 42}); result = _.keyBy(list); result = _.keyBy(list, listIterator); result = _.keyBy(list, 'a'); - result = _.keyBy<{a: number}, SampleObject>(list, {a: 42}); result = _.keyBy(list, {a: 42}); result = _.keyBy(numericDictionary); result = _.keyBy(numericDictionary, numericDictionaryIterator); result = _.keyBy(numericDictionary, 'a'); - result = _.keyBy<{a: number}, SampleObject>(numericDictionary, {a: 42}); result = _.keyBy(numericDictionary, {a: 42}); - result = _.keyBy(dictionary); - result = _.keyBy(dictionary, dictionaryIterator); - result = _.keyBy(dictionary, 'a'); - result = _.keyBy<{a: number}, SampleObject>(dictionary, {a: 42}); - result = _.keyBy(dictionary, {a: 42}); + result = _.keyBy(dictionary); + result = _.keyBy(dictionary, dictionaryIterator); + result = _.keyBy(dictionary, 'a'); + result = _.keyBy(dictionary, {a: 42}); } { @@ -5167,25 +5277,22 @@ namespace TestKeyBy { result = _(array).keyBy(); result = _(array).keyBy(listIterator); result = _(array).keyBy('a'); - result = _(array).keyBy<{a: number}>({a: 42}); + result = _(array).keyBy({a: 42}); result = _(list).keyBy(); result = _(list).keyBy(listIterator); result = _(list).keyBy('a'); - result = _(list).keyBy<{a: number}, SampleObject>({a: 42}); result = _(list).keyBy({a: 42}); result = _(numericDictionary).keyBy(); result = _(numericDictionary).keyBy(numericDictionaryIterator); result = _(numericDictionary).keyBy('a'); - result = _(numericDictionary).keyBy<{a: number}, SampleObject>({a: 42}); result = _(numericDictionary).keyBy({a: 42}); - result = _(dictionary).keyBy(); - result = _(dictionary).keyBy(dictionaryIterator); - result = _(dictionary).keyBy('a'); - result = _(dictionary).keyBy<{a: number}, SampleObject>({a: 42}); - result = _(dictionary).keyBy({a: 42}); + result = _(dictionary).keyBy(); + result = _(dictionary).keyBy(dictionaryIterator); + result = _(dictionary).keyBy('a'); + result = _(dictionary).keyBy({a: 42}); } { @@ -5201,25 +5308,22 @@ namespace TestKeyBy { result = _(array).chain().keyBy(); result = _(array).chain().keyBy(listIterator); result = _(array).chain().keyBy('a'); - result = _(array).chain().keyBy<{a: number}>({a: 42}); + result = _(array).chain().keyBy({a: 42}); result = _(list).chain().keyBy(); result = _(list).chain().keyBy(listIterator); result = _(list).chain().keyBy('a'); - result = _(list).chain().keyBy<{a: number}, SampleObject>({a: 42}); result = _(list).chain().keyBy({a: 42}); result = _(numericDictionary).chain().keyBy(); result = _(numericDictionary).chain().keyBy(numericDictionaryIterator); result = _(numericDictionary).chain().keyBy('a'); - result = _(numericDictionary).chain().keyBy<{a: number}, SampleObject>({a: 42}); result = _(numericDictionary).chain().keyBy({a: 42}); - result = _(dictionary).chain().keyBy(); - result = _(dictionary).chain().keyBy(dictionaryIterator); - result = _(dictionary).chain().keyBy('a'); - result = _(dictionary).chain().keyBy<{a: number}, SampleObject>({a: 42}); - result = _(dictionary).chain().keyBy({a: 42}); + result = _(dictionary).chain().keyBy(); + result = _(dictionary).chain().keyBy(dictionaryIterator); + result = _(dictionary).chain().keyBy('a'); + result = _(dictionary).chain().keyBy({a: 42}); } } @@ -5240,68 +5344,68 @@ namespace TestInvoke { let result: string; - result = _.invoke(boolArray, "[1]"); - result = _.invoke(boolArray, "[1]", 2); - result = _.invoke(boolArray, [1, "toString"]); - result = _.invoke(boolArray, [1, "toString"], 2); + result = _.invoke(boolArray, "[1]"); + result = _.invoke(boolArray, "[1]", 2); + result = _.invoke(boolArray, [1, "toString"]); + result = _.invoke(boolArray, [1, "toString"], 2); - result = _.invoke(boolArray, "[1]"); - result = _.invoke(boolArray, "[1]", 2); - result = _.invoke(boolArray, [1, "toString"]); - result = _.invoke(boolArray, [1, "toString"], 2); + result = _.invoke(boolArray, "[1]"); + result = _.invoke(boolArray, "[1]", 2); + result = _.invoke(boolArray, [1, "toString"]); + result = _.invoke(boolArray, [1, "toString"], 2); - result = _.invoke(numDict, "a.toString"); - result = _.invoke(numDict, "a.toString", 2); - result = _.invoke(numDict, ["a", "toString"]); - result = _.invoke(numDict, ["a", "toString"], 2); + result = _.invoke(numDict, "a.toString"); + result = _.invoke(numDict, "a.toString", 2); + result = _.invoke(numDict, ["a", "toString"]); + result = _.invoke(numDict, ["a", "toString"], 2); - result = _.invoke(numDict, "a.toString"); - result = _.invoke(numDict, "a.toString", 2); - result = _.invoke(numDict, ["a", "toString"]); - result = _.invoke(numDict, ["a", "toString"], 2); + result = _.invoke(numDict, "a.toString"); + result = _.invoke(numDict, "a.toString", 2); + result = _.invoke(numDict, ["a", "toString"]); + result = _.invoke(numDict, ["a", "toString"], 2); - result = _.invoke(nestedDict, ["a[0].toString"]); - result = _.invoke(nestedDict, ["a[0].toString"], 2); - result = _.invoke(nestedDict, ["a", 0, "toString"]); - result = _.invoke(nestedDict, ["a", 0, "toString"], 2); + result = _.invoke(nestedDict, ["a[0].toString"]); + result = _.invoke(nestedDict, ["a[0].toString"], 2); + result = _.invoke(nestedDict, ["a", 0, "toString"]); + result = _.invoke(nestedDict, ["a", 0, "toString"], 2); - result = _.invoke, string>(nestedDict, ["a[0].toString"]); - result = _.invoke, string>(nestedDict, ["a[0].toString"], 2); - result = _.invoke, string>(nestedDict, ["a", 0, "toString"]); - result = _.invoke, string>(nestedDict, ["a", 0, "toString"], 2); + result = _.invoke(nestedDict, ["a[0].toString"]); + result = _.invoke(nestedDict, ["a[0].toString"], 2); + result = _.invoke(nestedDict, ["a", 0, "toString"]); + result = _.invoke(nestedDict, ["a", 0, "toString"], 2); - result = _(boolArray).invoke("[1]"); - result = _(boolArray).invoke("[1]", 2); - result = _(boolArray).invoke([1, "toString"]); - result = _(boolArray).invoke([1, "toString"], 2); + result = _(boolArray).invoke("[1]"); + result = _(boolArray).invoke("[1]", 2); + result = _(boolArray).invoke([1, "toString"]); + result = _(boolArray).invoke([1, "toString"], 2); - result = _(numDict).invoke("a.toString"); - result = _(numDict).invoke("a.toString", 2); - result = _(numDict).invoke(["a", "toString"]); - result = _(numDict).invoke(["a", "toString"], 2); + result = _(numDict).invoke("a.toString"); + result = _(numDict).invoke("a.toString", 2); + result = _(numDict).invoke(["a", "toString"]); + result = _(numDict).invoke(["a", "toString"], 2); - result = _(nestedDict).invoke("a[0].toString"); - result = _(nestedDict).invoke("a[0].toString", 2); - result = _(nestedDict).invoke(["a", 0, "toString"]); - result = _(nestedDict).invoke(["a", 0, "toString"], 2); + result = _(nestedDict).invoke("a[0].toString"); + result = _(nestedDict).invoke("a[0].toString", 2); + result = _(nestedDict).invoke(["a", 0, "toString"]); + result = _(nestedDict).invoke(["a", 0, "toString"], 2); { let result: _.LoDashExplicitWrapper; - result = _(boolArray).chain().invoke<_.LoDashExplicitWrapper>("[1]"); - result = _(boolArray).chain().invoke<_.LoDashExplicitWrapper>("[1]", 2); - result = _(boolArray).chain().invoke<_.LoDashExplicitWrapper>([1, "toString"]); - result = _(boolArray).chain().invoke<_.LoDashExplicitWrapper>([1, "toString"], 2); + result = _(boolArray).chain().invoke("[1]"); + result = _(boolArray).chain().invoke("[1]", 2); + result = _(boolArray).chain().invoke([1, "toString"]); + result = _(boolArray).chain().invoke([1, "toString"], 2); - result = _(numDict).chain().invoke<_.LoDashExplicitWrapper>("a.toString"); - result = _(numDict).chain().invoke<_.LoDashExplicitWrapper>("a.toString", 2); - result = _(numDict).chain().invoke<_.LoDashExplicitWrapper>(["a", "toString"]); - result = _(numDict).chain().invoke<_.LoDashExplicitWrapper>(["a", "toString"], 2); + result = _(numDict).chain().invoke("a.toString"); + result = _(numDict).chain().invoke("a.toString", 2); + result = _(numDict).chain().invoke(["a", "toString"]); + result = _(numDict).chain().invoke(["a", "toString"], 2); - result = _(nestedDict).chain().invoke<_.LoDashExplicitWrapper>("a[0].toString"); - result = _(nestedDict).chain().invoke<_.LoDashExplicitWrapper>("a[0].toString", 2); - result = _(nestedDict).chain().invoke<_.LoDashExplicitWrapper>(["a", 0, "toString"]); - result = _(nestedDict).chain().invoke<_.LoDashExplicitWrapper>(["a", 0, "toString"], 2); + result = _(nestedDict).chain().invoke("a[0].toString"); + result = _(nestedDict).chain().invoke("a[0].toString", 2); + result = _(nestedDict).chain().invoke(["a", 0, "toString"]); + result = _(nestedDict).chain().invoke(["a", 0, "toString"], 2); } } @@ -5317,17 +5421,17 @@ namespace TestInvokeMap { let numDict: _.Dictionary | null | undefined = obj as any; let result: string[]; - result = _.invokeMap(numArray, 'toString'); - result = _.invokeMap(numArray, 'toString', 2); - result = _.invokeMap(numArray, 'toString'); - result = _.invokeMap(numArray, 'toString', 2); - result = _(numArray).invokeMap('toString').value(); - result = _(numArray).invokeMap('toString', 2).value(); - result = _(numArray).chain().invokeMap('toString').value(); - result = _(numArray).chain().invokeMap('toString', 2).value(); + result = _.invokeMap(numArray, 'toString'); + result = _.invokeMap(numArray, 'toString', 2); + result = _.invokeMap(numArray, 'toString'); + result = _.invokeMap(numArray, 'toString', 2); + result = _(numArray).invokeMap('toString').value(); + result = _(numArray).invokeMap('toString', 2).value(); + result = _(numArray).chain().invokeMap('toString').value(); + result = _(numArray).chain().invokeMap('toString', 2).value(); - result = _.invokeMap(numArray, Number.prototype.toString); - result = _.invokeMap(numArray, Number.prototype.toString, 2); + result = _.invokeMap(numArray, Number.prototype.toString); + result = _.invokeMap(numArray, Number.prototype.toString, 2); result = _.invokeMap(numArray, Number.prototype.toString); result = _.invokeMap(numArray, Number.prototype.toString, 2); result = _(numArray).invokeMap(Number.prototype.toString).value(); @@ -5335,17 +5439,17 @@ namespace TestInvokeMap { result = _(numArray).chain().invokeMap(Number.prototype.toString).value(); result = _(numArray).chain().invokeMap(Number.prototype.toString, 2).value(); - result = _.invokeMap(numDict, 'toString'); - result = _.invokeMap(numDict, 'toString', 2); - result = _.invokeMap(numDict, 'toString'); - result = _.invokeMap(numDict, 'toString', 2); - result = _(numDict).invokeMap('toString').value(); - result = _(numDict).invokeMap('toString', 2).value(); - result = _(numDict).chain().invokeMap('toString').value(); - result = _(numDict).chain().invokeMap('toString', 2).value(); + result = _.invokeMap(numDict, 'toString'); + result = _.invokeMap(numDict, 'toString', 2); + result = _.invokeMap(numDict, 'toString'); + result = _.invokeMap(numDict, 'toString', 2); + result = _(numDict).invokeMap('toString').value(); + result = _(numDict).invokeMap('toString', 2).value(); + result = _(numDict).chain().invokeMap('toString').value(); + result = _(numDict).chain().invokeMap('toString', 2).value(); - result = _.invokeMap(numDict, Number.prototype.toString); - result = _.invokeMap(numDict, Number.prototype.toString, 2); + result = _.invokeMap(numDict, Number.prototype.toString); + result = _.invokeMap(numDict, Number.prototype.toString, 2); result = _.invokeMap(numDict, Number.prototype.toString); result = _.invokeMap(numDict, Number.prototype.toString, 2); result = _(numDict).invokeMap(Number.prototype.toString).value(); @@ -5413,7 +5517,7 @@ namespace TestMap { { let result: _.LoDashExplicitArrayWrapper; - result = _(array).chain().map({}); + result = _(array).chain().map({}); result = _(list).chain().map({}); result = _(dictionary).chain().map({}); } @@ -5438,33 +5542,148 @@ namespace TestMap { } // _.partition -result = _.partition('abcd', (n) => n < 'c'); -result = _.partition(['a', 'b', 'c', 'd'], (n) => n < 'c'); -result = _.partition([1, 2, 3, 4], (n) => n < 3); -result = _.partition({0: 1, 1: 2, 2: 3, 3: 4, length: 4}, (n) => n < 3); -result = _.partition({a: 1, b: 2, c: 3, d: 4}, (n) => n < 3); -result = <{a: number}[][]>_.partition<{a: number}, {a: number}>([{a: 1}, {a: 2}], {a: 2}); -result = <{a: number}[][]>_.partition<{a: number}, {a: number}>({0: {a: 1}, 1: {a: 2}, length: 2}, {a: 2}); -result = <{a: number}[][]>_.partition<{a: number}, {a: number}>({0: {a: 1}, 1: {a: 2}}, {a: 2}); -result = <{a: number}[][]>_.partition<{a: number}>([{a: 1}, {a: 2}], 'a'); -result = <{a: number}[][]>_.partition<{a: number}>([{a: 1}, {a: 2}], 'a', 2); -result = <{a: number}[][]>_.partition<{a: number}>({0: {a: 1}, 1: {a: 2}, length: 2}, 'a'); -result = <{a: number}[][]>_.partition<{a: number}>({0: {a: 1}, 1: {a: 2}, length: 2}, 'a', 2); -result = <{a: number}[][]>_.partition<{a: number}>({0: {a: 1}, 1: {a: 2}}, 'a'); -result = <{a: number}[][]>_.partition<{a: number}>({0: {a: 1}, 1: {a: 2}}, 'a', 2); -result = <{a: number}[][]>_.partition<{a: number}>(null, 'a'); -result = _('abcd').partition((n) => n < 'c').value(); -result = _(['a', 'b', 'c', 'd']).partition((n) => n < 'c').value(); -result = _([1, 2, 3, 4]).partition((n) => n < 3).value(); -result = _({0: 1, 1: 2, 2: 3, 3: 4, length: 4}).partition((n) => n < 3).value(); -result = _({a: 1, b: 2, c: 3, d: 4}).partition((n) => n < 3).value(); -result = <{a: number}[][]>_([{a: 1}, {a: 2}]).partition<{a: number}>({a: 2}).value(); -result = <{a: number}[][]>_({0: {a: 1}, 1: {a: 2}, length: 2}).partition<{a: number}, {a: number}>({a: 2}).value(); -result = <{a: number}[][]>_({0: {a: 1}, 1: {a: 2}}).partition<{a: number}, {a: number}>({a: 2}).value(); -result = <{a: number}[][]>_([{a: 1}, {a: 2}]).partition('a').value(); -result = <{a: number}[][]>_([{a: 1}, {a: 2}]).partition('a', 2).value(); -result = <{a: number}[][]>_({0: {a: 1}, 1: {a: 2}}).partition<{a: number}>('a').value(); -result = <{a: number}[][]>_({0: {a: 1}, 1: {a: 2}}).partition<{a: number}>('a', 2).value(); +namespace TestPartition { + { + let result: any[][]; + + result = _.partition(any, (n) => { + n; // $ExpectType any + return n < 'c'; + }); + } + + { + let result: string[][]; + + result = _.partition('abcd', (n) => { + n; // $ExpectType string + return n < 'c'; + }); + result = _.partition(['a', 'b', 'c', 'd'], (n) => { + n; // $ExpectType string + return n < 'c'; + }); + } + + { + let result: number[][]; + + result = _.partition([1, 2, 3, 4], (n) => n < 3); + result = _.partition({0: 1, 1: 2, 2: 3, 3: 4, length: 4}, (n) => n < 3); + result = _.partition({a: 1, b: 2, c: 3, d: 4}, (n) => { + n; // $ExpectType number + return n < 3; + }); + } + + { + let result: Array>; + + result = _.partition([{a: 1}, {a: 2}], {a: 2}); + result = _.partition({0: {a: 1}, 1: {a: 2}, length: 2}, {a: 2}); + result = _.partition({0: {a: 1}, 1: {a: 2}}, {a: 2}); + result = _.partition([{a: 1}, {a: 2}], 'a'); + result = _.partition([{a: 1}, {a: 2}], ['a', 2]); + result = _.partition({0: {a: 1}, 1: {a: 2}, length: 2}, 'a'); + result = _.partition({0: {a: 1}, 1: {a: 2}, length: 2}, ['a', 2]); + result = _.partition({0: {a: 1}, 1: {a: 2}}, 'a'); + result = _.partition({0: {a: 1}, 1: {a: 2}}, ['a', 2]); + } + + { + _.partition(null, 'a'); + } + + { + let result: _.LoDashImplicitWrapper; + + result = _(any).partition((n) => { + n; // $ExpectType any + return n < 'c'; + }); + } + + { + let result: _.LoDashImplicitWrapper; + + result = _('abcd').partition((n) => { + n; // $ExpectType string + return n < 'c'; + }); + result = _(['a', 'b', 'c', 'd']).partition((n) => { + n; // $ExpectType string + return n < 'c'; + }); + } + + { + let result: _.LoDashImplicitWrapper; + + result = _([1, 2, 3, 4]).partition((n) => n < 3); + result = _({0: 1, 1: 2, 2: 3, 3: 4, length: 4}).partition((n) => n < 3); + result = _({a: 1, b: 2, c: 3, d: 4}).partition((n) => { + n; // $ExpectType number + return n < 3; + }); + } + + { + let result: _.LoDashImplicitWrapper>>; + + result = _([{a: 1}, {a: 2}]).partition({a: 2}); + result = _({0: {a: 1}, 1: {a: 2}, length: 2}).partition({a: 2}); + result = _({0: {a: 1}, 1: {a: 2}}).partition({a: 2}); + result = _([{a: 1}, {a: 2}]).partition('a'); + result = _([{a: 1}, {a: 2}]).partition(['a', 2]); + result = _({0: {a: 1}, 1: {a: 2}}).partition('a'); + result = _({0: {a: 1}, 1: {a: 2}}).partition(['a', 2]); + } + + { + let result: _.LoDashExplicitWrapper; + + result = _.chain(any).partition((n) => { + n; // $ExpectType any + return n < 'c'; + }); + } + + { + let result: _.LoDashExplicitWrapper; + + result = _.chain('abcd').partition((n) => { + n; // $ExpectType string + return n < 'c'; + }); + result = _.chain(['a', 'b', 'c', 'd']).partition((n) => { + n; // $ExpectType string + return n < 'c'; + }); + } + + { + let result: _.LoDashExplicitWrapper; + + result = _.chain([1, 2, 3, 4]).partition((n) => n < 3); + result = _.chain({0: 1, 1: 2, 2: 3, 3: 4, length: 4}).partition((n) => n < 3); + result = _.chain({a: 1, b: 2, c: 3, d: 4}).partition((n) => { + n; // $ExpectType number + return n < 3; + }); + } + + { + let result: _.LoDashExplicitWrapper>>; + + result = _.chain([{a: 1}, {a: 2}]).partition({a: 2}); + result = _.chain({0: {a: 1}, 1: {a: 2}, length: 2}).partition({a: 2}); + result = _.chain({0: {a: 1}, 1: {a: 2}}).partition({a: 2}); + result = _.chain([{a: 1}, {a: 2}]).partition('a'); + result = _.chain([{a: 1}, {a: 2}]).partition(['a', 2]); + result = _.chain({0: {a: 1}, 1: {a: 2}}).partition('a'); + result = _.chain({0: {a: 1}, 1: {a: 2}}).partition(['a', 2]); + } +} // TODO // _.map with iteratee shorthand @@ -5549,8 +5768,8 @@ namespace TestReduce { return r; }, {} as ABC); // tslint:disable-line no-object-literal-type-assertion - result = _([1, 2, 3]).reduce((sum: number, num: number) => sum + num); - result = _({ 'a': 1, 'b': 2, 'c': 3 }).reduce((r: ABC, num: number, key: string) => { + result = _([1, 2, 3]).reduce((sum: number, num: number) => sum + num); + result = _({ 'a': 1, 'b': 2, 'c': 3 }).reduce((r: ABC, num: number, key: string) => { r[key] = num * 3; return r; }, { a: 1, b: 2, c: 3 }); @@ -5579,15 +5798,15 @@ namespace TestReject { result = _.reject(array, listIterator); result = _.reject(array, ''); - result = _.reject<{a: number}, TResult>(array, {a: 42}); + result = _.reject(array, {a: 42}); result = _.reject(list, listIterator); result = _.reject(list, ''); - result = _.reject<{a: number}, TResult>(list, {a: 42}); + result = _.reject(list, {a: 42}); - result = _.reject(dictionary, dictionaryIterator); - result = _.reject(dictionary, ''); - result = _.reject<{a: number}, TResult>(dictionary, {a: 42}); + result = _.reject(dictionary, dictionaryIterator); + result = _.reject(dictionary, ''); + result = _.reject(dictionary, {a: 42}); } { @@ -5601,15 +5820,15 @@ namespace TestReject { result = _(array).reject(listIterator); result = _(array).reject(''); - result = _(array).reject<{a: number}>({a: 42}); + result = _(array).reject({a: 42}); result = _(list).reject(listIterator); result = _(list).reject(''); - result = _(list).reject<{a: number}, TResult>({a: 42}); + result = _(list).reject({a: 42}); - result = _(dictionary).reject(dictionaryIterator); - result = _(dictionary).reject(''); - result = _(dictionary).reject<{a: number}, TResult>({a: 42}); + result = _(dictionary).reject(dictionaryIterator); + result = _(dictionary).reject(''); + result = _(dictionary).reject({a: 42}); } { @@ -5623,15 +5842,15 @@ namespace TestReject { result = _(array).chain().reject(listIterator); result = _(array).chain().reject(''); - result = _(array).chain().reject<{a: number}>({a: 42}); + result = _(array).chain().reject({a: 42}); result = _(list).chain().reject(listIterator); result = _(list).chain().reject(''); - result = _(list).chain().reject<{a: number}, TResult>({a: 42}); + result = _(list).chain().reject({a: 42}); - result = _(dictionary).chain().reject(dictionaryIterator); - result = _(dictionary).chain().reject(''); - result = _(dictionary).chain().reject<{a: number}, TResult>({a: 42}); + result = _(dictionary).chain().reject(dictionaryIterator); + result = _(dictionary).chain().reject(''); + result = _(dictionary).chain().reject({a: 42}); } } @@ -5663,14 +5882,14 @@ namespace TestSample { } { - let result: _.LoDashExplicitWrapper; + let result: _.LoDashExplicitWrapper; result = _('abc').chain().sample(); - result = _(array).chain().sample<_.LoDashExplicitWrapper>(); - result = _(list).chain().sample<_.LoDashExplicitWrapper>(); - result = _(dictionary).chain().sample<_.LoDashExplicitWrapper>(); - result = _(numericDictionary).chain().sample<_.LoDashExplicitWrapper>(); - result = _({a: 'foo'}).chain().sample<_.LoDashExplicitWrapper>(); + result = _(array).chain().sample(); + result = _(list).chain().sample(); + result = _(dictionary).chain().sample(); + result = _(numericDictionary).chain().sample(); + result = _({a: 'foo'}).chain().sample(); } } @@ -5695,8 +5914,8 @@ namespace TestSampleSize { result = _.sampleSize(dictionary, 42); result = _.sampleSize(numericDictionary); result = _.sampleSize(numericDictionary, 42); - result = _.sampleSize<{a: string}, string>({a: 'foo'}); - result = _.sampleSize<{a: string}, string>({a: 'foo'}, 42); + result = _.sampleSize({a: 'foo'}); + result = _.sampleSize({a: 'foo'}, 42); result = _.sampleSize({a: 'foo'}); result = _.sampleSize({a: 'foo'}, 42); } @@ -5754,7 +5973,7 @@ namespace TestShuffle { result = _.shuffle(array); result = _.shuffle(list); - result = _.shuffle(dictionary); + result = _.shuffle(dictionary); } { @@ -5768,7 +5987,7 @@ namespace TestShuffle { result = _(array).shuffle(); result = _(list).shuffle(); - result = _(dictionary).shuffle(); + result = _(dictionary).shuffle(); } { @@ -5782,7 +6001,7 @@ namespace TestShuffle { result = _(array).chain().shuffle(); result = _(list).chain().shuffle(); - result = _(dictionary).chain().shuffle(); + result = _(dictionary).chain().shuffle(); } } @@ -5798,9 +6017,9 @@ namespace TestSize { { let result: number; - result = _.size(array); - result = _.size(list); - result = _.size(dictionary); + result = _.size(array); + result = _.size(list); + result = _.size(dictionary); result = _.size(''); result = _(array).size(); @@ -5852,10 +6071,10 @@ namespace TestSome { result = _.some(dictionary); result = _.some(numericDictionary, numericDictionaryIterator); - result = _.some(dictionary, (value, key, collection) => { - value.a--; - key.substr(0); - value = collection[key]; + result = _.some(dictionary, (value, key, collection) => { + value; // $ExpectType SampleObject + key; // $ExpectType string + collection; // $ExpectType Dictionary return true; }); result = _.some(dictionary, 'a'); @@ -5887,7 +6106,7 @@ namespace TestSome { result = _(list).some({a: 42}); result = _(dictionary).some(); - result = _(dictionary).some(dictionaryIterator); + result = _(dictionary).some(dictionaryIterator); result = _(dictionary).some('a'); result = _(dictionary).some(['a', 42]); result = _(dictionary).some({a: 42}); @@ -5921,7 +6140,7 @@ namespace TestSome { result = _(list).chain().some({a: 42}); result = _(dictionary).chain().some(); - result = _(dictionary).chain().some(dictionaryIterator); + result = _(dictionary).chain().some(dictionaryIterator); result = _(dictionary).chain().some('a'); result = _(dictionary).chain().some(['a', 42]); result = _(dictionary).chain().some({a: 42}); @@ -5953,58 +6172,58 @@ namespace TestSortBy { { let result: TResult[]; - result = _.sortBy(array); - result = _.sortBy(array, listIterator); - result = _.sortBy(array, ''); - result = _.sortBy<{a: number}, TResult>(array, {a: 42}); + result = _.sortBy(array); + result = _.sortBy(array, listIterator); + result = _.sortBy(array, ''); + result = _.sortBy(array, {a: 42}); - result = _.sortBy(list); - result = _.sortBy(list, listIterator); - result = _.sortBy(list, ''); - result = _.sortBy<{a: number}, TResult>(list, {a: 42}); + result = _.sortBy(list); + result = _.sortBy(list, listIterator); + result = _.sortBy(list, ''); + result = _.sortBy(list, {a: 42}); - result = _.sortBy(dictionary); - result = _.sortBy(dictionary, dictionaryIterator); - result = _.sortBy(dictionary, ''); - result = _.sortBy<{a: number}, TResult>(dictionary, {a: 42}); + result = _.sortBy(dictionary); + result = _.sortBy(dictionary, dictionaryIterator); + result = _.sortBy(dictionary, ''); + result = _.sortBy(dictionary, {a: 42}); } { let result: _.LoDashImplicitArrayWrapper; result = _(array).sortBy(); - result = _(array).sortBy(listIterator); + result = _(array).sortBy(listIterator); result = _(array).sortBy(''); - result = _(array).sortBy<{a: number}>({a: 42}); + result = _(array).sortBy({a: 42}); - result = _(list).sortBy(); - result = _(list).sortBy(listIterator); - result = _(list).sortBy(''); - result = _(list).sortBy<{a: number}, TResult>({a: 42}); + result = _(list).sortBy(); + result = _(list).sortBy(listIterator); + result = _(list).sortBy(''); + result = _(list).sortBy({a: 42}); - result = _(dictionary).sortBy(); - result = _(dictionary).sortBy(dictionaryIterator); - result = _(dictionary).sortBy(''); - result = _(dictionary).sortBy<{a: number}, TResult>({a: 42}); + result = _(dictionary).sortBy(); + result = _(dictionary).sortBy(dictionaryIterator); + result = _(dictionary).sortBy(''); + result = _(dictionary).sortBy({a: 42}); } { let result: _.LoDashExplicitArrayWrapper; result = _(array).chain().sortBy(); - result = _(array).chain().sortBy(listIterator); + result = _(array).chain().sortBy(listIterator); result = _(array).chain().sortBy(''); - result = _(array).chain().sortBy<{a: number}>({a: 42}); + result = _(array).chain().sortBy({a: 42}); - result = _(list).chain().sortBy(); - result = _(list).chain().sortBy(listIterator); - result = _(list).chain().sortBy(''); - result = _(list).chain().sortBy<{a: number}, TResult>({a: 42}); + result = _(list).chain().sortBy(); + result = _(list).chain().sortBy(listIterator); + result = _(list).chain().sortBy(''); + result = _(list).chain().sortBy({a: 42}); - result = _(dictionary).chain().sortBy(); - result = _(dictionary).chain().sortBy(dictionaryIterator); - result = _(dictionary).chain().sortBy(''); - result = _(dictionary).chain().sortBy<{a: number}, TResult>({a: 42}); + result = _(dictionary).chain().sortBy(); + result = _(dictionary).chain().sortBy(dictionaryIterator); + result = _(dictionary).chain().sortBy(''); + result = _(dictionary).chain().sortBy({a: 42}); } } @@ -6037,23 +6256,23 @@ namespace TestorderBy { let iteratees: (value: SampleObject) => any|string|{a: number}|((value: SampleObject) => any|string|{a: number})[] = (value) => 1; let result: SampleObject[]; - result = _.orderBy<{a: number}, SampleObject>(array, iteratees); - result = _.orderBy<{a: number}, SampleObject>(array, iteratees, orders); + result = _.orderBy(array, iteratees); + result = _.orderBy(array, iteratees, orders); result = _.orderBy(array, iteratees); result = _.orderBy(array, iteratees, orders); - result = _.orderBy<{a: number}, SampleObject>(list, iteratees); - result = _.orderBy<{a: number}, SampleObject>(list, iteratees, orders); + result = _.orderBy(list, iteratees); + result = _.orderBy(list, iteratees, orders); result = _.orderBy(list, iteratees); result = _.orderBy(list, iteratees, orders); - result = _.orderBy<{a: number}, SampleObject>(numericDictionary, iteratees); - result = _.orderBy<{a: number}, SampleObject>(numericDictionary, iteratees, orders); + result = _.orderBy(numericDictionary, iteratees); + result = _.orderBy(numericDictionary, iteratees, orders); result = _.orderBy(numericDictionary, iteratees); result = _.orderBy(numericDictionary, iteratees, orders); - result = _.orderBy<{a: number}, SampleObject>(dictionary, iteratees); - result = _.orderBy<{a: number}, SampleObject>(dictionary, iteratees, orders); + result = _.orderBy(dictionary, iteratees); + result = _.orderBy(dictionary, iteratees, orders); result = _.orderBy(dictionary, iteratees); result = _.orderBy(dictionary, iteratees, orders); } @@ -6062,21 +6281,21 @@ namespace TestorderBy { let iteratees: (value: SampleObject) => any|string|{a: number}|((value: SampleObject) => any|string|{a: number})[] = (value) => ""; let result: _.LoDashImplicitArrayWrapper; - result = _(array).orderBy<{a: number}>(iteratees); - result = _(array).orderBy<{a: number}>(iteratees, orders); + result = _(array).orderBy(iteratees); + result = _(array).orderBy(iteratees, orders); - result = _(list).orderBy<{a: number}, SampleObject>(iteratees); - result = _(list).orderBy<{a: number}, SampleObject>(iteratees, orders); + result = _(list).orderBy(iteratees); + result = _(list).orderBy(iteratees, orders); result = _(list).orderBy(iteratees); result = _(list).orderBy(iteratees, orders); - result = _(numericDictionary).orderBy<{a: number}, SampleObject>(iteratees); - result = _(numericDictionary).orderBy<{a: number}, SampleObject>(iteratees, orders); + result = _(numericDictionary).orderBy(iteratees); + result = _(numericDictionary).orderBy(iteratees, orders); result = _(numericDictionary).orderBy(iteratees); result = _(numericDictionary).orderBy(iteratees, orders); - result = _(dictionary).orderBy<{a: number}, SampleObject>(iteratees); - result = _(dictionary).orderBy<{a: number}, SampleObject>(iteratees, orders); + result = _(dictionary).orderBy(iteratees); + result = _(dictionary).orderBy(iteratees, orders); result = _(dictionary).orderBy(iteratees); result = _(dictionary).orderBy(iteratees, orders); } @@ -6085,21 +6304,21 @@ namespace TestorderBy { let iteratees: (value: SampleObject) => any|string|{a: number}|((value: SampleObject) => any|string|{a: number})[] = (value) => ""; let result: _.LoDashExplicitArrayWrapper; - result = _(array).chain().orderBy<{a: number}>(iteratees); - result = _(array).chain().orderBy<{a: number}>(iteratees, orders); + result = _(array).chain().orderBy(iteratees); + result = _(array).chain().orderBy(iteratees, orders); - result = _(list).chain().orderBy<{a: number}, SampleObject>(iteratees); - result = _(list).chain().orderBy<{a: number}, SampleObject>(iteratees, orders); + result = _(list).chain().orderBy(iteratees); + result = _(list).chain().orderBy(iteratees, orders); result = _(list).chain().orderBy(iteratees); result = _(list).chain().orderBy(iteratees, orders); - result = _(numericDictionary).chain().orderBy<{a: number}, SampleObject>(iteratees); - result = _(numericDictionary).chain().orderBy<{a: number}, SampleObject>(iteratees, orders); + result = _(numericDictionary).chain().orderBy(iteratees); + result = _(numericDictionary).chain().orderBy(iteratees, orders); result = _(numericDictionary).chain().orderBy(iteratees); result = _(numericDictionary).chain().orderBy(iteratees, orders); - result = _(dictionary).chain().orderBy<{a: number}, SampleObject>(iteratees); - result = _(dictionary).chain().orderBy<{a: number}, SampleObject>(iteratees, orders); + result = _(dictionary).chain().orderBy(iteratees); + result = _(dictionary).chain().orderBy(iteratees, orders); result = _(dictionary).chain().orderBy(iteratees); result = _(dictionary).chain().orderBy(iteratees, orders); } @@ -6167,24 +6386,24 @@ namespace TestAry { { let result: SampleFunc; - result = _.ary(func); - result = _.ary(func, 2); - result = _.ary(func); - result = _.ary(func, 2); + result = _.ary(func); + result = _.ary(func, 2); + result = _.ary(func); + result = _.ary(func, 2); } { let result: _.LoDashImplicitObjectWrapper; - result = _(func).ary(); - result = _(func).ary(2); + result = _(func).ary(); + result = _(func).ary(2); } { let result: _.LoDashExplicitObjectWrapper; - result = _(func).chain().ary(); - result = _(func).chain().ary(2); + result = _(func).chain().ary(); + result = _(func).chain().ary(2); } } @@ -6226,8 +6445,8 @@ namespace TestBind { let result: SampleResult; - result = _.bind(func, any); - result = _.bind(func, any); + result = _.bind(func, any); + result = _.bind(func, any); } { @@ -6235,8 +6454,8 @@ namespace TestBind { let result: SampleResult; - result = _.bind(func, any, 42); - result = _.bind(func, any, 42); + result = _.bind(func, any, 42); + result = _.bind(func, any, 42); } { @@ -6244,8 +6463,8 @@ namespace TestBind { let result: SampleResult; - result = _.bind(func, any, 42, ''); - result = _.bind(func, any, 42, ''); + result = _.bind(func, any, 42, ''); + result = _.bind(func, any, 42, ''); } { @@ -6253,7 +6472,7 @@ namespace TestBind { let result: _.LoDashImplicitObjectWrapper; - result = _(func).bind(any); + result = _(func).bind(any); } { @@ -6261,7 +6480,7 @@ namespace TestBind { let result: _.LoDashImplicitObjectWrapper; - result = _(func).bind(any, 42); + result = _(func).bind(any, 42); } { @@ -6269,7 +6488,7 @@ namespace TestBind { let result: _.LoDashImplicitObjectWrapper; - result = _(func).bind(any, 42, ''); + result = _(func).bind(any, 42, ''); } { @@ -6277,23 +6496,23 @@ namespace TestBind { let result: _.LoDashExplicitObjectWrapper; - result = _(func).chain().bind(any); + result = _(func).chain().bind(any); } { type SampleResult = (b: string) => boolean; - let result: _.LoDashExplicitObjectWrapper; + let result: _.LoDashExplicitWrapper; - result = _(func).chain().bind(any, 42); + result = _(func).chain().bind(any, 42); } { type SampleResult = () => boolean; - let result: _.LoDashExplicitObjectWrapper; + let result: _.LoDashExplicitWrapper; - result = _(func).chain().bind(any, 42, ''); + result = _(func).chain().bind(any, 42, ''); } } @@ -6346,8 +6565,7 @@ namespace TestBindKey { let result: SampleResult; - result = _.bindKey(object, 'foo'); - result = _.bindKey(object, 'foo'); + result = _.bindKey(object, 'foo'); } { @@ -6355,8 +6573,7 @@ namespace TestBindKey { let result: SampleResult; - result = _.bindKey(object, 'foo', 42); - result = _.bindKey(object, 'foo', 42); + result = _.bindKey(object, 'foo', 42); } { @@ -6364,8 +6581,7 @@ namespace TestBindKey { let result: SampleResult; - result = _.bindKey(object, 'foo', 42, ''); - result = _.bindKey(object, 'foo', 42, ''); + result = _.bindKey(object, 'foo', 42, ''); } { @@ -6373,7 +6589,7 @@ namespace TestBindKey { let result: _.LoDashImplicitObjectWrapper; - result = _(object).bindKey('foo'); + result = _(object).bindKey('foo'); } { @@ -6381,7 +6597,7 @@ namespace TestBindKey { let result: _.LoDashImplicitObjectWrapper; - result = _(object).bindKey('foo', 42); + result = _(object).bindKey('foo', 42); } { @@ -6389,7 +6605,7 @@ namespace TestBindKey { let result: _.LoDashImplicitObjectWrapper; - result = _(object).bindKey('foo', 42, ''); + result = _(object).bindKey('foo', 42, ''); } { @@ -6397,7 +6613,7 @@ namespace TestBindKey { let result: _.LoDashExplicitObjectWrapper; - result = _(object).chain().bindKey('foo'); + result = _(object).chain().bindKey('foo'); } { @@ -6405,7 +6621,7 @@ namespace TestBindKey { let result: _.LoDashExplicitObjectWrapper; - result = _(object).chain().bindKey('foo', 42); + result = _(object).chain().bindKey('foo', 42); } { @@ -6413,16 +6629,10 @@ namespace TestBindKey { let result: _.LoDashExplicitObjectWrapper; - result = _(object).chain().bindKey('foo', 42, ''); + result = _(object).chain().bindKey('foo', 42, ''); } } -const createCallbackObj: { [index: string]: string; } = { name: 'Joe' }; -result = <() => any>_.createCallback('name'); -result = <() => boolean>_.createCallback(createCallbackObj); -result = <_.LoDashImplicitObjectWrapper<() => any>>_('name').createCallback(); -result = <_.LoDashImplicitObjectWrapper<() => boolean>>_(createCallbackObj).createCallback(); - // _.curry const testCurryFn = (a: number, b: number, c: number) => [a, b, c]; let curryResult0: number[] @@ -6527,10 +6737,10 @@ namespace TestDefer { { let result: number; - result = _.defer(func); - result = _.defer(func, any); - result = _.defer(func, any, any); - result = _.defer(func, any, any, any); + result = _.defer(func); + result = _.defer(func, any); + result = _.defer(func, any, any); + result = _.defer(func, any, any, any); } { @@ -6561,9 +6771,9 @@ namespace TestDelay { { let result: number; - result = _.delay(func, 1); - result = _.delay(func, 1, 2); - result = _.delay(func, 1, 2, ''); + result = _.delay(func, 1); + result = _.delay(func, 1, 2); + result = _.delay(func, 1, 2, ''); } { @@ -6628,34 +6838,34 @@ namespace TestFlow { result = _.flow(Fn2, Fn1, Fn1, Fn1, Fn1, Fn1); result = _.flow(Fn2, Fn1, Fn1, Fn1, Fn1, Fn1, Fn1); result = _.flow(Fn2, Fn1, Fn3, Fn4); - result = _.flow<(m: number, n: number) => number>([Fn2, Fn1, Fn3, Fn4]); + result = _.flow([Fn2, Fn1, Fn3, Fn4]); } { let result: (m: number, n: number) => number; - result = _.flow<(m: number, n: number) => number>(Fn1, Fn2); - result = _.flow<(m: number, n: number) => number>(Fn1, Fn1, Fn2); - result = _.flow<(m: number, n: number) => number>(Fn1, Fn1, Fn1, Fn2); - result = _.flow<(m: number, n: number) => number>([Fn1, Fn1, Fn1, Fn2]); + result = _.flow(Fn1, Fn2); + result = _.flow(Fn1, Fn1, Fn2); + result = _.flow(Fn1, Fn1, Fn1, Fn2); + result = _.flow([Fn1, Fn1, Fn1, Fn2]); } { let result: _.LoDashImplicitObjectWrapper<(m: number, n: number) => number>; - result = _(Fn1).flow<(m: number, n: number) => number>(Fn2); - result = _(Fn1).flow<(m: number, n: number) => number>(Fn1, Fn2); - result = _(Fn1).flow<(m: number, n: number) => number>(Fn1, Fn1, Fn2); - result = _(Fn1).flow<(m: number, n: number) => number>([Fn1, Fn1, Fn2]); + result = _(Fn1).flow(Fn2); + result = _(Fn1).flow(Fn1, Fn2); + result = _(Fn1).flow(Fn1, Fn1, Fn2); + result = _(Fn1).flow([Fn1, Fn1, Fn2]); } { let result: _.LoDashExplicitObjectWrapper<(m: number, n: number) => number>; - result = _(Fn1).chain().flow<(m: number, n: number) => number>(Fn2); - result = _(Fn1).chain().flow<(m: number, n: number) => number>(Fn1, Fn2); - result = _(Fn1).chain().flow<(m: number, n: number) => number>(Fn1, Fn1, Fn2); - result = _(Fn1).chain().flow<(m: number, n: number) => number>([Fn1, Fn1, Fn2]); + result = _(Fn1).chain().flow(Fn2); + result = _(Fn1).chain().flow(Fn1, Fn2); + result = _(Fn1).chain().flow(Fn1, Fn1, Fn2); + result = _(Fn1).chain().flow([Fn1, Fn1, Fn2]); } } @@ -6667,28 +6877,28 @@ namespace TestFlowRight { { let result: (m: number, n: number) => number; - result = _.flowRight<(m: number, n: number) => number>(Fn1, Fn2); - result = _.flowRight<(m: number, n: number) => number>(Fn1, Fn1, Fn2); - result = _.flowRight<(m: number, n: number) => number>(Fn1, Fn1, Fn1, Fn2); - result = _.flowRight<(m: number, n: number) => number>([Fn1, Fn1, Fn1, Fn2]); + result = _.flowRight(Fn1, Fn2); + result = _.flowRight(Fn1, Fn1, Fn2); + result = _.flowRight(Fn1, Fn1, Fn1, Fn2); + result = _.flowRight([Fn1, Fn1, Fn1, Fn2]); } { let result: _.LoDashImplicitObjectWrapper<(m: number, n: number) => number>; - result = _(Fn1).flowRight<(m: number, n: number) => number>(Fn2); - result = _(Fn1).flowRight<(m: number, n: number) => number>(Fn1, Fn2); - result = _(Fn1).flowRight<(m: number, n: number) => number>(Fn1, Fn1, Fn2); - result = _(Fn1).flowRight<(m: number, n: number) => number>([Fn1, Fn1, Fn2]); + result = _(Fn1).flowRight(Fn2); + result = _(Fn1).flowRight(Fn1, Fn2); + result = _(Fn1).flowRight(Fn1, Fn1, Fn2); + result = _(Fn1).flowRight([Fn1, Fn1, Fn2]); } { let result: _.LoDashExplicitObjectWrapper<(m: number, n: number) => number>; - result = _(Fn1).chain().flowRight<(m: number, n: number) => number>(Fn2); - result = _(Fn1).chain().flowRight<(m: number, n: number) => number>(Fn1, Fn2); - result = _(Fn1).chain().flowRight<(m: number, n: number) => number>(Fn1, Fn1, Fn2); - result = _(Fn1).chain().flowRight<(m: number, n: number) => number>([Fn1, Fn1, Fn2]); + result = _(Fn1).chain().flowRight(Fn2); + result = _(Fn1).chain().flowRight(Fn1, Fn2); + result = _(Fn1).chain().flowRight(Fn1, Fn1, Fn2); + result = _(Fn1).chain().flowRight([Fn1, Fn1, Fn2]); } } @@ -6763,43 +6973,43 @@ namespace TestOverArgs { { let result: (a: string) => boolean; - result = _.overArgs boolean>(func1, transform1); - result = _.overArgs boolean>(func1, [transform1]); + result = _.overArgs(func1, transform1); + result = _.overArgs(func1, [transform1]); } { let result: (a: string, b: number) => boolean; - result = _.overArgs boolean>(func2, transform1, transform2); - result = _.overArgs boolean>(func2, [transform1, transform2]); + result = _.overArgs(func2, transform1, transform2); + result = _.overArgs(func2, [transform1, transform2]); } { let result: _.LoDashImplicitObjectWrapper<(a: string) => boolean>; - result = _(func1).overArgs<(a: string) => boolean>(transform1); - result = _(func1).overArgs<(a: string) => boolean>([transform1]); + result = _(func1).overArgs(transform1); + result = _(func1).overArgs([transform1]); } { let result: _.LoDashImplicitObjectWrapper<(a: string, b: number) => boolean>; - result = _(func2).overArgs<(a: string, b: number) => boolean>(transform1, transform2); - result = _(func2).overArgs<(a: string, b: number) => boolean>([transform1, transform2]); + result = _(func2).overArgs(transform1, transform2); + result = _(func2).overArgs([transform1, transform2]); } { let result: _.LoDashExplicitObjectWrapper<(a: string) => boolean>; - result = _(func1).chain().overArgs<(a: string) => boolean>(transform1); - result = _(func1).chain().overArgs<(a: string) => boolean>([transform1]); + result = _(func1).chain().overArgs(transform1); + result = _(func1).chain().overArgs([transform1]); } { let result: _.LoDashExplicitObjectWrapper<(a: string, b: number) => boolean>; - result = _(func2).chain().overArgs<(a: string, b: number) => boolean>(transform1, transform2); - result = _(func2).chain().overArgs<(a: string, b: number) => boolean>([transform1, transform2]); + result = _(func2).chain().overArgs(transform1, transform2); + result = _(func2).chain().overArgs([transform1, transform2]); } } @@ -6819,21 +7029,18 @@ namespace TestNegate { let result: ResultFn; result = _.negate(predicate); - result = _.negate(predicate); } { let result: _.LoDashImplicitObjectWrapper; result = _(predicate).negate(); - result = _(predicate).negate(); } { let result: _.LoDashExplicitObjectWrapper; result = _(predicate).chain().negate(); - result = _(predicate).chain().negate(); } } @@ -6882,10 +7089,10 @@ const testReargFn = (a: string, b: string, c: string) => [a, b, c]; interface TestReargResultFn { (b: string, c: string, a: string): string[]; } -result = (_.rearg(testReargFn, 2, 0, 1))('b', 'c', 'a'); -result = (_.rearg(testReargFn, [2, 0, 1]))('b', 'c', 'a'); -result = (_(testReargFn).rearg(2, 0, 1).value())('b', 'c', 'a'); -result = (_(testReargFn).rearg([2, 0, 1]).value())('b', 'c', 'a'); +result = (_.rearg(testReargFn, 2, 0, 1))('b', 'c', 'a'); +result = (_.rearg(testReargFn, [2, 0, 1]))('b', 'c', 'a'); +result = (_(testReargFn).rearg(2, 0, 1).value())('b', 'c', 'a'); +result = (_(testReargFn).rearg([2, 0, 1]).value())('b', 'c', 'a'); // _.rest namespace TestRest { @@ -6897,25 +7104,22 @@ namespace TestRest { { let result: ResultFunc; - result = _.rest(func); - result = _.rest(func, 1); - - result = _.rest(func); - result = _.rest(func, 1); + result = _.rest(func); + result = _.rest(func, 1); } { let result: _.LoDashImplicitObjectWrapper; - result = _(func).rest(); - result = _(func).rest(1); + result = _(func).rest(); + result = _(func).rest(1); } { let result: _.LoDashExplicitObjectWrapper; - result = _(func).chain().rest(); - result = _(func).chain().rest(1); + result = _(func).chain().rest(); + result = _(func).chain().rest(1); } } @@ -6929,20 +7133,19 @@ namespace TestSpread { { let result: SampleResult; - result = _.spread(func); - result = _.spread(func); + result = _.spread(func); } { let result: _.LoDashImplicitObjectWrapper; - result = _(func).spread(); + result = _(func).spread(); } { let result: _.LoDashExplicitObjectWrapper; - result = _(func).chain().spread(); + result = _(func).chain().spread(); } } @@ -7030,9 +7233,7 @@ namespace TestWrap { let wrapper: SampleWrapper = (a, b, c) => true; let result: SampleResult; - result = _.wrap(value, wrapper); - result = _.wrap(value, wrapper); - result = _.wrap(value, wrapper); + result = _.wrap(value, wrapper); } { @@ -7042,8 +7243,7 @@ namespace TestWrap { let wrapper: SampleWrapper = (a, b, c) => true; let result: _.LoDashImplicitObjectWrapper; - result = _(value).wrap(wrapper); - result = _(value).wrap(wrapper); + result = _(value).wrap(wrapper); } { @@ -7053,8 +7253,7 @@ namespace TestWrap { let wrapper: SampleWrapper = (a, b, c) => true; let result: _.LoDashImplicitObjectWrapper; - result = _(value).wrap(wrapper); - result = _(value).wrap(wrapper); + result = _(value).wrap(wrapper); } { @@ -7064,8 +7263,7 @@ namespace TestWrap { let wrapper: SampleWrapper = (a, b, c) => true; let result: _.LoDashImplicitObjectWrapper; - result = _(value).wrap(wrapper); - result = _(value).wrap(wrapper); + result = _(value).wrap(wrapper); } { @@ -7075,8 +7273,7 @@ namespace TestWrap { let wrapper: SampleWrapper = (a, b, c) => true; let result: _.LoDashExplicitObjectWrapper; - result = _(value).chain().wrap(wrapper); - result = _(value).chain().wrap(wrapper); + result = _(value).chain().wrap(wrapper); } { @@ -7086,8 +7283,7 @@ namespace TestWrap { let wrapper: SampleWrapper = (a, b, c) => true; let result: _.LoDashExplicitObjectWrapper; - result = _(value).chain().wrap(wrapper); - result = _(value).chain().wrap(wrapper); + result = _(value).chain().wrap(wrapper); } { @@ -7097,8 +7293,7 @@ namespace TestWrap { let wrapper: SampleWrapper = (a, b, c) => true; let result: _.LoDashExplicitObjectWrapper; - result = _(value).chain().wrap(wrapper); - result = _(value).chain().wrap(wrapper); + result = _(value).chain().wrap(wrapper); } } @@ -7160,7 +7355,7 @@ namespace TestClone { let result: string[]; result = _.clone(['']); - result = _(['']).clone(); + result = _(['']).clone(); } { @@ -7202,7 +7397,7 @@ namespace TestCloneDeep { let result: string[]; result = _.cloneDeep(['']); - result = _(['']).cloneDeep(); + result = _(['']).cloneDeep(); } { @@ -7235,48 +7430,45 @@ namespace TestCloneDeepWith { let customizer: CloneDeepWithCustomizer = (x) => ""; let reslut: string; - result = _.cloneDeepWith(42, customizer); - result = _.cloneDeepWith(42, customizer); - result = _(42).cloneDeepWith(customizer); + result = _.cloneDeepWith(42, customizer); + result = _(42).cloneDeepWith(customizer); } { let customizer: CloneDeepWithCustomizer = (x) => ""; let result: _.LoDashExplicitWrapper; - result = _(42).chain().cloneDeepWith(customizer); + result = _(42).chain().cloneDeepWith(customizer); } { let customizer: CloneDeepWithCustomizer = (x) => []; let reslut: string[]; - result = _.cloneDeepWith([42], customizer); - result = _.cloneDeepWith([42], customizer); - result = _([42]).cloneDeepWith(customizer); + result = _.cloneDeepWith([42], customizer); + result = _([42]).cloneDeepWith(customizer); } { let customizer: CloneDeepWithCustomizer = (x) => []; let result: _.LoDashExplicitArrayWrapper; - result = _([42]).chain().cloneDeepWith(customizer); + result = _([42]).chain().cloneDeepWith(customizer); } { let customizer: CloneDeepWithCustomizer<{a: {b: number;};}, {a: {b: string;};}> = (x) => ({ a: { b: "" } }); let reslut: {a: {b: string;};}; - result = _.cloneDeepWith<{a: {b: string;};}>({a: {b: 42}}, customizer); - result = _.cloneDeepWith<{a: {b: number;};}, {a: {b: string;};}>({a: {b: 42}}, customizer); - result = _({a: {b: 42}}).cloneDeepWith<{a: {b: string;};}>(customizer); + result = _.cloneDeepWith({a: {b: 42}}, customizer); + result = _({a: {b: 42}}).cloneDeepWith(customizer); } { let customizer: CloneDeepWithCustomizer<{a: {b: number;};}, {a: {b: string;};}> = (x) => ({ a: { b: "" } }); let result: _.LoDashExplicitObjectWrapper<{a: {b: string;};}>; - result = _({a: {b: 42}}).chain().cloneDeepWith<{a: {b: string;};}>(customizer); + result = _({a: {b: 42}}).chain().cloneDeepWith(customizer); } } @@ -7290,7 +7482,7 @@ namespace TestCloneWith { let customizer: CloneWithCustomizer = (x) => ""; let reslut: string; - result = _.cloneWith(42, customizer); + result = _.cloneWith(42, customizer); result = _.cloneWith(42, customizer); result = _(42).cloneWith(customizer); } @@ -7306,7 +7498,7 @@ namespace TestCloneWith { let customizer: CloneWithCustomizer = (x) => []; let reslut: string[]; - result = _.cloneWith([42], customizer); + result = _.cloneWith([42], customizer); result = _.cloneWith([42], customizer); result = _([42]).cloneWith(customizer); } @@ -7315,14 +7507,14 @@ namespace TestCloneWith { let customizer: CloneWithCustomizer = (x) => []; let result: _.LoDashExplicitArrayWrapper; - result = _([42]).chain().cloneWith(customizer); + result = _([42]).chain().cloneWith(customizer); } { let customizer: CloneWithCustomizer<{a: {b: number;};}, {a: {b: string;};}> = (x) => ({ a: { b: "" } }); let reslut: {a: {b: string;};}; - result = _.cloneWith<{a: {b: string;};}>({a: {b: 42}}, customizer); + result = _.cloneWith({a: {b: 42}}, customizer); result = _.cloneWith<{a: {b: number;};}, {a: {b: string;};}>({a: {b: 42}}, customizer); result = _({a: {b: 42}}).cloneWith<{a: {b: string;};}>(customizer); } @@ -7503,14 +7695,13 @@ namespace TestIsArrayBuffer { namespace TestIsArrayLike { { let value: string | string[] | { [index: number]: boolean, length: number } | [number, boolean] - | number | Function | { length: string } | { a: string } + | number | { length: string } | { a: string } | null | undefined = any; if (_.isArrayLike(value)) { let result: string | string[] | { [index: number]: boolean, length: number } | [number, boolean] = value; - } - else { - let result: number | Function | { length: string } | { a: string; } = value; + } else { + let result: number | { length: string } | { a: string; } | null | undefined = value; } } @@ -7530,8 +7721,7 @@ namespace TestIsArrayLike { if (_.isArrayLike(value)) { value; // $ExpectType never - } - else { + } else { value; // $ExpectType Function } } @@ -7580,14 +7770,13 @@ namespace TestIsArrayLike { namespace TestIsArrayLikeObject { { let value: string[] | { [index: number]: boolean, length: number } | [number, boolean] - | number | string | Function | { length: string } | { a: string } + | number | string | { length: string } | { a: string } | null | undefined = any; if (_.isArrayLikeObject(value)) { let result: string[] | { [index: number]: boolean, length: number } | [number, boolean] = value; - } - else { - let result: string | number | Function | { length: string; } | { a: string; } = value; + } else { + let result: string | number | { length: string; } | { a: string; } | null | undefined = value; } } @@ -7607,8 +7796,7 @@ namespace TestIsArrayLikeObject { if (_.isArrayLikeObject(value)) { value; // $ExpectType never - } - else { + } else { value; // $ExpectType string | Function } } @@ -7963,7 +8151,7 @@ namespace TestIsMap { { let value: number|Map = 0; - if (_.isMap(value)) { + if (_.isMap(value)) { let result: Map = value; } else { @@ -8253,7 +8441,7 @@ namespace TestIsSet { { let value: number|Set = 0; - if (_.isSet(value)) { + if (_.isSet(value)) { let result: Set = value; } else { @@ -8375,7 +8563,7 @@ namespace TestIsWeakMap { let value: number|WeakMap = 0; - if (_.isWeakMap(value)) { + if (_.isWeakMap(value)) { let result: WeakMap = value; } else { @@ -8531,23 +8719,23 @@ namespace TestToArray { namespace TestToPlainObject { { let result: TResult; - result = _.toPlainObject(); - result = _.toPlainObject(true); - result = _.toPlainObject(1); - result = _.toPlainObject('a'); - result = _.toPlainObject([]); - result = _.toPlainObject({}); + result = _.toPlainObject(); + result = _.toPlainObject(true); + result = _.toPlainObject(1); + result = _.toPlainObject('a'); + result = _.toPlainObject([]); + result = _.toPlainObject({}); } { let result: _.LoDashImplicitObjectWrapper; - result = _(true).toPlainObject(); - result = _(1).toPlainObject(); - result = _('a').toPlainObject(); - result = _([1]).toPlainObject(); - result = _([]).toPlainObject(); - result = _({}).toPlainObject(); + result = _(true).toPlainObject(); + result = _(1).toPlainObject(); + result = _('a').toPlainObject(); + result = _([1]).toPlainObject(); + result = _(['']).toPlainObject(); + result = _({}).toPlainObject(); } } @@ -8563,13 +8751,13 @@ namespace TestToFinite { } { - let result: _.LoDashImplicitWrapper; + let result: number; result = _(true).toFinite(); result = _(1).toFinite(); result = _('3.2').toFinite(); result = _([1]).toFinite(); - result = _([]).toFinite(); + result = _([]).toFinite(); result = _({}).toFinite(); } } @@ -8586,13 +8774,13 @@ namespace TestToInteger { } { - let result: _.LoDashImplicitWrapper; + let result: number; result = _(true).toInteger(); result = _(1).toInteger(); result = _('a').toInteger(); result = _([1]).toInteger(); - result = _([]).toInteger(); + result = _(['']).toInteger(); result = _({}).toInteger(); } } @@ -8609,13 +8797,13 @@ namespace TestToLength { } { - let result: _.LoDashImplicitWrapper; + let result: number; result = _(true).toLength(); result = _(1).toLength(); result = _('a').toLength(); result = _([1]).toLength(); - result = _([]).toLength(); + result = _(['']).toLength(); result = _({}).toLength(); } } @@ -8632,13 +8820,13 @@ namespace TestToNumber { } { - let result: _.LoDashImplicitWrapper; + let result: number; result = _(true).toNumber(); result = _(1).toNumber(); result = _('a').toNumber(); result = _([1]).toNumber(); - result = _([]).toNumber(); + result = _(['']).toNumber(); result = _({}).toNumber(); } } @@ -8655,13 +8843,13 @@ namespace TestToSafeInteger { } { - let result: _.LoDashImplicitWrapper; + let result: number; result = _(true).toSafeInteger(); result = _(1).toSafeInteger(); result = _('a').toSafeInteger(); result = _([1]).toSafeInteger(); - result = _([]).toSafeInteger(); + result = _(['']).toSafeInteger(); result = _({}).toSafeInteger(); } } @@ -8764,42 +8952,33 @@ namespace TestMax { namespace TestMaxBy { let array: number[] = []; let list: _.List = []; - let dictionary: _.Dictionary = {}; + let array2: TResult[] = []; + let list2: _.List = []; let listIterator = (value: number, index: number, collection: _.List) => 0; - let dictionaryIterator = (value: number, key: string, collection: _.Dictionary) => 0; let result: number | undefined; + let result2: TResult | undefined; result = _.maxBy(array); result = _.maxBy(array, listIterator); result = _.maxBy(array, ''); - result = _.maxBy<{a: number}, number>(array, {a: 42}); + result2 = _.maxBy(array2, {a: 42}); result = _.maxBy(list); result = _.maxBy(list, listIterator); result = _.maxBy(list, ''); - result = _.maxBy<{a: number}, number>(list, {a: 42}); - - result = _.maxBy(dictionary); - result = _.maxBy(dictionary, dictionaryIterator); - result = _.maxBy(dictionary, ''); - result = _.maxBy<{a: number}, number>(dictionary, {a: 42}); + result2 = _.maxBy(list2, {a: 42}); result = _(array).maxBy(); result = _(array).maxBy(listIterator); result = _(array).maxBy(''); - result = _(array).maxBy<{a: number}>({a: 42}); + result2 = _(array2).maxBy({a: 42}); result = _(list).maxBy(); result = _(list).maxBy(listIterator); result = _(list).maxBy(''); - result = _(list).maxBy<{a: number}, number>({a: 42}); - - result = _(dictionary).maxBy(); - result = _(dictionary).maxBy(dictionaryIterator); - result = _(dictionary).maxBy(''); - result = _(dictionary).maxBy<{a: number}, number>({a: 42}); + result2 = _(list2).maxBy({a: 42}); } // _.mean @@ -8809,7 +8988,6 @@ namespace TestMean { let result: number; result = _.mean(array); - result = _.mean(array); result = _(array).mean(); } @@ -8844,42 +9022,33 @@ namespace TestMin { namespace TestMinBy { let array: number[] = []; let list: _.List = []; - let dictionary: _.Dictionary = {}; + let array2: TResult[] = []; + let list2: _.List = []; let listIterator = (value: number, index: number, collection: _.List) => 0; - let dictionaryIterator = (value: number, key: string, collection: _.Dictionary) => 0; let result: number | undefined; + let result2: TResult | undefined; result = _.minBy(array); result = _.minBy(array, listIterator); result = _.minBy(array, ''); - result = _.minBy<{a: number}, number>(array, {a: 42}); + result2 = _.minBy(array2, {a: 42}); result = _.minBy(list); result = _.minBy(list, listIterator); result = _.minBy(list, ''); - result = _.minBy<{a: number}, number>(list, {a: 42}); - - result = _.minBy(dictionary); - result = _.minBy(dictionary, dictionaryIterator); - result = _.minBy(dictionary, ''); - result = _.minBy<{a: number}, number>(dictionary, {a: 42}); + result2 = _.minBy(list2, {a: 42}); result = _(array).minBy(); result = _(array).minBy(listIterator); result = _(array).minBy(''); - result = _(array).minBy<{a: number}>({a: 42}); + result2 = _(array2).minBy({a: 42}); result = _(list).minBy(); result = _(list).minBy(listIterator); result = _(list).minBy(''); - result = _(list).minBy<{a: number}, number>({a: 42}); - - result = _(dictionary).minBy(); - result = _(dictionary).minBy(dictionaryIterator); - result = _(dictionary).minBy(''); - result = _(dictionary).minBy<{a: number}, number>({a: 42}); + result2 = _(list2).minBy({a: 42}); } // _.multiply @@ -8933,10 +9102,8 @@ namespace TestSum { let result: number; result = _.sum(array); - result = _.sum(array); result = _.sum(list); - result = _.sum(list); result = _(array).sum(); @@ -8964,7 +9131,7 @@ namespace TestSumBy { let list: _.List | null | undefined = [] as any; let objectList: _.List<{ 'age': number }> | null | undefined = [] as any; - let listIterator = (value: number, index: number, collection: _.List) => 0; + let listIterator = (value: number) => 0; { let result: number; @@ -8972,17 +9139,15 @@ namespace TestSumBy { result = _.sumBy(array); result = _.sumBy(array, listIterator); result = _.sumBy(objectArray, 'age'); - result = _.sumBy(objectArray, { 'age': 30 }); result = _.sumBy(list); result = _.sumBy(list, listIterator); result = _.sumBy(objectList, 'age'); - result = _.sumBy(objectList, { 'age': 30 }); result = _(array).sumBy(listIterator); result = _(objectArray).sumBy('age'); - result = _(list).sumBy((value: _.List | null | undefined, index: number, collection: _.List<_.List | null | undefined>) => 0); + result = _(list).sumBy(listIterator); result = _(objectList).sumBy('age'); } @@ -8992,7 +9157,7 @@ namespace TestSumBy { result = _(array).chain().sumBy(listIterator); result = _(objectArray).chain().sumBy('age'); - result = _(list).chain().sumBy((value: _.List | null | undefined, index: number, collection: _.List<_.List | null | undefined>) => 0); + result = _(list).chain().sumBy(listIterator); result = _(objectList).chain().sumBy('age'); } } @@ -9138,7 +9303,7 @@ namespace TestAssign { { let result: { a: number, b: number, c: number, d: number, e: number }; - result = _.assign<{ a: number, b: number, c: number, d: number, e: number }>(obj, s1, s2, s3, s4, s5); + result = _.assign(obj, s1, s2, s3, s4, s5); } { @@ -9174,7 +9339,7 @@ namespace TestAssign { { let result: _.LoDashImplicitObjectWrapper<{ a: number, b: number, c: number, d: number, e: number }>; - result = _(obj).assign<{ a: number, b: number, c: number, d: number, e: number }>(s1, s2, s3, s4, s5); + result = _(obj).assign(s1, s2, s3, s4, s5); } { @@ -9210,7 +9375,7 @@ namespace TestAssign { { let result: _.LoDashExplicitObjectWrapper<{ a: number, b: number, c: number, d: number, e: number }>; - result = _(obj).chain().assign<{ a: number, b: number, c: number, d: number, e: number }>(s1, s2, s3, s4, s5); + result = _(obj).chain().assign(s1, s2, s3, s4, s5); } } @@ -9322,7 +9487,7 @@ namespace TestAssignWith { { let result: _.LoDashExplicitObjectWrapper<{ a: number, b: number, c: number, d: number, e: number }>; - result = _(obj).chain().assignWith<{ a: number, b: number, c: number, d: number, e: number }>(s1, s2, s3, s4, s5, customizer); + result = _(obj).chain().assignWith(s1, s2, s3, s4, s5, customizer); } } @@ -9449,7 +9614,7 @@ namespace TestAssignIn { { let result: _.LoDashExplicitObjectWrapper<{ a: number, b: number, c: number, d: number, e: number }>; - result = _(obj).chain().assignIn<{ a: number, b: number, c: number, d: number, e: number }>(s1, s2, s3, s4, s5); + result = _(obj).chain().assignIn(s1, s2, s3, s4, s5); } } @@ -9561,7 +9726,7 @@ namespace TestAssignInWith { { let result: _.LoDashExplicitObjectWrapper<{ a: number, b: number, c: number, d: number, e: number }>; - result = _(obj).chain().assignInWith<{ a: number, b: number, c: number, d: number, e: number }>(s1, s2, s3, s4, s5, customizer); + result = _(obj).chain().assignInWith(s1, s2, s3, s4, s5, customizer); } } @@ -9644,7 +9809,7 @@ namespace TestDefaults { { let result: { a: string, b: number, c: number, d: number, e: number }; - result = _.defaults<{ a: string, b: number, c: number, d: number, e: number }>(obj, s1, s2, s3, s4, s5); + result = _.defaults(obj, s1, s2, s3, s4, s5); } { @@ -9680,7 +9845,7 @@ namespace TestDefaults { { let result: _.LoDashImplicitObjectWrapper<{ a: string, b: number, c: number, d: number, e: number }>; - result = _(obj).defaults<{ a: string, b: number, c: number, d: number, e: number }>(s1, s2, s3, s4, s5); + result = _(obj).defaults(s1, s2, s3, s4, s5); } { @@ -9716,7 +9881,7 @@ namespace TestDefaults { { let result: _.LoDashExplicitObjectWrapper<{ a: string, b: number, c: number, d: number, e: number }>; - result = _(obj).chain().defaults<{ a: string, b: number, c: number, d: number, e: number }>(s1, s2, s3, s4, s5); + result = _(obj).chain().defaults(s1, s2, s3, s4, s5); } } @@ -9730,45 +9895,27 @@ interface DefaultsDeepResult { const TestDefaultsDeepObject = { 'user': { 'name': 'barney' } }; const TestDefaultsDeepSource = { 'user': { 'name': 'fred', 'age': 36 } }; result = _.defaultsDeep(TestDefaultsDeepObject, TestDefaultsDeepSource); -result = _(TestDefaultsDeepObject).defaultsDeep(TestDefaultsDeepSource).value(); +result = _(TestDefaultsDeepObject).defaultsDeep(TestDefaultsDeepSource).value(); // _.entries namespace TestEntries { let object: _.Dictionary = {}; - { - let result: [string, any][]; - - result = _.entries<_.Dictionary>(object); - } - { let result: [string, string][]; - result = _.entries<_.Dictionary, string>(object); + result = _.entries(object); } { let result: _.LoDashImplicitArrayWrapper<[string, string]>; - result = _(object).entries(); - } - - { - let result: _.LoDashImplicitArrayWrapper<[string, any]>; - result = _(object).entries(); } { let result: _.LoDashExplicitArrayWrapper<[string, string]>; - result = _(object).chain().entries(); - } - - { - let result: _.LoDashExplicitArrayWrapper<[string, any]>; - result = _(object).chain().entries(); } } @@ -9777,27 +9924,15 @@ namespace TestEntries { namespace TestEntriesIn { let object: _.Dictionary = {}; - { - let result: [string, any][]; - - result = _.entriesIn<_.Dictionary>(object); - } - { let result: [string, string][]; - result = _.entriesIn<_.Dictionary, string>(object); + result = _.entriesIn(object); } { let result: _.LoDashImplicitArrayWrapper<[string, string]>; - result = _(object).entriesIn(); - } - - { - let result: _.LoDashImplicitArrayWrapper<[string, any]>; - result = _(object).entriesIn(); } @@ -9901,7 +10036,7 @@ namespace TestExtend { { let result: _.LoDashImplicitObjectWrapper<{ a: number, b: number, c: number, d: number, e: number }>; - result = _(obj).extend<{ a: number, b: number, c: number, d: number, e: number }>(s1, s2, s3, s4, s5); + result = _(obj).extend(s1, s2, s3, s4, s5); } { @@ -9937,7 +10072,7 @@ namespace TestExtend { { let result: _.LoDashExplicitObjectWrapper<{ a: number, b: number, c: number, d: number, e: number }>; - result = _(obj).chain().extend<{ a: number, b: number, c: number, d: number, e: number }>(s1, s2, s3, s4, s5); + result = _(obj).chain().extend(s1, s2, s3, s4, s5); } } @@ -10028,7 +10163,7 @@ namespace TestExtendWith { { let result: _.LoDashImplicitObjectWrapper<{ a: number, b: number, c: number, d: number, e: number }>; - result = _(obj).extendWith<{ a: number, b: number, c: number, d: number, e: number }>(s1, s2, s3, s4, s5, customizer); + result = _(obj).extendWith(s1, s2, s3, s4, s5, customizer); } { @@ -10064,7 +10199,7 @@ namespace TestExtendWith { { let result: _.LoDashExplicitObjectWrapper<{ a: number, b: number, c: number, d: number, e: number }>; - result = _(obj).chain().extendWith<{ a: number, b: number, c: number, d: number, e: number }>(s1, s2, s3, s4, s5, customizer); + result = _(obj).chain().extendWith(s1, s2, s3, s4, s5, customizer); } } @@ -10081,7 +10216,7 @@ namespace TestFindKey { result = _.findKey<{a: string;}>({a: ''}, ''); - result = _.findKey<{a: number;}, {a: string;}>({a: ''}, {a: 42}); + result = _.findKey({a: { b: 5 }}, {b: 42}); result = _.findKey({a: { b: 5 }}, ['b', 5]); @@ -10091,16 +10226,16 @@ namespace TestFindKey { result = _<{a: string;}>({a: ''}).findKey(''); - result = _<{a: string;}>({a: ''}).findKey<{a: number;}>({a: 42}); + result = _({a: { b: 5 }}).findKey({b: 42}); } { let predicateFn = (value: string, key: string, collection: _.Dictionary) => true; let result: string | undefined; - result = _.findKey({a: ''}, predicateFn); + result = _.findKey({a: ''}, predicateFn); - result = _<{a: string;}>({a: ''}).findKey(predicateFn); + result = _({a: ''}).findKey(predicateFn); } { @@ -10113,14 +10248,14 @@ namespace TestFindKey { result = _<{a: string;}>({a: ''}).chain().findKey(''); - result = _<{a: string;}>({a: ''}).chain().findKey<{a: number;}>({a: 42}); + result = _({a: { b: 5 }}).chain().findKey({b: 42}); } { let predicateFn = (value: string, key: string, collection: _.Dictionary) => true; let result: _.LoDashExplicitWrapper; - result = _<{a: string;}>({a: ''}).chain().findKey(predicateFn); + result = _({a: ''}).chain().findKey(predicateFn); } } @@ -10136,7 +10271,7 @@ namespace TestFindLastKey { result = _.findLastKey<{a: string;}>({a: ''}, ''); - result = _.findLastKey<{a: number;}, {a: string;}>({a: ''}, {a: 42}); + result = _.findLastKey({a: { b: 5 }}, {b: 42}); result = _.findLastKey({a: { b: 5 }}, ['b', 5]); @@ -10146,16 +10281,16 @@ namespace TestFindLastKey { result = _<{a: string;}>({a: ''}).findLastKey(''); - result = _<{a: string;}>({a: ''}).findLastKey<{a: number;}>({a: 42}); + result = _({a: { b: 5 }}).findLastKey({b: 42}); } { let predicateFn = (value: string, key: string, collection: _.Dictionary) => true; let result: string | undefined; - result = _.findLastKey({a: ''}, predicateFn); + result = _.findLastKey({a: ''}, predicateFn); - result = _<{a: string;}>({a: ''}).findLastKey(predicateFn); + result = _({a: ''}).findLastKey(predicateFn); } { @@ -10168,14 +10303,14 @@ namespace TestFindLastKey { result = _<{a: string;}>({a: ''}).chain().findLastKey(''); - result = _<{a: string;}>({a: ''}).chain().findLastKey<{a: number;}>({a: 42}); + result = _({a: { b: 5 }}).chain().findLastKey({b: 42}); } { let predicateFn = (value: string, key: string, collection: _.Dictionary) => true; let result: _.LoDashExplicitWrapper; - result = _<{a: string;}>({a: ''}).chain().findLastKey(predicateFn); + result = _({a: ''}).chain().findLastKey(predicateFn); } } @@ -10194,15 +10329,15 @@ namespace TestForIn { { let result: _.Dictionary; - result = _.forIn(dictionary); - result = _.forIn(dictionary, dictionaryIterator); + result = _.forIn(dictionary); + result = _.forIn(dictionary, dictionaryIterator); } { let result: _.Dictionary | null | undefined; - result = _.forIn(nilDictionary); - result = _.forIn(nilDictionary, dictionaryIterator); + result = _.forIn(nilDictionary); + result = _.forIn(nilDictionary, dictionaryIterator); } { @@ -10222,29 +10357,29 @@ namespace TestForIn { { let result: _.LoDashImplicitObjectWrapper<_.Dictionary>; - result = _(dictionary).forIn(); - result = _(dictionary).forIn(dictionaryIterator); + result = _(dictionary).forIn(); + result = _(dictionary).forIn(dictionaryIterator); } { let result: _.LoDashImplicitNillableObjectWrapper<_.Dictionary>; - result = _(nilDictionary).forIn(); - result = _(nilDictionary).forIn(dictionaryIterator); + result = _(nilDictionary).forIn(); + result = _(nilDictionary).forIn(dictionaryIterator); } { let result: _.LoDashExplicitObjectWrapper<_.Dictionary>; - result = _(dictionary).chain().forIn(); - result = _(dictionary).chain().forIn(dictionaryIterator); + result = _(dictionary).chain().forIn(); + result = _(dictionary).chain().forIn(dictionaryIterator); } { let result: _.LoDashExplicitNillableObjectWrapper<_.Dictionary>; - result = _(nilDictionary).chain().forIn(); - result = _(nilDictionary).chain().forIn(dictionaryIterator); + result = _(nilDictionary).chain().forIn(); + result = _(nilDictionary).chain().forIn(dictionaryIterator); } } @@ -10263,15 +10398,15 @@ namespace TestForInRight { { let result: _.Dictionary; - result = _.forInRight(dictionary); - result = _.forInRight(dictionary, dictionaryIterator); + result = _.forInRight(dictionary); + result = _.forInRight(dictionary, dictionaryIterator); } { let result: _.Dictionary | null | undefined; - result = _.forInRight(nilDictionary); - result = _.forInRight(nilDictionary, dictionaryIterator); + result = _.forInRight(nilDictionary); + result = _.forInRight(nilDictionary, dictionaryIterator); } { @@ -10291,29 +10426,29 @@ namespace TestForInRight { { let result: _.LoDashImplicitObjectWrapper<_.Dictionary>; - result = _(dictionary).forInRight(); - result = _(dictionary).forInRight(dictionaryIterator); + result = _(dictionary).forInRight(); + result = _(dictionary).forInRight(dictionaryIterator); } { let result: _.LoDashImplicitNillableObjectWrapper<_.Dictionary>; - result = _(nilDictionary).forInRight(); - result = _(nilDictionary).forInRight(dictionaryIterator); + result = _(nilDictionary).forInRight(); + result = _(nilDictionary).forInRight(dictionaryIterator); } { let result: _.LoDashExplicitObjectWrapper<_.Dictionary>; - result = _(dictionary).chain().forInRight(); - result = _(dictionary).chain().forInRight(dictionaryIterator); + result = _(dictionary).chain().forInRight(); + result = _(dictionary).chain().forInRight(dictionaryIterator); } { let result: _.LoDashExplicitNillableObjectWrapper<_.Dictionary>; - result = _(nilDictionary).chain().forInRight(); - result = _(nilDictionary).chain().forInRight(dictionaryIterator); + result = _(nilDictionary).chain().forInRight(); + result = _(nilDictionary).chain().forInRight(dictionaryIterator); } } @@ -10332,15 +10467,15 @@ namespace TestForOwn { { let result: _.Dictionary; - result = _.forOwn(dictionary); - result = _.forOwn(dictionary, dictionaryIterator); + result = _.forOwn(dictionary); + result = _.forOwn(dictionary, dictionaryIterator); } { let result: _.Dictionary | null | undefined; - result = _.forOwn(nilDictionary); - result = _.forOwn(nilDictionary, dictionaryIterator); + result = _.forOwn(nilDictionary); + result = _.forOwn(nilDictionary, dictionaryIterator); } { @@ -10360,29 +10495,29 @@ namespace TestForOwn { { let result: _.LoDashImplicitObjectWrapper<_.Dictionary>; - result = _(dictionary).forOwn(); - result = _(dictionary).forOwn(dictionaryIterator); + result = _(dictionary).forOwn(); + result = _(dictionary).forOwn(dictionaryIterator); } { let result: _.LoDashImplicitNillableObjectWrapper<_.Dictionary>; - result = _(nilDictionary).forOwn(); - result = _(nilDictionary).forOwn(dictionaryIterator); + result = _(nilDictionary).forOwn(); + result = _(nilDictionary).forOwn(dictionaryIterator); } { let result: _.LoDashExplicitObjectWrapper<_.Dictionary>; - result = _(dictionary).chain().forOwn(); - result = _(dictionary).chain().forOwn(dictionaryIterator); + result = _(dictionary).chain().forOwn(); + result = _(dictionary).chain().forOwn(dictionaryIterator); } { let result: _.LoDashExplicitNillableObjectWrapper<_.Dictionary>; - result = _(nilDictionary).chain().forOwn(); - result = _(nilDictionary).chain().forOwn(dictionaryIterator); + result = _(nilDictionary).chain().forOwn(); + result = _(nilDictionary).chain().forOwn(dictionaryIterator); } } @@ -10401,15 +10536,15 @@ namespace TestForOwnRight { { let result: _.Dictionary; - result = _.forOwnRight(dictionary); - result = _.forOwnRight(dictionary, dictionaryIterator); + result = _.forOwnRight(dictionary); + result = _.forOwnRight(dictionary, dictionaryIterator); } { let result: _.Dictionary | null | undefined; - result = _.forOwnRight(nilDictionary); - result = _.forOwnRight(nilDictionary, dictionaryIterator); + result = _.forOwnRight(nilDictionary); + result = _.forOwnRight(nilDictionary, dictionaryIterator); } { @@ -10429,29 +10564,29 @@ namespace TestForOwnRight { { let result: _.LoDashImplicitObjectWrapper<_.Dictionary>; - result = _(dictionary).forOwnRight(); - result = _(dictionary).forOwnRight(dictionaryIterator); + result = _(dictionary).forOwnRight(); + result = _(dictionary).forOwnRight(dictionaryIterator); } { let result: _.LoDashImplicitNillableObjectWrapper<_.Dictionary>; - result = _(nilDictionary).forOwnRight(); - result = _(nilDictionary).forOwnRight(dictionaryIterator); + result = _(nilDictionary).forOwnRight(); + result = _(nilDictionary).forOwnRight(dictionaryIterator); } { let result: _.LoDashExplicitObjectWrapper<_.Dictionary>; - result = _(dictionary).chain().forOwnRight(); - result = _(dictionary).chain().forOwnRight(dictionaryIterator); + result = _(dictionary).chain().forOwnRight(); + result = _(dictionary).chain().forOwnRight(dictionaryIterator); } { let result: _.LoDashExplicitNillableObjectWrapper<_.Dictionary>; - result = _(nilDictionary).chain().forOwnRight(); - result = _(nilDictionary).chain().forOwnRight(dictionaryIterator); + result = _(nilDictionary).chain().forOwnRight(); + result = _(nilDictionary).chain().forOwnRight(dictionaryIterator); } } @@ -10464,7 +10599,7 @@ namespace TestFunctions { { let result: string[]; - result = _.functions(object); + result = _.functions(object); } { @@ -10510,15 +10645,15 @@ namespace TestGet { { let result: string; - result = _.get('abc', '0'); - result = _.get('abc', '0', '_'); - result = _.get('abc', ['0']); - result = _.get('abc', ['0'], '_'); + result = _.get('abc', '0'); + result = _.get('abc', '0', '_'); + result = _.get('abc', ['0']); + result = _.get('abc', ['0'], '_'); - result = _.get('abc', '0'); - result = _.get('abc', '0', '_'); - result = _.get('abc', ['0']); - result = _.get('abc', ['0'], '_'); + result = _.get('abc', '0'); + result = _.get('abc', '0', '_'); + result = _.get('abc', ['0']); + result = _.get('abc', ['0'], '_'); result = _('abc').get('0'); result = _('abc').get('0', '_'); @@ -10529,15 +10664,15 @@ namespace TestGet { { let result: number; - result = _.get([42], '0'); - result = _.get([42], '0', -1); - result = _.get([42], ['0']); - result = _.get([42], ['0'], -1); + result = _.get([42], '0'); + result = _.get([42], '0', -1); + result = _.get([42], ['0']); + result = _.get([42], ['0'], -1); - result = _.get([42], '0'); - result = _.get([42], '0', -1); - result = _.get([42], ['0']); - result = _.get([42], ['0'], -1); + result = _.get([42], '0'); + result = _.get([42], '0', -1); + result = _.get([42], ['0']); + result = _.get([42], ['0'], -1); result = _([42]).get('0'); result = _([42]).get('0', -1); @@ -10548,15 +10683,15 @@ namespace TestGet { { let result: boolean; - result = _.get<{a: boolean}, boolean>({a: true}, 'a'); - result = _.get<{a: boolean}, boolean>({a: true}, 'a', false); - result = _.get<{a: boolean}, boolean>({a: true}, ['a']); - result = _.get<{a: boolean}, boolean>({a: true}, ['a'], false); + result = _.get({a: true}, 'a'); + result = _.get({a: true}, 'a', false); + result = _.get({a: true}, ['a']); + result = _.get({a: true}, ['a'], false); - result = _.get({a: true}, 'a'); - result = _.get({a: true}, 'a', false); - result = _.get({a: true}, ['a']); - result = _.get({a: true}, ['a'], false); + result = _.get({a: true}, 'a'); + result = _.get({a: true}, 'a', false); + result = _.get({a: true}, ['a']); + result = _.get({a: true}, ['a'], false); result = _({a: true}).get('a'); result = _({a: true}).get('a', false); @@ -10567,28 +10702,28 @@ namespace TestGet { { let result: _.LoDashExplicitWrapper; - result = _('abc').chain().get<_.LoDashExplicitWrapper>('0'); - result = _('abc').chain().get<_.LoDashExplicitWrapper>('0', '_'); - result = _('abc').chain().get<_.LoDashExplicitWrapper>(['0']); - result = _('abc').chain().get<_.LoDashExplicitWrapper>(['0'], '_'); + result = _('abc').chain().get('0'); + result = _('abc').chain().get('0', '_'); + result = _('abc').chain().get(['0']); + result = _('abc').chain().get(['0'], '_'); } { let result: _.LoDashExplicitWrapper; - result = _([42]).chain().get<_.LoDashExplicitWrapper>('0'); - result = _([42]).chain().get<_.LoDashExplicitWrapper>('0', -1); - result = _([42]).chain().get<_.LoDashExplicitWrapper>(['0']); - result = _([42]).chain().get<_.LoDashExplicitWrapper>(['0'], -1); + result = _([42]).chain().get('0'); + result = _([42]).chain().get('0', -1); + result = _([42]).chain().get(['0']); + result = _([42]).chain().get(['0'], -1); } { let result: _.LoDashExplicitWrapper; - result = _({a: true}).chain().get<_.LoDashExplicitWrapper>('a'); - result = _({a: true}).chain().get<_.LoDashExplicitWrapper>('a', false); - result = _({a: true}).chain().get<_.LoDashExplicitWrapper>(['a']); - result = _({a: true}).chain().get<_.LoDashExplicitWrapper>(['a'], false); + result = _({a: true}).chain().get('a'); + result = _({a: true}).chain().get('a', false); + result = _({a: true}).chain().get(['a']); + result = _({a: true}).chain().get(['a'], false); } } @@ -10655,27 +10790,21 @@ namespace TestHasIn { // _.invert namespace TestInvert { { - let result: TResult; + let result: _.Dictionary; - result = _.invert({}); - result = _.invert({}, true); - - result = _.invert({}); - result = _.invert({}, true); + result = _.invert({}); } { - let result: _.LoDashImplicitObjectWrapper; + let result: _.LoDashImplicitObjectWrapper<_.Dictionary>; - result = _({}).invert(); - result = _({}).invert(true); + result = _({}).invert(); } { - let result: _.LoDashExplicitObjectWrapper; + let result: _.LoDashExplicitObjectWrapper<_.Dictionary>; - result = _({}).chain().invert(); - result = _({}).chain().invert(true); + result = _({}).chain().invert(); } } @@ -10832,58 +10961,58 @@ namespace TestMapKeys { { let result: _.Dictionary; - result = _.mapKeys(array); - result = _.mapKeys(array, listIterator); - result = _.mapKeys(array, ''); - result = _.mapKeys(array, {}); + result = _.mapKeys(array); + result = _.mapKeys(array, listIterator); + result = _.mapKeys(array, ''); + result = _.mapKeys(array, {}); - result = _.mapKeys(list); - result = _.mapKeys(list, listIterator); - result = _.mapKeys(list, ''); - result = _.mapKeys(list, {}); + result = _.mapKeys(list); + result = _.mapKeys(list, listIterator); + result = _.mapKeys(list, ''); + result = _.mapKeys(list, {}); - result = _.mapKeys(dictionary); - result = _.mapKeys(dictionary, dictionaryIterator); - result = _.mapKeys(dictionary, ''); - result = _.mapKeys(dictionary, {}); + result = _.mapKeys(dictionary); + result = _.mapKeys(dictionary, dictionaryIterator); + result = _.mapKeys(dictionary, ''); + result = _.mapKeys(dictionary, {}); } { let result: _.LoDashImplicitObjectWrapper<_.Dictionary>; - result = _(array).mapKeys(); - result = _(array).mapKeys(listIterator); + result = _(array).mapKeys(); + result = _(array).mapKeys(listIterator); result = _(array).mapKeys(''); - result = _(array).mapKeys<{}>({}); + result = _(array).mapKeys({}); - result = _(list).mapKeys(); - result = _(list).mapKeys(listIterator); - result = _(list).mapKeys(''); - result = _(list).mapKeys({}); + result = _(list).mapKeys(); + result = _(list).mapKeys(listIterator); + result = _(list).mapKeys(''); + result = _(list).mapKeys({}); - result = _(dictionary).mapKeys(); - result = _(dictionary).mapKeys(dictionaryIterator); - result = _(dictionary).mapKeys(''); - result = _(dictionary).mapKeys({}); + result = _(dictionary).mapKeys(); + result = _(dictionary).mapKeys(dictionaryIterator); + result = _(dictionary).mapKeys(''); + result = _(dictionary).mapKeys({}); } { let result: _.LoDashExplicitObjectWrapper<_.Dictionary>; - result = _(array).chain().mapKeys(); - result = _(array).chain().mapKeys(listIterator); + result = _(array).chain().mapKeys(); + result = _(array).chain().mapKeys(listIterator); result = _(array).chain().mapKeys(''); - result = _(array).chain().mapKeys<{}>({}); + result = _(array).chain().mapKeys({}); - result = _(list).chain().mapKeys(); - result = _(list).chain().mapKeys(listIterator); - result = _(list).chain().mapKeys(''); - result = _(list).chain().mapKeys({}); + result = _(list).chain().mapKeys(); + result = _(list).chain().mapKeys(listIterator); + result = _(list).chain().mapKeys(''); + result = _(list).chain().mapKeys({}); - result = _(dictionary).chain().mapKeys(); - result = _(dictionary).chain().mapKeys(dictionaryIterator); - result = _(dictionary).chain().mapKeys(''); - result = _(dictionary).chain().mapKeys({}); + result = _(dictionary).chain().mapKeys(); + result = _(dictionary).chain().mapKeys(dictionaryIterator); + result = _(dictionary).chain().mapKeys(''); + result = _(dictionary).chain().mapKeys({}); } } @@ -10909,7 +11038,7 @@ namespace TestMerge { result = _.merge(initialValue, {}, {}, {}, mergingValue); // Once we get to the varargs version, you have to specify the result explicitly - result = _.merge(initialValue, {}, {}, {}, {}, mergingValue); + result = _.merge(initialValue, {}, {}, {}, {}, mergingValue); type ComplicatedExpectedType = { a: number, b: string, c: {}, d: number[], e: boolean }; @@ -10939,7 +11068,7 @@ namespace TestMerge { result = _(initialValue).merge({}, {}, {}, mergingValue).value(); // Once we get to the varargs version, you have to specify the result explicitly - result = _(initialValue).merge({}, {}, {}, {}, mergingValue).value(); + result = _(initialValue).merge({}, {}, {}, {}, mergingValue).value(); // Test complex multiple combinations with chaining @@ -10997,34 +11126,32 @@ namespace TestMergeWith { result = _.mergeWith(initialValue, {}, {}, {}, mergingValue, customizer); // Once we get to the varargs version, you have to specify the result explicitl - result = _.mergeWith(initialValue, {}, {}, {}, {}, mergingValue, customizer); + result = _.mergeWith(initialValue, {}, {}, {}, {}, mergingValue, customizer); // Tests for basic chaining with mergeWith result = _(initialValue).mergeWith(mergingValue, customizer).value(); result = _(initialValue).mergeWith({}, mergingValue, customizer).value(); result = _(initialValue).mergeWith({}, {}, mergingValue, customizer).value(); result = _(initialValue).mergeWith({}, {}, {}, mergingValue, customizer).value(); - - // Once we get to the varargs version, you have to specify the result explicitly - result = _(initialValue).mergeWith({}, {}, {}, {}, mergingValue, customizer).value(); + result = _(initialValue).mergeWith({}, {}, {}, {}, mergingValue, customizer).value(); } // _.omit namespace TestOmit { - let obj: {} | null | undefined = any; + let obj: TResult | null | undefined = any; let predicate: (element: any, key: string, collection: any) => boolean; { - let result: TResult; + let result: Partial; - result = _.omit(obj, 'a'); - result = _.omit(obj, 0, 'a'); - result = _.omit(obj, true, 0, 'a'); - result = _.omit(obj, ['b', 1, false], true, 0, 'a'); + result = _.omit(obj, 'a'); + result = _.omit(obj, 0, 'a'); + result = _.omit(obj, true, 0, 'a'); + result = _.omit(obj, ['b', 1, false], true, 0, 'a'); } { - let result: _.LoDashImplicitObjectWrapper; + let result: _.LoDashImplicitWrapper>; result = _(obj).omit('a'); result = _(obj).omit(0, 'a'); @@ -11033,7 +11160,7 @@ namespace TestOmit { } { - let result: _.LoDashExplicitObjectWrapper; + let result: _.LoDashExplicitWrapper>; result = _(obj).chain().omit('a'); result = _(obj).chain().omit(0, 'a'); @@ -11044,23 +11171,23 @@ namespace TestOmit { // _.omitBy namespace TestOmitBy { - let obj: {} | null | undefined = any; - let predicate = (element: any, key: string, collection: any) => true; + let obj: TResult | null | undefined = any; + let predicate = (element: any, key: string) => true; { - let result: TResult; + let result: Partial; - result = _.omitBy(obj, predicate); + result = _.omitBy(obj, predicate); } { - let result: _.LoDashImplicitObjectWrapper; + let result: _.LoDashImplicitWrapper>; result = _(obj).omitBy(predicate); } { - let result: _.LoDashExplicitObjectWrapper; + let result: _.LoDashExplicitWrapper>; result = _(obj).chain().omitBy(predicate); } @@ -11068,19 +11195,19 @@ namespace TestOmitBy { // _.pick namespace TestPick { - let obj: {} | null | undefined = any; + let obj: TResult | null | undefined = any; { - let result: TResult; + let result: Partial; - result = _.pick(obj, 'a'); - result = _.pick(obj, 0, 'a'); - result = _.pick(obj, true, 0, 'a'); - result = _.pick(obj, ['b', 1, false], true, 0, 'a'); + result = _.pick(obj, 'a'); + result = _.pick(obj, 0, 'a'); + result = _.pick(obj, true, 0, 'a'); + result = _.pick(obj, ['b', 1, false], true, 0, 'a'); } { - let result: _.LoDashImplicitObjectWrapper; + let result: _.LoDashImplicitWrapper>; result = _(obj).pick('a'); result = _(obj).pick(0, 'a'); @@ -11089,7 +11216,7 @@ namespace TestPick { } { - let result: _.LoDashExplicitObjectWrapper; + let result: _.LoDashExplicitWrapper>; result = _(obj).chain().pick('a'); result = _(obj).chain().pick(0, 'a'); @@ -11100,23 +11227,23 @@ namespace TestPick { // _.pickBy namespace TestPickBy { - let obj: {} | null | undefined = any; - let predicate = (element: any, key: string, collection: any) => true; + let obj: TResult | null | undefined = any; + let predicate = (element: any, key: string) => true; { - let result: TResult; + let result: Partial; - result = _.pickBy(obj, predicate); + result = _.pickBy(obj, predicate); } { - let result: _.LoDashImplicitObjectWrapper; + let result: _.LoDashImplicitWrapper>; result = _(obj).pickBy(predicate); } { - let result: _.LoDashExplicitObjectWrapper; + let result: _.LoDashExplicitWrapper>; result = _(obj).chain().pickBy(predicate); } @@ -11127,13 +11254,6 @@ namespace TestResult { { let result: string; - result = _.result('abc', '0'); - result = _.result('abc', '0', '_'); - result = _.result('abc', '0', () => '_'); - result = _.result('abc', ['0']); - result = _.result('abc', ['0'], '_'); - result = _.result('abc', ['0'], () => '_'); - result = _.result('abc', '0'); result = _.result('abc', '0', '_'); result = _.result('abc', '0', () => '_'); @@ -11152,13 +11272,6 @@ namespace TestResult { { let result: number; - result = _.result([42], '0'); - result = _.result([42], '0', -1); - result = _.result([42], '0', () => -1); - result = _.result([42], ['0']); - result = _.result([42], ['0'], -1); - result = _.result([42], ['0'], () => -1); - result = _.result([42], '0'); result = _.result([42], '0', -1); result = _.result([42], '0', () => -1); @@ -11177,13 +11290,6 @@ namespace TestResult { { let result: boolean; - result = _.result<{a: boolean}, boolean>({a: true}, 'a'); - result = _.result<{a: boolean}, boolean>({a: true}, 'a', false); - result = _.result<{a: boolean}, boolean>({a: true}, 'a', () => false); - result = _.result<{a: boolean}, boolean>({a: true}, ['a']); - result = _.result<{a: boolean}, boolean>({a: true}, ['a'], false); - result = _.result<{a: boolean}, boolean>({a: true}, ['a'], () => false); - result = _.result({a: true}, 'a'); result = _.result({a: true}, 'a', false); result = _.result({a: true}, 'a', () => false); @@ -11202,34 +11308,34 @@ namespace TestResult { { let result: _.LoDashExplicitWrapper; - result = _('abc').chain().result<_.LoDashExplicitWrapper>('0'); - result = _('abc').chain().result<_.LoDashExplicitWrapper>('0', '_'); - result = _('abc').chain().result<_.LoDashExplicitWrapper>('0', '_'); - result = _('abc').chain().result<_.LoDashExplicitWrapper>(['0']); - result = _('abc').chain().result<_.LoDashExplicitWrapper>(['0'], () => '_'); - result = _('abc').chain().result<_.LoDashExplicitWrapper>(['0'], () => '_'); + result = _('abc').chain().result('0'); + result = _('abc').chain().result('0', '_'); + result = _('abc').chain().result('0', '_'); + result = _('abc').chain().result(['0']); + result = _('abc').chain().result(['0'], () => '_'); + result = _('abc').chain().result(['0'], () => '_'); } { let result: _.LoDashExplicitWrapper; - result = _([42]).chain().result<_.LoDashExplicitWrapper>('0'); - result = _([42]).chain().result<_.LoDashExplicitWrapper>('0', -1); - result = _([42]).chain().result<_.LoDashExplicitWrapper>('0', () => -1); - result = _([42]).chain().result<_.LoDashExplicitWrapper>(['0']); - result = _([42]).chain().result<_.LoDashExplicitWrapper>(['0'], -1); - result = _([42]).chain().result<_.LoDashExplicitWrapper>(['0'], () => -1); + result = _([42]).chain().result('0'); + result = _([42]).chain().result('0', -1); + result = _([42]).chain().result('0', () => -1); + result = _([42]).chain().result(['0']); + result = _([42]).chain().result(['0'], -1); + result = _([42]).chain().result(['0'], () => -1); } { let result: _.LoDashExplicitWrapper; - result = _({a: true}).chain().result<_.LoDashExplicitWrapper>('a'); - result = _({a: true}).chain().result<_.LoDashExplicitWrapper>('a', false); - result = _({a: true}).chain().result<_.LoDashExplicitWrapper>('a', () => false); - result = _({a: true}).chain().result<_.LoDashExplicitWrapper>(['a']); - result = _({a: true}).chain().result<_.LoDashExplicitWrapper>(['a'], false); - result = _({a: true}).chain().result<_.LoDashExplicitWrapper>(['a'], () => false); + result = _({a: true}).chain().result('a'); + result = _({a: true}).chain().result('a', false); + result = _({a: true}).chain().result('a', () => false); + result = _({a: true}).chain().result(['a']); + result = _({a: true}).chain().result(['a'], false); + result = _({a: true}).chain().result(['a'], () => false); } } @@ -11246,12 +11352,6 @@ namespace TestSet { result = _.set(object, 'a.b[1]', value); result = _.set(object, ['a', 'b', 1], value); - - result = _.set(object, 'a.b[1]', value); - result = _.set(object, ['a', 'b', 1], value); - - result = _.set(object, 'a.b[1]', value); - result = _.set(object, ['a', 'b', 1], value); } { @@ -11259,9 +11359,6 @@ namespace TestSet { result = _(object).set('a.b[1]', value); result = _(object).set(['a', 'b', 1], value); - - result = _(object).set('a.b[1]', value); - result = _(object).set(['a', 'b', 1], value); } { @@ -11269,20 +11366,16 @@ namespace TestSet { result = _(object).chain().set('a.b[1]', value); result = _(object).chain().set(['a', 'b', 1], value); - - result = _(object).chain().set('a.b[1]', value); - result = _(object).chain().set(['a', 'b', 1], value); } } // _.setWith namespace TestSetWith { - type SampleObject = {a: {}}; type SampleResult = {a: {b: number[]}}; - let object: SampleObject = { a: {} }; + let object: SampleResult = { a: { b: [] } }; let value = 0; - let customizer = (value: any, key: string, object: SampleObject) => 0; + let customizer = (value: any, key: string, object: SampleResult) => 0; { let result: SampleResult; @@ -11291,16 +11384,6 @@ namespace TestSetWith { result = _.setWith(object, 'a.b[1]', value, customizer); result = _.setWith(object, ['a', 'b', 1], value); result = _.setWith(object, ['a', 'b', 1], value, customizer); - - result = _.setWith(object, 'a.b[1]', value); - result = _.setWith(object, 'a.b[1]', value, customizer); - result = _.setWith(object, ['a', 'b', 1], value); - result = _.setWith(object, ['a', 'b', 1], value, customizer); - - result = _.setWith(object, 'a.b[1]', value); - result = _.setWith(object, 'a.b[1]', value, customizer); - result = _.setWith(object, ['a', 'b', 1], value); - result = _.setWith(object, ['a', 'b', 1], value, customizer); } { @@ -11310,11 +11393,6 @@ namespace TestSetWith { result = _(object).setWith('a.b[1]', value, customizer); result = _(object).setWith(['a', 'b', 1], value); result = _(object).setWith(['a', 'b', 1], value, customizer); - - result = _(object).setWith('a.b[1]', value); - result = _(object).setWith('a.b[1]', value, customizer); - result = _(object).setWith(['a', 'b', 1], value); - result = _(object).setWith(['a', 'b', 1], value, customizer); } { @@ -11324,11 +11402,6 @@ namespace TestSetWith { result = _(object).chain().setWith('a.b[1]', value, customizer); result = _(object).chain().setWith(['a', 'b', 1], value); result = _(object).chain().setWith(['a', 'b', 1], value, customizer); - - result = _(object).chain().setWith('a.b[1]', value); - result = _(object).chain().setWith('a.b[1]', value, customizer); - result = _(object).chain().setWith(['a', 'b', 1], value); - result = _(object).chain().setWith(['a', 'b', 1], value, customizer); } } @@ -11336,39 +11409,21 @@ namespace TestSetWith { namespace TestToPairs { let object: _.Dictionary = {}; - { - let result: [string, any][]; - - result = _.toPairs<_.Dictionary>(object); - } - { let result: [string, string][]; - result = _.toPairs<_.Dictionary, string>(object); + result = _.toPairs(object); } { let result: _.LoDashImplicitArrayWrapper<[string, string]>; - result = _(object).toPairs(); - } - - { - let result: _.LoDashImplicitArrayWrapper<[string, any]>; - result = _(object).toPairs(); } { let result: _.LoDashExplicitArrayWrapper<[string, string]>; - result = _(object).chain().toPairs(); - } - - { - let result: _.LoDashExplicitArrayWrapper<[string, any]>; - result = _(object).chain().toPairs(); } } @@ -11377,27 +11432,15 @@ namespace TestToPairs { namespace TestToPairsIn { let object: _.Dictionary = {}; - { - let result: [string, any][]; - - result = _.toPairsIn<_.Dictionary>(object); - } - { let result: [string, string][]; - result = _.toPairsIn<_.Dictionary, string>(object); + result = _.toPairsIn(object); } { let result: _.LoDashImplicitArrayWrapper<[string, string]>; - result = _(object).toPairsIn(); - } - - { - let result: _.LoDashImplicitArrayWrapper<[string, any]>; - result = _(object).toPairsIn(); } @@ -11424,13 +11467,13 @@ namespace TestTransform { let accumulator: TResult[] = []; let result: TResult[]; - result = _.transform(array); + result = _.transform(array); result = _.transform(array, iterator); result = _.transform(array, iterator, accumulator); - result = _(array).transform().value(); - result = _(array).transform(iterator).value(); - result = _(array).transform(iterator, accumulator).value(); + result = _(array).transform().value(); + result = _(array).transform(iterator).value(); + result = _(array).transform(iterator, accumulator).value(); } { @@ -11438,11 +11481,9 @@ namespace TestTransform { let accumulator: _.Dictionary = {}; let result: _.Dictionary; - result = _.transform(array, iterator); result = _.transform(array, iterator, accumulator); - result = _(array).transform(iterator).value(); - result = _(array).transform(iterator, accumulator).value(); + result = _(array).transform(iterator, accumulator).value(); } { @@ -11450,11 +11491,11 @@ namespace TestTransform { let accumulator: _.Dictionary = {}; let result: _.Dictionary; - result = _.transform(dictionary); + result = _.transform(dictionary); result = _.transform(dictionary, iterator); result = _.transform(dictionary, iterator, accumulator); - result = _(dictionary).transform().value(); + result = _(dictionary).transform().value(); result = _(dictionary).transform(iterator).value(); result = _(dictionary).transform(iterator, accumulator).value(); } @@ -11464,10 +11505,8 @@ namespace TestTransform { let accumulator: TResult[] = []; let result: TResult[]; - result = _.transform(dictionary, iterator); result = _.transform(dictionary, iterator, accumulator); - result = _(dictionary).transform(iterator).value(); result = _(dictionary).transform(iterator, accumulator).value(); } } @@ -11481,8 +11520,8 @@ namespace TestUnset { { let result: boolean; - _.unset(object, 'a.b'); - _.unset(object, ['a', 'b']); + result = _.unset(object, 'a.b'); + result = _.unset(object, ['a', 'b']); } { @@ -11502,57 +11541,40 @@ namespace TestUnset { // _.update namespace TestUpdate { - type SampleObject = {a: {}}; type SampleResult = {a: {b: number[]}}; - let object: SampleObject = { a: {} }; + let object: SampleResult = { a: { b: [] } }; let updater = (value: any) => 0; { let result: SampleResult; - result = _.update(object, 'a.b[1]', updater); - result = _.update(object, ['a', 'b', 1], updater); - - result = _.update<(value: any) => number, SampleResult>(object, 'a.b[1]', updater); - result = _.update<(value: any) => number, SampleResult>(object, ['a', 'b', 1], updater); - - result = _.update(object, 'a.b[1]', updater); - result = _.update(object, ['a', 'b', 1], updater); - - result = _.update number, SampleResult>(object, 'a.b[1]', updater); - result = _.update number, SampleResult>(object, ['a', 'b', 1], updater); + result = _.update(object, 'a.b[1]', updater); + result = _.update(object, ['a', 'b', 1], updater); } { let result: _.LoDashImplicitObjectWrapper; - result = _(object).update('a.b[1]', updater); - result = _(object).update(['a', 'b', 1], updater); - - result = _(object).update<(value: any) => number, SampleResult>('a.b[1]', updater); - result = _(object).update<(value: any) => number, SampleResult>(['a', 'b', 1], updater); + result = _(object).update('a.b[1]', updater); + result = _(object).update(['a', 'b', 1], updater); } { let result: _.LoDashExplicitObjectWrapper; - result = _(object).chain().update('a.b[1]', updater); - result = _(object).chain().update(['a', 'b', 1], updater); - - result = _(object).chain().update<(value: any) => number, SampleResult>('a.b[1]', updater); - result = _(object).chain().update<(value: any) => number, SampleResult>(['a', 'b', 1], updater); + result = _(object).chain().update('a.b[1]', updater); + result = _(object).chain().update(['a', 'b', 1], updater); } } // _.updateWith namespace TestUpdateWith { - type SampleObject = {a: {}}; type SampleResult = {a: {b: number[]}}; - let object: SampleObject = { a: {} }; + let object: SampleResult = { a: { b: [] } }; let updater = (value: any) => 0; - let customizer = (value: any, key: string, object: SampleObject) => 0; + let customizer = (value: any, key: string, object: SampleResult) => 0; { let result: SampleResult; @@ -11594,7 +11616,6 @@ namespace TestValues { { let result: any[]; - result = _.values(); result = _.values(123); result = _.values(true); result = _.values(null); @@ -12026,11 +12047,9 @@ namespace TestReplace { result = _.replace('Hi Fred', /fred/i, 'Barney'); result = _.replace('Hi Fred', /fred/i, replacer); - result = _.replace('Fred'); result = _.replace('Fred', 'Barney'); result = _.replace('Fred', replacer); - result = _.replace(/fred/i); result = _.replace(/fred/i, 'Barney'); result = _.replace(/fred/i, replacer); @@ -12040,11 +12059,9 @@ namespace TestReplace { result = _('Hi Fred').replace(/fred/i, 'Barney'); result = _('Hi Fred').replace(/fred/i, replacer); - result = _('Fred').replace(); result = _('Fred').replace('Barney'); result = _('Fred').replace(replacer); - result = _(/fred/i).replace(); result = _(/fred/i).replace('Barney'); result = _(/fred/i).replace(replacer); } @@ -12058,11 +12075,9 @@ namespace TestReplace { result = _('Hi Fred').chain().replace(/fred/i, 'Barney'); result = _('Hi Fred').chain().replace(/fred/i, replacer); - result = _('Fred').chain().replace(); result = _('Fred').chain().replace('Barney'); result = _('Fred').chain().replace(replacer); - result = _(/fred/i).chain().replace(); result = _(/fred/i).chain().replace('Barney'); result = _(/fred/i).chain().replace(replacer); } @@ -12438,52 +12453,52 @@ namespace TestConstant { { let result: _.LoDashImplicitObjectWrapper<() => number>; - result = _(42).constant(); + result = _(42).constant(); } { let result: _.LoDashImplicitObjectWrapper<() => string>; - result = _('a').constant(); + result = _('a').constant(); } { let result: _.LoDashImplicitObjectWrapper<() => boolean>; - result = _(true).constant(); + result = _(true).constant(); } { let result: _.LoDashImplicitObjectWrapper<() => string[]>; - result = _(['a']).constant(); + result = _(['a']).constant(); } { let result: _.LoDashImplicitObjectWrapper<() => {a: string}>; - result = _({a: 'a'}).constant<{a: string}>(); + result = _({a: 'a'}).constant(); } { let result: _.LoDashExplicitObjectWrapper<() => number>; - result = _(42).chain().constant(); + result = _(42).chain().constant(); } { let result: _.LoDashExplicitObjectWrapper<() => string>; - result = _('a').chain().constant(); + result = _('a').chain().constant(); } { let result: _.LoDashExplicitObjectWrapper<() => boolean>; - result = _(true).chain().constant(); + result = _(true).chain().constant(); } { let result: _.LoDashExplicitObjectWrapper<() => string[]>; - result = _(['a']).chain().constant(); + result = _(['a']).chain().constant(); } { let result: _.LoDashExplicitObjectWrapper<() => {a: string}>; - result = _({a: 'a'}).chain().constant<{a: string}>(); + result = _({a: 'a'}).chain().constant(); } } @@ -12526,7 +12541,7 @@ namespace TestDefaultTo { } { - let result: _.LoDashImplicitObjectWrapper; + let result: number; result = _(42).defaultTo(42); result = _(undefined).defaultTo(42); result = _(null).defaultTo(42); @@ -12534,34 +12549,30 @@ namespace TestDefaultTo { } { - let result: _.LoDashImplicitObjectWrapper; + let result: string; result = _('a').defaultTo('default'); result = _(null).defaultTo('default'); - result = _(NaN).defaultTo('default'); } { - let result: _.LoDashImplicitObjectWrapper; + let result: boolean; result = _(true).defaultTo(true); result = _(undefined).defaultTo(true); result = _(null).defaultTo(true); - result = _(NaN).defaultTo(true); } { - let result: _.LoDashImplicitObjectWrapper; + let result: string[]; result = _(['a']).defaultTo(['default']); result = _(undefined).defaultTo(['default']); result = _(null).defaultTo(['default']); - result = _(NaN).defaultTo(['default']); } { - let result: _.LoDashImplicitObjectWrapper<{ a: string }>; + let result: { a: string }; result = _({ a: 'a' }).defaultTo({a : 'a'}); result = _(undefined).defaultTo({a : 'a'}); result = _(null).defaultTo({a : 'a'}); - result = _(NaN).defaultTo({a : 'a'}); } { @@ -12577,7 +12588,6 @@ namespace TestDefaultTo { result = _('a').chain().defaultTo('default'); result = _(undefined).chain().defaultTo('default'); result = _(null).chain().defaultTo('default'); - result = _(NaN).chain().defaultTo('default'); } { @@ -12585,7 +12595,6 @@ namespace TestDefaultTo { result = _(true).chain().defaultTo(true); result = _(undefined).chain().defaultTo(true); result = _(null).chain().defaultTo(true); - result = _(NaN).chain().defaultTo(true); } { @@ -12593,7 +12602,6 @@ namespace TestDefaultTo { result = _(['a']).chain().defaultTo(['default']); result = _(undefined).chain().defaultTo(['default']); result = _(null).chain().defaultTo(['default']); - result = _(NaN).chain().defaultTo(['default']); } { @@ -12601,7 +12609,6 @@ namespace TestDefaultTo { result = _({ a: 'a' }).chain().defaultTo({a : 'a'}); result = _(undefined).chain().defaultTo({a : 'a'}); result = _(null).chain().defaultTo({a : 'a'}); - result = _(NaN).chain().defaultTo({a : 'a'}); } } @@ -12664,7 +12671,7 @@ namespace TestIteratee { { let result: (object: any) => TResult; - result = _.iteratee(''); + result = _.iteratee(''); } { @@ -12676,13 +12683,14 @@ namespace TestIteratee { { let result: _.LoDashImplicitObjectWrapper<(...args: any[]) => TResult>; - result = _(Function).iteratee(); + let func: (...args: any[]) => TResult = any; + result = _(func).iteratee(); } { let result: _.LoDashImplicitObjectWrapper<(object: any) => TResult>; - result = _('').iteratee(); + result = _('').iteratee(); } { @@ -12694,13 +12702,14 @@ namespace TestIteratee { { let result: _.LoDashExplicitObjectWrapper<(...args: any[]) => TResult>; - result = _(Function).chain().iteratee(); + let func: (...args: any[]) => TResult = any; + result = _(func).chain().iteratee(); } { let result: _.LoDashExplicitObjectWrapper<(object: any) => TResult>; - result = _('').chain().iteratee(); + result = _('').chain().iteratee(); } { @@ -12782,83 +12791,83 @@ namespace TestMethod { { let result: (object: any) => {a: string}; - result = _.method<{a: string}>('a.0'); - result = _.method<{a: string}>('a.0', any, any); - result = _.method<{a: string}>('a.0', any, any, any); + result = _.method('a.0'); + result = _.method('a.0', any, any); + result = _.method('a.0', any, any, any); - result = _.method<{a: string}>(['a', 0]); - result = _.method<{a: string}>(['a', 0], any); - result = _.method<{a: string}>(['a', 0], any, any); - result = _.method<{a: string}>(['a', 0], any, any, any); + result = _.method(['a', 0]); + result = _.method(['a', 0], any); + result = _.method(['a', 0], any, any); + result = _.method(['a', 0], any, any, any); } { let result: (object: {a: string}) => {b: string}; - result = _.method<{a: string}, {b: string}>('a.0'); - result = _.method<{a: string}, {b: string}>('a.0', any, any); - result = _.method<{a: string}, {b: string}>('a.0', any, any, any); + result = _.method('a.0'); + result = _.method('a.0', any, any); + result = _.method('a.0', any, any, any); - result = _.method<{a: string}, {b: string}>(['a', 0]); - result = _.method<{a: string}, {b: string}>(['a', 0], any); - result = _.method<{a: string}, {b: string}>(['a', 0], any, any); - result = _.method<{a: string}, {b: string}>(['a', 0], any, any, any); + result = _.method(['a', 0]); + result = _.method(['a', 0], any); + result = _.method(['a', 0], any, any); + result = _.method(['a', 0], any, any, any); } { let result: _.LoDashImplicitObjectWrapper<(object: any) => {a: string}>; - result = _('a.0').method<{a: string}>(); - result = _('a.0').method<{a: string}>(any); - result = _('a.0').method<{a: string}>(any, any); - result = _('a.0').method<{a: string}>(any, any, any); + result = _('a.0').method(); + result = _('a.0').method(any); + result = _('a.0').method(any, any); + result = _('a.0').method(any, any, any); - result = _(['a', 0]).method<{a: string}>(); - result = _(['a', 0]).method<{a: string}>(any); - result = _(['a', 0]).method<{a: string}>(any, any); - result = _(['a', 0]).method<{a: string}>(any, any, any); + result = _(['a', 0]).method(); + result = _(['a', 0]).method(any); + result = _(['a', 0]).method(any, any); + result = _(['a', 0]).method(any, any, any); } { let result: _.LoDashImplicitObjectWrapper<(object: {a: string}) => {b: string}>; - result = _('a.0').method<{a: string}, {b: string}>(); - result = _('a.0').method<{a: string}, {b: string}>(any); - result = _('a.0').method<{a: string}, {b: string}>(any, any); - result = _('a.0').method<{a: string}, {b: string}>(any, any, any); + result = _('a.0').method(); + result = _('a.0').method(any); + result = _('a.0').method(any, any); + result = _('a.0').method(any, any, any); - result = _(['a', 0]).method<{a: string}, {b: string}>(); - result = _(['a', 0]).method<{a: string}, {b: string}>(any); - result = _(['a', 0]).method<{a: string}, {b: string}>(any, any); - result = _(['a', 0]).method<{a: string}, {b: string}>(any, any, any); + result = _(['a', 0]).method(); + result = _(['a', 0]).method(any); + result = _(['a', 0]).method(any, any); + result = _(['a', 0]).method(any, any, any); } { let result: _.LoDashExplicitObjectWrapper<(object: any) => {a: string}>; - result = _('a.0').chain().method<{a: string}>(); - result = _('a.0').chain().method<{a: string}>(any); - result = _('a.0').chain().method<{a: string}>(any, any); - result = _('a.0').chain().method<{a: string}>(any, any, any); + result = _('a.0').chain().method(); + result = _('a.0').chain().method(any); + result = _('a.0').chain().method(any, any); + result = _('a.0').chain().method(any, any, any); - result = _(['a', 0]).chain().method<{a: string}>(); - result = _(['a', 0]).chain().method<{a: string}>(any); - result = _(['a', 0]).chain().method<{a: string}>(any, any); - result = _(['a', 0]).chain().method<{a: string}>(any, any, any); + result = _(['a', 0]).chain().method(); + result = _(['a', 0]).chain().method(any); + result = _(['a', 0]).chain().method(any, any); + result = _(['a', 0]).chain().method(any, any, any); } { let result: _.LoDashExplicitObjectWrapper<(object: {a: string}) => {b: string}>; - result = _('a.0').chain().method<{a: string}, {b: string}>(); - result = _('a.0').chain().method<{a: string}, {b: string}>(any); - result = _('a.0').chain().method<{a: string}, {b: string}>(any, any); - result = _('a.0').chain().method<{a: string}, {b: string}>(any, any, any); + result = _('a.0').chain().method(); + result = _('a.0').chain().method(any); + result = _('a.0').chain().method(any, any); + result = _('a.0').chain().method(any, any, any); - result = _(['a', 0]).chain().method<{a: string}, {b: string}>(); - result = _(['a', 0]).chain().method<{a: string}, {b: string}>(any); - result = _(['a', 0]).chain().method<{a: string}, {b: string}>(any, any); - result = _(['a', 0]).chain().method<{a: string}, {b: string}>(any, any, any); + result = _(['a', 0]).chain().method(); + result = _(['a', 0]).chain().method(any); + result = _(['a', 0]).chain().method(any, any); + result = _(['a', 0]).chain().method(any, any, any); } } @@ -12872,66 +12881,77 @@ namespace TestMethodOf { { let result: ResultFn; - result = _.methodOf(object); - result = _.methodOf(object, any); - result = _.methodOf(object, any, any); - result = _.methodOf(object, any, any, any); - - result = _.methodOf(object); - result = _.methodOf(object, any); - result = _.methodOf(object, any, any); - result = _.methodOf(object, any, any, any); + result = _.methodOf(object); + result = _.methodOf(object, any); + result = _.methodOf(object, any, any); + result = _.methodOf(object, any, any, any); } { let result: _.LoDashImplicitObjectWrapper; - result = _(object).methodOf(); - result = _(object).methodOf(any); - result = _(object).methodOf(any, any); - result = _(object).methodOf(any, any, any); + result = _(object).methodOf(); + result = _(object).methodOf(any); + result = _(object).methodOf(any, any); + result = _(object).methodOf(any, any, any); } { let result: _.LoDashExplicitObjectWrapper; - result = _(object).chain().methodOf(); - result = _(object).chain().methodOf(any); - result = _(object).chain().methodOf(any, any); - result = _(object).chain().methodOf(any, any, any); + result = _(object).chain().methodOf(); + result = _(object).chain().methodOf(any); + result = _(object).chain().methodOf(any, any); + result = _(object).chain().methodOf(any, any, any); } } // _.mixin namespace TestMixin { - let source: _.Dictionary = {}; + let source: _.Dictionary<(...args: any[]) => any> = {}; + let dest: TResult = any; let options: {chain?: boolean} = {}; + { + let result: _.LoDashStatic; + + result = _.mixin(source); + result = _.mixin(source, options); + } + { let result: TResult; - result = _.mixin({}, source); - result = _.mixin({}, source, options); - result = _.mixin(source); - result = _.mixin(source, options); + result = _.mixin(dest, source); + result = _.mixin(dest, source, options); } { - let result: _.LoDashImplicitObjectWrapper; + let result: _.LoDashImplicitWrapper<_.LoDashStatic>; - result = _({}).mixin(source); - result = _({}).mixin(source, options); - result = _(source).mixin(); - result = _(source).mixin(options); + result = _(source).mixin(); + result = _(source).mixin(options); } { - let result: _.LoDashExplicitObjectWrapper; + let result: _.LoDashImplicitWrapper; - result = _({}).chain().mixin(source); - result = _({}).chain().mixin(source, options); - result = _(source).chain().mixin(); - result = _(source).chain().mixin(options); + result = _(dest).mixin(source); + result = _(dest).mixin(source, options); + } + + { + let result: _.LoDashExplicitWrapper<_.LoDashStatic>; + + result = _(source).chain().mixin(); + result = _(source).chain().mixin(options); + } + + { + let result: _.LoDashExplicitWrapper; + + result = _(dest).chain().mixin(source); + result = _(dest).chain().mixin(source, options); } } @@ -12967,7 +12987,7 @@ namespace TestNoop { result = _('a').noop(true, 'a', 1); result = _([1]).noop(true, 'a', 1); - result = _([]).noop(true, 'a', 1); + result = _(['']).noop(true, 'a', 1); result = _({}).noop(true, 'a', 1); result = _(any).noop(true, 'a', 1); } @@ -12977,7 +12997,7 @@ namespace TestNoop { result = _('a').chain().noop(true, 'a', 1); result = _([1]).chain().noop(true, 'a', 1); - result = _([]).chain().noop(true, 'a', 1); + result = _(['']).chain().noop(true, 'a', 1); result = _({}).chain().noop(true, 'a', 1); result = _(any).chain().noop(true, 'a', 1); } @@ -12989,20 +13009,20 @@ namespace TestNthArg { { let result: SampleFunc; - result = _.nthArg(); - result = _.nthArg(1); + result = _.nthArg(); + result = _.nthArg(1); } { let result: _.LoDashImplicitObjectWrapper; - result = _(1).nthArg(); + result = _(1).nthArg(); } { let result: _.LoDashExplicitObjectWrapper; - result = _(1).chain().nthArg(); + result = _(1).chain().nthArg(); } } @@ -13232,7 +13252,7 @@ namespace TestRangeRight { result = _('a').chain().stubArray(); result = _([1]).chain().stubArray(); - result = _([]).chain().stubArray(); + result = _(['']).chain().stubArray(); result = _({}).chain().stubArray(); result = _(any).chain().stubArray(); } @@ -13252,7 +13272,7 @@ namespace TestRangeRight { result = _('a').chain().stubFalse(); result = _([1]).chain().stubFalse(); - result = _([]).chain().stubFalse(); + result = _(['']).chain().stubFalse(); result = _({}).chain().stubFalse(); result = _(any).chain().stubFalse(); } @@ -13272,7 +13292,7 @@ namespace TestRangeRight { result = _('a').chain().stubObject(); result = _([1]).chain().stubObject(); - result = _([]).chain().stubObject(); + result = _(['']).chain().stubObject(); result = _({}).chain().stubObject(); result = _(any).chain().stubObject(); } @@ -13292,7 +13312,7 @@ namespace TestRangeRight { result = _('a').chain().stubString(); result = _([1]).chain().stubString(); - result = _([]).chain().stubString(); + result = _(['']).chain().stubString(); result = _({}).chain().stubString(); result = _(any).chain().stubString(); } @@ -13312,7 +13332,7 @@ namespace TestRangeRight { result = _('a').chain().stubTrue(); result = _([1]).chain().stubTrue(); - result = _([]).chain().stubTrue(); + result = _(['']).chain().stubTrue(); result = _({}).chain().stubTrue(); result = _(any).chain().stubTrue(); } @@ -13367,7 +13387,7 @@ namespace TestToPath { result = _(1).toPath(); result = _('a').toPath(); result = _([1]).toPath(); - result = _(["a"]).toPath(); + result = _(["a"]).toPath(); result = _({}).toPath(); } } diff --git a/types/lodash/tslint.json b/types/lodash/tslint.json index 02254dbc60..44e681fc18 100644 --- a/types/lodash/tslint.json +++ b/types/lodash/tslint.json @@ -2,35 +2,28 @@ "extends": "dtslint/dt.json", "rules": { // All are TODOs - "adjacent-overload-signatures": false, - "align": false, "array-type": false, "ban-types": false, "callable-types": false, - "comment-format": false, - "eofline": false, + "comment-format": [false], "interface-name": false, "interface-over-type-literal": false, "jsdoc-format": false, - "max-line-length": false, + "max-line-length": [false], "no-any-union": false, "no-empty-interface": false, - "no-namespace": false, "no-mergeable-namespace": false, + "no-namespace": false, "no-unnecessary-generics": false, - "no-unnecessary-qualifier": false, "no-unnecessary-type-assertion": false, "no-void-expression": false, - "no-trailing-whitespace": false, "object-literal-key-quotes": false, "one-line": false, - "one-variable-per-declaration": false, "prefer-const": false, "semicolon": false, "space-within-parens": false, - "triple-equals": false, - "typedef-whitespace": false, + "typedef-whitespace": [false], "unified-signatures": false, - "whitespace": false + "whitespace": [false] } } From 1d3179901c97f1f5a18c717d986ade3881dd7b13 Mon Sep 17 00:00:00 2001 From: Rob Sterner Date: Thu, 19 Oct 2017 11:27:29 -0400 Subject: [PATCH 053/828] per the docs/comments the order can be null (#20721) --- types/c3/index.d.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/types/c3/index.d.ts b/types/c3/index.d.ts index 00d1cf1840..eb727233a0 100644 --- a/types/c3/index.d.ts +++ b/types/c3/index.d.ts @@ -366,7 +366,7 @@ declare namespace c3 { * and it will recieve the data as argument. * Available Values: desc, asc, function (data1, data2) { ... }, null */ - order?: string | ((...data: string[]) => void); + order?: string | ((...data: string[]) => void) | null; /** * Define regions for each data. * The values must be an array for each data and it should include an object that has start, end, style. If start is not set, the start will be the first data point. If end is not set, the From f9aa971b2735046772a12d8b7ad4f6d04932bba6 Mon Sep 17 00:00:00 2001 From: Viktor Isaev Date: Thu, 19 Oct 2017 18:31:05 +0300 Subject: [PATCH 054/828] Added typings for "heapdump". (#20716) * Added typings for "require-dir". * Fixed dtslint errors. * Fixed By field. * Added typings for "restify-cookies". * Added "cookies" field to Request interface. * Added typings for "heapdump". --- types/heapdump/heapdump-tests.ts | 9 +++++++++ types/heapdump/index.d.ts | 6 ++++++ types/heapdump/tsconfig.json | 25 +++++++++++++++++++++++++ types/heapdump/tslint.json | 1 + 4 files changed, 41 insertions(+) create mode 100644 types/heapdump/heapdump-tests.ts create mode 100644 types/heapdump/index.d.ts create mode 100644 types/heapdump/tsconfig.json create mode 100644 types/heapdump/tslint.json diff --git a/types/heapdump/heapdump-tests.ts b/types/heapdump/heapdump-tests.ts new file mode 100644 index 0000000000..49019f83fc --- /dev/null +++ b/types/heapdump/heapdump-tests.ts @@ -0,0 +1,9 @@ +import * as heapdump from 'heapdump'; + +heapdump.writeSnapshot('/tmp/myDump', (err) => { + if (err) { + console.log('Failed to dump heap: ' + err); + } else { + console.log('Successfully dumped heap!'); + } +}); diff --git a/types/heapdump/index.d.ts b/types/heapdump/index.d.ts new file mode 100644 index 0000000000..d4e0477a32 --- /dev/null +++ b/types/heapdump/index.d.ts @@ -0,0 +1,6 @@ +// Type definitions for heapdump 0.3 +// Project: https://github.com/bnoordhuis/node-heapdump +// Definitions by: weekens +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +export function writeSnapshot(dumpFileName: string, callback: (err?: Error) => void): void; diff --git a/types/heapdump/tsconfig.json b/types/heapdump/tsconfig.json new file mode 100644 index 0000000000..a15a306b41 --- /dev/null +++ b/types/heapdump/tsconfig.json @@ -0,0 +1,25 @@ +{ + "compilerOptions": { + "target": "es6", + "module": "commonjs", + "lib": [ + "es6", + "dom" + ], + "noImplicitAny": true, + "noImplicitThis": true, + "strictNullChecks": true, + "strictFunctionTypes": true, + "baseUrl": "../", + "typeRoots": [ + "../" + ], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true + }, + "files": [ + "index.d.ts", + "heapdump-tests.ts" + ] +} diff --git a/types/heapdump/tslint.json b/types/heapdump/tslint.json new file mode 100644 index 0000000000..3db14f85ea --- /dev/null +++ b/types/heapdump/tslint.json @@ -0,0 +1 @@ +{ "extends": "dtslint/dt.json" } From 5b3c2c61117a6d713af90d8b1efe8492749c97e0 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Emre=20Do=C4=9Fan?= Date: Thu, 19 Oct 2017 18:35:06 +0300 Subject: [PATCH 055/828] Optional parameters for constructor has been changed according to package's description (#20712) --- types/neo4j/index.d.ts | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/types/neo4j/index.d.ts b/types/neo4j/index.d.ts index f0923557ca..dc9567f725 100644 --- a/types/neo4j/index.d.ts +++ b/types/neo4j/index.d.ts @@ -57,7 +57,7 @@ export interface GraphDatabaseOptions { * HTTP agent. * @type {any} */ - agent: any; + agent?: any; /** * Authentication information. @@ -69,13 +69,13 @@ export interface GraphDatabaseOptions { * HTTP headers. * @type {Object} */ - headers: {}; + headers?: {}; /** * Proxy address. * @type {string} */ - proxy: string; + proxy?: string; /** * URL connection. From 12eb86bd1bbc28f5d49965adb63bfc25fd8e4558 Mon Sep 17 00:00:00 2001 From: Ika Date: Thu, 19 Oct 2017 23:36:58 +0800 Subject: [PATCH 056/828] feat(prettier): update to v1.7.x (#20708) --- types/prettier/index.d.ts | 26 +++++++++++++++++++++----- types/prettier/prettier-tests.ts | 3 +++ 2 files changed, 24 insertions(+), 5 deletions(-) diff --git a/types/prettier/index.d.ts b/types/prettier/index.d.ts index 1ed2568a1e..6ea1fcbbf9 100644 --- a/types/prettier/index.d.ts +++ b/types/prettier/index.d.ts @@ -9,7 +9,16 @@ import { File } from 'babel-types'; export type AST = File; export type BuiltInParser = (text: string, options?: any) => AST; -export type BuiltInParserName = 'babylon' | 'flow' | 'typescript' | 'postcss' | 'json' | 'graphql'; +export type BuiltInParserName = + | 'babylon' + | 'flow' + | 'typescript' + | 'postcss' // deprecated + | 'css' + | 'less' + | 'scss' + | 'json' + | 'graphql'; export type CustomParser = (text: string, parsers: Record, options: Options) => AST; @@ -107,11 +116,18 @@ export interface ResolveConfigOptions { * If set to `false`, all caching will be bypassed. */ useCache?: boolean; + /** + * Pass directly the path of the config file if you don't wish to search for it. + */ + config?: string; } /** - * `resolveConfig` can be used to resolve configuration for a given source file. - * The function optionally accepts an input file path as an argument, which defaults to the current working directory. + * `resolveConfig` can be used to resolve configuration for a given source file, + * passing its path as the first argument. The config search will start at the + * file path and continue to search up the directory. + * (You can use `process.cwd()` to start searching from the current directory). + * * A promise is returned which will resolve to: * * - An options object, providing a [config file](https://github.com/prettier/prettier#configuration-file) was found. @@ -119,9 +135,9 @@ export interface ResolveConfigOptions { * * The promise will be rejected if there was an error parsing the configuration file. */ -export function resolveConfig(filePath?: string, options?: ResolveConfigOptions): Promise; +export function resolveConfig(filePath: string, options?: ResolveConfigOptions): Promise; export namespace resolveConfig { - function sync(filePath?: string, options?: ResolveConfigOptions): null | Options; + function sync(filePath: string, options?: ResolveConfigOptions): null | Options; } /** diff --git a/types/prettier/prettier-tests.ts b/types/prettier/prettier-tests.ts index 8d95196101..9d78453bae 100644 --- a/types/prettier/prettier-tests.ts +++ b/types/prettier/prettier-tests.ts @@ -24,6 +24,9 @@ prettier.resolveConfig('path/to/somewhere').then(options => { } }); +// $ExpectError +prettier.resolveConfig(); + const options = prettier.resolveConfig.sync('path/to/somewhere'); if (options !== null) { const formatted = prettier.format('hello world', options); From fb6179c085bcf89d530555bda1828c79a025627a Mon Sep 17 00:00:00 2001 From: segayuu Date: Fri, 20 Oct 2017 00:39:42 +0900 Subject: [PATCH 057/828] [hexo-fs] cleanup unnecessary type annotation (#20702) --- types/hexo-fs/hexo-fs-tests.ts | 147 ++++++++++++++++----------------- types/hexo-fs/index.d.ts | 1 + 2 files changed, 74 insertions(+), 74 deletions(-) diff --git a/types/hexo-fs/hexo-fs-tests.ts b/types/hexo-fs/hexo-fs-tests.ts index 71e6d99e1b..d53a790ac1 100644 --- a/types/hexo-fs/hexo-fs-tests.ts +++ b/types/hexo-fs/hexo-fs-tests.ts @@ -1,11 +1,10 @@ import fs = require('hexo-fs'); -import path = require('path'); -import mocha = require('mocha'); +import { join, dirname } from 'path'; +import 'mocha'; import chai = require('chai'); import Promise = require('bluebird'); const should = chai.should(); -const { join } = path; function createDummyFolder(path: string) { return Promise.all([ @@ -31,18 +30,18 @@ const tmpDir = join(__dirname, 'fs_tmp'); before(() => fs.mkdirs(tmpDir)); -after((done) => { +after(done => { fs.rmdir(tmpDir); done(); }); it('exists()', () => { - return fs.exists(tmpDir).then((exist) => { + return fs.exists(tmpDir).then(exist => { exist.should.be.true; }); }); -it('exists() - callback', (callback) => { +it('exists() - callback', callback => { fs.exists(tmpDir, (exist) => { exist.should.be.true; callback(); @@ -54,19 +53,19 @@ it('mkdirs()', () => { return fs.mkdirs(target).then(() => { return fs.exists(target); - }).then((exist) => { + }).then(exist => { exist.should.be.true; return fs.rmdir(join(tmpDir, 'a')); }); }); -it('mkdirs() - callback', (callback) => { +it('mkdirs() - callback', callback => { const target = join(tmpDir, 'a', 'b', 'c'); - fs.mkdirs(target, (err) => { + fs.mkdirs(target, err => { should.not.exist(err); - fs.exists(target, (exist) => { + fs.exists(target, exist => { exist.should.be.true; fs.rmdir(join(tmpDir, 'a'), callback); }); @@ -78,7 +77,7 @@ it('mkdirsSync()', () => { fs.mkdirsSync(target); - return fs.exists(target).then((exist) => { + return fs.exists(target).then(exist => { exist.should.be.true; return fs.rmdir(join(tmpDir, 'a')); }); @@ -90,17 +89,17 @@ it('writeFile()', () => { return fs.writeFile(target, body).then(() => { return fs.readFile(target); - }).then((content) => { + }).then(content => { content.should.eql(body); return fs.rmdir(join(tmpDir, 'a')); }); }); -it('writeFile() - callback', (callback) => { +it('writeFile() - callback', callback => { const target = join(tmpDir, 'a', 'b', 'test.txt'); const body = 'foo'; - fs.writeFile(target, body, (err) => { + fs.writeFile(target, body, err => { should.not.exist(err); fs.readFile(target, (_, content) => { @@ -116,7 +115,7 @@ it('writeFileSync()', () => { fs.writeFileSync(target, body); - return fs.readFile(target).then((content) => { + return fs.readFile(target).then(content => { content.should.eql(body); return fs.rmdir(join(tmpDir, 'a')); }); @@ -131,19 +130,19 @@ it('appendFile()', () => { return fs.appendFile(target, body2); }).then(() => { return fs.readFile(target); - }).then((content) => { + }).then(content => { content.should.eql(body + body2); return fs.rmdir(join(tmpDir, 'a')); }); }); -it('appendFile() - callback', (callback) => { +it('appendFile() - callback', callback => { const target = join(tmpDir, 'a', 'b', 'test.txt'); const body = 'foo'; const body2 = 'bar'; fs.writeFile(target, body, () => { - fs.appendFile(target, body2, (err) => { + fs.appendFile(target, body2, err => { should.not.exist(err); fs.readFile(target, (_, content) => { @@ -162,7 +161,7 @@ it('appendFileSync()', () => { return fs.writeFile(target, body).then(() => { fs.appendFileSync(target, body2); return fs.readFile(target); - }).then((content) => { + }).then(content => { content.should.eql(body + body2); return fs.rmdir(join(tmpDir, 'a')); }); @@ -177,7 +176,7 @@ it('copyFile()', () => { return fs.copyFile(src, dest); }).then(() => { return fs.readFile(dest); - }).then((content) => { + }).then(content => { content.should.eql(body); return Promise.all([ @@ -187,15 +186,15 @@ it('copyFile()', () => { }); }); -it('copyFile() - callback', (callback) => { +it('copyFile() - callback', callback => { const src = join(tmpDir, 'test.txt'); const dest = join(tmpDir, 'a', 'b', 'test.txt'); const body = 'foo'; - fs.writeFile(src, body, (err) => { + fs.writeFile(src, body, err => { if (err) return callback(err); - fs.copyFile(src, dest, (err) => { + fs.copyFile(src, dest, err => { if (err) return callback(err); fs.readFile(dest, (err, content) => { @@ -217,7 +216,7 @@ it('copyDir()', () => { return createDummyFolder(src).then(() => { return fs.copyDir(src, dest); - }).then((files) => { + }).then(files => { files.should.have.members([ 'e.txt', 'f.js', @@ -231,7 +230,7 @@ it('copyDir()', () => { fs.readFile(join(dest, 'folder', 'h.txt')), fs.readFile(join(dest, 'folder', 'i.js')) ]); - }).then((result) => { + }).then(result => { result.should.eql(['e', 'f', 'h', 'i']); }).then(() => { return Promise.all([ @@ -241,7 +240,7 @@ it('copyDir()', () => { }); }); -it('copyDir() - callback', (callback) => { +it('copyDir() - callback', callback => { const src = join(tmpDir, 'a'); const dest = join(tmpDir, 'b'); @@ -260,7 +259,7 @@ it('copyDir() - callback', (callback) => { fs.readFile(join(dest, 'f.js')), fs.readFile(join(dest, 'folder', 'h.txt')), fs.readFile(join(dest, 'folder', 'i.js')) - ]).then((result) => { + ]).then(result => { result.should.eql(['e', 'f', 'h', 'i']); }).then(() => { return Promise.all([ @@ -278,7 +277,7 @@ it('copyDir() - ignoreHidden off', () => { return createDummyFolder(src).then(() => { return fs.copyDir(src, dest, { ignoreHidden: false }); - }).then((files) => { + }).then(files => { files.should.have.members([ join('.hidden', 'a.txt'), join('.hidden', 'b.js'), @@ -302,7 +301,7 @@ it('copyDir() - ignoreHidden off', () => { fs.readFile(join(dest, 'folder', 'i.js')), fs.readFile(join(dest, 'folder', '.j')) ]); - }).then((result) => { + }).then(result => { result.should.eql(['a', 'b', 'd', 'e', 'f', 'g', 'h', 'i', 'j']); }).then(() => { return Promise.all([ @@ -318,14 +317,14 @@ it('copyDir() - ignorePattern', () => { return createDummyFolder(src).then(() => { return fs.copyDir(src, dest, { ignorePattern: /\.js/ }); - }).then((files) => { + }).then(files => { files.should.have.members(['e.txt', join('folder', 'h.txt')]); return Promise.all([ fs.readFile(join(dest, 'e.txt')), fs.readFile(join(dest, 'folder', 'h.txt')) ]); - }).then((result) => { + }).then(result => { result.should.eql(['e', 'h']); }).then(() => { return Promise.all([ @@ -340,7 +339,7 @@ it('listDir()', () => { return createDummyFolder(target).then(() => { return fs.listDir(target); - }).then((files) => { + }).then(files => { files.should.have.members([ 'e.txt', 'f.js', @@ -352,7 +351,7 @@ it('listDir()', () => { }); }); -it('listDir() - callback', (callback) => { +it('listDir() - callback', callback => { const target = join(tmpDir, 'test'); createDummyFolder(target).then(() => { @@ -376,7 +375,7 @@ it('listDir() - ignoreHidden off', () => { return createDummyFolder(target).then(() => { return fs.listDir(target, { ignoreHidden: false }); - }).then((files) => { + }).then(files => { files.should.have.members([ join('.hidden', 'a.txt'), join('.hidden', 'b.js'), @@ -398,7 +397,7 @@ it('listDir() - ignorePattern', () => { return createDummyFolder(target).then(() => { return fs.listDir(target, { ignorePattern: /\.js/ }); - }).then((files) => { + }).then(files => { files.should.have.members(['e.txt', join('folder', 'h.txt')]); return fs.rmdir(target); }); @@ -457,17 +456,17 @@ it('readFile()', () => { return fs.writeFile(target, body).then(() => { return fs.readFile(target); - }).then((content) => { + }).then(content => { content.should.eql(body); return fs.unlink(target); }); }); -it('readFile() - callback', (callback) => { +it('readFile() - callback', callback => { const target = join(tmpDir, 'test.txt'); const body = 'test'; - fs.writeFile(target, body, (err) => { + fs.writeFile(target, body, err => { if (err) return callback(err); fs.readFile(target, (err, content) => { @@ -486,7 +485,7 @@ it('readFile() - escape BOM', () => { return fs.writeFile(target, body).then(() => { return fs.readFile(target); - }).then((content) => { + }).then(content => { content.should.eql('foo'); return fs.unlink(target); }); @@ -498,7 +497,7 @@ it('readFile() - escape Windows line ending', () => { return fs.writeFile(target, body).then(() => { return fs.readFile(target); - }).then((content) => { + }).then(content => { content.should.eql('foo\nbar'); return fs.unlink(target); }); @@ -539,12 +538,12 @@ it('unlink()', () => { return fs.writeFile(target, '').then(() => { return fs.exists(target); - }).then((exist) => { + }).then(exist => { exist.should.eql(true); return fs.unlink(target); }).then(() => { return fs.exists(target); - }).then((exist) => { + }).then(exist => { exist.should.eql(false); }); }); @@ -554,7 +553,7 @@ it('emptyDir()', () => { return createDummyFolder(target).then(() => { return fs.emptyDir(target); - }).then>((files) => { + }).then(files => { files.should.have.members([ 'e.txt', 'f.js', @@ -574,7 +573,7 @@ it('emptyDir()', () => { [join(target, 'folder', '.j'), true] ]; }).map((data: [string, boolean]) => { - return fs.exists(data[0]).then((exist) => { + return fs.exists(data[0]).then(exist => { exist.should.eql(data[1]); }); }).then(() => { @@ -582,7 +581,7 @@ it('emptyDir()', () => { }); }); -it('emptyDir() - callback', (callback) => { +it('emptyDir() - callback', callback => { const target = join(tmpDir, 'test'); createDummyFolder(target).then(() => { @@ -596,7 +595,7 @@ it('emptyDir() - callback', (callback) => { join('folder', 'i.js') ]); - Promise.map<[string, boolean], void>([ + Promise.map([ [join(target, '.hidden', 'a.txt'), true], [join(target, '.hidden', 'b.js'), true], [join(target, '.hidden', 'c', 'd'), true], @@ -606,8 +605,8 @@ it('emptyDir() - callback', (callback) => { [join(target, 'folder', 'h.txt'), false], [join(target, 'folder', 'i.js'), false], [join(target, 'folder', '.j'), true] - ], (data: [string, boolean]) => { - return fs.exists(data[0]).then((exist) => { + ] as Array<[string, boolean]>, data => { + return fs.exists(data[0]).then(exist => { exist.should.eql(data[1]); }); }).then(() => { @@ -622,7 +621,7 @@ it('emptyDir() - ignoreHidden off', () => { return createDummyFolder(target).then(() => { return fs.emptyDir(target, { ignoreHidden: false }); - }).then>((files) => { + }).then(files => { files.should.have.members([ join('.hidden', 'a.txt'), join('.hidden', 'b.js'), @@ -647,7 +646,7 @@ it('emptyDir() - ignoreHidden off', () => { [join(target, 'folder', '.j'), false] ]; }).map((data: [string, boolean]) => { - return fs.exists(data[0]).then((exist) => { + return fs.exists(data[0]).then(exist => { exist.should.eql(data[1]); }); }).then(() => { @@ -660,7 +659,7 @@ it('emptyDir() - ignorePattern', () => { return createDummyFolder(target).then(() => { return fs.emptyDir(target, { ignorePattern: /\.js/ }); - }).then>((files) => { + }).then(files => { files.should.have.members(['e.txt', join('folder', 'h.txt')]); return [ @@ -675,7 +674,7 @@ it('emptyDir() - ignorePattern', () => { [join(target, 'folder', '.j'), true] ]; }).map((data: [string, boolean]) => { - return fs.exists(data[0]).then((exist) => { + return fs.exists(data[0]).then(exist => { exist.should.eql(data[1]); }); }).then(() => { @@ -688,7 +687,7 @@ it('emptyDir() - exclude', () => { return createDummyFolder(target).then(() => { return fs.emptyDir(target, { exclude: ['e.txt', join('folder', 'i.js')] }); - }).then>((files) => { + }).then(files => { files.should.have.members(['f.js', join('folder', 'h.txt')]); return [ @@ -703,7 +702,7 @@ it('emptyDir() - exclude', () => { [join(target, 'folder', '.j'), true] ]; }).map((data: [string, boolean]) => { - return fs.exists(data[0]).then((exist) => { + return fs.exists(data[0]).then(exist => { exist.should.eql(data[1]); }); }).then(() => { @@ -714,7 +713,7 @@ it('emptyDir() - exclude', () => { it('emptyDirSync()', () => { const target = join(tmpDir, 'test'); - return createDummyFolder(target).then>(() => { + return createDummyFolder(target).then(() => { const files = fs.emptyDirSync(target); files.should.have.members([ 'e.txt', @@ -735,7 +734,7 @@ it('emptyDirSync()', () => { [join(target, 'folder', '.j'), true] ]; }).map((data: [string, boolean]) => { - return fs.exists(data[0]).then((exist) => { + return fs.exists(data[0]).then(exist => { exist.should.eql(data[1]); }); }).then(() => { @@ -746,7 +745,7 @@ it('emptyDirSync()', () => { it('emptyDirSync() - ignoreHidden off', () => { const target = join(tmpDir, 'test'); - return createDummyFolder(target).then>(() => { + return createDummyFolder(target).then(() => { const files = fs.emptyDirSync(target, { ignoreHidden: false }); files.should.have.members([ join('.hidden', 'a.txt'), @@ -772,7 +771,7 @@ it('emptyDirSync() - ignoreHidden off', () => { [join(target, 'folder', '.j'), false] ]; }).map((data: [string, boolean]) => { - return fs.exists(data[0]).then((exist) => { + return fs.exists(data[0]).then(exist => { exist.should.eql(data[1]); }); }).then(() => { @@ -783,7 +782,7 @@ it('emptyDirSync() - ignoreHidden off', () => { it('emptyDirSync() - ignorePattern', () => { const target = join(tmpDir, 'test'); - return createDummyFolder(target).then>(() => { + return createDummyFolder(target).then(() => { const files = fs.emptyDirSync(target, { ignorePattern: /\.js/ }); files.should.have.members(['e.txt', join('folder', 'h.txt')]); @@ -799,7 +798,7 @@ it('emptyDirSync() - ignorePattern', () => { [join(target, 'folder', '.j'), true] ]; }).map((data: [string, boolean]) => { - return fs.exists(data[0]).then((exist) => { + return fs.exists(data[0]).then(exist => { exist.should.eql(data[1]); }); }).then(() => { @@ -810,7 +809,7 @@ it('emptyDirSync() - ignorePattern', () => { it('emptyDirSync() - exclude', () => { const target = join(tmpDir, 'test'); - return createDummyFolder(target).then>(() => { + return createDummyFolder(target).then(() => { const files = fs.emptyDirSync(target, { exclude: ['e.txt', join('folder', 'i.js')] }); files.should.have.members(['f.js', join('folder', 'h.txt')]); @@ -826,7 +825,7 @@ it('emptyDirSync() - exclude', () => { [join(target, 'folder', '.j'), true] ]; }).map((data: [string, boolean]) => { - return fs.exists(data[0]).then((exist) => { + return fs.exists(data[0]).then(exist => { exist.should.eql(data[1]); }); }).then(() => { @@ -841,19 +840,19 @@ it('rmdir()', () => { return fs.rmdir(target); }).then(() => { return fs.exists(target); - }).then((exist) => { + }).then(exist => { exist.should.be.false; }); }); -it('rmdir() - callback', (callback) => { +it('rmdir() - callback', callback => { const target = join(tmpDir, 'test'); createDummyFolder(target).then(() => { - fs.rmdir(target, (err) => { + fs.rmdir(target, err => { should.not.exist(err); - fs.exists(target, (exist) => { + fs.exists(target, exist => { exist.should.be.false; callback(); }); @@ -867,7 +866,7 @@ it('rmdirSync()', () => { return createDummyFolder(target).then(() => { fs.rmdirSync(target); return fs.exists(target); - }).then((exist) => { + }).then(exist => { exist.should.be.false; }); }); @@ -877,7 +876,7 @@ import { FSWatcher } from 'chokidar'; it('watch()', () => { let watcher: FSWatcher; - return fs.watch(tmpDir).then((watcher_) => { + return fs.watch(tmpDir).then(watcher_ => { watcher = watcher_; return new Promise((resolve, reject) => { @@ -905,7 +904,7 @@ it('ensurePath() - file exists', () => { fs.writeFile(join(target, 'bar.txt'), '') ]).then(() => { return fs.ensurePath(join(target, 'foo.txt')); - }).then((path) => { + }).then(path => { path.should.eql(join(target, 'foo-2.txt')); return fs.rmdir(target); }); @@ -914,12 +913,12 @@ it('ensurePath() - file exists', () => { it('ensurePath() - file not exist', () => { const target = join(tmpDir, 'foo.txt'); - return fs.ensurePath(target).then((path) => { + return fs.ensurePath(target).then(path => { path.should.eql(target); }); }); -it('ensurePath() - callback', (callback) => { +it('ensurePath() - callback', callback => { const target = join(tmpDir, 'test'); Promise.all([ @@ -962,7 +961,7 @@ it('ensurePathSync() - file not exist', () => { it('ensureWriteStream()', () => { const target = join(tmpDir, 'foo', 'bar.txt'); - return fs.ensureWriteStream(target).then((stream) => { + return fs.ensureWriteStream(target).then(stream => { stream.path.should.eql(target); stream.on('finish', () => { return fs.unlink(target); @@ -970,7 +969,7 @@ it('ensureWriteStream()', () => { }); }); -it('ensureWriteStream() - callback', (callback) => { +it('ensureWriteStream() - callback', callback => { const target = join(tmpDir, 'foo', 'bar.txt'); fs.ensureWriteStream(target, (err, stream) => { @@ -986,6 +985,6 @@ it('ensureWriteStreamSync()', () => { stream.path.should.eql(target); stream.on('finish', () => { - return fs.rmdir(path.dirname(target)); + return fs.rmdir(dirname(target)); }); }); diff --git a/types/hexo-fs/index.d.ts b/types/hexo-fs/index.d.ts index 237071d7c6..b1b9ef0405 100644 --- a/types/hexo-fs/index.d.ts +++ b/types/hexo-fs/index.d.ts @@ -2,6 +2,7 @@ // Project: http://hexo.io/ // Definitions by: segayuu // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.1 import Promise = require('bluebird'); import { From 498e2c46417703cf11f930cc235708b13a5904dd Mon Sep 17 00:00:00 2001 From: renjfk Date: Thu, 19 Oct 2017 18:40:40 +0300 Subject: [PATCH 058/828] add definitions for mark.js (#20700) --- types/mark.js/index.d.ts | 61 ++++++++++++++++++++++++++++++++++ types/mark.js/mark.js-tests.ts | 4 +++ types/mark.js/tsconfig.json | 24 +++++++++++++ types/mark.js/tslint.json | 1 + 4 files changed, 90 insertions(+) create mode 100644 types/mark.js/index.d.ts create mode 100644 types/mark.js/mark.js-tests.ts create mode 100644 types/mark.js/tsconfig.json create mode 100644 types/mark.js/tslint.json diff --git a/types/mark.js/index.d.ts b/types/mark.js/index.d.ts new file mode 100644 index 0000000000..2215c4e65c --- /dev/null +++ b/types/mark.js/index.d.ts @@ -0,0 +1,61 @@ +// Type definitions for mark.js 8.11 +// Project: https://markjs.io/ +// Definitions by: Soner Köksal +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.3 + +/// + +type MarkAccuracy = "partially" | "complementary" | "exactly"; + +interface MarkOptions { + element?: string; + className?: string; + exclude?: string[]; + separateWordSearch?: boolean; + accuracy?: MarkAccuracy | { value: MarkAccuracy }; + diacritics?: boolean; + synonyms?: { [index: string]: string }; + iframes?: boolean; + iframesTimeout?: number; + acrossElements?: boolean; + caseSensitive?: boolean; + ignoreJoiners?: boolean; + wildcards?: "disabled" | "enabled" | "withSpaces"; + + each?(element: Element): void; + + filter?(textNode: Element, term: string, marksSoFar: number, marksTotal: number): boolean; + + noMatch?(term: string): void; + + done?(marksTotal: number): void; + + debug?: boolean; + log?: object; +} + +interface UnmarkOptions { + element?: string; + className?: string; + exclude?: string[]; + iframes?: boolean; + iframesTimeout?: number; + + done?(marksTotal: number): void; + + debug?: boolean; + log?: object; +} + +interface JQuery { + mark(term: string, options?: MarkOptions): void; + + unmark(options?: UnmarkOptions): void; +} + +interface JQueryStatic { + mark(term: string, options?: MarkOptions): void; + + unmark(options?: UnmarkOptions): void; +} diff --git a/types/mark.js/mark.js-tests.ts b/types/mark.js/mark.js-tests.ts new file mode 100644 index 0000000000..136098d39d --- /dev/null +++ b/types/mark.js/mark.js-tests.ts @@ -0,0 +1,4 @@ +$("div.context").mark("text", { + element: "span", + className: "highlight" +}); diff --git a/types/mark.js/tsconfig.json b/types/mark.js/tsconfig.json new file mode 100644 index 0000000000..381f150954 --- /dev/null +++ b/types/mark.js/tsconfig.json @@ -0,0 +1,24 @@ +{ + "compilerOptions": { + "module": "commonjs", + "lib": [ + "es6", + "dom" + ], + "noImplicitAny": true, + "noImplicitThis": true, + "strictNullChecks": true, + "strictFunctionTypes": true, + "baseUrl": "../", + "typeRoots": [ + "../" + ], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true + }, + "files": [ + "index.d.ts", + "mark.js-tests.ts" + ] +} diff --git a/types/mark.js/tslint.json b/types/mark.js/tslint.json new file mode 100644 index 0000000000..3db14f85ea --- /dev/null +++ b/types/mark.js/tslint.json @@ -0,0 +1 @@ +{ "extends": "dtslint/dt.json" } From 6688ade3ea728ae56e15288f14f2f3a43cbc6708 Mon Sep 17 00:00:00 2001 From: renjfk Date: Thu, 19 Oct 2017 18:42:05 +0300 Subject: [PATCH 059/828] added definitions for selectables 1.4 (#20699) * added definitions for selectables 1.4 * options are now optional * constructor is now optional --- types/selectables/index.d.ts | 35 ++++++++++++++++++++++++++ types/selectables/selectables-tests.ts | 15 +++++++++++ types/selectables/tsconfig.json | 24 ++++++++++++++++++ types/selectables/tslint.json | 1 + 4 files changed, 75 insertions(+) create mode 100644 types/selectables/index.d.ts create mode 100644 types/selectables/selectables-tests.ts create mode 100644 types/selectables/tsconfig.json create mode 100644 types/selectables/tslint.json diff --git a/types/selectables/index.d.ts b/types/selectables/index.d.ts new file mode 100644 index 0000000000..3834428240 --- /dev/null +++ b/types/selectables/index.d.ts @@ -0,0 +1,35 @@ +// Type definitions for selectables 1.4 +// Project: https://github.com/p34eu/Selectables#readme +// Definitions by: Soner Köksal +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +export = Selectables; + +declare class Selectables { + options: Selectables.Options; + + constructor(options?: Selectables.Options); + + enable(): void; + + disable(): void; +} + +declare namespace Selectables { + interface Options { + zone?: string; + elements?: string; + selectedClass?: string; + key?: string | boolean; + moreUsing?: string; + enabled?: boolean; + + start?(e: Event): void; + + stop?(e: Event): void; + + onSelect?(el: Element): void; + + onDeselect?(el: Element): void; + } +} diff --git a/types/selectables/selectables-tests.ts b/types/selectables/selectables-tests.ts new file mode 100644 index 0000000000..595f2ca738 --- /dev/null +++ b/types/selectables/selectables-tests.ts @@ -0,0 +1,15 @@ +import * as Selectables from "selectables"; + +const dr = new Selectables({ + zone: '#div', + elements: 'li' +}); + +// later +dr.disable(); + +// enable again +dr.enable(); + +// set options +dr.options.key = 'altKey'; diff --git a/types/selectables/tsconfig.json b/types/selectables/tsconfig.json new file mode 100644 index 0000000000..e34d4a6078 --- /dev/null +++ b/types/selectables/tsconfig.json @@ -0,0 +1,24 @@ +{ + "compilerOptions": { + "module": "commonjs", + "lib": [ + "es6", + "dom" + ], + "noImplicitAny": true, + "noImplicitThis": true, + "strictNullChecks": true, + "strictFunctionTypes": true, + "baseUrl": "../", + "typeRoots": [ + "../" + ], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true + }, + "files": [ + "index.d.ts", + "selectables-tests.ts" + ] +} diff --git a/types/selectables/tslint.json b/types/selectables/tslint.json new file mode 100644 index 0000000000..3db14f85ea --- /dev/null +++ b/types/selectables/tslint.json @@ -0,0 +1 @@ +{ "extends": "dtslint/dt.json" } From ba5c25b8c7aa5acd0a062c832f53857cf8958663 Mon Sep 17 00:00:00 2001 From: Junyoung Clare Jang Date: Thu, 19 Oct 2017 11:42:41 -0400 Subject: [PATCH 060/828] Fix ModifyOptions (#20698) --- types/openlayers/index.d.ts | 2 ++ types/openlayers/openlayers-tests.ts | 5 +++-- 2 files changed, 5 insertions(+), 2 deletions(-) diff --git a/types/openlayers/index.d.ts b/types/openlayers/index.d.ts index 539db01b4d..441214cce6 100644 --- a/types/openlayers/index.d.ts +++ b/types/openlayers/index.d.ts @@ -12617,6 +12617,7 @@ declare module olx { /** * @typedef {{condition: (ol.EventsConditionType|undefined), * deleteCondition: (ol.EventsConditionType|undefined), + * insertVertexCondition: (ol.EventsConditionType|undefined), * pixelTolerance: (number|undefined), * style: (ol.style.Style|Array.|ol.StyleFunction|undefined), * features: ol.Collection., @@ -12626,6 +12627,7 @@ declare module olx { interface ModifyOptions { condition?: ol.EventsConditionType; deleteCondition?: ol.EventsConditionType; + insertVertexCondition?: ol.EventsConditionType; pixelTolerance?: number; style?: (ol.style.Style | ol.style.Style[] | ol.StyleFunction); features: ol.Collection; diff --git a/types/openlayers/openlayers-tests.ts b/types/openlayers/openlayers-tests.ts index 29d763344a..50281ff0fe 100644 --- a/types/openlayers/openlayers-tests.ts +++ b/types/openlayers/openlayers-tests.ts @@ -703,7 +703,8 @@ jsonValue = geojsonFormat.writeGeometryObject(geometry, writeOptions); // ol.interactions // let modify: ol.interaction.Modify = new ol.interaction.Modify({ - features: new ol.Collection(featureArray) + insertVertexCondition: ol.events.condition.never, + features: new ol.Collection(featureArray), }); let draw: ol.interaction.Draw = new ol.interaction.Draw({ @@ -811,4 +812,4 @@ numberValue = ol.Sphere.getArea(geometry, { numberValue = ol.Sphere.getLength(geometry, { projection: projection, radius: numberValue, -}); \ No newline at end of file +}); From 2c1dc4970e23bfcff04851e4b9e241832b18c680 Mon Sep 17 00:00:00 2001 From: Pratheek Adidela Date: Thu, 19 Oct 2017 22:46:17 +0530 Subject: [PATCH 061/828] Added types for node-horseman (#20030) * Added declarations for 'node-horseman'. * Linting is successful. * Made required changes for pushing to @types. --- types/node-horseman/index.d.ts | 241 +++++++++++++++++++++ types/node-horseman/node-horseman-tests.ts | 11 + types/node-horseman/tsconfig.json | 24 ++ types/node-horseman/tslint.json | 1 + 4 files changed, 277 insertions(+) create mode 100644 types/node-horseman/index.d.ts create mode 100644 types/node-horseman/node-horseman-tests.ts create mode 100644 types/node-horseman/tsconfig.json create mode 100644 types/node-horseman/tslint.json diff --git a/types/node-horseman/index.d.ts b/types/node-horseman/index.d.ts new file mode 100644 index 0000000000..46ca810233 --- /dev/null +++ b/types/node-horseman/index.d.ts @@ -0,0 +1,241 @@ +// Type definitions for node-horseman 3.3 +// Project: https://github.com/johntitus/node-horseman#readme +// Definitions by: Pratheek Adidela +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.2 + +export = horseman; + +declare class horseman { + constructor(options: any); + /** Handle page events inside PhantomJS. Phantom receives callback return value with .at but not with .on */ + at(eventType: string, callback: () => void): this; + + /** Get the value of an attribute for a selector. */ + attribute(selector: string, attr: string): string; + + /** Use basic HTTP authentication when opening a page. */ + authentication(username: string, password: string): this; + + /** Go back a page. */ + back(): this; + + /** Get the bounding rectangle of a selector. */ + boundingRectangle(selector: string): ClientRect; + + /** Clear an input field. */ + clear(selector: string): any; + + /** Click on a selector and fire a 'click event'. */ + click(selector: string): this; + + /** Close the instance and perform cleanup. */ + close(): this; + + /** Close a tab and release its resources. */ + closeTab(tabNumber: string): this; + + /** Set the cookies for Phantom. */ + cookies(args: object | object[] | string): this; + /** Get the cookies from Phantom. */ + cookies(): string; + + /** Count the number of occurances of 'selector' on the page. */ + count(selector: string): number; + + /** Save a cropped screenshot to disk. */ + crop(area: string | object, path: string): this; + + /** Take a base64 encoded cropped screenshot. */ + cropBase64(area: string, type: string | 'PNG'): any; + + /** Get the value of an css property of a selector. */ + cssProperty(selector: string, prop: string): string; + + /** Execute a function without breaking the api chain. */ + do(fn: () => void): this; + + /** Download a URL. */ + download(url: string, path: string, binary: boolean, method: string, data: string): this; + + /** Run a javascript function on the current page and optionally return the results. */ + evaluate(fn: () => void, args?: any[]): this; + + /** Determine if the selector exists, at least once, on the page. */ + exists(selector: string): boolean; + + /** Go forward a page. */ + forward(): this; + + /** Get the count of frames inside the current frame. */ + frameCount(): number; + + /** Get the name of the current frame. */ + frameName(): string; + + /** Get the names of the frames inside the current frame. */ + frameNames(): string; + + /** Set headers sent to the remote server during an 'open'. */ + headers(headers: object[]): this; + + /** Get the height of an element. */ + height(selector: string): number; + + /** Get the HTML for the page, or optionally for a selector. */ + html(selector?: string, file?: string): Promise; + + /** Includes javascript script from a url on the page. */ + includeJs(url: string): this; + + /** Injects javascript from a file into the page. */ + injectJs(file: string): this; + + /** Fire a key event. */ + keyboardEvent(type?: string, key?: string, modifier?: number): this; + + /** Log the output from either a previous chain method, or a string the user passed in. */ + log(output?: string): this; + + /** Run javascript on the page. */ + manipulate(fn: () => void, args?: any[]): this; + + /** Fire a mouse event. */ + mouseEvent(type?: string, x?: number, y?: number, button?: string): this; + + /** Handles page events. * eventType can be one of: + * initialized - callback() + * loadStarted - callback() + * loadFinished - callback(status) + * tabCreated - callback(tabNum, tab) + * tabClosed - callback(tabNum, tab) + * urlChanged - callback(targetUrl) + * navigationRequested - callback(url, type, willNavigate, main) + * resourceRequested - callback(requestData, networkRequest) + * resourceReceived - callback(response) + * pageCreated - callback(newPage) + * consoleMessage(msg, lineNum, sourceId) + * alert - callback(msg) + * confirm - callback(msg) + * prompt - callback(msg, defaultVal) + * filePicker - callback(oldFile) + * error - callback(msg, trace); + * timeout - callback(type) + */ + on(event: string | "timeout" | "tabCreated" | "tabClosed"| "resourceTimeout"| "urlChanged"| "resourceReceived"| "pageCreated"| "loadFinished", func: (...args: any[]) => void): this; + + /** Open a url in Phantom. */ + open(url: string, method?: string | 'GET'): this; + + /** Open URL in a new tab */ + openTab(url: string): this; + + pageMaker(url: any, _page: any, ...args: any[]): any; + + /** Save the current page as a pdf. */ + pdf(path: string, paperSize: { + format?: "A3" | "A4" | "A5" | "Legal" | "Letter" | "Tabloid", + orientation?: "portrait" | "landscape", + margin?: string + }): this; + + /** Get the plain text for the body of the page. */ + plainText(): string; + + /** Send Post data to a url. */ + post(url: string, postData: string): this; + + /** Send Put data to a url. */ + put(url: string, putData: string): this; + + /** Reload the page. */ + reload(): this; + + /** Save a screenshot to disk. */ + screenshot(path: string): this; + + /** Take a base64 encoded screenshot, e.g., PNG. */ + screenshotBase64(type: string | 'PNG'): any; + + /** Scroll to a position on the page. */ + scrollTo(top: number, left: number): this; + + /** Select a value in an html select element. */ + select(selector: string, value: string): any; + + /** Change the proxy settings. */ + setProxy(ip: string, port: string, type: string, username: string, password: string): this; + + /** Get the HTTP status of the last opened page. */ + status(): string; + + /** Switch to a child frame. */ + switchToChildFrame(nameOrPosition: string | number): this; + + /** Switch to the focused frame. */ + switchToFocusedFrame(): this; + + /** Switch to a frame inside the current frame. */ + switchToFrame(nameOrPosition: string | number): this; + + /** Switch to the main frame. */ + switchToMainFrame(): this; + + /** Switch to the parent frame of the current frame. */ + switchToParentFrame(): this; + + /** Switch to another of the open tabs */ + switchToTab(tabNumber: number): this; + + /** Returns the number of tabs */ + tabCount(): number; + + /** Get the text for the body of the page, or optionally for a selector. */ + text(selector?: string): string; + + /** Get the title of the current page. */ + title(): string; + + /** Simulate a keypress on a selector */ + type(selector: string, text: string, options?: object): this; + + /** Upload a file to the page. */ + upload(selector: string, file: string): this; + + /** Get the url of the current page. */ + url(): string; + + /** Get or set the user agent for Phantom. */ + userAgent(...args: any[]): any; + + /** Get the value of an element. */ + value(selector: string): string; + /** Sets the value of an element. */ + value(selector: string, value: string): this; + + /** Set the size of the viewport. */ + viewport(width: number, height: number): this; + /** Get the size of the viewport. */ + viewport(): object; + + /** Determines if an element is visible. */ + visible(selector: string): boolean; + + /** Wait for a specified period of time */ + wait(milliseconds: number): this; + + /** Waits for a function to evaluate to a given value in browser. If optsOrFn is a function, use the classic signature waitFor(fn, arg1, arg2, value), If arg is an object, use waitFor(options). */ + waitFor(...args: any[]): this; + + /** Wait for a page load to occur */ + waitForNextPage(object?: object): this; + + /** Wait for a selector to be present on the current page. */ + waitForSelector(selector: string, options: object): this; + + /** Get the width of an element. */ + width(selector: string): number; + + /** Set the zoom factor of the page. */ + zoom(zoomFactor: number): this; +} diff --git a/types/node-horseman/node-horseman-tests.ts b/types/node-horseman/node-horseman-tests.ts new file mode 100644 index 0000000000..f1d81058f6 --- /dev/null +++ b/types/node-horseman/node-horseman-tests.ts @@ -0,0 +1,11 @@ +import horseman = require("node-horseman"); + +const horse = new horseman({ + timeout: 10000 +}); + +horse.on('error', (msg: any, trace: any) => { console.log(msg, trace); }) +.open("http://example.org/").waitForNextPage().html().then((pageContent: string) => { + console.log(pageContent); + horse.close(); +}); diff --git a/types/node-horseman/tsconfig.json b/types/node-horseman/tsconfig.json new file mode 100644 index 0000000000..5490648512 --- /dev/null +++ b/types/node-horseman/tsconfig.json @@ -0,0 +1,24 @@ +{ + "compilerOptions": { + "module": "commonjs", + "lib": [ + "es6", + "dom" + ], + "noImplicitAny": true, + "noImplicitThis": true, + "strictNullChecks": true, + "baseUrl": "../", + "strictFunctionTypes": true, + "typeRoots": [ + "../" + ], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true + }, + "files": [ + "index.d.ts", + "node-horseman-tests.ts" + ] +} diff --git a/types/node-horseman/tslint.json b/types/node-horseman/tslint.json new file mode 100644 index 0000000000..3db14f85ea --- /dev/null +++ b/types/node-horseman/tslint.json @@ -0,0 +1 @@ +{ "extends": "dtslint/dt.json" } From e86a56d0ccd8cf5d074e2cf5b0cc41acba663bf3 Mon Sep 17 00:00:00 2001 From: Jinwoo Lee Date: Thu, 19 Oct 2017 10:22:12 -0700 Subject: [PATCH 062/828] Node http2: statCheck() may also return `false`. (#20692) * Node http2: statCheck() may also return `false`. https://nodejs.org/dist/latest-v8.x/docs/api/http2.html#http2_http2stream_respondwithfile_path_headers_options says: The options.statCheck function may also be used to cancel the send operation by returning false Related node code: - https://github.com/nodejs/node/blob/master/lib/internal/http2/core.js#L1621 - https://github.com/nodejs/node/blob/master/lib/internal/http2/core.js#L1671 * add tests for returning false from statCheck() * change `void|false` to `void|boolean` * fix lint error --- types/node/index.d.ts | 2 +- types/node/node-tests.ts | 2 ++ 2 files changed, 3 insertions(+), 1 deletion(-) diff --git a/types/node/index.d.ts b/types/node/index.d.ts index d8e8fe3358..5d0ba05b93 100644 --- a/types/node/index.d.ts +++ b/types/node/index.d.ts @@ -6112,7 +6112,7 @@ declare module "http2" { } export interface ServerStreamFileResponseOptions { - statCheck?: (stats: fs.Stats, headers: IncomingHttpHeaders, statOptions: StatOptions) => void; + statCheck?: (stats: fs.Stats, headers: IncomingHttpHeaders, statOptions: StatOptions) => void|boolean; getTrailers?: (trailers: IncomingHttpHeaders) => void; offset?: number; length?: number; diff --git a/types/node/node-tests.ts b/types/node/node-tests.ts index c4cd693e03..7b36c859c7 100644 --- a/types/node/node-tests.ts +++ b/types/node/node-tests.ts @@ -3288,6 +3288,7 @@ namespace http2_tests { serverHttp2Stream.respondWithFD(0); serverHttp2Stream.respondWithFD(0, headers); serverHttp2Stream.respondWithFD(0, headers, options2); + serverHttp2Stream.respondWithFD(0, headers, {statCheck: () => false}); let options3: http2.ServerStreamFileResponseOptionsWithError = { onError: (err: NodeJS.ErrnoException) => {}, statCheck: (stats: fs.Stats, headers: http2.IncomingHttpHeaders, statOptions: http2.StatOptions) => {}, @@ -3298,6 +3299,7 @@ namespace http2_tests { serverHttp2Stream.respondWithFile(''); serverHttp2Stream.respondWithFile('', headers); serverHttp2Stream.respondWithFile('', headers, options3); + serverHttp2Stream.respondWithFile('', headers, {statCheck: () => false}); } // Http2Server / Http2SecureServer From 891a0d68419009e460948febd1d40f19b3efff4d Mon Sep 17 00:00:00 2001 From: Andy Date: Thu, 19 Oct 2017 11:29:04 -0700 Subject: [PATCH 063/828] dts-generator: Add dependency on "typescript" (#20730) --- types/dts-generator/package.json | 6 ++++++ 1 file changed, 6 insertions(+) create mode 100644 types/dts-generator/package.json diff --git a/types/dts-generator/package.json b/types/dts-generator/package.json new file mode 100644 index 0000000000..2195330f38 --- /dev/null +++ b/types/dts-generator/package.json @@ -0,0 +1,6 @@ +{ + "private": true, + "dependencies": { + "typescript": "*" + } +} From fec630a446d8cd1155d0d8e4f53a4bc119143e92 Mon Sep 17 00:00:00 2001 From: Stephen Ierodiaconou Date: Thu, 19 Oct 2017 19:34:06 +0100 Subject: [PATCH 064/828] [next-redux-wrapper] update to support new option param and export interfaces used in return types (#20732) * [next-redux-wrapper] update to support new option param and export interfaces used in return types * Revert change to package.json --- types/next-redux-wrapper/index.d.ts | 29 ++++++++++--------- .../next-redux-wrapper-tests.tsx | 2 +- types/next-redux-wrapper/package.json | 2 +- 3 files changed, 17 insertions(+), 16 deletions(-) diff --git a/types/next-redux-wrapper/index.d.ts b/types/next-redux-wrapper/index.d.ts index dae0cf3841..1f5945741b 100644 --- a/types/next-redux-wrapper/index.d.ts +++ b/types/next-redux-wrapper/index.d.ts @@ -14,7 +14,7 @@ */ import * as React from 'react'; -import { IncomingMessage } from 'http'; +import { IncomingMessage, ServerResponse } from 'http'; import { Store, Component, MapDispatchToPropsParam, MapStateToPropsParam, @@ -23,28 +23,28 @@ import { export = nextReduxWrapper; -interface NextPageComponentMethods { - getInitialProps(props: any): Promise; -} -type NextReduxWrappedComponent = React.Component & NextPageComponentMethods; - -type NextStoreCreator = ( - initialState: TInitialState, - options: nextReduxWrapper.StoreCreatorOptions -) => Store; - declare function nextReduxWrapper( options: nextReduxWrapper.Options -): (Component: Component) => NextReduxWrappedComponent; +): (Component: Component) => nextReduxWrapper.NextReduxWrappedComponent; declare function nextReduxWrapper( - createStore: NextStoreCreator, + createStore: nextReduxWrapper.NextStoreCreator, mapStateToProps?: MapStateToPropsParam, mapDispatchToProps?: MapDispatchToPropsParam, mergeProps?: MergeProps, options?: ConnectOptions -): (Component: Component) => NextReduxWrappedComponent; +): (Component: Component) => nextReduxWrapper.NextReduxWrappedComponent; declare namespace nextReduxWrapper { + interface NextPageComponentMethods { + getInitialProps(props: any): Promise; + } + type NextReduxWrappedComponent = React.Component & NextPageComponentMethods; + + type NextStoreCreator = ( + initialState: TInitialState, + options: StoreCreatorOptions + ) => Store; + interface Options { createStore: NextStoreCreator; debug?: boolean; @@ -57,6 +57,7 @@ declare namespace nextReduxWrapper { interface StoreCreatorOptions extends Options { isServer: boolean; req?: IncomingMessage; + res?: ServerResponse; query?: any; } diff --git a/types/next-redux-wrapper/next-redux-wrapper-tests.tsx b/types/next-redux-wrapper/next-redux-wrapper-tests.tsx index 37bd8af4b8..40069aeb8d 100644 --- a/types/next-redux-wrapper/next-redux-wrapper-tests.tsx +++ b/types/next-redux-wrapper/next-redux-wrapper-tests.tsx @@ -70,7 +70,7 @@ const com5 = withRedux( (initialState: InitialState, options: StoreCreatorOptions) => { - if (options.isServer || options.req || options.query) { + if (options.isServer || options.req || options.query || options.res) { const a = 1; } return createStore(reducer, initialState); diff --git a/types/next-redux-wrapper/package.json b/types/next-redux-wrapper/package.json index 4bcc170ca3..6d68bf2f9b 100644 --- a/types/next-redux-wrapper/package.json +++ b/types/next-redux-wrapper/package.json @@ -3,4 +3,4 @@ "dependencies": { "redux": "^3.6.0" } -} \ No newline at end of file +} From 254fb86815a697567662f27592dc1f07256ae6ba Mon Sep 17 00:00:00 2001 From: Simon McClive Date: Thu, 19 Oct 2017 19:38:48 +0100 Subject: [PATCH 065/828] Add types for parent-package-json (#20714) * Add types for parent-package-json * Update return type to false and restructure tests * Remove multiple calls of parent() in tests * Test optional properties --- types/parent-package-json/index.d.ts | 17 +++++++++++++ .../parent-package-json-tests.ts | 10 ++++++++ types/parent-package-json/tsconfig.json | 24 +++++++++++++++++++ types/parent-package-json/tslint.json | 3 +++ 4 files changed, 54 insertions(+) create mode 100644 types/parent-package-json/index.d.ts create mode 100644 types/parent-package-json/parent-package-json-tests.ts create mode 100644 types/parent-package-json/tsconfig.json create mode 100644 types/parent-package-json/tslint.json diff --git a/types/parent-package-json/index.d.ts b/types/parent-package-json/index.d.ts new file mode 100644 index 0000000000..b0ab9ec3ce --- /dev/null +++ b/types/parent-package-json/index.d.ts @@ -0,0 +1,17 @@ +// Type definitions for parent-package-json 2.0 +// Project: https://github.com/maxrimue/parent-package-json +// Definitions by: Simon McClive +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.2 + +export = ParentPackageJson; + +declare function ParentPackageJson(startPath?: string | null, ignore?: number): ParentPackageJson.ParentPackage | false; + +declare namespace ParentPackageJson { + interface ParentPackage { + read(): string; + path: string; + parse(): {[key: string]: any}; + } +} diff --git a/types/parent-package-json/parent-package-json-tests.ts b/types/parent-package-json/parent-package-json-tests.ts new file mode 100644 index 0000000000..41a5a7bdd0 --- /dev/null +++ b/types/parent-package-json/parent-package-json-tests.ts @@ -0,0 +1,10 @@ +import * as parent from 'parent-package-json'; + +const hasParent = parent('/optional/path/', 1); + +if (hasParent !== false) { + const pathToParent: string = hasParent.path; + const contentOfParent: string = hasParent.read(); + const JSONOfParent = hasParent.parse(); + const versionOfParent = JSONOfParent.version; +} diff --git a/types/parent-package-json/tsconfig.json b/types/parent-package-json/tsconfig.json new file mode 100644 index 0000000000..33d474c851 --- /dev/null +++ b/types/parent-package-json/tsconfig.json @@ -0,0 +1,24 @@ +{ + "compilerOptions": { + "module": "commonjs", + "lib": [ + "es6", + "dom" + ], + "noImplicitAny": true, + "noImplicitThis": true, + "strictNullChecks": true, + "strictFunctionTypes": true, + "baseUrl": "../", + "typeRoots": [ + "../" + ], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true + }, + "files": [ + "index.d.ts", + "parent-package-json-tests.ts" + ] +} diff --git a/types/parent-package-json/tslint.json b/types/parent-package-json/tslint.json new file mode 100644 index 0000000000..f93cf8562a --- /dev/null +++ b/types/parent-package-json/tslint.json @@ -0,0 +1,3 @@ +{ + "extends": "dtslint/dt.json" +} From c6343d34d85acebc46c81e6187cf86c3623b958e Mon Sep 17 00:00:00 2001 From: pr1st0n Date: Thu, 19 Oct 2017 22:06:32 +0300 Subject: [PATCH 066/828] Added definitions for clusterize.js --- types/clusterize.js/clusterize.js-tests.ts | 19 +++++++++++ types/clusterize.js/index.d.ts | 39 ++++++++++++++++++++++ types/clusterize.js/tsconfig.json | 23 +++++++++++++ types/clusterize.js/tslint.json | 1 + 4 files changed, 82 insertions(+) create mode 100644 types/clusterize.js/clusterize.js-tests.ts create mode 100644 types/clusterize.js/index.d.ts create mode 100644 types/clusterize.js/tsconfig.json create mode 100644 types/clusterize.js/tslint.json diff --git a/types/clusterize.js/clusterize.js-tests.ts b/types/clusterize.js/clusterize.js-tests.ts new file mode 100644 index 0000000000..e7e8359185 --- /dev/null +++ b/types/clusterize.js/clusterize.js-tests.ts @@ -0,0 +1,19 @@ +import Clusterize = require('clusterize.js'); + +const clusterize = new Clusterize({ contentId: '', scrollId: '' }); + +clusterize.append(['
  • ']); + +clusterize.prepend(['
  • ']); + +clusterize.getRowsAmount(); + +clusterize.update(['
  • ']); + +clusterize.getScrollProgress(); + +clusterize.refresh(); + +clusterize.clear(); + +clusterize.destroy(); diff --git a/types/clusterize.js/index.d.ts b/types/clusterize.js/index.d.ts new file mode 100644 index 0000000000..31b4f072ca --- /dev/null +++ b/types/clusterize.js/index.d.ts @@ -0,0 +1,39 @@ +// Type definitions for clusterize.js 0.17 +// Project: https://github.com/NeXTs/Clusterize.js +// Definitions by: My Self +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +declare class Clusterize { + constructor(options: ClusterizeOptions); + + destroy(clean?: boolean): void; + refresh(force?: boolean): void; + clear(): void; + getRowsAmount(): number; + getScrollProgress(): number; + update(data?: string[]): void; + append(rows: string[]): void; + prepend(rows: string[]): void; +} + +interface ClusterizeOptions { + scrollId: string; + contentId: string; + rows?: string[]; + tag?: string; + rows_in_block?: number; + blocks_in_cluster?: number; + show_no_data_row?: boolean; + no_data_text?: string; + no_data_class?: string; + keep_parity?: boolean; + callbacks?: ClusterizeCallbacks; +} + +interface ClusterizeCallbacks { + clusterWillChange?(cb: () => any): any; + clusterChanged?(cb: () => any): any; + scrollingProgress?(cb: (progress: number) => any): any; +} + +export = Clusterize; diff --git a/types/clusterize.js/tsconfig.json b/types/clusterize.js/tsconfig.json new file mode 100644 index 0000000000..319aca3588 --- /dev/null +++ b/types/clusterize.js/tsconfig.json @@ -0,0 +1,23 @@ +{ + "compilerOptions": { + "module": "commonjs", + "lib": [ + "es6" + ], + "noImplicitAny": true, + "noImplicitThis": true, + "strictNullChecks": true, + "strictFunctionTypes": false, + "baseUrl": "../", + "typeRoots": [ + "../" + ], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true + }, + "files": [ + "index.d.ts", + "clusterize.js-tests.ts" + ] +} diff --git a/types/clusterize.js/tslint.json b/types/clusterize.js/tslint.json new file mode 100644 index 0000000000..3db14f85ea --- /dev/null +++ b/types/clusterize.js/tslint.json @@ -0,0 +1 @@ +{ "extends": "dtslint/dt.json" } From d1daeda3b26820c140a33a68c62335cdd4456dc1 Mon Sep 17 00:00:00 2001 From: pr1st0n Date: Thu, 19 Oct 2017 22:28:55 +0300 Subject: [PATCH 067/828] Fixed definitions author. --- types/clusterize.js/index.d.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/types/clusterize.js/index.d.ts b/types/clusterize.js/index.d.ts index 31b4f072ca..beda96d79d 100644 --- a/types/clusterize.js/index.d.ts +++ b/types/clusterize.js/index.d.ts @@ -1,6 +1,6 @@ // Type definitions for clusterize.js 0.17 // Project: https://github.com/NeXTs/Clusterize.js -// Definitions by: My Self +// Definitions by: Pr1st0n // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped declare class Clusterize { From 18ab71a912052b27d2ab2af235865f3cd6cd74ae Mon Sep 17 00:00:00 2001 From: Andy Date: Thu, 19 Oct 2017 13:23:16 -0700 Subject: [PATCH 068/828] Additions to ISSUE_TEMPLATE (#20735) --- .github/ISSUE_TEMPLATE.md | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/.github/ISSUE_TEMPLATE.md b/.github/ISSUE_TEMPLATE.md index 4078b4808b..536e38c4e2 100644 --- a/.github/ISSUE_TEMPLATE.md +++ b/.github/ISSUE_TEMPLATE.md @@ -1,5 +1,9 @@ +If you know how to fix the issue, make a pull request instead. + - [ ] I tried using the `@types/xxxx` package and had problems. - [ ] I tried using the latest stable version of tsc. https://www.npmjs.com/package/typescript - [ ] I have a question that is inappropriate for [StackOverflow](https://stackoverflow.com/). (Please ask any appropriate questions there). - [ ] [Mention](https://github.com/blog/821-mention-somebody-they-re-notified) the authors (see `Definitions by:` in `index.d.ts`) so they can respond. - Authors: @.... + +If you do not mention the authors the issue will be ignored. From be60958bd85d1a2d63cfc3c403b06bad3635112b Mon Sep 17 00:00:00 2001 From: Andy Date: Thu, 19 Oct 2017 13:23:32 -0700 Subject: [PATCH 069/828] Mention strictFunctionTypes in PULL_REQUUEST_TEMPLATE (#20736) --- .github/PULL_REQUEST_TEMPLATE.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.github/PULL_REQUEST_TEMPLATE.md b/.github/PULL_REQUEST_TEMPLATE.md index 979a8311e0..4217471f9d 100644 --- a/.github/PULL_REQUEST_TEMPLATE.md +++ b/.github/PULL_REQUEST_TEMPLATE.md @@ -12,7 +12,7 @@ If adding a new definition: - [ ] The package does not provide its own types, and you can not add them. - [ ] If this is for an NPM package, match the name. If not, do not conflict with the name of an NPM package. - [ ] Create it with `dts-gen --dt`, not by basing it on an existing project. -- [ ] `tslint.json` should be present, and `tsconfig.json` should have `noImplicitAny`, `noImplicitThis`, and `strictNullChecks` set to `true`. +- [ ] `tslint.json` should be present, and `tsconfig.json` should have `noImplicitAny`, `noImplicitThis`, `strictNullChecks`, and `strictFunctionTypes` set to `true`. If changing an existing definition: - [ ] Provide a URL to documentation or source code which provides context for the suggested changes: <> From 8f53357a4cc054add2111f7c3a07a92541298b5c Mon Sep 17 00:00:00 2001 From: Andy Date: Thu, 19 Oct 2017 13:32:47 -0700 Subject: [PATCH 070/828] sequelize: Allow 'boolean' in WhereOptions (#20690) --- types/sequelize/index.d.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/types/sequelize/index.d.ts b/types/sequelize/index.d.ts index f1dc66fce5..f5b1befcc4 100644 --- a/types/sequelize/index.d.ts +++ b/types/sequelize/index.d.ts @@ -3108,7 +3108,7 @@ declare namespace sequelize { * typesafety, but there is no way to pass the tests if we just remove it. */ type WhereOptions = { - [P in keyof T]?: string | number | WhereLogic | WhereOptions | col | and | or | WhereGeometryOptions | Array | null; + [P in keyof T]?: string | number | boolean | WhereLogic | WhereOptions | col | and | or | WhereGeometryOptions | Array | null; }; /** From 149031f781bcd52fe8b13940d51bbe6feae289ca Mon Sep 17 00:00:00 2001 From: Andy Date: Thu, 19 Oct 2017 13:32:59 -0700 Subject: [PATCH 071/828] Update TypeScript versions of packages that depend on vue (#20733) --- types/vue-i18n/index.d.ts | 1 + types/vue-scrollto/index.d.ts | 1 + types/vue-scrollto/tsconfig.json | 1 + 3 files changed, 3 insertions(+) diff --git a/types/vue-i18n/index.d.ts b/types/vue-i18n/index.d.ts index 19225a83dd..030487a98b 100644 --- a/types/vue-i18n/index.d.ts +++ b/types/vue-i18n/index.d.ts @@ -2,6 +2,7 @@ // Project: https://github.com/kazupon/vue-i18n // Definitions by: Kombu // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.3 import Vue, { PluginFunction } from 'vue'; diff --git a/types/vue-scrollto/index.d.ts b/types/vue-scrollto/index.d.ts index e20879473f..5ca330d646 100644 --- a/types/vue-scrollto/index.d.ts +++ b/types/vue-scrollto/index.d.ts @@ -2,6 +2,7 @@ // Project: https://github.com/rigor789/vue-scrollto#readme // Definitions by: Kovács Vince // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.4 import { PluginFunction } from "vue"; diff --git a/types/vue-scrollto/tsconfig.json b/types/vue-scrollto/tsconfig.json index 6afe67dfcb..fd030de5e6 100644 --- a/types/vue-scrollto/tsconfig.json +++ b/types/vue-scrollto/tsconfig.json @@ -8,6 +8,7 @@ "noImplicitAny": true, "noImplicitThis": true, "strictNullChecks": true, + "strictFunctionTypes": true, "baseUrl": "../", "typeRoots": [ "../" From dd980c087a917ef4dc93cf4c3de6cab228fd8936 Mon Sep 17 00:00:00 2001 From: BehindTheMath Date: Thu, 19 Oct 2017 19:15:07 -0400 Subject: [PATCH 072/828] [github-username-regex] Add definitions (#20665) * [github-username-regex] Add definitions * [github-username-regex] Change to match CommonJS export format --- .../github-username-regex-tests.ts | 4 ++++ types/github-username-regex/index.d.ts | 7 ++++++ types/github-username-regex/tsconfig.json | 23 +++++++++++++++++++ types/github-username-regex/tslint.json | 1 + 4 files changed, 35 insertions(+) create mode 100644 types/github-username-regex/github-username-regex-tests.ts create mode 100644 types/github-username-regex/index.d.ts create mode 100644 types/github-username-regex/tsconfig.json create mode 100644 types/github-username-regex/tslint.json diff --git a/types/github-username-regex/github-username-regex-tests.ts b/types/github-username-regex/github-username-regex-tests.ts new file mode 100644 index 0000000000..d829752776 --- /dev/null +++ b/types/github-username-regex/github-username-regex-tests.ts @@ -0,0 +1,4 @@ +import githubUsernameRegex = require("github-username-regex"); + +const githubUsernameRegexString: string = githubUsernameRegex.source; +const valid: boolean = githubUsernameRegex.test("abc-123"); diff --git a/types/github-username-regex/index.d.ts b/types/github-username-regex/index.d.ts new file mode 100644 index 0000000000..59b3d703f7 --- /dev/null +++ b/types/github-username-regex/index.d.ts @@ -0,0 +1,7 @@ +// Type definitions for github-username-regex 1.0 +// Project: https://github.com/shinnn/github-username-regex +// Definitions by: BehindTheMath +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +declare const githubUsernameRegex: RegExp; +export = githubUsernameRegex; diff --git a/types/github-username-regex/tsconfig.json b/types/github-username-regex/tsconfig.json new file mode 100644 index 0000000000..4a30cf07ad --- /dev/null +++ b/types/github-username-regex/tsconfig.json @@ -0,0 +1,23 @@ +{ + "compilerOptions": { + "module": "commonjs", + "lib": [ + "es6" + ], + "noImplicitAny": true, + "noImplicitThis": true, + "strictNullChecks": true, + "strictFunctionTypes": true, + "baseUrl": "../", + "typeRoots": [ + "../" + ], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true + }, + "files": [ + "index.d.ts", + "github-username-regex-tests.ts" + ] +} diff --git a/types/github-username-regex/tslint.json b/types/github-username-regex/tslint.json new file mode 100644 index 0000000000..3db14f85ea --- /dev/null +++ b/types/github-username-regex/tslint.json @@ -0,0 +1 @@ +{ "extends": "dtslint/dt.json" } From d2cfe0ba3e1ecd6592700b346f4dae4957173e8a Mon Sep 17 00:00:00 2001 From: voxmatt Date: Thu, 19 Oct 2017 16:43:17 -0700 Subject: [PATCH 073/828] fixes for compat mode types when you're straddling modern and classic environments --- types/react-relay/compat.d.ts | 42 +++++++++++++---- types/react-relay/test/react-relay-tests.tsx | 47 +++++++++++++++++++- 2 files changed, 79 insertions(+), 10 deletions(-) diff --git a/types/react-relay/compat.d.ts b/types/react-relay/compat.d.ts index d214e451ae..527ef6fa42 100644 --- a/types/react-relay/compat.d.ts +++ b/types/react-relay/compat.d.ts @@ -1,13 +1,13 @@ export { QueryRenderer, - commitMutation, - createFragmentContainer, - createPaginationContainer, - createRefetchContainer, fetchQuery, graphql, } from "./index"; - +import { + ConnectionConfig, + RelayPaginationProp as RelayModernPaginationProp, + RelayRefetchProp as RelayModernRefetchProp +} from "./index"; import * as RelayRuntimeTypes from "relay-runtime"; import { RelayEnvironmentInterface } from "./classic"; @@ -33,34 +33,58 @@ export type ReactFragmentComponent = ComponentWithFragment | StatelessWith export type ReactBaseComponent = React.ComponentClass | React.StatelessComponent; export type RelayClassicEnvironment = RelayEnvironmentInterface; + // ~~~~~~~~~~~~~~~~~~~~~ // RelayCompatTypes // ~~~~~~~~~~~~~~~~~~~~~ export type CompatEnvironment = RelayRuntimeTypes.Environment | RelayClassicEnvironment; +// ~~~~~~~~~~~~~~~~~~~~~ +// RelayProps +// ~~~~~~~~~~~~~~~~~~~~~ +export interface RelayProp { + environment: CompatEnvironment; +} + +export type RelayPaginationProp = RelayModernPaginationProp & RelayProp; +export type RelayRefetchProp = RelayModernRefetchProp & RelayProp; + // ~~~~~~~~~~~~~~~~~~~~~ // RelayCompatMutations // ~~~~~~~~~~~~~~~~~~~~~ -export function commitUpdate( +export function commitMutation( environment: CompatEnvironment, config: RelayRuntimeTypes.MutationConfig ): RelayRuntimeTypes.Disposable; -export function applyUpdate( +export function applyOptimisticMutation( environment: CompatEnvironment, config: RelayRuntimeTypes.OptimisticMutationConfig ): RelayRuntimeTypes.Disposable; // ~~~~~~~~~~~~~~~~~~~~~ -// RelayCompatContainer +// RelayCompatContainers // ~~~~~~~~~~~~~~~~~~~~~ export interface GeneratedNodeMap { [key: string]: RelayRuntimeTypes.GraphQLTaggedNode; } -export function createContainer( + +export function createFragmentContainer( Component: ReactBaseComponent, fragmentSpec: RelayRuntimeTypes.GraphQLTaggedNode | GeneratedNodeMap ): ReactFragmentComponent; +export function createRefetchContainer( + Component: ReactBaseComponent, + fragmentSpec: RelayRuntimeTypes.GraphQLTaggedNode | GeneratedNodeMap, + taggedNode: RelayRuntimeTypes.GraphQLTaggedNode +): ReactFragmentComponent; + +export function createPaginationContainer( + Component: ReactBaseComponent, + fragmentSpec: RelayRuntimeTypes.GraphQLTaggedNode | GeneratedNodeMap, + connectionConfig: ConnectionConfig +): ReactFragmentComponent; + // ~~~~~~~~~~~~~~~~~~~~~ // injectDefaultVariablesProvider // ~~~~~~~~~~~~~~~~~~~~~ diff --git a/types/react-relay/test/react-relay-tests.tsx b/types/react-relay/test/react-relay-tests.tsx index 6caf997dba..612df078a1 100644 --- a/types/react-relay/test/react-relay-tests.tsx +++ b/types/react-relay/test/react-relay-tests.tsx @@ -332,9 +332,53 @@ requestSubscription( import { QueryRenderer as CompatQueryRenderer, createFragmentContainer as createFragmentContainerCompat, + commitMutation as commitMutationCompat, + CompatEnvironment, + RelayPaginationProp as RelayPaginationPropCompat, } from "react-relay/compat"; -// TODO? This is all more or less identical to modern... +// testting compat mutation with classic environment +function markNotificationAsReadCompat(environment: CompatEnvironment, source: string, storyID: string) { + const variables = { + input: { + source, + storyID, + }, + }; + + commitMutationCompat(environment, { + configs, + mutation, + optimisticResponse, + variables, + onCompleted: (response, errors) => { + console.log("Response received from server."); + }, + onError: err => console.error(err), + updater: (store, data) => { + const field = store.get(storyID); + if (field) { + field.setValue(data.story, "story"); + } + } + }); +} + +interface CompatProps { + relay: RelayPaginationPropCompat; +} + +export class CompatComponent extends React.Component { + markNotificationAsRead(source: string, storyID: string) { + markNotificationAsReadCompat(this.props.relay.environment, source, storyID); + } + + render() { + return (
    ); + } +} + +const CompatContainer = createFragmentContainerCompat(CompatComponent, {}); //////////////////////////// // RELAY-CLASSIC TESTS @@ -398,6 +442,7 @@ const ArtworkContainer = Relay.createContainer(Artwork, { artwork: () => Relay.QL` fragment on Artwork { title + ${ CompatContainer.getFragment('whatever') } } `, }, From f697a7ca1db4ca1a2a26c7379b4d6231caf8a628 Mon Sep 17 00:00:00 2001 From: voxmatt Date: Thu, 19 Oct 2017 16:59:00 -0700 Subject: [PATCH 074/828] fixing linting errors surfaced by Travis --- types/react-relay/compat.d.ts | 1 - types/react-relay/test/react-relay-tests.tsx | 2 +- 2 files changed, 1 insertion(+), 2 deletions(-) diff --git a/types/react-relay/compat.d.ts b/types/react-relay/compat.d.ts index 527ef6fa42..22585d03d0 100644 --- a/types/react-relay/compat.d.ts +++ b/types/react-relay/compat.d.ts @@ -33,7 +33,6 @@ export type ReactFragmentComponent = ComponentWithFragment | StatelessWith export type ReactBaseComponent = React.ComponentClass | React.StatelessComponent; export type RelayClassicEnvironment = RelayEnvironmentInterface; - // ~~~~~~~~~~~~~~~~~~~~~ // RelayCompatTypes // ~~~~~~~~~~~~~~~~~~~~~ diff --git a/types/react-relay/test/react-relay-tests.tsx b/types/react-relay/test/react-relay-tests.tsx index 612df078a1..f73b7c00c7 100644 --- a/types/react-relay/test/react-relay-tests.tsx +++ b/types/react-relay/test/react-relay-tests.tsx @@ -368,7 +368,7 @@ interface CompatProps { relay: RelayPaginationPropCompat; } -export class CompatComponent extends React.Component { +export class CompatComponent extends React.Component { markNotificationAsRead(source: string, storyID: string) { markNotificationAsReadCompat(this.props.relay.environment, source, storyID); } From 64b1289e185646ffffb2e23f3292dbbe19ebb09e Mon Sep 17 00:00:00 2001 From: pr1st0n Date: Fri, 20 Oct 2017 11:23:51 +0300 Subject: [PATCH 075/828] Review fixes. --- types/clusterize.js/clusterize.js-tests.ts | 3 +- types/clusterize.js/index.d.ts | 38 ++++++++++++---------- types/clusterize.js/tsconfig.json | 2 +- 3 files changed, 23 insertions(+), 20 deletions(-) diff --git a/types/clusterize.js/clusterize.js-tests.ts b/types/clusterize.js/clusterize.js-tests.ts index e7e8359185..acbfbc36f8 100644 --- a/types/clusterize.js/clusterize.js-tests.ts +++ b/types/clusterize.js/clusterize.js-tests.ts @@ -1,6 +1,7 @@ import Clusterize = require('clusterize.js'); -const clusterize = new Clusterize({ contentId: '', scrollId: '' }); +const options: Clusterize.Options = { contentId: '', scrollId: '' }; +const clusterize = new Clusterize(options); clusterize.append(['
  • ']); diff --git a/types/clusterize.js/index.d.ts b/types/clusterize.js/index.d.ts index beda96d79d..2d0e169c38 100644 --- a/types/clusterize.js/index.d.ts +++ b/types/clusterize.js/index.d.ts @@ -4,7 +4,7 @@ // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped declare class Clusterize { - constructor(options: ClusterizeOptions); + constructor(options: Clusterize.Options); destroy(clean?: boolean): void; refresh(force?: boolean): void; @@ -16,24 +16,26 @@ declare class Clusterize { prepend(rows: string[]): void; } -interface ClusterizeOptions { - scrollId: string; - contentId: string; - rows?: string[]; - tag?: string; - rows_in_block?: number; - blocks_in_cluster?: number; - show_no_data_row?: boolean; - no_data_text?: string; - no_data_class?: string; - keep_parity?: boolean; - callbacks?: ClusterizeCallbacks; -} +declare namespace Clusterize { + interface Options { + scrollId: string; + contentId: string; + rows?: string[]; + tag?: string; + rows_in_block?: number; + blocks_in_cluster?: number; + show_no_data_row?: boolean; + no_data_text?: string; + no_data_class?: string; + keep_parity?: boolean; + callbacks?: Callbacks; + } -interface ClusterizeCallbacks { - clusterWillChange?(cb: () => any): any; - clusterChanged?(cb: () => any): any; - scrollingProgress?(cb: (progress: number) => any): any; + interface Callbacks { + clusterWillChange?(cb: () => any): void; + clusterChanged?(cb: () => any): void; + scrollingProgress?(cb: (progress: number) => any): void; + } } export = Clusterize; diff --git a/types/clusterize.js/tsconfig.json b/types/clusterize.js/tsconfig.json index 319aca3588..10ca5c2a1a 100644 --- a/types/clusterize.js/tsconfig.json +++ b/types/clusterize.js/tsconfig.json @@ -7,7 +7,7 @@ "noImplicitAny": true, "noImplicitThis": true, "strictNullChecks": true, - "strictFunctionTypes": false, + "strictFunctionTypes": true, "baseUrl": "../", "typeRoots": [ "../" From 6deecd5aaf40a74c1ba43911ee1ffab97e4fca17 Mon Sep 17 00:00:00 2001 From: Viktor Isaev Date: Fri, 20 Oct 2017 17:09:01 +0300 Subject: [PATCH 076/828] Fixed types in "restify-cookies". (#20752) * Added typings for "require-dir". * Fixed dtslint errors. * Fixed By field. * Added typings for "restify-cookies". * Added "cookies" field to Request interface. * Added typings for "heapdump". * Fixed types in "restify-cookies". * Added sameSite field to types in "restify-cookies". * Bumped version for "restify-cookies". * Fixed version for "restify-cookies". --- types/restify-cookies/index.d.ts | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/types/restify-cookies/index.d.ts b/types/restify-cookies/index.d.ts index 7e794855cb..8f00f97538 100644 --- a/types/restify-cookies/index.d.ts +++ b/types/restify-cookies/index.d.ts @@ -11,9 +11,10 @@ declare module 'restify' { maxAge?: number; domain?: string; path?: string; - expires?: string; + expires?: Date; httpOnly?: boolean; secure?: boolean; + sameSite?: boolean|'lax'|'strict'; } interface Request { From 67a8a0fd9151c27321ef932ebae6622f4b6452b0 Mon Sep 17 00:00:00 2001 From: pr1st0n Date: Fri, 20 Oct 2017 17:21:20 +0300 Subject: [PATCH 077/828] Review fix. --- types/clusterize.js/index.d.ts | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/types/clusterize.js/index.d.ts b/types/clusterize.js/index.d.ts index 2d0e169c38..7c549761d6 100644 --- a/types/clusterize.js/index.d.ts +++ b/types/clusterize.js/index.d.ts @@ -32,9 +32,9 @@ declare namespace Clusterize { } interface Callbacks { - clusterWillChange?(cb: () => any): void; - clusterChanged?(cb: () => any): void; - scrollingProgress?(cb: (progress: number) => any): void; + clusterWillChange?(cb: () => void): void; + clusterChanged?(cb: () => void): void; + scrollingProgress?(cb: (progress: number) => void): void; } } From 7239c6a38d1454aeb7ecffa297292de9a96da6c3 Mon Sep 17 00:00:00 2001 From: Bogdan Date: Fri, 20 Oct 2017 17:21:38 +0300 Subject: [PATCH 078/828] new definition for youtube-dl (#20428) * new definition for youtube-dl * Could not parse version 2.5 * fixes * fixes * fixes * fixes * fixes * fixes * Prefer /// * few fixes * fixes * assert info: youtubedl.Info * fixes --- types/youtube-dl/index.d.ts | 22 ++++++++++++++++++++++ types/youtube-dl/tsconfig.json | 21 +++++++++++++++++++++ types/youtube-dl/tslint.json | 1 + types/youtube-dl/youtube-dl-tests.ts | 18 ++++++++++++++++++ 4 files changed, 62 insertions(+) create mode 100644 types/youtube-dl/index.d.ts create mode 100644 types/youtube-dl/tsconfig.json create mode 100644 types/youtube-dl/tslint.json create mode 100644 types/youtube-dl/youtube-dl-tests.ts diff --git a/types/youtube-dl/index.d.ts b/types/youtube-dl/index.d.ts new file mode 100644 index 0000000000..4daf21884b --- /dev/null +++ b/types/youtube-dl/index.d.ts @@ -0,0 +1,22 @@ +// Type definitions for youtube-dl 1.12 +// Project: https://www.npmjs.com/package/youtube-dl +// Definitions by: Bogdan Surai +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.4 + +/// +import * as fs from "fs"; + +export = youtubedl; +declare function youtubedl(url: string, arg: string[], opt: {[key: string]: string}): youtubedl.Youtubedl; +declare namespace youtubedl { + interface Youtubedl { + on(event: string, func: (info: Info) => void): this; + pipe(stream: fs.WriteStream): this; + } + interface Info { + _filename: string; + filename: string; + size: number; + } +} diff --git a/types/youtube-dl/tsconfig.json b/types/youtube-dl/tsconfig.json new file mode 100644 index 0000000000..2634bd2234 --- /dev/null +++ b/types/youtube-dl/tsconfig.json @@ -0,0 +1,21 @@ +{ + "files": [ + "index.d.ts", + "youtube-dl-tests.ts" + ], + "compilerOptions": { + "module": "commonjs", + "lib": ["es6"], + "noImplicitAny": true, + "noImplicitThis": true, + "strictNullChecks": true, + "strictFunctionTypes": true, + "baseUrl": "../", + "typeRoots": [ + "../" + ], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true + } +} \ No newline at end of file diff --git a/types/youtube-dl/tslint.json b/types/youtube-dl/tslint.json new file mode 100644 index 0000000000..2750cc0197 --- /dev/null +++ b/types/youtube-dl/tslint.json @@ -0,0 +1 @@ +{ "extends": "dtslint/dt.json" } \ No newline at end of file diff --git a/types/youtube-dl/youtube-dl-tests.ts b/types/youtube-dl/youtube-dl-tests.ts new file mode 100644 index 0000000000..c85b1ffc92 --- /dev/null +++ b/types/youtube-dl/youtube-dl-tests.ts @@ -0,0 +1,18 @@ +import * as fs from 'fs'; +import youtubedl = require('youtube-dl'); + +const video = youtubedl('http://www.youtube.com/watch?v=90AiXO1pAiA', + // Optional arguments passed to youtube-dl. + ['--format=18'], + // Additional options can be given for calling `child_process.execFile()`. + { cwd: __dirname }); + +// Will be called when the download starts. +video.on('info', (info: youtubedl.Info) => { + console.log('Download started'); + console.log('_filename: ' + info._filename); + console.log('filename: ' + info.filename); + console.log('size: ' + info.size); +}); + +video.pipe(fs.createWriteStream('myvideo.mp4')); From 490c4210d68c8bb0b271b39695eec76016cebbf4 Mon Sep 17 00:00:00 2001 From: Philipp Shestakov Date: Fri, 20 Oct 2017 17:25:57 +0300 Subject: [PATCH 079/828] Added definitions for clusterize.js (#20738) * Added definitions for clusterize.js * Fixed definitions author. * Review fixes. * Review fix. --- types/clusterize.js/clusterize.js-tests.ts | 20 +++++++++++ types/clusterize.js/index.d.ts | 41 ++++++++++++++++++++++ types/clusterize.js/tsconfig.json | 23 ++++++++++++ types/clusterize.js/tslint.json | 1 + 4 files changed, 85 insertions(+) create mode 100644 types/clusterize.js/clusterize.js-tests.ts create mode 100644 types/clusterize.js/index.d.ts create mode 100644 types/clusterize.js/tsconfig.json create mode 100644 types/clusterize.js/tslint.json diff --git a/types/clusterize.js/clusterize.js-tests.ts b/types/clusterize.js/clusterize.js-tests.ts new file mode 100644 index 0000000000..acbfbc36f8 --- /dev/null +++ b/types/clusterize.js/clusterize.js-tests.ts @@ -0,0 +1,20 @@ +import Clusterize = require('clusterize.js'); + +const options: Clusterize.Options = { contentId: '', scrollId: '' }; +const clusterize = new Clusterize(options); + +clusterize.append(['
  • ']); + +clusterize.prepend(['
  • ']); + +clusterize.getRowsAmount(); + +clusterize.update(['
  • ']); + +clusterize.getScrollProgress(); + +clusterize.refresh(); + +clusterize.clear(); + +clusterize.destroy(); diff --git a/types/clusterize.js/index.d.ts b/types/clusterize.js/index.d.ts new file mode 100644 index 0000000000..7c549761d6 --- /dev/null +++ b/types/clusterize.js/index.d.ts @@ -0,0 +1,41 @@ +// Type definitions for clusterize.js 0.17 +// Project: https://github.com/NeXTs/Clusterize.js +// Definitions by: Pr1st0n +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +declare class Clusterize { + constructor(options: Clusterize.Options); + + destroy(clean?: boolean): void; + refresh(force?: boolean): void; + clear(): void; + getRowsAmount(): number; + getScrollProgress(): number; + update(data?: string[]): void; + append(rows: string[]): void; + prepend(rows: string[]): void; +} + +declare namespace Clusterize { + interface Options { + scrollId: string; + contentId: string; + rows?: string[]; + tag?: string; + rows_in_block?: number; + blocks_in_cluster?: number; + show_no_data_row?: boolean; + no_data_text?: string; + no_data_class?: string; + keep_parity?: boolean; + callbacks?: Callbacks; + } + + interface Callbacks { + clusterWillChange?(cb: () => void): void; + clusterChanged?(cb: () => void): void; + scrollingProgress?(cb: (progress: number) => void): void; + } +} + +export = Clusterize; diff --git a/types/clusterize.js/tsconfig.json b/types/clusterize.js/tsconfig.json new file mode 100644 index 0000000000..10ca5c2a1a --- /dev/null +++ b/types/clusterize.js/tsconfig.json @@ -0,0 +1,23 @@ +{ + "compilerOptions": { + "module": "commonjs", + "lib": [ + "es6" + ], + "noImplicitAny": true, + "noImplicitThis": true, + "strictNullChecks": true, + "strictFunctionTypes": true, + "baseUrl": "../", + "typeRoots": [ + "../" + ], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true + }, + "files": [ + "index.d.ts", + "clusterize.js-tests.ts" + ] +} diff --git a/types/clusterize.js/tslint.json b/types/clusterize.js/tslint.json new file mode 100644 index 0000000000..3db14f85ea --- /dev/null +++ b/types/clusterize.js/tslint.json @@ -0,0 +1 @@ +{ "extends": "dtslint/dt.json" } From ed5cfecfd7ae7ce0a4a2c6911ffa4f5c05fbef83 Mon Sep 17 00:00:00 2001 From: Jacek Dargiel Date: Fri, 20 Oct 2017 17:17:25 +0200 Subject: [PATCH 080/828] Add ChartLayoutOptions (#20758) --- types/chart.js/index.d.ts | 13 +++++++++++++ 1 file changed, 13 insertions(+) diff --git a/types/chart.js/index.d.ts b/types/chart.js/index.d.ts index 78f1aa6142..7d416ff6c5 100644 --- a/types/chart.js/index.d.ts +++ b/types/chart.js/index.d.ts @@ -160,6 +160,7 @@ declare namespace Chart { hover?: ChartHoverOptions; animation?: ChartAnimationOptions; elements?: ChartElementsOptions; + layout?: ChartLayoutOptions; scales?: ChartScales; showLines?: boolean; spanGaps?: boolean; @@ -312,6 +313,18 @@ declare namespace Chart { borderColor?: ChartColor; borderSkipped?: string; } + + interface ChartLayoutOptions { + padding?: ChartLayoutPaddingObject | number; + } + + interface ChartLayoutPaddingObject { + top?: number; + right?: number; + bottom?: number; + left?: number; + } + interface GridLineOptions { display?: boolean; color?: ChartColor; From 2753c44ac158c13db00c111153195062ca23df36 Mon Sep 17 00:00:00 2001 From: Nikolay Solovyov Date: Fri, 20 Oct 2017 18:17:49 +0300 Subject: [PATCH 081/828] Update index.d.ts (#20756) `activeIndex` and `activeShape` is optional parameters. Also, `activeIndex` can contains numbers and array of numbers, not an array of any. --- types/recharts/index.d.ts | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/types/recharts/index.d.ts b/types/recharts/index.d.ts index 95656a7247..404fe5c444 100644 --- a/types/recharts/index.d.ts +++ b/types/recharts/index.d.ts @@ -345,8 +345,8 @@ export interface PieProps extends Partial { label?: boolean | any | React.ReactElement | RechartsFunction; labelLine?: boolean | any | React.ReactElement | RechartsFunction; data: any[]; - activeIndex: any[]; - activeShape: any | React.ReactElement | RechartsFunction; + activeIndex?: number | number[]; + activeShape?: any | React.ReactElement | RechartsFunction; isAnimationActive?: boolean; animationBegin?: number; animationEasing?: AnimationEasingType | RechartsFunction; From a41f8d2ddd0d325a0da5fb0b996da6897f8f50ae Mon Sep 17 00:00:00 2001 From: Piotr Roszatycki Date: Fri, 20 Oct 2017 17:21:44 +0200 Subject: [PATCH 082/828] nodemailer: version 4.2 (#20754) --- types/nodemailer/index.d.ts | 2 +- types/nodemailer/lib/smtp-connection.d.ts | 6 ++++++ types/nodemailer/nodemailer-tests.ts | 1 - 3 files changed, 7 insertions(+), 2 deletions(-) diff --git a/types/nodemailer/index.d.ts b/types/nodemailer/index.d.ts index da0605ddcf..6a587bb720 100644 --- a/types/nodemailer/index.d.ts +++ b/types/nodemailer/index.d.ts @@ -1,4 +1,4 @@ -// Type definitions for Nodemailer 4.1 +// Type definitions for Nodemailer 4.2 // Project: https://github.com/nodemailer/nodemailer // Definitions by: Rogier Schouten // Piotr Roszatycki diff --git a/types/nodemailer/lib/smtp-connection.d.ts b/types/nodemailer/lib/smtp-connection.d.ts index a2cb095210..49b1adef8e 100644 --- a/types/nodemailer/lib/smtp-connection.d.ts +++ b/types/nodemailer/lib/smtp-connection.d.ts @@ -88,6 +88,12 @@ declare namespace SMTPConnection { rejectedErrors?: SMTPError[]; /** the last response received from the server */ response: string; + /** how long was envelope prepared */ + envelopeTime: number; + /** how long was send stream prepared */ + messageTime: number; + /** how many bytes were streamed */ + messageSize: number; } interface Options { diff --git a/types/nodemailer/nodemailer-tests.ts b/types/nodemailer/nodemailer-tests.ts index 8baff03674..cb2cd9641f 100644 --- a/types/nodemailer/nodemailer-tests.ts +++ b/types/nodemailer/nodemailer-tests.ts @@ -1036,7 +1036,6 @@ namespace smtp_connection_test { if (err) throw err; connection.send({ from: 'a@example.com', to: 'b@example.net' }, 'message', (err, info) => { if (err) throw err; - console.log(info); connection.reset(() => { if (err) throw err; connection.quit(); From 399af551e6963ceca3b7ad15b0cc14f3708d1d24 Mon Sep 17 00:00:00 2001 From: Diogo Franco Date: Sat, 21 Oct 2017 00:28:12 +0900 Subject: [PATCH 083/828] [react-router] Fix for --strictFunctionTypes (#20746) * [react-router] Fix for --strictFunctionTypes It seems it's not possible for a SFC to conform to React.ComponentType | {}> with both strictFunctionTypes and strictNullChecks (they have to either be `Partial>` or `{}`). The whole point of the `| {}` is to allow for components that have defaulted `Props` / don't use any `Props` anyway, so adding it as another listed type should work. * Fix dtslint errors --- types/react-router/index.d.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/types/react-router/index.d.ts b/types/react-router/index.d.ts index bfb5f16e7b..4e547c8341 100644 --- a/types/react-router/index.d.ts +++ b/types/react-router/index.d.ts @@ -65,7 +65,7 @@ export interface RouteComponentProps

    { export interface RouteProps { location?: H.Location; - component?: React.ComponentType | {}>; + component?: React.ComponentType> | React.ComponentType; render?: ((props: RouteComponentProps) => React.ReactNode); children?: ((props: RouteComponentProps) => React.ReactNode) | React.ReactNode; path?: string; From 25af4237d27e89e49166b007861a8e9ee5370329 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Bj=C3=B6rn=20Tegelund?= Date: Sat, 21 Oct 2017 00:28:27 +0900 Subject: [PATCH 084/828] Add passHref to Link (#20745) --- types/next/link.d.ts | 1 + 1 file changed, 1 insertion(+) diff --git a/types/next/link.d.ts b/types/next/link.d.ts index aca3190f7e..d931dd550d 100644 --- a/types/next/link.d.ts +++ b/types/next/link.d.ts @@ -10,6 +10,7 @@ export interface LinkState { onError?(error: any): void; href?: string | UrlLike; as?: string | UrlLike; + passHref?: boolean; children: React.ReactElement; } From 3bb8a665130be3304a81d52279d0b227f10ebd59 Mon Sep 17 00:00:00 2001 From: Cory Deppen Date: Fri, 20 Oct 2017 10:28:39 -0500 Subject: [PATCH 085/828] [redux-logger] Add optional logEntry param to LoggerPredicate (#20740) * Add optional logEntry param to LoggerPredicate * Enable linting Resolve errors and comply with DT formatting recommendations. --- types/redux-logger/index.d.ts | 64 ++++++---- types/redux-logger/package.json | 2 +- types/redux-logger/redux-logger-tests.ts | 152 ++++++++++++----------- types/redux-logger/tsconfig.json | 16 +-- types/redux-logger/tslint.json | 3 + 5 files changed, 125 insertions(+), 112 deletions(-) create mode 100644 types/redux-logger/tslint.json diff --git a/types/redux-logger/index.d.ts b/types/redux-logger/index.d.ts index d60d3ad218..c8ca66eda0 100644 --- a/types/redux-logger/index.d.ts +++ b/types/redux-logger/index.d.ts @@ -1,4 +1,4 @@ -// Type definitions for redux-logger v3.0.0 +// Type definitions for redux-logger 3.0 // Project: https://github.com/fcomb/redux-logger // Definitions by: Alexander Rusakov // Kevin Groat @@ -6,45 +6,59 @@ export as namespace ReduxLogger; -import * as Redux from "redux"; +import * as Redux from 'redux'; export const logger: Redux.Middleware; -export type LoggerPredicate = (getState: () => any, action: any) => boolean; +export type LoggerPredicate = ( + getState: () => any, + action: any, + logEntry?: LogEntryObject +) => boolean; export type StateToString = (state: any) => string; export type ActionToString = (action: any) => string; export type ErrorToString = (error: any, prevState: any) => string; export interface ColorsObject { - title?: boolean | ActionToString; - prevState?: boolean | StateToString; - action?: boolean | ActionToString; - nextState?: boolean | StateToString; - error?: boolean | ErrorToString; + title?: boolean | ActionToString; + prevState?: boolean | StateToString; + action?: boolean | ActionToString; + nextState?: boolean | StateToString; + error?: boolean | ErrorToString; } export interface LevelObject { - prevState?: string | boolean | StateToString; - action?: string | boolean | ActionToString; - nextState?: string | boolean | StateToString; - error?: string | boolean | ErrorToString; + prevState?: string | boolean | StateToString; + action?: string | boolean | ActionToString; + nextState?: string | boolean | StateToString; + error?: string | boolean | ErrorToString; +} + +export interface LogEntryObject { + action?: string | boolean | ActionToString; + started?: number; + startedTime?: Date; + took?: number; + error?(error: any): any; + nextState?(state: any): any; + prevState?(state: any): any; } export interface ReduxLoggerOptions { - level?: string | ActionToString | LevelObject; - duration?: boolean; - timestamp?: boolean; - colors?: ColorsObject | false; - logger?: any; - logErrors?: boolean; - collapsed?: boolean | LoggerPredicate; - predicate?: LoggerPredicate; - stateTransformer?: (state: any) => any; - actionTransformer?: (action: any) => any; - errorTransformer?: (error: any) => any; - diff?: boolean; - diffPredicate?: LoggerPredicate; + level?: string | ActionToString | LevelObject; + duration?: boolean; + timestamp?: boolean; + colors?: ColorsObject | false; + logger?: any; + logErrors?: boolean; + collapsed?: boolean | LoggerPredicate; + predicate?: LoggerPredicate; + diff?: boolean; + diffPredicate?: LoggerPredicate; + stateTransformer?(state: any): any; + actionTransformer?(action: any): any; + errorTransformer?(error: any): any; } export function createLogger(options?: ReduxLoggerOptions): Redux.Middleware; diff --git a/types/redux-logger/package.json b/types/redux-logger/package.json index 4bcc170ca3..6d68bf2f9b 100644 --- a/types/redux-logger/package.json +++ b/types/redux-logger/package.json @@ -3,4 +3,4 @@ "dependencies": { "redux": "^3.6.0" } -} \ No newline at end of file +} diff --git a/types/redux-logger/redux-logger-tests.ts b/types/redux-logger/redux-logger-tests.ts index 7349e556c4..a3b77debd8 100644 --- a/types/redux-logger/redux-logger-tests.ts +++ b/types/redux-logger/redux-logger-tests.ts @@ -1,100 +1,104 @@ - -import { createLogger } from 'redux-logger'; -import logger from 'redux-logger'; +import logger, { createLogger } from 'redux-logger'; import { applyMiddleware, createStore } from 'redux'; -let loggerSimple = createLogger(); +const loggerSimple = createLogger(); -let loggerSimpleOpts = createLogger({ - duration: true, - timestamp: true, - logger: console, - logErrors: true, - predicate: (getState, action) => true, - stateTransformer: (state) => state, - actionTransformer: (action) => action, - errorTransformer: (error) => error, - diff: true, - diffPredicate: (getState, action) => true, +const loggerSimpleOpts = createLogger({ + duration: true, + timestamp: true, + logger: console, + logErrors: true, + predicate: (getState, action) => true, + stateTransformer: state => state, + actionTransformer: action => action, + errorTransformer: error => error, + diff: true, + diffPredicate: (getState, action) => true }); -let loggerCollapsedBool = createLogger({ - collapsed: true +const loggerCollapsedBool = createLogger({ + collapsed: true }); -let loggerCollapsedPredicate = createLogger({ - collapsed: (getAction, action) => true +const loggerCollapsedPredicate = createLogger({ + collapsed: (getAction, action) => true }); -let loggerColorsOverallBoolean = createLogger({ - colors: false +const loggerCollapsedLogEntryPredicate = createLogger({ + collapsed: (getAction, action, logEntry) => + logEntry !== undefined && !logEntry.error }); -let loggerColorsBoolean = createLogger({ - colors: { - title: false, - prevState: false, - action: false, - nextState: false, - error: false - } +const loggerColorsOverallBoolean = createLogger({ + colors: false }); -let loggerColorsFunction = createLogger({ - colors: { - title: (action) => '#000', - prevState: (state) => '#000', - action: (action) => '#000', - nextState: (state) => '#000', - error: (error, prevState) => '#000' - } +const loggerColorsBoolean = createLogger({ + colors: { + title: false, + prevState: false, + action: false, + nextState: false, + error: false + } }); -let loggerLevelString = createLogger({ - level: 'log' +const loggerColorsFunction = createLogger({ + colors: { + title: action => '#000', + prevState: state => '#000', + action: action => '#000', + nextState: state => '#000', + error: (error, prevState) => '#000' + } }); -let loggerLevelFunction = createLogger({ - level: (action) => 'log' +const loggerLevelString = createLogger({ + level: 'log' }); -let loggerLevelObjectFunction = createLogger({ - level: { - prevState: (state) => 'log', - action: (action) => 'log', - nextState: (state) => 'log', - error: (error, prevState) => 'log' - } +const loggerLevelFunction = createLogger({ + level: action => 'log' }); -let loggerLevelObjectBoolean = createLogger({ - level: { - prevState: false, - action: false, - nextState: false, - error: false - } +const loggerLevelObjectFunction = createLogger({ + level: { + prevState: state => 'log', + action: action => 'log', + nextState: state => 'log', + error: (error, prevState) => 'log' + } }); -let loggerLevelObjectString = createLogger({ - level: { - prevState: 'log', - action: 'log', - nextState: 'log', - error: 'log' - } +const loggerLevelObjectBoolean = createLogger({ + level: { + prevState: false, + action: false, + nextState: false, + error: false + } }); -let createStoreWithMiddleware = applyMiddleware( - logger, - loggerSimpleOpts, - loggerCollapsedBool, - loggerCollapsedPredicate, - loggerColorsBoolean, - loggerColorsFunction, - loggerLevelString, - loggerLevelFunction, - loggerLevelObjectFunction, - loggerLevelObjectBoolean, - loggerLevelObjectString +const loggerLevelObjectString = createLogger({ + level: { + prevState: 'log', + action: 'log', + nextState: 'log', + error: 'log' + } +}); + +const createStoreWithMiddleware = applyMiddleware( + logger, + loggerSimpleOpts, + loggerCollapsedBool, + loggerCollapsedPredicate, + loggerCollapsedLogEntryPredicate, + loggerColorsBoolean, + loggerColorsFunction, + loggerLevelString, + loggerLevelFunction, + loggerLevelObjectFunction, + loggerLevelObjectBoolean, + loggerLevelObjectString )(createStore); diff --git a/types/redux-logger/tsconfig.json b/types/redux-logger/tsconfig.json index 7441f646d7..1789641398 100644 --- a/types/redux-logger/tsconfig.json +++ b/types/redux-logger/tsconfig.json @@ -1,24 +1,16 @@ { "compilerOptions": { "module": "commonjs", - "lib": [ - "es6", - "dom" - ], + "lib": ["es6", "dom"], "noImplicitAny": true, "noImplicitThis": false, "strictNullChecks": false, "strictFunctionTypes": true, "baseUrl": "../", - "typeRoots": [ - "../" - ], + "typeRoots": ["../"], "types": [], "noEmit": true, "forceConsistentCasingInFileNames": true }, - "files": [ - "index.d.ts", - "redux-logger-tests.ts" - ] -} \ No newline at end of file + "files": ["index.d.ts", "redux-logger-tests.ts"] +} diff --git a/types/redux-logger/tslint.json b/types/redux-logger/tslint.json new file mode 100644 index 0000000000..f93cf8562a --- /dev/null +++ b/types/redux-logger/tslint.json @@ -0,0 +1,3 @@ +{ + "extends": "dtslint/dt.json" +} From fee527c10343127ea695ac1370e893d60d0558d6 Mon Sep 17 00:00:00 2001 From: UrielCh Date: Fri, 20 Oct 2017 18:28:54 +0300 Subject: [PATCH 086/828] update CasperJS 1.0.29 to 1.1.4 (#20739) * update CasperJS 1.0.29 to 1.1.4 remove most oh the any type Set Optional parameter As Optional. * tslint casperJS --- types/casperjs/index.d.ts | 173 +++++++++++++++++++++++-------------- types/casperjs/tslint.json | 12 +++ 2 files changed, 119 insertions(+), 66 deletions(-) create mode 100644 types/casperjs/tslint.json diff --git a/types/casperjs/index.d.ts b/types/casperjs/index.d.ts index e8388d17c7..f2378f1f97 100644 --- a/types/casperjs/index.d.ts +++ b/types/casperjs/index.d.ts @@ -1,17 +1,17 @@ -// Type definitions for CasperJS v1.0.29 +// Type definitions for CasperJS 1.1 // Project: http://casperjs.org/ // Definitions by: Jed Mao +// Uriel Chemouni // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.2 /// - export function create(options?: CasperOptions): Casper; -export function selectXPath(expression: string): Object; +export function selectXPath(expression: string): object; export class Casper { - constructor(options: CasperOptions); test: Tester; @@ -23,23 +23,23 @@ export class Casper { // Methods back(): Casper; base64encode(url: string, method?: string, data?: any): string; - bypass(nb: number): any; - click(selector: string): boolean; + bypass(nb: number): Casper; + click(selector: string, X?: number | string, Y?: number | string): boolean; clickLabel(label: string, tag?: string): boolean; - capture(targetFilePath: string, clipRect: ClipRect): Casper; - captureBase64(format: string): string; - captureBase64(format: string, area: string): string; - captureBase64(format: string, area: ClipRect): string; - captureBase64(format: string, area: any): string; - captureSelector(targetFile: string, selector: string): Casper; + capture(targetFilePath: string, clipRect?: ClipRect, imgOptions?: ImgOptions): Casper; + captureBase64(format: string, area?: string | ClipRect | CasperSelector): string; + captureSelector(targetFile: string, selector: string, imgOptions?: ImgOptions): Casper; clear(): Casper; + clearCache(): Casper; + clearMemoryCache(): Casper; debugHTML(selector?: string, outer?: boolean): Casper; debugPage(): Casper; die(message: string, status?: number): Casper; - download(url: string, target?: string, method?: string, data?: any): Casper; + download(url: string, target: string, method?: string, data?: any): Casper; each(array: T[], fn: (this: Casper, item: T, index: number) => void): Casper; + eachThen(array: any[], then?: FunctionThen): Casper; echo(message: string, style?: string): Casper; - evaluate(fn: (...args: any[]) => T, ...args: any[]): T + evaluate(fn: (...args: any[]) => T, ...args: any[]): T; evaluateOrDie(fn: () => any, message?: string, status?: number): Casper; exit(status?: number): Casper; exists(selector: string): boolean; @@ -52,7 +52,7 @@ export class Casper { getCurrentUrl(): string; getElementAttribute(selector: string, attribute: string): string; getElementsAttribute(selector: string, attribute: string): string; - getElementBounds(selector: string): ElementBounds; + getElementBounds(selector: string, page?: boolean): ElementBounds | null; getElementsBounds(selector: string): ElementBounds[]; getElementInfo(selector: string): ElementInfo; getElementsInfo(selector: string): ElementInfo; @@ -61,83 +61,125 @@ export class Casper { getHTML(selector?: string, outer?: boolean): string; getPageContent(): string; getTitle(): string; - mouseEvent(type: string, selector: string): boolean; + mouseEvent(type: string, selector: string, X?: number|string, Y?: number|string): boolean; + newPage(): any; open(location: string, settings: OpenSettings): Casper; - reload(then?: (response: HttpResponse) => void): Casper; - repeat(times: number, then: Function): Casper; - resourceExists(test: Function): boolean; - resourceExists(test: string): boolean; - run(onComplete: Function, time?: number): Casper; + reload(then?: FunctionThen): Casper; + repeat(times: number, then: FunctionThen): Casper; + resourceExists(test: string | Function | RegExp): boolean; + run(onComplete?: Function, time?: number): Casper; scrollTo(x: number, y: number): Casper; scrollToBottom(): Casper; - sendKeys(selector: string, keys: string, options?: any): Casper; + sendKeys(selector: string, keys: string, options?: KeyOptions): Casper; setHttpAuth(username: string, password: string): Casper; - start(url?: string, then?: (response: HttpResponse) => void): Casper; - status(asString: boolean): any; + setMaxListeners(maxListeners: number): Casper; + start(url?: string, then?: FunctionThen): Casper; + status(asString?: false): number; + status(asString: true): string; + switchToFrame(frameInfo: string | number): Casper; + switchToMainFrame(): Casper; + switchToParentFrame(): Casper; then(fn: (this: Casper) => void): Casper; thenBypass(nb: number): Casper; thenBypassIf(condition: any, nb: number): Casper; thenBypassUnless(condition: any, nb: number): Casper; - thenClick(selector: string): Casper; + thenClick(selector: string, then?: FunctionThen): Casper; thenEvaluate(fn: () => any, ...args: any[]): Casper; thenOpen(location: string, then?: (response: HttpResponse) => void): Casper; thenOpen(location: string, options?: OpenSettings, then?: (response: HttpResponse) => void): Casper; - thenOpenAndEvaluate(location: string, then?: Function, ...args: any[]): Casper; + thenOpenAndEvaluate(location: string, then?: FunctionThen, ...args: any[]): Casper; toString(): string; unwait(): Casper; - userAgent(agent: string): string; - viewport(width: number, height: number): Casper; + // 2017-10-19 Doc said returning String but code return Casper object. + userAgent(agent: string): Casper; + viewport(width: number, height: number, then?: FunctionThen): Casper; visible(selector: string): boolean; - wait(timeout: number, then?: Function): Casper; - waitFor(testFx: Function, then?: Function, onTimeout?: Function, timeout?: number): Casper; - waitForAlert(then: Function, onTimeout?: Function, timeout?: number): Casper; - waitForPopup(urlPattern: string, then?: Function, onTimeout?: Function, timeout?: number): Casper; - waitForPopup(urlPattern: RegExp, then?: Function, onTimeout?: Function, timeout?: number): Casper; - waitForUrl(url: string, then?: Function, onTimeout?: Function, timeout?: number): Casper; - waitForUrl(url: RegExp, then?: Function, onTimeout?: Function, timeout?: number): Casper; - waitForSelector(selector: string, then?: Function, onTimeout?: Function, timeout?: number): Casper; - waitWhileSelector(selector: string, then?: Function, onTimeout?: Function, timeout?: number): Casper; - waitForResource(testFx: Function, then?: Function, onTimeout?: Function, timeout?: number): Casper; - waitForText(pattern: string, then?: Function, onTimeout?: Function, timeout?: number): Casper; - waitForText(pattern: RegExp, then?: Function, onTimeout?: Function, timeout?: number): Casper; - waitUntilVisible(selector: string, then?: Function, onTimeout?: Function, timeout?: number): Casper; - waitWhileVisible(selector: string, then?: Function, onTimeout?: Function, timeout?: number): Casper; + wait(timeout: number, then?: FunctionThen): Casper; + waitFor(testFx: Function, then?: FunctionThen, onTimeout?: FunctionOnTimeout, timeout?: number, details?: any): Casper; + waitForAlert(then: FunctionThen, onTimeout?: FunctionOnTimeout, timeout?: number): Casper; + waitForExec(command: string | null, parameter: string[], then?: FunctionThen, onTimeout?: FunctionOnTimeout, timeout?: number): Casper; + waitForPopup(urlPattern: RegExp | string | number | FindByUrlNameTitle, then?: FunctionThen, onTimeout?: Function, timeout?: number): Casper; + waitForResource(testFx: RegExp | string | ((resource: {url: string}) => boolean), then?: FunctionThen, onTimeout?: Function, timeout?: number): Casper; + waitForUrl(url: RegExp | string, then?: FunctionThen, onTimeout?: FunctionOnTimeout, timeout?: number): Casper; + waitForSelector(selector: string, then?: FunctionThen, onTimeout?: FunctionOnTimeout, timeout?: number): Casper; + waitWhileSelector(selector: string, then?: FunctionThen, onTimeout?: FunctionOnTimeout, timeout?: number): Casper; + waitForSelectorTextChange(selectors: string, then?: FunctionThen, onTimeout?: FunctionOnTimeout, timeout?: number): Casper; + waitForText(pattern: RegExp | string, then?: FunctionThen, onTimeout?: FunctionOnTimeout, timeout?: number): Casper; + waitUntilVisible(selector: string, then?: FunctionThen, onTimeout?: FunctionOnTimeout, timeout?: number): Casper; + waitWhileVisible(selector: string, then?: FunctionThen, onTimeout?: FunctionOnTimeout, timeout?: number): Casper; warn(message: string): Casper; - withFrame(frameInfo: string, then: Function): Casper; - withFrame(frameInfo: number, then: Function): Casper; - withPopup(popupInfo: string, step: Function): Casper; - withPopup(popupInfo: RegExp, step: Function): Casper; + withFrame(frameInfo: string | number, then: FunctionThen): Casper; + withPopup(popupInfo: RegExp | string | number | FindByUrlNameTitle, step: FunctionThen): Casper; + withSelectorScope(selector: string, then: FunctionThen): Casper; zoom(factor: number): Casper; - removeAllFilters(filter: string): Casper; - setFilter(filter: string, cb: Function): boolean; + // do not exists anymore + // removeAllFilters(filter: string): Casper; + // do not exists anymore + // setFilter(filter: string, cb: Function): boolean; } -interface HttpResponse { +export type FunctionThen = (this: Casper, response: HttpResponse) => void; +export type FunctionOnTimeout = (this: Casper, timeout: number, details: any) => void; +// not visible in doc +// interface QtRuntimeObject {id?: any; url?: string;} +// see modules/pagestack.js in casperjs + +export interface ImgOptions { + // format to set the image format manually, avoiding relying on the filename + format?: string; + // quality to set the image quality, from 1 to 100 + quality?: number; +} + +export interface FindByUrlNameTitle { + url?: string; + title?: string; + windowName?: string; +} + +export interface Header { + name: string; + value: string; +} + +export interface CasperSelector { + type?: 'xpath' | 'css'; + path: string; +} + +export interface KeyOptions { + reset?: boolean; + keepFocus?: boolean; + modifiers?: string; // combinaison of 'ctrl+alt+shift+meta+keypad' +} + +export interface HttpResponse { contentType: string; - headers: any[]; + headers: Header[]; id: number; - redirectURL: string; + redirectURL: string | null; stage: string; status: number; statusText: string; time: string; url: string; + data: any; } -interface OpenSettings { +export interface OpenSettings { method: string; data: any; headers: any; } -interface ElementBounds { +export interface ElementBounds { top: number; left: number; width: number; height: number; } -interface ElementInfo { +export interface ElementInfo { nodeName: string; attributes: any; tag: string; @@ -150,7 +192,7 @@ interface ElementInfo { visible: boolean; } -interface CasperOptions { +export interface CasperOptions { clientScripts?: any[]; exitOnError?: boolean; httpStatusHandlers?: any; @@ -179,7 +221,7 @@ interface CasperOptions { waitTimeout?: number; } -interface ClientUtils { +export interface ClientUtils { echo(message: string): void; encode(contents: string): void; exists(selector: string): void; @@ -200,12 +242,12 @@ interface ClientUtils { visible(selector: string): void; } -interface Colorizer { +export interface Colorizer { colorize(text: string, styleName: string): void; format(text: string, style: any): void; } -interface Tester { +export interface Tester { assert(condition: boolean, message?: string): any; assertDoesntExist(selector: string, message?: string): any; assertElementCount(selctor: string, expected: number, message?: string): any; @@ -235,15 +277,14 @@ interface Tester { assertTruthy(subject: any, message?: string): any; assertType(input: any, type: string, message?: string): any; assertInstanceOf(input: any, ctor: Function, message?: string): any; - assertUrlMatch(pattern: string, message?: string): any; - assertUrlMatch(pattern: RegExp, message?: string): any; + assertUrlMatch(pattern: RegExp | string, message?: string): any; assertVisible(selector: string, message?: string): any; /* since 1.1 */ begin(description: string, planned: number, suite: Function): any; begin(description: string, suite: Function): any; - begin(description: string, planned: number, config: Object): any; - begin(description: string, config: Object): any; + begin(description: string, planned: number, config: object): any; + begin(description: string, config: object): any; colorize(message: string, style: string): any; comment(message: string): any; @@ -262,12 +303,12 @@ interface Tester { tearDown(fn: Function): any; } -interface Cases { +export interface Cases { length: number; cases: Case[]; } -interface Case { +export interface Case { success: boolean; type: string; standard: string; @@ -275,12 +316,12 @@ interface Case { values: CaseValues; } -interface CaseValues { +export interface CaseValues { subject: boolean; expected: boolean; } -interface Utils { +export interface Utils { betterTypeOf(input: any): any; dump(value: any): any; fileExt(file: string): any; diff --git a/types/casperjs/tslint.json b/types/casperjs/tslint.json new file mode 100644 index 0000000000..c2a140228c --- /dev/null +++ b/types/casperjs/tslint.json @@ -0,0 +1,12 @@ +{ + "extends": "dtslint/dt.json", + "rules": { + // need to fix some Function type + "ban-types": false, + // can not merge + // begin(description: string, planned: number, suite: Function): any; + // and + // begin(description: string, planned: number, config: object): any; + "unified-signatures": false + } +} From e670e0731cad74822fb9f7329f2f4dead346e7c5 Mon Sep 17 00:00:00 2001 From: rlindgren Date: Fri, 20 Oct 2017 12:01:00 -0400 Subject: [PATCH 087/828] Fix doWhilst, doUntil definitions and tests --- types/async/index.d.ts | 4 ++-- types/async/test/index.ts | 8 ++++---- 2 files changed, 6 insertions(+), 6 deletions(-) diff --git a/types/async/index.d.ts b/types/async/index.d.ts index 80f2888a8b..7c32079086 100644 --- a/types/async/index.d.ts +++ b/types/async/index.d.ts @@ -174,9 +174,9 @@ export function parallel(tasks: Dictionary>, callback? export function parallelLimit(tasks: Array>, limit: number, callback?: AsyncResultArrayCallback): void; export function parallelLimit(tasks: Dictionary>, limit: number, callback?: AsyncResultObjectCallback): void; export function whilst(test: () => boolean, fn: AsyncVoidFunction, callback: ErrorCallback): void; -export function doWhilst(fn: AsyncVoidFunction, test: () => boolean, callback: ErrorCallback): void; +export function doWhilst(fn: AsyncVoidFunction, test: (result?: any) => boolean, callback: ErrorCallback): void; export function until(test: () => boolean, fn: AsyncVoidFunction, callback: ErrorCallback): void; -export function doUntil(fn: AsyncVoidFunction, test: () => boolean, callback: ErrorCallback): void; +export function doUntil(fn: AsyncVoidFunction, test: (result?: any) => boolean, callback: ErrorCallback): void; export function during(test: (testCallback : AsyncBooleanResultCallback) => void, fn: AsyncVoidFunction, callback: ErrorCallback): void; export function doDuring(fn: AsyncVoidFunction, test: (testCallback: AsyncBooleanResultCallback) => void, callback: ErrorCallback): void; export function forever(next: (next : ErrorCallback) => void, errBack: ErrorCallback) : void; diff --git a/types/async/test/index.ts b/types/async/test/index.ts index 821ccd0650..3c6c2f5dfe 100644 --- a/types/async/test/index.ts +++ b/types/async/test/index.ts @@ -239,16 +239,16 @@ async.parallelLimit({ function whileFn(callback: any) { - count++; - setTimeout(callback, 1000); + setTimeout(() => callback(null, ++count), 1000); } function whileTest() { return count < 5; } +function doWhileTest(count: number) { return count < 5; } var count = 0; async.whilst(whileTest, whileFn, function (err) { }); async.until(whileTest, whileFn, function (err) { }); -async.doWhilst(whileFn, whileTest, function (err) { }); -async.doUntil(whileFn, whileTest, function (err) { }); +async.doWhilst(whileFn, doWhileTest, function (err) { }); +async.doUntil(whileFn, doWhileTest, function (err) { }); async.during(function (testCallback) { testCallback(new Error(), false); }, function (callback) { callback() }, function (error) { console.log(error) }); async.doDuring(function (callback) { callback() }, function (testCallback) { testCallback(new Error(), false); }, function (error) { console.log(error) }); From 09b08e4b7d90608d4849bfd7aecc937860314ea9 Mon Sep 17 00:00:00 2001 From: Alessandro Vergani Date: Fri, 20 Oct 2017 18:10:45 +0200 Subject: [PATCH 088/828] Fix circular-json declarations to match JSON object (#20755) * Fix circular-json declarations * Simplify definitions of circular-json --- types/circular-json/circular-json-tests.ts | 10 +++------- types/circular-json/index.d.ts | 13 +++---------- types/circular-json/tslint.json | 3 +++ 3 files changed, 9 insertions(+), 17 deletions(-) create mode 100644 types/circular-json/tslint.json diff --git a/types/circular-json/circular-json-tests.ts b/types/circular-json/circular-json-tests.ts index 41ec8f0a36..786ec5cec6 100644 --- a/types/circular-json/circular-json-tests.ts +++ b/types/circular-json/circular-json-tests.ts @@ -1,14 +1,10 @@ - import CircularJSON = require('circular-json'); -var replacer = (key: any, val: any) => { +const replacer = (key: any, val: any) => { return val; -} +}; -var replacerArray = ['a', 'x']; - -// implements JSON interface -var json_obj: JSON = CircularJSON; +const replacerArray = ['a', 'x']; CircularJSON.parse('{"a":"b"}'); diff --git a/types/circular-json/index.d.ts b/types/circular-json/index.d.ts index 1b4e5c1d2b..ce94972de4 100644 --- a/types/circular-json/index.d.ts +++ b/types/circular-json/index.d.ts @@ -1,14 +1,7 @@ -// Type definitions for circular-json v0.1.6 +// Type definitions for circular-json 0.4 // Project: https://github.com/WebReflection/circular-json // Definitions by: Jonathan Pevarnek // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped - -interface ICircularJSON extends JSON { - parse(text: string, reviver?: (key: any, value: any) => any): any; - stringify(value: any, replacer?: ((key: string, value: any) => any) | any[], space?: any, placeholder?: boolean): string; -} - -declare var CircularJSON: ICircularJSON; - -export = CircularJSON; +export function parse(text: string, reviver?: (key: any, value: any) => any): any; +export function stringify(value: any, replacer?: ((key: string, value: any) => any) | Array | null, space?: any, placeholder?: boolean): string; diff --git a/types/circular-json/tslint.json b/types/circular-json/tslint.json new file mode 100644 index 0000000000..b4b47a0378 --- /dev/null +++ b/types/circular-json/tslint.json @@ -0,0 +1,3 @@ +{ + "extends": "dtslint/dt.json" +} From bba52abf8e508948643f09549b9b9fde025a4f33 Mon Sep 17 00:00:00 2001 From: Andy Date: Fri, 20 Oct 2017 10:00:14 -0700 Subject: [PATCH 089/828] js-data-angular and js-data-http: Add dependency on the old @types/js-data (#20689) --- types/js-data-angular/package.json | 6 ++++++ types/js-data-http/package.json | 6 ++++++ 2 files changed, 12 insertions(+) create mode 100644 types/js-data-angular/package.json create mode 100644 types/js-data-http/package.json diff --git a/types/js-data-angular/package.json b/types/js-data-angular/package.json new file mode 100644 index 0000000000..f932c0aa52 --- /dev/null +++ b/types/js-data-angular/package.json @@ -0,0 +1,6 @@ +{ + "private": true, + "dependencies": { + "@types/js-data": "^2.8.31" + } +} diff --git a/types/js-data-http/package.json b/types/js-data-http/package.json new file mode 100644 index 0000000000..f932c0aa52 --- /dev/null +++ b/types/js-data-http/package.json @@ -0,0 +1,6 @@ +{ + "private": true, + "dependencies": { + "@types/js-data": "^2.8.31" + } +} From ab68c62063e2289fcf636ab9d2f3aa4f7b3ddc9a Mon Sep 17 00:00:00 2001 From: Andy Date: Fri, 20 Oct 2017 10:00:53 -0700 Subject: [PATCH 090/828] signals: Lint (#20648) --- types/signals/index.d.ts | 24 ++-- types/signals/signals-tests.ts | 206 ++++++++++++++++----------------- types/signals/tslint.json | 8 ++ 3 files changed, 125 insertions(+), 113 deletions(-) create mode 100644 types/signals/tslint.json diff --git a/types/signals/index.d.ts b/types/signals/index.d.ts index 3f0ed1fa84..50982ec988 100644 --- a/types/signals/index.d.ts +++ b/types/signals/index.d.ts @@ -1,7 +1,8 @@ -// Type definitions for JS-Signals +// Type definitions for JS-Signals 1.0 // Project: http://millermedeiros.github.io/js-signals/ // Definitions by: Diullei Gomes // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.3 declare var signals: signals.SignalWrapper; @@ -9,9 +10,8 @@ export = signals; export as namespace signals; declare namespace signals { - interface SignalWrapper { - Signal: Signal + Signal: Signal; } interface SignalBinding { @@ -57,17 +57,21 @@ declare namespace signals { * * @param listener Signal handler function. * @param listenercontext Context on which listener will be executed (object that should represent the `this` variable inside listener function). - * @param priority The priority level of the event listener. Listeners with higher priority will be executed before listeners with lower priority. Listeners with same priority level will be executed at the same order as they were added. (default = 0) + * @param priority The priority level of the event listener. + * Listeners with higher priority will be executed before listeners with lower priority. + * Listeners with same priority level will be executed at the same order as they were added. (default = 0) */ add(listener: (...params: T[]) => void, listenerContext?: any, priority?: Number): SignalBinding; /** - * Add listener to the signal that should be removed after first execution (will be executed only once). - * - * @param listener Signal handler function. - * @param listenercontext Context on which listener will be executed (object that should represent the `this` variable inside listener function). - * @param priority The priority level of the event listener. Listeners with higher priority will be executed before listeners with lower priority. Listeners with same priority level will be executed at the same order as they were added. (default = 0) - */ + * Add listener to the signal that should be removed after first execution (will be executed only once). + * + * @param listener Signal handler function. + * @param listenercontext Context on which listener will be executed (object that should represent the `this` variable inside listener function). + * @param priority The priority level of the event listener. + * Listeners with higher priority will be executed before listeners with lower priority. + * Listeners with same priority level will be executed at the same order as they were added. (default = 0) + */ addOnce(listener: (...params: T[]) => void, listenerContext?: any, priority?: Number): SignalBinding; /** diff --git a/types/signals/signals-tests.ts b/types/signals/signals-tests.ts index 414b91edd7..b3d16d9d39 100644 --- a/types/signals/signals-tests.ts +++ b/types/signals/signals-tests.ts @@ -1,207 +1,207 @@ import signals = require("signals"); // lifted from https://github.com/millermedeiros/js-signals/wiki/Examples interface TestObject { - started: signals.Signal; - stopped: signals.Signal; + started: signals.Signal; + stopped: signals.Signal; } -namespace Signals.Tests { - //store local reference for brevity - var Signal = signals.Signal; +function tests() { + // store local reference for brevity + const Signal = signals.Signal; - //custom object that dispatch signals - var myObject: TestObject = { - started : new Signal(), //past tense is the recommended signal naming convention + // custom object that dispatch signals + const myObject: TestObject = { + started : new Signal(), // past tense is the recommended signal naming convention stopped : new Signal() }; - //single listener - function onStarted(param1:string, param2:string){ + // single listener + function onStarted(param1: string, param2: string) { alert(param1 + param2); } - myObject.started.add(onStarted); //add listener - myObject.started.dispatch('foo', 'bar'); //dispatch signal passing custom parameters - myObject.started.remove(onStarted); //remove a single listener + myObject.started.add(onStarted); // add listener + myObject.started.dispatch('foo', 'bar'); // dispatch signal passing custom parameters + myObject.started.remove(onStarted); // remove a single listener - //multiple listeners - function onStopped(){ + // multiple listeners + function onStopped() { alert('stopped'); } - function onStopped2(){ + function onStopped2() { alert('stopped listener 2'); } myObject.stopped.add(onStopped); myObject.stopped.add(onStopped2); myObject.stopped.dispatch(); - myObject.stopped.removeAll(); //remove all listeners of the `stopped` signal + myObject.stopped.removeAll(); // remove all listeners of the `stopped` signal - //multiple dispatches - var i = 0; - myObject.started.add(function(){ + // multiple dispatches + let i = 0; + myObject.started.add(() => { i += 1; alert(i); }); - myObject.started.dispatch(); //will alert 1 - myObject.started.dispatch(); //will alert 2 + myObject.started.dispatch(); // will alert 1 + myObject.started.dispatch(); // will alert 2 - //multiple dispatches + addOnce() - var i = 0; - myObject.started.addOnce(function(){ + // multiple dispatches + addOnce() + i = 0; + myObject.started.addOnce(() => { i += 1; alert(i); }); - myObject.started.dispatch(); //will alert 1 - myObject.started.dispatch(); //nothing happens + myObject.started.dispatch(); // will alert 1 + myObject.started.dispatch(); // nothing happens - //enable/disable signal - var i = 0; - myObject.started.add(function(){ + // enable/disable signal + i = 0; + myObject.started.add(() => { i += 1; alert(i); }); - myObject.started.dispatch(); //will alert 1 + myObject.started.dispatch(); // will alert 1 myObject.started.active = false; - myObject.started.dispatch(); //nothing happens + myObject.started.dispatch(); // nothing happens myObject.started.active = true; - myObject.started.dispatch(); //will alert 2 + myObject.started.dispatch(); // will alert 2 - //Stop/Halt Propagation (method 1) - myObject.started.add(function(){ - myObject.started.halt(); //prevent next listeners on the queue from being executed + // Stop/Halt Propagation (method 1) + myObject.started.add(() => { + myObject.started.halt(); // prevent next listeners on the queue from being executed }); - myObject.started.add(function(){ - alert('second listener'); //won't be called since first listener stops propagation + myObject.started.add(() => { + alert('second listener'); // won't be called since first listener stops propagation }); myObject.started.dispatch(); - //Stop/Halt Propagation (method 2) - myObject.started.add(function(){ - return false; //if handler returns `false` will also stop propagation + // Stop/Halt Propagation (method 2) + myObject.started.add(() => { + return false; // if handler returns `false` will also stop propagation }); - myObject.started.add(function(){ - alert('second listener'); //won't be called since first listener stops propagation + myObject.started.add(() => { + alert('second listener'); // won't be called since first listener stops propagation }); myObject.started.dispatch(); - //Set execution context of the listener handler - var foo = 'bar'; - var obj = { + // Set execution context of the listener handler + const foo = 'bar'; + const obj = { foo : 10 }; - function handler1(){ + function handler1() { alert(this.foo); } - function handler2(){ + function handler2() { alert(this.foo); } - //note that you cannot add the same handler twice to the same signal without removing it first - myObject.started.add(handler1); //default execution context - myObject.started.add(handler2, obj); //set a different execution context - myObject.started.dispatch(); //first handler will alert "bar", second will alert "10". + // note that you cannot add the same handler twice to the same signal without removing it first + myObject.started.add(handler1); // default execution context + myObject.started.add(handler2, obj); // set a different execution context + myObject.started.dispatch(); // first handler will alert "bar", second will alert "10". } -namespace Signals.AdvancedTests { - //store local reference for brevity - var Signal = signals.Signal; +function advancedTests() { + // store local reference for brevity + const Signal = signals.Signal; - //custom object that dispatch signals - var myObject: TestObject = { - started : new Signal(), //past tense is the recommended signal naming convention + // custom object that dispatch signals + const myObject: TestObject = { + started : new Signal(), // past tense is the recommended signal naming convention stopped : new Signal() }; - //Set listener priority/order (v0.5.3+) - var handler1 = function(){ + // Set listener priority/order (v0.5.3+) + let handler1 = () => { alert('foo'); }; - var handler2 = function(){ + let handler2 = () => { alert('bar'); }; - myObject.started.add(handler1); //default priority is 0 - myObject.started.add(handler2, null, 2); //setting priority to 2 will make `handler2` execute before `handler1` - myObject.started.dispatch(); //will alert "bar" than "foo" + myObject.started.add(handler1); // default priority is 0 + myObject.started.add(handler2, null, 2); // setting priority to 2 will make `handler2` execute before `handler1` + myObject.started.dispatch(); // will alert "bar" than "foo" - //Enable/Disable a single SignalBinding - var handler1 = function(){ + // Enable/Disable a single SignalBinding + handler1 = () => { alert('foo bar'); }; - var handler2 = function(){ + handler2 = () => { alert('lorem ipsum'); }; - var binding1 = myObject.started.add(handler1); //methods `add()` and `addOnce()` returns a SignalBinding object + let binding1 = myObject.started.add(handler1); // methods `add()` and `addOnce()` returns a SignalBinding object myObject.started.add(handler2); - myObject.started.dispatch(); //will alert "foo bar" than "lorem ipsum" - binding1.active = false; //disable a single binding - myObject.started.dispatch(); //will alert "lorem ipsum" + myObject.started.dispatch(); // will alert "foo bar" than "lorem ipsum" + binding1.active = false; // disable a single binding + myObject.started.dispatch(); // will alert "lorem ipsum" binding1.active = true; - myObject.started.dispatch(); //will alert "foo bar" than "lorem ipsum" + myObject.started.dispatch(); // will alert "foo bar" than "lorem ipsum" - //Manually execute a signal handler - var handler = function(){ + // Manually execute a signal handler + const handler = () => { alert('foo bar'); }; - var binding: signals.SignalBinding<() => void> = myObject.started.add(handler); //methods `add()` and `addOnce()` returns a SignalBinding object - binding.execute(); //will alert "foo bar" + let binding: signals.SignalBinding<() => void> = myObject.started.add(handler); // methods `add()` and `addOnce()` returns a SignalBinding object + binding.execute(); // will alert "foo bar" - //Retrieve anonymous listener - var binding:signals.SignalBinding<() => void> = myObject.started.add(function(){ + // Retrieve anonymous listener + binding = myObject.started.add(() => { alert('foo bar'); }); // note: in the original docs, this is handler, but that collides with handler above because these are in one giant scope // perhaps these are best split into functions for readability - var anonymousHandler = binding.getListener(); //reference to the anonymous function + const anonymousHandler = binding.getListener(); // reference to the anonymous function - //Remove / Detach anonymous listener - var binding:signals.SignalBinding<() => void> = myObject.started.add(function(){ + // Remove / Detach anonymous listener + binding = myObject.started.add(() => { alert('foo bar'); }); - myObject.started.dispatch(); //will alert "foo bar" + myObject.started.dispatch(); // will alert "foo bar" binding.detach(); - alert(binding.isBound()); //will alert `false` - myObject.started.dispatch(); //nothing happens + alert(binding.isBound()); // will alert `false` + myObject.started.dispatch(); // nothing happens - //Check if binding will execute only once - var binding1:signals.SignalBinding = myObject.started.add(function(){ + // Check if binding will execute only once + binding1 = myObject.started.add(() => { alert('foo bar'); }); - var binding2:signals.SignalBinding<() => void> = myObject.started.addOnce(function(){ + const binding2: signals.SignalBinding<() => void> = myObject.started.addOnce(() => { alert('foo bar'); }); - alert(binding1.isOnce()); //alert "false" - alert(binding2.isOnce()); //alert "true" + alert(binding1.isOnce()); // alert "false" + alert(binding2.isOnce()); // alert "true" - //Change listener execution context on-the-fly - var foo = 'bar'; - var obj = { + // Change listener execution context on-the-fly + const foo = 'bar'; + const obj = { foo : "it's over 9000!" }; - var binding:signals.SignalBinding<() => void> = myObject.started.add(function(){ + binding = myObject.started.add(function() { alert(this.foo); }); - myObject.started.dispatch(); //will alert "bar" + myObject.started.dispatch(); // will alert "bar" binding.context = obj; - myObject.started.dispatch(); //will alert "it's over 9000!" + myObject.started.dispatch(); // will alert "it's over 9000!" - //Add default parameters to Signal dispatch (v0.6.3+) - var binding:signals.SignalBinding<() => void> = myObject.started.add(function(a:string, b:string, c:string){ - alert(a +' '+ b +' '+ c); + // Add default parameters to Signal dispatch (v0.6.3+) + binding = myObject.started.add((a: string, b: string, c: string) => { + alert(`${a} ${b} ${c}`); }); - binding.params = ['lorem', 'ipsum']; //set default parameters of the binding - myObject.started.dispatch('dolor'); //will alert "lorem ipsum dolor" + binding.params = ['lorem', 'ipsum']; // set default parameters of the binding + myObject.started.dispatch('dolor'); // will alert "lorem ipsum dolor" - //Check if Signal has specific listener (v0.7.0+) - function onStart(a:string){ + // Check if Signal has specific listener (v0.7.0+) + function onStart(a: string) { console.log(a); } myObject.started.add(onStart); myObject.started.has(onStart); // true - //Memorize previously dispatched values / forget values (v0.7.0+) + // Memorize previously dispatched values / forget values (v0.7.0+) myObject.started.memorize = true; // default is false myObject.started.dispatch('foo'); diff --git a/types/signals/tslint.json b/types/signals/tslint.json new file mode 100644 index 0000000000..09c89d645d --- /dev/null +++ b/types/signals/tslint.json @@ -0,0 +1,8 @@ +{ + "extends": "dtslint/dt.json", + "rules": { + // TODOs + "ban-types": false, + "no-misused-new": false + } +} From e51980df25f26e7aa53816a4d6b5cf991a715454 Mon Sep 17 00:00:00 2001 From: Andy Date: Fri, 20 Oct 2017 10:02:01 -0700 Subject: [PATCH 091/828] openpgp: Convert to external module (#20622) --- types/openpgp/index.d.ts | 407 ++++++++++++++++----------------- types/openpgp/openpgp-tests.ts | 4 +- types/openpgp/tslint.json | 20 ++ 3 files changed, 221 insertions(+), 210 deletions(-) create mode 100644 types/openpgp/tslint.json diff --git a/types/openpgp/index.d.ts b/types/openpgp/index.d.ts index 91b8dc2ca6..79e92daa7f 100644 --- a/types/openpgp/index.d.ts +++ b/types/openpgp/index.d.ts @@ -3,120 +3,119 @@ // Definitions by: Guillaume Lacasa // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -declare namespace openpgp { +export as namespace openpgp; - interface KeyPair { - key: key.Key, - privateKeyArmored: string, - publicKeyArmored: string - } - - interface KeyOptions { - keyType?: enums.publicKey, - numBits: number, - userId: string, - passphrase: string, - unlocked?: boolean - } - - interface Keyid { - bytes: string, - } - - interface Signature { - keyid: Keyid, - valid: boolean - } - - interface VerifiedMessage { - text: string, - signatures: Array - } - - /** Decrypts message and verifies signatures - - @param privateKey private key with decrypted secret key data - @param publicKeys array of keys to verify signatures - @param msg the message object with signed and encrypted data - */ - function decryptAndVerifyMessage(privateKey: key.Key, publicKeys: Array, msg: string): Promise; - /** Decrypts message and verifies signatures - - @param privateKey private key with decrypted secret key data - @param publicKey single key to verify signatures - @param msg the message object with signed and encrypted data - */ - function decryptAndVerifyMessage(privateKey: key.Key, publicKey: key.Key, msg: string): Promise; - - /** Decrypts message - - @param privateKey private key with decrypted secret key data - @param msg the message object with the encrypted data - */ - function decryptMessage(privateKey: key.Key, msg: message.Message): Promise; - - /** Encrypts message text with keys - @param keys array of keys used to encrypt the message - @param text message as native JavaScript string - @returns encrypted ASCII armored message - */ - function encryptMessage(keys: Array, message: string): Promise; - /** Encrypts message text with keys - - @param single key used to encrypt the message - @param text message as native JavaScript string - */ - function encryptMessage(key: key.Key, message: string): Promise; - - /** Generates a new OpenPGP key pair. Currently only supports RSA keys. Primary and subkey will be of same type. - @param options - */ - function generateKeyPair(options: KeyOptions): Promise; - - /** Signs message text and encrypts it - - @param publicKeys array of keys used to encrypt the message - @param privateKey private key with decrypted secret key data for signing - @param text private key with decrypted secret key data for signing - */ - function signAndEncryptMessage(publicKeys: Array, privateKey: key.Key, text: string): Promise; - /** Signs message text and encrypts it - - @param publicKeys single key used to encrypt the message - @param privateKey private key with decrypted secret key data for signing - @param text private key with decrypted secret key data for signing - */ - function signAndEncryptMessage(publicKey: key.Key, privateKey: key.Key, text: string): Promise; - - /** Signs a cleartext message - - @param privateKeys array of keys with decrypted secret key data to sign cleartext - @param text cleartext - */ - function signClearMessage(privateKeys: Array, text: string): Promise; - /** Signs a cleartext message - - @param privateKeys single key with decrypted secret key data to sign cleartext - @param text cleartext - */ - function signClearMessage(privateKey: key.Key, text: string): Promise; - - /** Verifies signatures of cleartext signed message - - @param publicKeys array of keys to verify signatures - @param msg cleartext message object with signatures - */ - function verifyClearSignedMessage(publicKeys: Array, msg: cleartext.CleartextMessage): Promise; - /** Verifies signatures of cleartext signed message - - @param publicKeys single key to verify signatures - @param msg cleartext message object with signatures - */ - function verifyClearSignedMessage(publicKey: key.Key, msg: cleartext.CleartextMessage): Promise; +export interface KeyPair { + key: key.Key, + privateKeyArmored: string, + publicKeyArmored: string } -declare namespace openpgp.armor { +export interface KeyOptions { + keyType?: enums.publicKey, + numBits: number, + userId: string, + passphrase: string, + unlocked?: boolean +} +export interface Keyid { + bytes: string, +} + +export interface Signature { + keyid: Keyid, + valid: boolean +} + +export interface VerifiedMessage { + text: string, + signatures: Array +} + +/** Decrypts message and verifies signatures + + @param privateKey private key with decrypted secret key data + @param publicKeys array of keys to verify signatures + @param msg the message object with signed and encrypted data + */ +export function decryptAndVerifyMessage(privateKey: key.Key, publicKeys: Array, msg: string): Promise; +/** Decrypts message and verifies signatures + + @param privateKey private key with decrypted secret key data + @param publicKey single key to verify signatures + @param msg the message object with signed and encrypted data + */ +export function decryptAndVerifyMessage(privateKey: key.Key, publicKey: key.Key, msg: string): Promise; + +/** Decrypts message + + @param privateKey private key with decrypted secret key data + @param msg the message object with the encrypted data + */ +export function decryptMessage(privateKey: key.Key, msg: message.Message): Promise; + +/** Encrypts message text with keys + @param keys array of keys used to encrypt the message + @param text message as native JavaScript string + @returns encrypted ASCII armored message + */ +export function encryptMessage(keys: Array, message: string): Promise; +/** Encrypts message text with keys + + @param single key used to encrypt the message + @param text message as native JavaScript string + */ +export function encryptMessage(key: key.Key, message: string): Promise; + +/** Generates a new OpenPGP key pair. Currently only supports RSA keys. Primary and subkey will be of same type. + @param options + */ +export function generateKeyPair(options: KeyOptions): Promise; + +/** Signs message text and encrypts it + + @param publicKeys array of keys used to encrypt the message + @param privateKey private key with decrypted secret key data for signing + @param text private key with decrypted secret key data for signing + */ +export function signAndEncryptMessage(publicKeys: Array, privateKey: key.Key, text: string): Promise; +/** Signs message text and encrypts it + + @param publicKeys single key used to encrypt the message + @param privateKey private key with decrypted secret key data for signing + @param text private key with decrypted secret key data for signing + */ +export function signAndEncryptMessage(publicKey: key.Key, privateKey: key.Key, text: string): Promise; + +/** Signs a cleartext message + + @param privateKeys array of keys with decrypted secret key data to sign cleartext + @param text cleartext + */ +export function signClearMessage(privateKeys: Array, text: string): Promise; +/** Signs a cleartext message + + @param privateKeys single key with decrypted secret key data to sign cleartext + @param text cleartext + */ +export function signClearMessage(privateKey: key.Key, text: string): Promise; + +/** Verifies signatures of cleartext signed message + + @param publicKeys array of keys to verify signatures + @param msg cleartext message object with signatures + */ +export function verifyClearSignedMessage(publicKeys: Array, msg: cleartext.CleartextMessage): Promise; +/** Verifies signatures of cleartext signed message + + @param publicKeys single key to verify signatures + @param msg cleartext message object with signatures + */ +export function verifyClearSignedMessage(publicKey: key.Key, msg: cleartext.CleartextMessage): Promise; + + +export namespace armor { /** Armor an OpenPGP binary packet block @param messagetype type of the message @@ -133,8 +132,7 @@ declare namespace openpgp.armor { function dearmor(text: string): Object; } -declare namespace openpgp.cleartext { - +export namespace cleartext { /** Class that represents an OpenPGP cleartext signed message. */ interface CleartextMessage { @@ -164,7 +162,7 @@ declare namespace openpgp.cleartext { function readArmored(armoredText: string): CleartextMessage; } -declare namespace openpgp.config { +export namespace config { var prefer_hash_algorithm: enums.hash; var encryption_cipher: enums.symmetric; var compression: enums.compression; @@ -175,7 +173,7 @@ declare namespace openpgp.config { var debug: boolean; } -declare namespace openpgp.crypto { +export namespace crypto { interface Mpi { data: number, read(input: string): number, @@ -211,92 +209,92 @@ declare namespace openpgp.crypto { @param data Data to be encrypted as MPI */ function publicKeyEncrypt(algo: enums.publicKey, publicMPIs: Array, data: Mpi): Array; + + + namespace cfb { + /** This function decrypts a given plaintext using the specified blockcipher to decrypt a message + @param cipherfn the algorithm cipher class to decrypt data in one block_size encryption + @param key binary string representation of key to be used to decrypt the ciphertext. This will be passed to the cipherfn + @param ciphertext to be decrypted provided as a string + @param resync a boolean value specifying if a resync of the IV should be used or not. The encrypteddatapacket uses the "old" style with a resync. Decryption within an encryptedintegrityprotecteddata packet is not resyncing the IV. + */ + function decrypt(cipherfn: string, key: string, ciphertext: string, resync: boolean): string; + + /** This function encrypts a given with the specified prefixrandom using the specified blockcipher to encrypt a message + @param prefixrandom random bytes of block_size length provided as a string to be used in prefixing the data + @param cipherfn the algorithm cipher class to encrypt data in one block_size encryption + @param plaintext data to be encrypted provided as a string + @param key binary string representation of key to be used to encrypt the plaintext. This will be passed to the cipherfn + @param resync a boolean value specifying if a resync of the IV should be used or not. The encrypteddatapacket uses the "old" style with a resync. Encryption within an encryptedintegrityprotecteddata packet is not resyncing the IV. + */ + function encrypt(prefixrandom: string, cipherfn: string, plaintext: string, key: string, resync: boolean): string; + + /** Decrypts the prefixed data for the Modification Detection Code (MDC) computation + @param cipherfn cipherfn.encrypt Cipher function to use + @param key binary string representation of key to be used to check the mdc This will be passed to the cipherfn + @param ciphertext The encrypted data + */ + function mdc(cipherfn: Object, key: string, ciphertext: string): string; + } + + namespace hash { + /** Create a hash on the specified data using the specified algorithm + @param algo Hash algorithm type + @param data Data to be hashed + */ + function digest(algo: enums.hash, data: string): string; + + /** Returns the hash size in bytes of the specified hash algorithm type + @param algo Hash algorithm type + */ + function getHashByteLength(algo: enums.hash): number; + } + + namespace random { + /** Create a secure random big integer of bits length + @param bits Bit length of the MPI to create + */ + function getRandomBigInteger(bits: number): number; + + /** Retrieve secure random byte string of the specified length + @param length Length in bytes to generate + */ + function getRandomBytes(length: number): string; + + /** Helper routine which calls platform specific crypto random generator + @param buf + */ + function getRandomValues(buf: Uint8Array): void; + + /** Return a secure random number in the specified range + @param from Min of the random number + @param to Max of the random number (max 32bit) + */ + function getSecureRandom(from: number, to: number): number; + } + + namespace signature { + /** Create a signature on data using the specified algorithm + @param hash_algo hash Algorithm to use + @param algo Asymmetric cipher algorithm to use + @param publicMPIs Public key multiprecision integers of the private key + @param secretMPIs Private key multiprecision integers which is used to sign the data + @param data Data to be signed + */ + function sign(hash_algo: enums.hash, algo: enums.publicKey, publicMPIs: Array, secretMPIs: Array, data: string): Mpi; + + /** + @param algo public Key algorithm + @param hash_algo Hash algorithm + @param msg_MPIs Signature multiprecision integers + @param publickey_MPIs Public key multiprecision integers + @param data Data on where the signature was computed on + */ + function verify(algo: enums.publicKey, hash_algo: enums.hash, msg_MPIs: Array, publickey_MPIs: Array, data: string): boolean; + } } -declare namespace openpgp.crypto.cfb { - /** This function decrypts a given plaintext using the specified blockcipher to decrypt a message - @param cipherfn the algorithm cipher class to decrypt data in one block_size encryption - @param key binary string representation of key to be used to decrypt the ciphertext. This will be passed to the cipherfn - @param ciphertext to be decrypted provided as a string - @param resync a boolean value specifying if a resync of the IV should be used or not. The encrypteddatapacket uses the "old" style with a resync. Decryption within an encryptedintegrityprotecteddata packet is not resyncing the IV. - */ - function decrypt(cipherfn: string, key: string, ciphertext: string, resync: boolean): string; - - /** This function encrypts a given with the specified prefixrandom using the specified blockcipher to encrypt a message - @param prefixrandom random bytes of block_size length provided as a string to be used in prefixing the data - @param cipherfn the algorithm cipher class to encrypt data in one block_size encryption - @param plaintext data to be encrypted provided as a string - @param key binary string representation of key to be used to encrypt the plaintext. This will be passed to the cipherfn - @param resync a boolean value specifying if a resync of the IV should be used or not. The encrypteddatapacket uses the "old" style with a resync. Encryption within an encryptedintegrityprotecteddata packet is not resyncing the IV. - */ - function encrypt(prefixrandom: string, cipherfn: string, plaintext: string, key: string, resync: boolean): string; - - /** Decrypts the prefixed data for the Modification Detection Code (MDC) computation - @param cipherfn cipherfn.encrypt Cipher function to use - @param key binary string representation of key to be used to check the mdc This will be passed to the cipherfn - @param ciphertext The encrypted data - */ - function mdc(cipherfn: Object, key: string, ciphertext: string): string; -} - -declare namespace openpgp.crypto.hash { - /** Create a hash on the specified data using the specified algorithm - @param algo Hash algorithm type - @param data Data to be hashed - */ - function digest(algo: enums.hash, data: string): string; - - /** Returns the hash size in bytes of the specified hash algorithm type - @param algo Hash algorithm type - */ - function getHashByteLength(algo: enums.hash): number; -} - -declare namespace openpgp.crypto.random { - /** Create a secure random big integer of bits length - @param bits Bit length of the MPI to create - */ - function getRandomBigInteger(bits: number): number; - - /** Retrieve secure random byte string of the specified length - @param length Length in bytes to generate - */ - function getRandomBytes(length: number): string; - - /** Helper routine which calls platform specific crypto random generator - @param buf - */ - function getRandomValues(buf: Uint8Array): void; - - /** Return a secure random number in the specified range - @param from Min of the random number - @param to Max of the random number (max 32bit) - */ - function getSecureRandom(from: number, to: number): number; -} - -declare namespace openpgp.crypto.signature { - /** Create a signature on data using the specified algorithm - @param hash_algo hash Algorithm to use - @param algo Asymmetric cipher algorithm to use - @param publicMPIs Public key multiprecision integers of the private key - @param secretMPIs Private key multiprecision integers which is used to sign the data - @param data Data to be signed - */ - function sign(hash_algo: enums.hash, algo: enums.publicKey, publicMPIs: Array, secretMPIs: Array, data: string): Mpi; - - /** - @param algo public Key algorithm - @param hash_algo Hash algorithm - @param msg_MPIs Signature multiprecision integers - @param publickey_MPIs Public key multiprecision integers - @param data Data on where the signature was computed on - */ - function verify(algo: enums.publicKey, hash_algo: enums.hash, msg_MPIs: Array, publickey_MPIs: Array, data: string): boolean; -} - -declare namespace openpgp.enums { - +export namespace enums { enum armor { multipart_section, multipart_last, @@ -372,8 +370,7 @@ declare namespace openpgp.enums { } } -declare namespace openpgp.key { - +export namespace key { interface KeyResult { keys: Array, err: Array @@ -408,10 +405,9 @@ declare namespace openpgp.key { @param armoredText text to be parsed */ function readArmored(armoredText: string): KeyResult; - } -declare namespace openpgp.message { +export namespace message { /** Class that represents an OpenPGP message. Can be an encrypted message, signed message, compressed message or literal message */ interface Message { @@ -477,8 +473,7 @@ declare namespace openpgp.message { function readArmored(armoredText: string): Message; } -declare namespace openpgp.packet { - +export namespace packet { interface PublicKey { algorithm: enums.publicKey; created: Date; @@ -509,7 +504,7 @@ declare namespace openpgp.packet { function newPacketFromTag(tag: string): Object; } -declare namespace openpgp.util { +export namespace util { /** Convert an array of integers(0.255) to a string @param bin An array of (binary) integers to convert */ @@ -583,6 +578,4 @@ declare namespace openpgp.util { @param bin An array of (binary) integers to convert */ function Uint8Array2str(bin: Uint8Array): string; - - } diff --git a/types/openpgp/openpgp-tests.ts b/types/openpgp/openpgp-tests.ts index a4a4200c56..fbe8a2e691 100644 --- a/types/openpgp/openpgp-tests.ts +++ b/types/openpgp/openpgp-tests.ts @@ -1,5 +1,3 @@ - - // Open PGP Sample codes var options: openpgp.KeyOptions = { @@ -125,4 +123,4 @@ openpgp.util.print_debug_hexstr_dump(""); openpgp.util.shiftRight("", 1); openpgp.util.str2bin(""); openpgp.util.str2Uint8Array(""); -openpgp.util.Uint8Array2str(openpgp.util.str2Uint8Array("")); \ No newline at end of file +openpgp.util.Uint8Array2str(openpgp.util.str2Uint8Array("")); diff --git a/types/openpgp/tslint.json b/types/openpgp/tslint.json new file mode 100644 index 0000000000..c28368c002 --- /dev/null +++ b/types/openpgp/tslint.json @@ -0,0 +1,20 @@ +{ + "extends": "dtslint/dt.json", + "rules": { + // TODOs + "array-type": false, + "ban-types": false, + "dt-header": false, + "jsdoc-format": false, + "max-line-length": false, + "no-consecutive-blank-lines": false, + "no-var-keyword": false, + "only-arrow-functions": false, + "prefer-const": false, + "semicolon": false, + "space-before-function-paren": false, + "typedef-whitespace": false, + "unified-signatures": false, + "whitespace": false + } +} \ No newline at end of file From 38e3db12b83247ccb7ad61503edd726cf2bfb080 Mon Sep 17 00:00:00 2001 From: Artem Malko Date: Sat, 21 Oct 2017 01:36:49 +0700 Subject: [PATCH 092/828] react Add 'as' attribute for link element (#20769) --- types/react/index.d.ts | 3 +++ 1 file changed, 3 insertions(+) diff --git a/types/react/index.d.ts b/types/react/index.d.ts index 93cb62fbfa..f79caad296 100644 --- a/types/react/index.d.ts +++ b/types/react/index.d.ts @@ -2493,6 +2493,7 @@ declare namespace React { allowFullScreen?: boolean; allowTransparency?: boolean; alt?: string; + as?: string; async?: boolean; autoComplete?: string; autoFocus?: boolean; @@ -2602,6 +2603,7 @@ declare namespace React { rel?: string; target?: string; type?: string; + as?: string; } // tslint:disable-next-line:no-empty-interface @@ -2787,6 +2789,7 @@ declare namespace React { rel?: string; sizes?: string; type?: string; + as?: string; } interface MapHTMLAttributes extends HTMLAttributes { From da6e5dabc87b1590c9f4e90ec71a4871de164663 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Daniel=20Kr=C3=B3l?= Date: Fri, 20 Oct 2017 22:19:43 +0200 Subject: [PATCH 093/828] Add react-dnd-touch-backend types (#20770) * Add react-dnd-touch-backend types * CS fixes * Add dom lib --- types/react-dnd-touch-backend/index.d.ts | 12 ++++++++++ .../react-dnd-touch-backend-tests.ts | 7 ++++++ types/react-dnd-touch-backend/tsconfig.json | 24 +++++++++++++++++++ types/react-dnd-touch-backend/tslint.json | 1 + 4 files changed, 44 insertions(+) create mode 100644 types/react-dnd-touch-backend/index.d.ts create mode 100644 types/react-dnd-touch-backend/react-dnd-touch-backend-tests.ts create mode 100644 types/react-dnd-touch-backend/tsconfig.json create mode 100644 types/react-dnd-touch-backend/tslint.json diff --git a/types/react-dnd-touch-backend/index.d.ts b/types/react-dnd-touch-backend/index.d.ts new file mode 100644 index 0000000000..91ea6ce999 --- /dev/null +++ b/types/react-dnd-touch-backend/index.d.ts @@ -0,0 +1,12 @@ +// Type definitions for react-dnd-touch-backend 0.3 +// Project: https://github.com/yahoo/react-dnd-touch-backend#readme +// Definitions by: Daniel Król +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +import * as ReactDnd from "react-dnd"; + +export default function createTouchBackend(options: TouchBackendOptions): ReactDnd.Backend; + +export interface TouchBackendOptions { + enableMouseEvents?: boolean; +} diff --git a/types/react-dnd-touch-backend/react-dnd-touch-backend-tests.ts b/types/react-dnd-touch-backend/react-dnd-touch-backend-tests.ts new file mode 100644 index 0000000000..07994e71be --- /dev/null +++ b/types/react-dnd-touch-backend/react-dnd-touch-backend-tests.ts @@ -0,0 +1,7 @@ +import * as ReactDnd from "react-dnd"; +import TouchBackend from "react-dnd-touch-backend"; + +const component = () => null; + +const dndComponent = ReactDnd.DragDropContext(TouchBackend)(component); +const dndComponentMouseEvents = ReactDnd.DragDropContext(TouchBackend({enableMouseEvents: true}))(component); diff --git a/types/react-dnd-touch-backend/tsconfig.json b/types/react-dnd-touch-backend/tsconfig.json new file mode 100644 index 0000000000..926592e1c3 --- /dev/null +++ b/types/react-dnd-touch-backend/tsconfig.json @@ -0,0 +1,24 @@ +{ + "compilerOptions": { + "module": "commonjs", + "lib": [ + "es6", + "dom" + ], + "noImplicitAny": true, + "noImplicitThis": true, + "strictNullChecks": true, + "strictFunctionTypes": true, + "baseUrl": "../", + "typeRoots": [ + "../" + ], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true + }, + "files": [ + "index.d.ts", + "react-dnd-touch-backend-tests.ts" + ] +} diff --git a/types/react-dnd-touch-backend/tslint.json b/types/react-dnd-touch-backend/tslint.json new file mode 100644 index 0000000000..3db14f85ea --- /dev/null +++ b/types/react-dnd-touch-backend/tslint.json @@ -0,0 +1 @@ +{ "extends": "dtslint/dt.json" } From 9839cce53d7398d40f2a7d04270944a0065e4a9b Mon Sep 17 00:00:00 2001 From: Joel Hegg Date: Wed, 4 Oct 2017 19:38:10 -0400 Subject: [PATCH 094/828] Add type defintions for actions-on-google --- .../actions-on-google-tests.ts | 33 + types/actions-on-google/actions-sdk-app.d.ts | 408 +++++ types/actions-on-google/api-ai-app.d.ts | 572 +++++++ types/actions-on-google/assistant-app.d.ts | 1399 ++++++++++++++++ types/actions-on-google/index.d.ts | 39 + types/actions-on-google/response-builder.d.ts | 333 ++++ types/actions-on-google/transactions.d.ts | 1406 +++++++++++++++++ types/actions-on-google/tsconfig.json | 27 + types/actions-on-google/tslint.json | 1 + 9 files changed, 4218 insertions(+) create mode 100644 types/actions-on-google/actions-on-google-tests.ts create mode 100644 types/actions-on-google/actions-sdk-app.d.ts create mode 100644 types/actions-on-google/api-ai-app.d.ts create mode 100644 types/actions-on-google/assistant-app.d.ts create mode 100644 types/actions-on-google/index.d.ts create mode 100644 types/actions-on-google/response-builder.d.ts create mode 100644 types/actions-on-google/transactions.d.ts create mode 100644 types/actions-on-google/tsconfig.json create mode 100644 types/actions-on-google/tslint.json diff --git a/types/actions-on-google/actions-on-google-tests.ts b/types/actions-on-google/actions-on-google-tests.ts new file mode 100644 index 0000000000..b7632217e2 --- /dev/null +++ b/types/actions-on-google/actions-on-google-tests.ts @@ -0,0 +1,33 @@ +import { ActionsSdkApp, ActionsSdkAppOptions, ApiAiApp, ApiAiAppOptions, AssistantApp, + Responses, Transactions } from 'actions-on-google'; +import * as express from 'express'; + +function testActionsSdk(request: express.Request, response: express.Response) { + const app = new ActionsSdkApp({request, response}); + const actionMap = new Map(); + actionMap.set(app.StandardIntents.MAIN, () => { + const richResponse: Responses.RichResponse = app.buildRichResponse() + .addSimpleResponse('Hello world') + .addSuggestions(['foo', 'bar']); + app.ask(richResponse); + }); + app.handleRequest(actionMap); +} + +function testApiAi(request: express.Request, response: express.Response) { + const app = new ApiAiApp({request, response}); + const actionMap = new Map(); + actionMap.set(app.StandardIntents.MAIN, () => { + const order: Transactions.Order = app.buildOrder('foo'); + app.askForTransactionDecision(order, { + type: app.Transactions.PaymentType.PAYMENT_CARD, + displayName: 'VISA-1234', + deliveryAddressRequired: true + }); + }); + app.handleRequest(actionMap); +} + +const expressApp = express(); +expressApp.get('/actionssdk', (req, res) => testActionsSdk); +expressApp.get('/apiai', (req, res) => testApiAi); diff --git a/types/actions-on-google/actions-sdk-app.d.ts b/types/actions-on-google/actions-sdk-app.d.ts new file mode 100644 index 0000000000..be399b4783 --- /dev/null +++ b/types/actions-on-google/actions-sdk-app.d.ts @@ -0,0 +1,408 @@ +/** + * Copyright 2017 Google Inc. All Rights Reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import { Request, Response } from 'express'; + +import { AssistantApp, DeviceLocation, SessionStartedFunction, User } from './assistant-app'; +import { Carousel, List, RichResponse, SimpleResponse } from './response-builder'; +import { TransactionDecision } from './transactions'; + +// --------------------------------------------------------------------------- +// Actions SDK support +// --------------------------------------------------------------------------- + +export interface ActionsSdkAppOptions { + request: Request; + response: Response; + sessionStarted?: SessionStartedFunction; +} + +/** + * This is the class that handles the conversation API directly from Assistant, + * providing implementation for all the methods available in the API. + */ +export class ActionsSdkApp extends AssistantApp { + /** + * Constructor for ActionsSdkApp object. + * To be used in the Actions SDK HTTP endpoint logic. + * + * @example + * const ActionsSdkApp = require('actions-on-google').ActionsSdkApp; + * const app = new ActionsSdkApp({request: request, response: response, + * sessionStarted:sessionStarted}); + * + * @param {Object} options JSON configuration. + * @param {Object} options.request Express HTTP request object. + * @param {Object} options.response Express HTTP response object. + * @param {Function=} options.sessionStarted Function callback when session starts. + * @actionssdk + */ + constructor(options: ActionsSdkAppOptions); + + /** + * Validates whether request is from Assistant through signature verification. + * Uses Google-Auth-Library to verify authorization token against given + * Google Cloud Project ID. Auth token is given in request header with key, + * "Authorization". + * + * @example + * const app = new ActionsSdkApp({request, response}); + * app.isRequestFromAssistant('nodejs-cloud-test-project-1234') + * .then(() => { + * app.ask('Hey there, thanks for stopping by!'); + * }) + * .catch(err => { + * response.status(400).send(); + * }); + * + * @param {string} projectId Google Cloud Project ID for the Assistant app. + * @param {Promise} Promise resolving with ID token if request is from + * a valid source, otherwise rejects with the error reason for an invalid + * token. + * @actionssdk + */ + isRequestFromAssistant(projectId: string): Promise; + + /** + * Gets the request Conversation API version. + * + * @example + * const app = new ActionsSdkApp({request: request, response: response}); + * const apiVersion = app.getApiVersion(); + * + * @return {string} Version value or null if no value. + * @actionssdk + */ + getApiVersion(): string; + + /** + * Gets the user's raw input query. + * + * @example + * const app = new ActionsSdkApp({request: request, response: response}); + * app.tell('You said ' + app.getRawInput()); + * + * @return {string} User's raw query or null if no value. + * @actionssdk + */ + getRawInput(): string; + + /** + * Gets previous JSON dialog state that the app sent to Assistant. + * Alternatively, use the app.data field to store JSON values between requests. + * + * @example + * const app = new ActionsSdkApp({request: request, response: response}); + * const dialogState = app.getDialogState(); + * + * @return {Object} JSON object provided to the Assistant in the previous + * user turn or {} if no value. + * @actionssdk + */ + getDialogState(): object; + + /** + * Gets the "versionLabel" specified inside the Action Package. + * Used by app to do version control. + * + * @example + * const app = new ActionsSdkApp({request: request, response: response}); + * const actionVersionLabel = app.getActionVersionLabel(); + * + * @return {string} The specified version label or null if unspecified. + * @actionssdk + */ + getActionVersionLabel(): string; + + /** + * Gets the unique conversation ID. It's a new ID for the initial query, + * and stays the same until the end of the conversation. + * + * @example + * const app = new ActionsSdkApp({request: request, response: response}); + * const conversationId = app.getConversationId(); + * + * @return {string} Conversation ID or null if no value. + * @actionssdk + */ + getConversationId(): string; + + /** + * Get the current intent. Alternatively, using a handler Map with + * {@link AssistantApp#handleRequest|handleRequest}, the client library will + * automatically handle the incoming intents. + * + * @example + * const app = new ActionsSdkApp({request: request, response: response}); + * + * function responseHandler (app) { + * const intent = app.getIntent(); + * switch (intent) { + * case app.StandardIntents.MAIN: + * const inputPrompt = app.buildInputPrompt(false, 'Welcome to action snippets! Say anything.'); + * app.ask(inputPrompt); + * break; + * + * case app.StandardIntents.TEXT: + * app.tell('You said ' + app.getRawInput()); + * break; + * } + * } + * + * app.handleRequest(responseHandler); + * + * @return {string} Intent id or null if no value. + * @actionssdk + */ + getIntent(): string; + + /** + * Get the argument value by name from the current intent. If the argument + * is not a text argument, the entire argument object is returned. + * + * Note: If incoming request is using an API version under 2 (e.g. 'v1'), + * the argument object will be in Proto2 format (snake_case, etc). + * + * @param {string} argName Name of the argument. + * @return {string} Argument value matching argName + * or null if no matching argument. + * @actionssdk + */ + getArgument(argName: string): string; + + /** + * Returns the option key user chose from options response. + * + * @example + * const app = new App({request: req, response: res}); + * + * function pickOption (app) { + * if (app.hasSurfaceCapability(app.SurfaceCapabilities.SCREEN_OUTPUT)) { + * app.askWithCarousel('Which of these looks good?', + * app.buildCarousel().addItems( + * app.buildOptionItem('another_choice', ['Another choice']). + * setTitle('Another choice').setDescription('Choose me!'))); + * } else { + * app.ask('What would you like?'); + * } + * } + * + * function optionPicked (app) { + * app.ask('You picked ' + app.getSelectedOption()); + * } + * + * const actionMap = new Map(); + * actionMap.set(app.StandardIntents.TEXT, pickOption); + * actionMap.set(app.StandardIntents.OPTION, optionPicked); + * + * app.handleRequest(actionMap); + * + * @return {string} Option key of selected item. Null if no option selected or + * if current intent is not OPTION intent. + * @actionssdk + */ + getSelectedOption(): string; + + /** + * Asks to collect user's input; all user's queries need to be sent to + * the app. + * {@link https://developers.google.com/actions/policies/general-policies#user_experience|The guidelines when prompting the user for a response must be followed at all times}. + * + * @example + * const app = new ActionsSdkApp({request: request, response: response}); + * + * function mainIntent (app) { + * const inputPrompt = app.buildInputPrompt(true, 'Hi! ' + + * 'I can read out an ordinal like ' + + * '123. Say a number.', + * ['I didn\'t hear a number', 'If you\'re still there, what\'s the number?', 'What is the number?']); + * app.ask(inputPrompt); + * } + * + * function rawInput (app) { + * if (app.getRawInput() === 'bye') { + * app.tell('Goodbye!'); + * } else { + * const inputPrompt = app.buildInputPrompt(true, 'You said, ' + + * app.getRawInput() + '', + * ['I didn\'t hear a number', 'If you\'re still there, what\'s the number?', 'What is the number?']); + * app.ask(inputPrompt); + * } + * } + * + * const actionMap = new Map(); + * actionMap.set(app.StandardIntents.MAIN, mainIntent); + * actionMap.set(app.StandardIntents.TEXT, rawInput); + * + * app.handleRequest(actionMap); + * + * @param {Object|SimpleResponse|RichResponse} inputPrompt Holding initial and + * no-input prompts. + * @param {Object=} dialogState JSON object the app uses to hold dialog state that + * will be circulated back by App. + * @return The response that is sent to Assistant to ask user to provide input. + * @actionssdk + */ + ask(inputPrompt: object | SimpleResponse | RichResponse, dialogState?: object): object; + + /** + * Asks to collect user's input with a list. + * + * @example + * const app = new ActionsSdkApp({request, response}); + * + * function welcomeIntent (app) { + * app.askWithlist('Which of these looks good?', + * app.buildList('List title') + * .addItems([ + * app.buildOptionItem(SELECTION_KEY_ONE, + * ['synonym of KEY_ONE 1', 'synonym of KEY_ONE 2']) + * .setTitle('Number one'), + * app.buildOptionItem(SELECTION_KEY_TWO, + * ['synonym of KEY_TWO 1', 'synonym of KEY_TWO 2']) + * .setTitle('Number two'), + * ])); + * } + * + * function optionIntent (app) { + * if (app.getSelectedOption() === SELECTION_KEY_ONE) { + * app.tell('Number one is a great choice!'); + * } else { + * app.tell('Number two is a great choice!'); + * } + * } + * + * const actionMap = new Map(); + * actionMap.set(app.StandardIntents.TEXT, welcomeIntent); + * actionMap.set(app.StandardIntents.OPTION, optionIntent); + * app.handleRequest(actionMap); + * + * @param {Object|SimpleResponse|RichResponse} inputPrompt Holding initial and + * no-input prompts. Cannot contain basic card. + * @param {List} list List built with {@link AssistantApp#buildList|buildList}. + * @param {Object=} dialogState JSON object the app uses to hold dialog state that + * will be circulated back by Assistant. + * @return The response that is sent to Assistant to ask user to provide input. + * @actionssdk + */ + askWithList(inputPrompt: object | SimpleResponse | RichResponse, list: List, dialogState?: object): object; + + /** + * Asks to collect user's input with a carousel. + * + * @example + * const app = new ActionsSdkApp({request, response}); + * + * function welcomeIntent (app) { + * app.askWithCarousel('Which of these looks good?', + * app.buildCarousel() + * .addItems([ + * app.buildOptionItem(SELECTION_KEY_ONE, + * ['synonym of KEY_ONE 1', 'synonym of KEY_ONE 2']) + * .setTitle('Number one'), + * app.buildOptionItem(SELECTION_KEY_TWO, + * ['synonym of KEY_TWO 1', 'synonym of KEY_TWO 2']) + * .setTitle('Number two'), + * ])); + * } + * + * function optionIntent (app) { + * if (app.getSelectedOption() === SELECTION_KEY_ONE) { + * app.tell('Number one is a great choice!'); + * } else { + * app.tell('Number two is a great choice!'); + * } + * } + * + * const actionMap = new Map(); + * actionMap.set(app.StandardIntents.TEXT, welcomeIntent); + * actionMap.set(app.StandardIntents.OPTION, optionIntent); + * app.handleRequest(actionMap); + * + * @param {Object|SimpleResponse|RichResponse} inputPrompt Holding initial and + * no-input prompts. Cannot contain basic card. + * @param {Carousel} carousel Carousel built with + * {@link AssistantApp#buildCarousel|buildCarousel}. + * @param {Object=} dialogState JSON object the app uses to hold dialog state that + * will be circulated back by Assistant. + * @return The response that is sent to Assistant to ask user to provide input. + * @actionssdk + */ + askWithCarousel(inputPrompt: object | SimpleResponse | RichResponse, carousel: Carousel, dialogState?: object): object; + + /** + * Tells Assistant to render the speech response and close the mic. + * + * @example + * const app = new ActionsSdkApp({request: request, response: response}); + * + * function mainIntent (app) { + * const inputPrompt = app.buildInputPrompt(true, 'Hi! ' + + * 'I can read out an ordinal like ' + + * '123. Say a number.', + * ['I didn\'t hear a number', 'If you\'re still there, what\'s the number?', 'What is the number?']); + * app.ask(inputPrompt); + * } + * + * function rawInput (app) { + * if (app.getRawInput() === 'bye') { + * app.tell('Goodbye!'); + * } else { + * const inputPrompt = app.buildInputPrompt(true, 'You said, ' + + * app.getRawInput() + '', + * ['I didn\'t hear a number', 'If you\'re still there, what\'s the number?', 'What is the number?']); + * app.ask(inputPrompt); + * } + * } + * + * const actionMap = new Map(); + * actionMap.set(app.StandardIntents.MAIN, mainIntent); + * actionMap.set(app.StandardIntents.TEXT, rawInput); + * + * app.handleRequest(actionMap); + * + * @param {string|SimpleResponse|RichResponse} textToSpeech Final response. + * Spoken response can be SSML. + * @return The HTTP response that is sent back to Assistant. + * @actionssdk + */ + tell(textToSpeech: string | SimpleResponse | RichResponse): object; + + /** + * Builds the {@link https://developers.google.com/actions/reference/conversation#InputPrompt|InputPrompt object} + * from initial prompt and no-input prompts. + * + * The App needs one initial prompt to start the conversation. If there is no user response, + * the App re-opens the mic and renders the no-input prompts three times + * (one for each no-input prompt that was configured) to help the user + * provide the right response. + * + * Note: we highly recommend app to provide all the prompts required here in order to ensure a + * good user experience. + * + * @example + * const inputPrompt = app.buildInputPrompt(false, 'Welcome to action snippets! Say a number.', + * ['Say any number', 'Pick a number', 'What is the number?']); + * app.ask(inputPrompt); + * + * @param {boolean} isSsml Indicates whether the text to speech is SSML or not. + * @param {string} initialPrompt The initial prompt the App asks the user. + * @param {Array=} noInputs Array of re-prompts when the user does not respond (max 3). + * @return {Object} An {@link https://developers.google.com/actions/reference/conversation#InputPrompt|InputPrompt object}. + * @actionssdk + */ + buildInputPrompt(isSsml: boolean, initialPrompt: string, noInputs: string[]): object; +} diff --git a/types/actions-on-google/api-ai-app.d.ts b/types/actions-on-google/api-ai-app.d.ts new file mode 100644 index 0000000000..b7dc28b86a --- /dev/null +++ b/types/actions-on-google/api-ai-app.d.ts @@ -0,0 +1,572 @@ +/** + * Copyright 2017 Google Inc. All Rights Reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import { Request, Response } from 'express'; + +import { AssistantApp, DeviceLocation, SessionStartedFunction, User } from './assistant-app'; +import { Carousel, List, RichResponse, SimpleResponse } from './response-builder'; +import { TransactionDecision } from './transactions'; + +// --------------------------------------------------------------------------- +// API.AI support +// --------------------------------------------------------------------------- + +/** + * API.AI {@link https://docs.api.ai/docs/concept-contexts|Context}. + */ +export interface Context { + /** Full name of the context. */ + name: string; + /** + * Parameters carried within this context. + * See {@link https://docs.api.ai/docs/concept-actions#section-extracting-values-from-contexts|here}. + */ + parameters: object; + /** Remaining number of intents */ + lifespan: number; +} + +export interface ApiAiAppOptions { + request: Request; + response: Response; + sessionStarted?: SessionStartedFunction; +} + +/** + * This is the class that handles the communication with API.AI's fulfillment API. + */ +export class ApiAiApp extends AssistantApp { + /** + * Constructor for ApiAiApp object. + * To be used in the API.AI fulfillment webhook logic. + * + * @example + * const ApiAiApp = require('actions-on-google').ApiAiApp; + * const app = new ApiAiApp({request: request, response: response, + * sessionStarted:sessionStarted}); + * + * @param {Object} options JSON configuration. + * @param {Object} options.request Express HTTP request object. + * @param {Object} options.response Express HTTP response object. + * @param {Function=} options.sessionStarted Function callback when session starts. + * Only called if webhook is enabled for welcome/triggering intents, and + * called from Web Simulator or Google Home device (i.e., not API.AI simulator). + * @apiai + */ + constructor(options: ApiAiAppOptions); + + /** + * Verifies whether the request comes from API.AI. + * + * @param {string} key The header key specified by the developer in the + * API.AI Fulfillment settings of the app. + * @param {string} value The private value specified by the developer inside the + * fulfillment header. + * @return {boolean} True if the request comes from API.AI. + * @apiai + */ + isRequestFromApiAi(key: string, value: string): boolean; + + /** + * Get the current intent. Alternatively, using a handler Map with + * {@link AssistantApp#handleRequest|handleRequest}, + * the client library will automatically handle the incoming intents. + * 'Intent' in the API.ai context translates into the current action. + * + * @example + * const app = new ApiAiApp({request: request, response: response}); + * + * function responseHandler (app) { + * const intent = app.getIntent(); + * switch (intent) { + * case WELCOME_INTENT: + * app.ask('Welcome to action snippets! Say a number.'); + * break; + * + * case NUMBER_INTENT: + * const number = app.getArgument(NUMBER_ARGUMENT); + * app.tell('You said ' + number); + * break; + * } + * } + * + * app.handleRequest(responseHandler); + * + * @return {string} Intent id or null if no value (action name). + * @apiai + */ + getIntent(): string; + + /** + * Get the argument value by name from the current intent. If the argument + * is included in originalRequest, and is not a text argument, the entire + * argument object is returned. + * + * Note: If incoming request is using an API version under 2 (e.g. 'v1'), + * the argument object will be in Proto2 format (snake_case, etc). + * + * @example + * const app = new ApiAiApp({request: request, response: response}); + * const WELCOME_INTENT = 'input.welcome'; + * const NUMBER_INTENT = 'input.number'; + * + * function welcomeIntent (app) { + * app.ask('Welcome to action snippets! Say a number.'); + * } + * + * function numberIntent (app) { + * const number = app.getArgument(NUMBER_ARGUMENT); + * app.tell('You said ' + number); + * } + * + * const actionMap = new Map(); + * actionMap.set(WELCOME_INTENT, welcomeIntent); + * actionMap.set(NUMBER_INTENT, numberIntent); + * app.handleRequest(actionMap); + * + * @param {string} argName Name of the argument. + * @return {Object} Argument value matching argName + * or null if no matching argument. + * @apiai + */ + getArgument(argName: string): object; + + /** + * Get the context argument value by name from the current intent. Context + * arguments include parameters collected in previous intents during the + * lifespan of the given context. If the context argument has an original + * value, usually representing the underlying entity value, that will be given + * as part of the return object. + * + * @example + * const app = new ApiAiApp({request: request, response: response}); + * const WELCOME_INTENT = 'input.welcome'; + * const NUMBER_INTENT = 'input.number'; + * const OUT_CONTEXT = 'output_context'; + * const NUMBER_ARG = 'myNumberArg'; + * + * function welcomeIntent (app) { + * const parameters = {}; + * parameters[NUMBER_ARG] = '42'; + * app.setContext(OUT_CONTEXT, 1, parameters); + * app.ask('Welcome to action snippets! Ask me for your number.'); + * } + * + * function numberIntent (app) { + * const number = app.getContextArgument(OUT_CONTEXT, NUMBER_ARG); + * // number === { value: 42 } + * app.tell('Your number is ' + number.value); + * } + * + * const actionMap = new Map(); + * actionMap.set(WELCOME_INTENT, welcomeIntent); + * actionMap.set(NUMBER_INTENT, numberIntent); + * app.handleRequest(actionMap); + * + * @param {string} contextName Name of the context. + * @param {string} argName Name of the argument. + * @return {Object} Object containing value property and optional original + * property matching context argument. Null if no matching argument. + * @apiai + */ + getContextArgument(contextName: string, argName: string): object; + + /** + * Returns the RichResponse constructed in API.AI response builder. + * + * @example + * const app = new App({request: req, response: res}); + * + * function tellFact (app) { + * let fact = 'Google was founded in 1998'; + * + * if (app.hasSurfaceCapability(app.SurfaceCapabilities.SCREEN_OUTPUT)) { + * app.ask(app.getIncomingRichResponse().addSimpleResponse('Here\'s a ' + + * 'fact for you. ' + fact + ' Which one do you want to hear about ' + + * 'next, Google\'s history or headquarters?')); + * } else { + * app.ask('Here\'s a fact for you. ' + fact + ' Which one ' + + * 'do you want to hear about next, Google\'s history or headquarters?'); + * } + * } + * + * const actionMap = new Map(); + * actionMap.set('tell.fact', tellFact); + * + * app.handleRequest(actionMap); + * + * @return {RichResponse} RichResponse created in API.AI. If no RichResponse was + * created, an empty RichResponse is returned. + * @apiai + */ + getIncomingRichResponse(): RichResponse; + + /** + * Returns the List constructed in API.AI response builder. + * + * @example + * const app = new App({request: req, response: res}); + * + * function pickOption (app) { + * if (app.hasSurfaceCapability(app.SurfaceCapabilities.SCREEN_OUTPUT)) { + * app.askWithList('Which of these looks good?', + * app.getIncomingList().addItems( + * app.buildOptionItem('another_choice', ['Another choice']). + * setTitle('Another choice'))); + * } else { + * app.ask('What would you like?'); + * } + * } + * + * const actionMap = new Map(); + * actionMap.set('pick.option', pickOption); + * + * app.handleRequest(actionMap); + * + * @return {List} List created in API.AI. If no List was created, an empty + * List is returned. + * @apiai + */ + getIncomingList(): List; + + /** + * Returns the Carousel constructed in API.AI response builder. + * + * @example + * const app = new App({request: req, response: res}); + * + * function pickOption (app) { + * if (app.hasSurfaceCapability(app.SurfaceCapabilities.SCREEN_OUTPUT)) { + * app.askWithCarousel('Which of these looks good?', + * app.getIncomingCarousel().addItems( + * app.buildOptionItem('another_choice', ['Another choice']). + * setTitle('Another choice').setDescription('Choose me!'))); + * } else { + * app.ask('What would you like?'); + * } + * } + * + * const actionMap = new Map(); + * actionMap.set('pick.option', pickOption); + * + * app.handleRequest(actionMap); + * + * @return {Carousel} Carousel created in API.AI. If no Carousel was created, + * an empty Carousel is returned. + * @apiai + */ + getIncomingCarousel(): Carousel; + + /** + * Returns the option key user chose from options response. + * + * @example + * const app = new App({request: req, response: res}); + * + * function pickOption (app) { + * if (app.hasSurfaceCapability(app.SurfaceCapabilities.SCREEN_OUTPUT)) { + * app.askWithCarousel('Which of these looks good?', + * app.getIncomingCarousel().addItems( + * app.buildOptionItem('another_choice', ['Another choice']). + * setTitle('Another choice').setDescription('Choose me!'))); + * } else { + * app.ask('What would you like?'); + * } + * } + * + * function optionPicked (app) { + * app.ask('You picked ' + app.getSelectedOption()); + * } + * + * const actionMap = new Map(); + * actionMap.set('pick.option', pickOption); + * actionMap.set('option.picked', optionPicked); + * + * app.handleRequest(actionMap); + * + * @return {string} Option key of selected item. Null if no option selected or + * if current intent is not OPTION intent. + * @apiai + */ + getSelectedOption(): string; + + /** + * Asks to collect the user's input. + * {@link https://developers.google.com/actions/policies/general-policies#user_experience|The guidelines when prompting the user for a response must be followed at all times}. + * + * NOTE: Due to a bug, if you specify the no-input prompts, + * the mic is closed after the 3rd prompt, so you should use the 3rd prompt + * for a bye message until the bug is fixed. + * + * @example + * const app = new ApiAiApp({request: request, response: response}); + * const WELCOME_INTENT = 'input.welcome'; + * const NUMBER_INTENT = 'input.number'; + * + * function welcomeIntent (app) { + * app.ask('Welcome to action snippets! Say a number.', + * ['Say any number', 'Pick a number', 'We can stop here. See you soon.']); + * } + * + * function numberIntent (app) { + * const number = app.getArgument(NUMBER_ARGUMENT); + * app.tell('You said ' + number); + * } + * + * const actionMap = new Map(); + * actionMap.set(WELCOME_INTENT, welcomeIntent); + * actionMap.set(NUMBER_INTENT, numberIntent); + * app.handleRequest(actionMap); + * + * @param {string|SimpleResponse|RichResponse} inputPrompt The input prompt + * response. + * @param {Array=} noInputs Array of re-prompts when the user does not respond (max 3). + * @return {Object} HTTP response. + * @apiai + */ + ask(inputPrompt: string | SimpleResponse | RichResponse, noInputs?: string[]): object; + + /** + * Asks to collect the user's input with a list. + * + * @example + * const app = new ApiAiApp({request, response}); + * const WELCOME_INTENT = 'input.welcome'; + * const OPTION_INTENT = 'option.select'; + * + * function welcomeIntent (app) { + * app.askWithList('Which of these looks good?', + * app.buildList('List title') + * .addItems([ + * app.buildOptionItem(SELECTION_KEY_ONE, + * ['synonym of KEY_ONE 1', 'synonym of KEY_ONE 2']) + * .setTitle('Title of First List Item'), + * app.buildOptionItem(SELECTION_KEY_TWO, + * ['synonym of KEY_TWO 1', 'synonym of KEY_TWO 2']) + * .setTitle('Title of Second List Item'), + * ])); + * } + * + * function optionIntent (app) { + * if (app.getSelectedOption() === SELECTION_KEY_ONE) { + * app.tell('Number one is a great choice!'); + * } else { + * app.tell('Number two is a great choice!'); + * } + * } + * + * const actionMap = new Map(); + * actionMap.set(WELCOME_INTENT, welcomeIntent); + * actionMap.set(OPTION_INTENT, optionIntent); + * app.handleRequest(actionMap); + * + * @param {string|RichResponse|SimpleResponse} inputPrompt The input prompt + * response. + * @param {List} list List built with {@link AssistantApp#buildList|buildList}. + * @return {Object} HTTP response. + * @apiai + */ + askWithList(inputPrompt: string | RichResponse | SimpleResponse, list: List): object; + + /** + * Asks to collect the user's input with a carousel. + * + * @example + * const app = new ApiAiApp({request, response}); + * const WELCOME_INTENT = 'input.welcome'; + * const OPTION_INTENT = 'option.select'; + * + * function welcomeIntent (app) { + * app.askWithCarousel('Which of these looks good?', + * app.buildCarousel() + * .addItems([ + * app.buildOptionItem(SELECTION_KEY_ONE, + * ['synonym of KEY_ONE 1', 'synonym of KEY_ONE 2']) + * .setTitle('Number one'), + * app.buildOptionItem(SELECTION_KEY_TWO, + * ['synonym of KEY_TWO 1', 'synonym of KEY_TWO 2']) + * .setTitle('Number two'), + * ])); + * } + * + * function optionIntent (app) { + * if (app.getSelectedOption() === SELECTION_KEY_ONE) { + * app.tell('Number one is a great choice!'); + * } else { + * app.tell('Number two is a great choice!'); + * } + * } + * + * const actionMap = new Map(); + * actionMap.set(WELCOME_INTENT, welcomeIntent); + * actionMap.set(OPTION_INTENT, optionIntent); + * app.handleRequest(actionMap); + * + * @param {string|RichResponse|SimpleResponse} inputPrompt The input prompt + * response. + * @param {Carousel} carousel Carousel built with + * {@link AssistantApp#buildCarousel|buildCarousel}. + * @return {Object} HTTP response. + * @apiai + */ + askWithCarousel(inputPrompt: string | RichResponse | SimpleResponse, carousel: Carousel): object; + + /** + * Tells the Assistant to render the speech response and close the mic. + * + * @example + * const app = new ApiAiApp({request: request, response: response}); + * const WELCOME_INTENT = 'input.welcome'; + * const NUMBER_INTENT = 'input.number'; + * + * function welcomeIntent (app) { + * app.ask('Welcome to action snippets! Say a number.'); + * } + * + * function numberIntent (app) { + * const number = app.getArgument(NUMBER_ARGUMENT); + * app.tell('You said ' + number); + * } + * + * const actionMap = new Map(); + * actionMap.set(WELCOME_INTENT, welcomeIntent); + * actionMap.set(NUMBER_INTENT, numberIntent); + * app.handleRequest(actionMap); + * + * @param {string|SimpleResponse|RichResponse} textToSpeech Final response. + * Spoken response can be SSML. + * @return The response that is sent back to Assistant. + * @apiai + */ + tell(speechResponse: string | SimpleResponse | RichResponse): object; + + /** + * Set a new context for the current intent. + * + * @example + * const app = new ApiAiApp({request: request, response: response}); + * const CONTEXT_NUMBER = 'number'; + * const NUMBER_ARGUMENT = 'myNumber'; + * + * function welcomeIntent (app) { + * app.setContext(CONTEXT_NUMBER); + * app.ask('Welcome to action snippets! Say a number.'); + * } + * + * function numberIntent (app) { + * const number = app.getArgument(NUMBER_ARGUMENT); + * app.tell('You said ' + number); + * } + * + * const actionMap = new Map(); + * actionMap.set(WELCOME_INTENT, welcomeIntent); + * actionMap.set(NUMBER_INTENT, numberIntent); + * app.handleRequest(actionMap); + * + * @param {string} name Name of the context. API.AI converts to lowercase. + * @param {int} [lifespan=1] Context lifespan. + * @param {Object=} parameters Context JSON parameters. + * @apiai + */ + setContext(name: string, lifespan: number, parameters?: object): void; + + /** + * Returns the incoming contexts for this intent. + * + * @example + * const app = new ApiAiApp({request: request, response: response}); + * const CONTEXT_NUMBER = 'number'; + * const NUMBER_ARGUMENT = 'myNumber'; + * + * function welcomeIntent (app) { + * app.setContext(CONTEXT_NUMBER); + * app.ask('Welcome to action snippets! Say a number.'); + * } + * + * function numberIntent (app) { + * let contexts = app.getContexts(); + * // contexts === [{ + * // name: 'number', + * // lifespan: 0, + * // parameters: { + * // myNumber: '23', + * // myNumber.original: '23' + * // } + * // }] + * const number = app.getArgument(NUMBER_ARGUMENT); + * app.tell('You said ' + number); + * } + * + * const actionMap = new Map(); + * actionMap.set(WELCOME_INTENT, welcomeIntent); + * actionMap.set(NUMBER_INTENT, numberIntent); + * app.handleRequest(actionMap); + * + * @return {Context[]} Empty if no active contexts. + * @apiai + */ + getContexts(): Context[]; + + /** + * Returns the incoming context by name for this intent. + * + * @example + * const app = new ApiAiapp({request: request, response: response}); + * const CONTEXT_NUMBER = 'number'; + * const NUMBER_ARGUMENT = 'myNumber'; + * + * function welcomeIntent (app) { + * app.setContext(CONTEXT_NUMBER); + * app.ask('Welcome to action snippets! Say a number.'); + * } + * + * function numberIntent (app) { + * let context = app.getContext(CONTEXT_NUMBER); + * // context === { + * // name: 'number', + * // lifespan: 0, + * // parameters: { + * // myNumber: '23', + * // myNumber.original: '23' + * // } + * // } + * const number = app.getArgument(NUMBER_ARGUMENT); + * app.tell('You said ' + number); + * } + * + * const actionMap = new Map(); + * actionMap.set(WELCOME_INTENT, welcomeIntent); + * actionMap.set(NUMBER_INTENT, numberIntent); + * app.handleRequest(actionMap); + * + * @return {Object} Context value matching name + * or null if no matching context. + * @apiai + */ + getContext(name: string): object; + + /** + * Gets the user's raw input query. + * + * @example + * const app = new ApiAiApp({request: request, response: response}); + * app.tell('You said ' + app.getRawInput()); + * + * @return {string} User's raw query or null if no value. + * @apiai + */ + getRawInput(): string; +} diff --git a/types/actions-on-google/assistant-app.d.ts b/types/actions-on-google/assistant-app.d.ts new file mode 100644 index 0000000000..01d3bcf046 --- /dev/null +++ b/types/actions-on-google/assistant-app.d.ts @@ -0,0 +1,1399 @@ +/** + * Copyright 2017 Google Inc. All Rights Reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import { Request, Response } from 'express'; + +import { BasicCard, Carousel, List, OptionItem, RichResponse } from './response-builder'; +import { ActionPaymentTransactionConfig, Cart, GooglePaymentTransactionConfig, + LineItem, Location, Order, OrderUpdate, TransactionDecision, + TransactionValues } from './transactions'; + +/** + * User provided date/time info. + */ +export interface DateTime { + date: { + year: number; + month: number; + day: number; + }; + time: { + hours: number; + minutes: number; + seconds: number; + nanos: number; + }; +} + +/** + * User's permissioned name info. + */ +export interface UserName { + /** User's display name. */ + displayName: string; + /** User's given name. */ + givenName: string; + /** User's family name. */ + familyName: string; +} + +/** + * User's permissioned device location. + */ +export interface DeviceLocation { + /** {latitude, longitude}. Requested with SupportedPermissions.DEVICE_PRECISE_LOCATION. */ + coordinates: object; + /** Full, formatted street address. Requested with SupportedPermissions.DEVICE_PRECISE_LOCATION. */ + address: string; + /** Zip code. Requested with SupportedPermissions.DEVICE_COARSE_LOCATION. */ + zipCode: string; + /** Device city. Requested with SupportedPermissions.DEVICE_COARSE_LOCATION. */ + city: string; +} + +/** + * User object. + */ +export interface User { + /** Random string ID for Google user. */ + userId: string; + /** User name information. Null if not requested with {@link AssistantApp#askForPermission|askForPermission(SupportedPermissions.NAME)}. */ + userName: UserName; + /** Unique Oauth2 token. Only available with account linking. */ + accessToken: string; +} + +/** + * Actions on Google Surface. + */ +export interface Surface { + /** Capabilities of the surface. */ + capabilities: Capability[]; +} + +/** + * Surface capability. + */ +export interface Capability { + /** Name of the capability. */ + name: string; +} + +/** + * List of standard intents that the app provides. + * @enum {string} + */ +export type StandardIntents = + /** App fires MAIN intent for queries like [talk to $app]. */ + 'actions.intent.MAIN' | 'assistant.intent.action.MAIN' | + /** App fires TEXT intent when action issues ask intent. */ + 'actions.intent.TEXT' | 'assistant.intent.action.TEXT' | + /** App fires PERMISSION intent when action invokes askForPermission. */ + 'actions.intent.PERMISSION' | 'assistant.intent.action.PERMISSION' | + /** App fires OPTION intent when user chooses from options provided. */ + 'actions.intent.OPTION' | + /** App fires TRANSACTION_REQUIREMENTS_CHECK intent when action sets up transaction. */ + 'actions.intent.TRANSACTION_REQUIREMENTS_CHECK' | + /** App fires DELIVERY_ADDRESS intent when action asks for delivery address. */ + 'actions.intent.DELIVERY_ADDRESS' | + /** App fires TRANSACTION_DECISION intent when action asks for transaction decision. */ + 'actions.intent.TRANSACTION_DECISION' | + /** App fires CONFIRMATION intent when requesting affirmation from user. */ + 'actions.intent.CONFIRMATION' | + /** App fires DATETIME intent when requesting date/time from user. */ + 'actions.intent.DATETIME' | + /** App fires SIGN_IN intent when requesting sign-in from user. */ + 'actions.intent.SIGN_IN' | + /** App fires NO_INPUT intent when user doesn't provide input. */ + 'actions.intent.NO_INPUT' | + /** App fires CANCEL intent when user exits app mid-dialog. */ + 'actions.intent.CANCEL' | + /** App fires NEW_SURFACE intent when requesting handoff to a new surface from user. */ + 'actions.intent.NEW_SURFACE'; + +/** + * List of supported permissions the app supports. + * @enum {string} + */ +export type SupportedPermissions = + /** + * The user's name as defined in the + * {@link https://developers.google.com/actions/reference/conversation#UserProfile|UserProfile object} + */ + 'NAME' | + /** + * The location of the user's current device, as defined in the + * {@link https://developers.google.com/actions/reference/conversation#Location|Location object}. + */ + 'DEVICE_PRECISE_LOCATION' | + /** + * City and zipcode corresponding to the location of the user's current device, as defined in the + * {@link https://developers.google.com/actions/reference/conversation#Location|Location object}. + */ + 'DEVICE_COARSE_LOCATION'; + +/** + * List of built-in argument names. + * @enum {string} + */ +export type BuiltInArgNames = + /** Permission granted argument. */ + 'PERMISSION' | 'permission_granted' | + /** Option selected argument. */ + 'OPTION' | + /** Transaction requirements check result argument. */ + 'TRANSACTION_REQUIREMENTS_CHECK_RESULT' | + /** Delivery address value argument. */ + 'DELIVERY_ADDRESS_VALUE' | + /** Transactions decision argument. */ + 'TRANSACTION_DECISION_VALUE' | + /** Confirmation argument. */ + 'CONFIRMATION' | + /** DateTime argument. */ + 'DATETIME' | + /** Sign in status argument. */ + 'SIGN_IN' | + /** Reprompt count for consecutive NO_INPUT intents. */ + 'REPROMPT_COUNT' | + /** Flag representing finality of NO_INPUT intent. */ + 'IS_FINAL_REPROMPT' | + /** New surface value argument. */ + 'NEW_SURFACE'; + +/** + * List of possible conversation stages, as defined in the + * {@link https://developers.google.com/actions/reference/conversation#Conversation|Conversation object}. + * @enum {number} + */ +export type ConversationStages = + /** + * Unspecified conversation state. + */ + 'UNSPECIFIED' | 0 | + /** + * A new conversation. + */ + 'NEW' | 1 | + /** + * An active (ongoing) conversation. + */ + 'ACTIVE' | 2; + +/** + * List of surface capabilities supported by the app. + * @enum {string} + */ +export type SurfaceCapabilities = + /** + * The ability to output audio. + */ + 'actions.capability.AUDIO_OUTPUT' | + /** + * The ability to output on a screen + */ + 'actions.capability.SCREEN_OUTPUT'; + +/** + * List of possible user input types. + * @enum {number} + */ +export type InputTypes = + /** + * Unspecified. + */ + 'UNSPECIFIED' | 0 | + /** + * Input given by touch. + */ + 'TOUCH' | 1 | + /** + * Input given by voice (spoken). + */ + 'VOICE' | 2 | + /** + * Input given by keyboard (typed). + */ + 'KEYBOARD' | 3; + +/** + * List of possible sign in result status values. + * @enum {string} + */ +export type SignInStatus = + // Unknown status. + 'SIGN_IN_STATUS_UNSPECIFIED' | + // User successfully completed the account linking. + 'OK' | + // Cancelled or dismissed account linking. + 'CANCELLED' | + // System or network error. + 'ERROR'; + +export type SessionStartedFunction = () => any; + +export interface AssistantAppOptions { + request: Request; + response: Response; + sessionStarted?: SessionStartedFunction; +} + +export type AssistantAppRequestData = () => any; + +export type RequestHandler = (app: AssistantApp) => any; + +/** + * The Actions on Google client library AssistantApp base class. + * + * This class contains the methods that are shared between platforms to support the conversation API + * protocol from Assistant. It also exports the 'State' class as a helper to represent states by + * name. + */ +export class AssistantApp { + /** + * The session state. + */ + readonly state: string; + + /** + * The session data in JSON format. + */ + readonly data: object; + + /** + * List of standard intents that the app provides. + * @enum {string} + */ + readonly StandardIntents: { + /** App fires MAIN intent for queries like [talk to $app]. */ + MAIN: StandardIntents, + /** App fires TEXT intent when action issues ask intent. */ + TEXT: StandardIntents, + /** App fires PERMISSION intent when action invokes askForPermission. */ + PERMISSION: StandardIntents, + /** App fires OPTION intent when user chooses from options provided. */ + OPTION: StandardIntents, + /** App fires TRANSACTION_REQUIREMENTS_CHECK intent when action sets up transaction. */ + TRANSACTION_REQUIREMENTS_CHECK: StandardIntents, + /** App fires DELIVERY_ADDRESS intent when action asks for delivery address. */ + DELIVERY_ADDRESS: StandardIntents, + /** App fires TRANSACTION_DECISION intent when action asks for transaction decision. */ + TRANSACTION_DECISION: StandardIntents, + /** App fires CONFIRMATION intent when requesting affirmation from user. */ + CONFIRMATION: StandardIntents, + /** App fires DATETIME intent when requesting date/time from user. */ + DATETIME: StandardIntents, + /** App fires SIGN_IN intent when requesting sign-in from user. */ + SIGN_IN: StandardIntents, + /** App fires NO_INPUT intent when user doesn't provide input. */ + NO_INPUT: StandardIntents, + /** App fires CANCEL intent when user exits app mid-dialog. */ + CANCEL: StandardIntents, + /** App fires NEW_SURFACE intent when requesting handoff to a new surface from user. */ + NEW_SURFACE: StandardIntents, + }; + + /** + * List of supported permissions the app supports. + * @enum {string} + */ + readonly SupportedPermissions: { + /** + * The user's name as defined in the + * {@link https://developers.google.com/actions/reference/conversation#UserProfile|UserProfile object} + */ + NAME: SupportedPermissions, + /** + * The location of the user's current device, as defined in the + * {@link https://developers.google.com/actions/reference/conversation#Location|Location object}. + */ + DEVICE_PRECISE_LOCATION: SupportedPermissions, + /** + * City and zipcode corresponding to the location of the user's current device, as defined in the + * {@link https://developers.google.com/actions/reference/conversation#Location|Location object}. + */ + DEVICE_COARSE_LOCATION: SupportedPermissions, + }; + + /** + * List of built-in argument names. + * @enum {string} + */ + readonly BuiltInArgNames: { + /** Permission granted argument. */ + PERMISSION_GRANTED: BuiltInArgNames, + /** Option selected argument. */ + OPTION: BuiltInArgNames, + /** Transaction requirements check result argument. */ + TRANSACTION_REQ_CHECK_RESULT: BuiltInArgNames, + /** Delivery address value argument. */ + DELIVERY_ADDRESS_VALUE: BuiltInArgNames, + /** Transactions decision argument. */ + TRANSACTION_DECISION_VALUE: BuiltInArgNames, + /** Confirmation argument. */ + CONFIRMATION: BuiltInArgNames, + /** DateTime argument. */ + DATETIME: BuiltInArgNames, + /** Sign in status argument. */ + SIGN_IN: BuiltInArgNames, + /** Reprompt count for consecutive NO_INPUT intents. */ + REPROMPT_COUNT: BuiltInArgNames, + /** Flag representing finality of NO_INPUT intent. */ + IS_FINAL_REPROMPT: BuiltInArgNames, + /** New surface value argument. */ + NEW_SURFACE: BuiltInArgNames, + }; + + /** + * List of possible conversation stages, as defined in the + * {@link https://developers.google.com/actions/reference/conversation#Conversation|Conversation object}. + * @enum {number} + */ + readonly ConversationStages: { + /** + * Unspecified conversation state. + */ + UNSPECIFIED: ConversationStages, + /** + * A new conversation. + */ + NEW: ConversationStages, + /** + * An active (ongoing) conversation. + */ + ACTIVE: ConversationStages, + }; + + /** + * List of surface capabilities supported by the app. + * @enum {string} + */ + readonly SurfaceCapabilities: { + /** + * The ability to output audio. + */ + AUDIO_OUTPUT: SurfaceCapabilities, + /** + * The ability to output on a screen + */ + SCREEN_OUTPUT: SurfaceCapabilities, + }; + + /** + * List of possible user input types. + * @enum {number} + */ + readonly InputTypes: { + /** + * Unspecified. + */ + UNSPECIFIED: InputTypes, + /** + * Input given by touch. + */ + TOUCH: InputTypes, + /** + * Input given by voice (spoken). + */ + VOICE: InputTypes, + /** + * Input given by keyboard (typed). + */ + KEYBOARD: InputTypes, + }; + + /** + * List of possible sign in result status values. + * @enum {string} + */ + readonly SignInStatus: { + // Unknown status. + UNSPECIFIED: SignInStatus, + // User successfully completed the account linking. + OK: SignInStatus, + // Cancelled or dismissed account linking. + CANCELLED: SignInStatus, + // System or network error. + ERROR: SignInStatus, + }; + + /** + * Values related to supporting {@link Transactions}. + * @type {object} + */ + readonly Transactions: typeof TransactionValues; + + readonly requestData: AssistantAppRequestData; + + /** + * Constructor for AssistantApp object. + * Should not be instantiated; rather instantiate one of the subclasses + * + * {@link ActionsSdkApp} or {@link ApiAiApp}. + * + * @param {Object} options JSON configuration. + * @param {Object} options.request Express HTTP request object. + * @param {Object} options.response Express HTTP response object. + * @param {Function=} options.sessionStarted Function callback when session starts. + * @param {function(): *} requestData Function that returns the + * request data object to be processed. + */ + constructor(options: AssistantAppOptions, requestData: AssistantAppRequestData); + + // --------------------------------------------------------------------------- + // Public APIs + // --------------------------------------------------------------------------- + + /** + * Handles the incoming Assistant request using a handler or Map of handlers. + * Each handler can be a function callback or Promise. + * + * @example + * // Actions SDK + * const app = new ActionsSdkApp({request: request, response: response}); + * + * function mainIntent (app) { + * const inputPrompt = app.buildInputPrompt(true, 'Hi! ' + + * 'I can read out an ordinal like ' + + * '123. Say a number.', + * ['I didn\'t hear a number', 'If you\'re still there, what\'s the number?', 'What is the number?']); + * app.ask(inputPrompt); + * } + * + * function rawInput (app) { + * if (app.getRawInput() === 'bye') { + * app.tell('Goodbye!'); + * } else { + * const inputPrompt = app.buildInputPrompt(true, 'You said, ' + + * app.getRawInput() + '', + * ['I didn\'t hear a number', 'If you\'re still there, what\'s the number?', 'What is the number?']); + * app.ask(inputPrompt); + * } + * } + * + * const actionMap = new Map(); + * actionMap.set(app.StandardIntents.MAIN, mainIntent); + * actionMap.set(app.StandardIntents.TEXT, rawInput); + * + * app.handleRequest(actionMap); + * + * // API.AI + * const app = new ApiAiApp({request: req, response: res}); + * const NAME_ACTION = 'make_name'; + * const COLOR_ARGUMENT = 'color'; + * const NUMBER_ARGUMENT = 'number'; + * + * function makeName (app) { + * const number = app.getArgument(NUMBER_ARGUMENT); + * const color = app.getArgument(COLOR_ARGUMENT); + * app.tell('Alright, your silly name is ' + + * color + ' ' + number + + * '! I hope you like it. See you next time.'); + * } + * + * const actionMap = new Map(); + * actionMap.set(NAME_ACTION, makeName); + * app.handleRequest(actionMap); + * + * @param {(Function|Map)} handler The handler (or Map of handlers) for the request. + * @actionssdk + * @apiai + */ + handleRequest(handler?: RequestHandler | Map): void; + + /** + * Equivalent to {@link AssistantApp#askForPermission|askForPermission}, + * but allows you to prompt the user for more than one permission at once. + * + * Notes: + * + * * The order in which you specify the permission prompts does not matter - + * it is controlled by the Assistant to provide a consistent user experience. + * * The user will be able to either accept all permissions at once, or none. + * If you wish to allow them to selectively accept one or other, make several + * dialog turns asking for each permission independently with askForPermission. + * * Asking for DEVICE_COARSE_LOCATION and DEVICE_PRECISE_LOCATION at once is + * equivalent to just asking for DEVICE_PRECISE_LOCATION + * + * @example + * const app = new ApiAIApp({request: req, response: res}); + * const REQUEST_PERMISSION_ACTION = 'request_permission'; + * const GET_RIDE_ACTION = 'get_ride'; + * + * function requestPermission (app) { + * const permission = [ + * app.SupportedPermissions.NAME, + * app.SupportedPermissions.DEVICE_PRECISE_LOCATION + * ]; + * app.askForPermissions('To pick you up', permissions); + * } + * + * function sendRide (app) { + * if (app.isPermissionGranted()) { + * const displayName = app.getUserName().displayName; + * const address = app.getDeviceLocation().address; + * app.tell('I will tell your driver to pick up ' + displayName + + * ' at ' + address); + * } else { + * // Response shows that user did not grant permission + * app.tell('Sorry, I could not figure out where to pick you up.'); + * } + * } + * const actionMap = new Map(); + * actionMap.set(REQUEST_PERMISSION_ACTION, requestPermission); + * actionMap.set(GET_RIDE_ACTION, sendRide); + * app.handleRequest(actionMap); + * + * @param {string} context Context why the permission is being asked; it's the TTS + * prompt prefix (action phrase) we ask the user. + * @param {Array} permissions Array of permissions App supports, each of + * which comes from AssistantApp.SupportedPermissions. + * @param {Object=} dialogState JSON object the app uses to hold dialog state that + * will be circulated back by Assistant. Used in {@link ActionsSdkAssistant}. + * @return A response is sent to Assistant to ask for the user's permission; for any + * invalid input, we return null. + * @actionssdk + * @apiai + */ + askForPermissions(context: string, permissions: string[], dialogState?: object): object; + + /** + * Checks whether user is in transactable state. + * + * @example + * const app = new ApiAiApp({request: request, response: response}); + * const WELCOME_INTENT = 'input.welcome'; + * const TXN_REQ_COMPLETE = 'txn.req.complete'; + * + * let transactionConfig = { + * deliveryAddressRequired: false, + * type: app.Transactions.PaymentType.BANK, + * displayName: 'Checking-1234' + * }; + * function welcomeIntent (app) { + * app.askForTransactionRequirements(transactionConfig); + * } + * + * function txnReqCheck (app) { + * if (app.getTransactionRequirementsResult() === app.Transactions.ResultType.OK) { + * // continue cart building flow + * } else { + * // don't continue cart building + * } + * } + * + * const actionMap = new Map(); + * actionMap.set(WELCOME_INTENT, welcomeIntent); + * actionMap.set(TXN_REQ_COMPLETE, txnReqCheck); + * app.handleRequest(actionMap); + * + * @param {ActionPaymentTransactionConfig|GooglePaymentTransactionConfig=} + * transactionConfig Configuration for the transaction. Includes payment + * options and order options. Optional if order has no payment or + * delivery. + * @param {Object=} dialogState JSON object the app uses to hold dialog state that + * will be circulated back by Assistant. Used in {@link ActionsSdkAssistant}. + * @return {Object} HTTP response. + * @actionssdk + * @apiai + */ + askForTransactionRequirements(transactionConfig?: ActionPaymentTransactionConfig | GooglePaymentTransactionConfig, dialogState?: object): object; + + /** + * Asks user to confirm transaction information. + * + * @example + * const app = new ApiAiApp({request: request, response: response}); + * const WELCOME_INTENT = 'input.welcome'; + * const TXN_COMPLETE = 'txn.complete'; + * + * let transactionConfig = { + * deliveryAddressRequired: false, + * type: app.Transactions.PaymentType.BANK, + * displayName: 'Checking-1234' + * }; + * + * let order = app.buildOrder(); + * // fill order cart + * + * function welcomeIntent (app) { + * app.askForTransaction(order, transactionConfig); + * } + * + * function txnComplete (app) { + * // respond with order update + * } + * + * const actionMap = new Map(); + * actionMap.set(WELCOME_INTENT, welcomeIntent); + * actionMap.set(TXN_COMPLETE, txnComplete); + * app.handleRequest(actionMap); + * + * @param {Object} order Order built with buildOrder(). + * @param {ActionPaymentTransactionConfig|GooglePaymentTransactionConfig} + * transactionConfig Configuration for the transaction. Includes payment + * options and order options. + * @param {Object=} dialogState JSON object the app uses to hold dialog state that + * will be circulated back by Assistant. Used in {@link ActionsSdkAssistant}. + * @apiai + */ + askForTransactionDecision(order: object, transactionConfig?: ActionPaymentTransactionConfig | GooglePaymentTransactionConfig, dialogState?: object): object; + + /** + * Asks the Assistant to guide the user to grant a permission. For example, + * if you want your app to get access to the user's name, you would invoke + * the askForPermission method with a context containing the reason for the request, + * and the AssistantApp.SupportedPermissions.NAME permission. With this, the Assistant will ask + * the user, in your agent's voice, the following: '[Context with reason for the request], + * I'll just need to get your name from Google, is that OK?'. + * + * Once the user accepts or denies the request, the Assistant will fire another intent: + * assistant.intent.action.PERMISSION with a boolean argument: AssistantApp.BuiltInArgNames.PERMISSION_GRANTED + * and, if granted, the information that you requested. + * + * Read more: + * + * * {@link https://developers.google.com/actions/reference/conversation#ExpectedIntent|Supported Permissions} + * * Check if the permission has been granted with {@link AssistantApp#isPermissionGranted|isPermissionsGranted} + * * {@link AssistantApp#getDeviceLocation|getDeviceLocation} + * * {@link AssistantApp#getUserName|getUserName} + * + * @example + * const app = new ApiAiApp({request: req, response: res}); + * const REQUEST_PERMISSION_ACTION = 'request_permission'; + * const GET_RIDE_ACTION = 'get_ride'; + * + * function requestPermission (app) { + * const permission = app.SupportedPermissions.NAME; + * app.askForPermission('To pick you up', permission); + * } + * + * function sendRide (app) { + * if (app.isPermissionGranted()) { + * const displayName = app.getUserName().displayName; + * app.tell('I will tell your driver to pick up ' + displayName); + * } else { + * // Response shows that user did not grant permission + * app.tell('Sorry, I could not figure out who to pick up.'); + * } + * } + * const actionMap = new Map(); + * actionMap.set(REQUEST_PERMISSION_ACTION, requestPermission); + * actionMap.set(GET_RIDE_ACTION, sendRide); + * app.handleRequest(actionMap); + * + * @param {string} context Context why permission is asked; it's the TTS + * prompt prefix (action phrase) we ask the user. + * @param {string} permission One of the permissions Assistant supports, each of + * which comes from AssistantApp.SupportedPermissions. + * @param {Object=} dialogState JSON object the app uses to hold dialog state that + * will be circulated back by Assistant. + * @return A response is sent to the Assistant to ask for the user's permission; + * for any invalid input, we return null. + * @actionssdk + * @apiai + */ + askForPermission(context: string, permission: string, dialogState?: object): object; + + /** + * Returns true if the request follows a previous request asking for + * permission from the user and the user granted the permission(s). Otherwise, + * false. Use with {@link AssistantApp#askForPermissions|askForPermissions}. + * + * @example + * const app = new ActionsSdkApp({request: request, response: response}); + * // or + * const app = new ApiAiApp({request: request, response: response}); + * app.askForPermissions("To get you a ride", [ + * app.SupportedPermissions.NAME, + * app.SupportedPermissions.DEVICE_PRECISE_LOCATION + * ]); + * // ... + * // In response handler for subsequent intent: + * if (app.isPermissionGranted()) { + * // Use the requested permission(s) to get the user a ride + * } + * + * @return {boolean} true if permissions granted. + * @apiai + * @actionssdk + */ + isPermissionGranted(): boolean; + + /** + * Asks user for delivery address. + * + * @example + * // For ApiAiApp: + * const app = new ApiAiApp({request, response}); + * const WELCOME_INTENT = 'input.welcome'; + * const DELIVERY_INTENT = 'delivery.address'; + * + * function welcomeIntent (app) { + * app.askForDeliveryAddress('To make sure I can deliver to you'); + * } + * + * function addressIntent (app) { + * const postalCode = app.getDeliveryAddress().postalAddress.postalCode; + * if (isInDeliveryZone(postalCode)) { + * app.tell('Great looks like you\'re in our delivery area!'); + * } else { + * app.tell('I\'m sorry it looks like we can\'t deliver to you.'); + * } + * } + * + * const actionMap = new Map(); + * actionMap.set(WELCOME_INTENT, welcomeIntent); + * actionMap.set(DELIVERY_INTENT, addressIntent); + * app.handleRequest(actionMap); + * + * // For ActionsSdkApp: + * const app = new ActionsSdkApp({request, response}); + * const WELCOME_INTENT = app.StandardIntents.MAIN; + * const DELIVERY_INTENT = app.StandardIntents.DELIVERY_ADDRESS; + * + * function welcomeIntent (app) { + * app.askForDeliveryAddress('To make sure I can deliver to you'); + * } + * + * function addressIntent (app) { + * const postalCode = app.getDeliveryAddress().postalAddress.postalCode; + * if (isInDeliveryZone(postalCode)) { + * app.tell('Great looks like you\'re in our delivery area!'); + * } else { + * app.tell('I\'m sorry it looks like we can\'t deliver to you.'); + * } + * } + * + * const actionMap = new Map(); + * actionMap.set(WELCOME_INTENT, welcomeIntent); + * actionMap.set(DELIVERY_INTENT, addressIntent); + * app.handleRequest(actionMap); + * + * @param {string} reason Reason given to user for asking delivery address. + * @param {Object=} dialogState JSON object the app uses to hold dialog state that + * will be circulated back by Assistant. + * @return {Object} HTTP response. + * @actionssdk + * @apiai + */ + askForDeliveryAddress(reason: string, dialogState?: object): object; + + /** + * Asks user for a confirmation. + * + * @example + * const app = new ApiAiApp({ request, response }); + * const WELCOME_INTENT = 'input.welcome'; + * const CONFIRMATION = 'confirmation'; + * + * function welcomeIntent (app) { + * app.askForConfirmation('Are you sure you want to do that?'); + * } + * + * function confirmation (app) { + * if (app.getUserConfirmation()) { + * app.tell('Great! I\'m glad you want to do it!'); + * } else { + * app.tell('That\'s okay. Let\'s not do it now.'); + * } + * } + * + * const actionMap = new Map(); + * actionMap.set(WELCOME_INTENT, welcomeIntent); + * actionMap.set(CONFIRMATION, confirmation); + * app.handleRequest(actionMap); + * + * @param {string=} prompt The confirmation prompt presented to the user to + * query for an affirmative or negative response. If undefined or null, + * Google will use a generic yes/no prompt. + * @param {Object=} dialogState JSON object the app uses to hold dialog state that + * will be circulated back by Assistant. Used in {@link ActionsSdkAssistant}. + * @actionssdk + * @apiai + */ + askForConfirmation(prompt?: string, dialogState?: object): object; + + /** + * Asks user for a timezone-agnostic date and time. + * + * @example + * const app = new ApiAiApp({ request, response }); + * const WELCOME_INTENT = 'input.welcome'; + * const DATETIME = 'datetime'; + * + * function welcomeIntent (app) { + * app.askForDateTime('When do you want to come in?', + * 'Which date works best for you?', + * 'What time of day works best for you?'); + * } + * + * function datetime (app) { + * app.tell({speech: 'Great see you at your appointment!', + * displayText: 'Great, we will see you on ' + * + app.getDateTime().date.month + * + '/' + app.getDateTime().date.day + * + ' at ' + app.getDateTime().time.hours + * + (app.getDateTime().time.minutes || '')}); + * } + * + * const actionMap = new Map(); + * actionMap.set(WELCOME_INTENT, welcomeIntent); + * actionMap.set(DATETIME, datetime); + * app.handleRequest(actionMap); + * + * @param {string=} initialPrompt The initial prompt used to ask for a + * date and time. If undefined or null, Google will use a generic + * prompt. + * @param {string=} datePrompt The prompt used to specifically ask for the + * date if not provided by user. If undefined or null, Google will use a + * generic prompt. + * @param {string=} timePrompt The prompt used to specifically ask for the + * time if not provided by user. If undefined or null, Google will use a + * generic prompt. + * @param {Object=} dialogState JSON object the app uses to hold dialog state that + * will be circulated back by Assistant. Used in {@link ActionsSdkAssistant}. + * @actionssdk + * @apiai + */ + askForDateTime(initialPrompt?: string, datePrompt?: string, timePrompt?: string, dialogState?: object): object; + + /** + * Hands the user off to a web sign in flow. App sign in and OAuth credentials + * are set in the {@link https://console.actions.google.com|Actions Console}. + * Retrieve the access token in subsequent intents using + * app.getUser().accessToken. + * + * Note: Currently this API requires enabling the app for Transactions APIs. + * To do this, fill out the App Info section of the Actions Console project + * and check the box indicating the use of Transactions under "Privacy and + * consent". + * + * @example + * const app = new ApiAiApp({ request, response }); + * const WELCOME_INTENT = 'input.welcome'; + * const SIGN_IN = 'sign.in'; + * + * function welcomeIntent (app) { + * app.askForSignIn(); + * } + * + * function signIn (app) { + * if (app.getSignInStatus() === app.SignInstatus.OK) { + * let accessToken = app.getUser().accessToken; + * app.ask('Great, thanks for signing in!'); + * } else { + * app.ask('I won\'t be able to save your data, but let\'s continue!'); + * } + * } + * + * const actionMap = new Map(); + * actionMap.set(WELCOME_INTENT, welcomeIntent); + * actionMap.set(SIGN_IN, signIn); + * app.handleRequest(actionMap); + * + * @param {Object=} dialogState JSON object the app uses to hold dialog state that + * will be circulated back by Assistant. Used in {@link ActionsSdkAssistant}. + * @actionssdk + * @apiai + */ + askForSignIn(dialogState?: object): object; + + /** + * Requests the user to switch to another surface during the conversation. + * + * @example + * const app = new ApiAiApp({ request, response }); + * const WELCOME_INTENT = 'input.welcome'; + * const SHOW_IMAGE = 'show.image'; + * + * function welcomeIntent (app) { + * if (app.hasSurfaceCapability(app.SurfaceCapabilities.SCREEN_OUTPUT)) { + * showPicture(app); + * } else if (app.hasAvailableSurfaceCapabilities(app.SurfaceCapabilities.SCREEN_OUTPUT)) { + * app.askForNewSurface('To show you an image', + * 'Check out this image', + * [app.SurfaceCapabilities.SCREEN_OUTPUT] + * ); + * } else { + * app.tell('This part of the app only works on screen devices. Sorry about that'); + * } + * } + * + * function showImage (app) { + * if (!app.isNewSurface()) { + * app.tell('Ok, I understand. You don't want to see pictures. Bye'); + * } else { + * showPicture(app, pictureType); + * } + * } + * + * const actionMap = new Map(); + * actionMap.set(WELCOME_INTENT, welcomeIntent); + * actionMap.set(SHOW_IMAGE, showImage); + * app.handleRequest(actionMap); + * + * @param {string} context Context why new surface is requested; it's the TTS + * prompt prefix (action phrase) we ask the user. + * @param {string} notificationTitle Title of the notification appearing on + * new surface device. + * @param {Array} capabilities The list of capabilities required in + * the surface. + * @param {Object=} dialogState JSON object the app uses to hold dialog state that + * will be circulated back by Assistant. Used in {@link ActionsSdkAssistant}. + * @apiai + * @actionssdk + */ + askForNewSurface(context: string, notificationTitle: string, capabilities: string[], dialogState?: object): object; + + /** + * Gets the {@link User} object. + * The user object contains information about the user, including + * a string identifier and personal information (requires requesting permissions, + * see {@link AssistantApp#askForPermissions|askForPermissions}). + * + * @example + * const app = new ApiAiApp({request: request, response: response}); + * // or + * const app = new ActionsSdkApp({request: request, response: response}); + * const userId = app.getUser().userId; + * + * @return {User} Null if no value. + * @actionssdk + * @apiai + */ + getUser(): User; + + /** + * If granted permission to user's name in previous intent, returns user's + * display name, family name, and given name. If name info is unavailable, + * returns null. + * + * @example + * const app = new ApiAIApp({request: req, response: res}); + * const REQUEST_PERMISSION_ACTION = 'request_permission'; + * const SAY_NAME_ACTION = 'get_name'; + * + * function requestPermission (app) { + * const permission = app.SupportedPermissions.NAME; + * app.askForPermission('To know who you are', permission); + * } + * + * function sayName (app) { + * if (app.isPermissionGranted()) { + * app.tell('Your name is ' + app.getUserName().displayName)); + * } else { + * // Response shows that user did not grant permission + * app.tell('Sorry, I could not get your name.'); + * } + * } + * const actionMap = new Map(); + * actionMap.set(REQUEST_PERMISSION_ACTION, requestPermission); + * actionMap.set(SAY_NAME_ACTION, sayName); + * app.handleRequest(actionMap); + * @return {UserName} Null if name permission is not granted. + * @actionssdk + * @apiai + */ + getUserName(): UserName; + + /** + * Gets the user locale. Returned string represents the regional language + * information of the user set in their Assistant settings. + * For example, 'en-US' represents US English. + * + * @example + * const app = new ApiAiApp({request, response}); + * const locale = app.getUserLocale(); + * + * @return {string} User's locale, e.g. 'en-US'. Null if no locale given. + * @actionssdk + * @apiai + */ + getUserLocale(): string; + + /** + * If granted permission to device's location in previous intent, returns device's + * location (see {@link AssistantApp#askForPermissions|askForPermissions}). + * If device info is unavailable, returns null. + * + * @example + * const app = new ApiAiApp({request: req, response: res}); + * // or + * const app = new ActionsSdkApp({request: req, response: res}); + * app.askForPermission("To get you a ride", + * app.SupportedPermissions.DEVICE_PRECISE_LOCATION); + * // ... + * // In response handler for permissions fallback intent: + * if (app.isPermissionGranted()) { + * sendCarTo(app.getDeviceLocation().coordinates); + * } + * + * @return {DeviceLocation} Null if location permission is not granted. + * @actionssdk + * @apiai + */ + getDeviceLocation(): DeviceLocation; + + /** + * Gets type of input used for this request. + * + * @return {number} One of AssistantApp.InputTypes. + * Null if no input type given. + * @apiai + * @actionssdk + */ + getInputType(): number; + + /** + * Get the argument value by name from the current intent. + * If the argument is included in originalRequest, and is not a text argument, + * the entire argument object is returned. + * + * Note: If incoming request is using an API version under 2 (e.g. 'v1'), + * the argument object will be in Proto2 format (snake_case, etc). + * + * @example + * const app = new ApiAiApp({request: request, response: response}); + * const WELCOME_INTENT = 'input.welcome'; + * const NUMBER_INTENT = 'input.number'; + * + * function welcomeIntent (app) { + * app.ask('Welcome to action snippets! Say a number.'); + * } + * + * function numberIntent (app) { + * const number = app.getArgument(NUMBER_ARGUMENT); + * app.tell('You said ' + number); + * } + * + * const actionMap = new Map(); + * actionMap.set(WELCOME_INTENT, welcomeIntent); + * actionMap.set(NUMBER_INTENT, numberIntent); + * app.handleRequest(actionMap); + * + * @param {string} argName Name of the argument. + * @return {Object} Argument value matching argName + * or null if no matching argument. + * @apiai + * @actionssdk + */ + getArgumentCommon(argName: string): object; + + /** + * Gets transactability of user. Only use after calling + * askForTransactionRequirements. Null if no result given. + * + * @return {string} One of Transactions.ResultType. + * @apiai + * @actionssdk + */ + getTransactionRequirementsResult(): string; + + /** + * Gets order delivery address. Only use after calling askForDeliveryAddress. + * + * @return {DeliveryAddress} Delivery address information. Null if user + * denies permission, or no address given. + * @apiai + * @actionssdk + */ + getDeliveryAddress(): Location; + + /** + * Gets transaction decision information. Only use after calling + * askForTransactionDecision. + * + * @return {TransactionDecision} Transaction decision data. Returns object with + * userDecision only if user declines. userDecision will be one of + * Transactions.ConfirmationDecision. Null if no decision given. + * @apiai + * @actionssdk + */ + getTransactionDecision(): TransactionDecision; + + /** + * Gets confirmation decision. Use after askForConfirmation. + * + * False if user replied with negative response. Null if no user + * confirmation decision given. + * @apiai + * @actionssdk + */ + getUserConfirmation(): boolean | null; + + /** + * Gets user provided date and time. Use after askForDateTime. + * + * @return {DateTime} Date and time given by the user. Null if no user + * date and time given. + * @apiai + * @actionssdk + */ + getDateTime(): DateTime; + + /** + * Gets status of user sign in request. + * + * @return {string} Result of user sign in request. One of + * ApiAiApp.SignInStatus or ActionsSdkApp.SignInStatus + * Null if no sign in status. + * @apiai + * @actionssdk + */ + getSignInStatus(): string; + + /** + * Returns true if user device has a given surface capability. + * + * @param {string} capability Must be one of {@link SurfaceCapabilities}. + * @return {boolean} True if user device has the given capability. + * + * @example + * const app = new ApiAIApp({request: req, response: res}); + * const DESCRIBE_SOMETHING = 'DESCRIBE_SOMETHING'; + * + * function describe (app) { + * if (app.hasSurfaceCapability(app.SurfaceCapabilities.SCREEN_OUTPUT)) { + * app.tell(richResponseWithBasicCard); + * } else { + * app.tell('Let me tell you about ...'); + * } + * } + * const actionMap = new Map(); + * actionMap.set(DESCRIBE_SOMETHING, describe); + * app.handleRequest(actionMap); + * + * @apiai + * @actionssdk + */ + hasSurfaceCapability(requestedCapability: string): boolean; + + /** + * Gets surface capabilities of user device. + * + * @return {Array} Supported surface capabilities, as defined in + * AssistantApp.SurfaceCapabilities. + * @apiai + * @actionssdk + */ + getSurfaceCapabilities(): string[]; + + /** + * Returns the set of other available surfaces for the user. + * + * @return {Array} Empty if no available surfaces. + * @actionssdk + * @apiai + */ + getAvailableSurfaces(): Surface[]; + + /** + * Returns true if user has an available surface which includes all given + * capabilities. Available surfaces capabilities may exist on surfaces other + * than that used for an ongoing conversation. + * + * @param {string|Array} capabilities Must be one of + * {@link SurfaceCapabilities}. + * @return {boolean} True if user has a capability available on some surface. + * + * @apiai + * @actionssdk + */ + hasAvailableSurfaceCapabilities(capabilities: string | string[]): boolean; + + /** + * Returns the result of the AskForNewSurface helper. + * + * @return {boolean} True if user has triggered conversation on a new device + * following the NEW_SURFACE intent. + * @actionssdk + * @apiai + */ + isNewSurface(): boolean; + + /** + * Returns true if the app is being tested in sandbox mode. Enable sandbox + * mode in the (Actions console)[console.actions.google.com] to test + * transactions. + * + * @return {boolean} True if app is being used in Sandbox mode. + * @apiai + * @actionssdk + */ + isInSandbox(): boolean; + + /** + * Returns the number of subsequent reprompts related to silent input from the + * user. This should be used along with the NO_INPUT intent to reprompt the + * user for input in cases where the Google Assistant could not pick up any + * speech. + * + * @example + * const app = new ActionsSdkApp({request, response}); + * + * function welcome (app) { + * app.ask('Welcome to your app!'); + * } + * + * function noInput (app) { + * if (app.getRepromptCount() === 0) { + * app.ask(`What was that?`); + * } else if (app.getRepromptCount() === 1) { + * app.ask(`Sorry I didn't catch that. Could you repeat yourself?`); + * } else if (app.isFinalReprompt()) { + * app.tell(`Okay let's try this again later.`); + * } + * } + * + * const actionMap = new Map(); + * actionMap.set(app.StandardIntents.MAIN, welcome); + * actionMap.set(app.StandardIntents.NO_INPUT, noInput); + * app.handleRequest(actionMap); + * + * @return {number} The current reprompt count. Null if no reprompt count + * available (e.g. not in the NO_INPUT intent). + * @apiai + * @actionssdk + */ + getRepromptCount(): number; + + /** + * Returns true if it is the final reprompt related to silent input from the + * user. This should be used along with the NO_INPUT intent to give the final + * response to the user after multiple silences and should be an app.tell + * which ends the conversation. + * + * @example + * const app = new ActionsSdkApp({request, response}); + * + * function welcome (app) { + * app.ask('Welcome to your app!'); + * } + * + * function noInput (app) { + * if (app.getRepromptCount() === 0) { + * app.ask(`What was that?`); + * } else if (app.getRepromptCount() === 1) { + * app.ask(`Sorry I didn't catch that. Could you repeat yourself?`); + * } else if (app.isFinalReprompt()) { + * app.tell(`Okay let's try this again later.`); + * } + * } + * + * const actionMap = new Map(); + * actionMap.set(app.StandardIntents.MAIN, welcome); + * actionMap.set(app.StandardIntents.NO_INPUT, noInput); + * app.handleRequest(actionMap); + * + * @return {boolean} True if in a NO_INPUT intent and this is the final turn + * of dialog. + * @apiai + * @actionssdk + */ + isFinalReprompt(): boolean; + + // --------------------------------------------------------------------------- + // Response Builders + // --------------------------------------------------------------------------- + + /** + * Constructs RichResponse with chainable property setters. + * + * @param {RichResponse=} richResponse RichResponse to clone. + * @return {RichResponse} Constructed RichResponse. + */ + buildRichResponse(richResponse?: RichResponse): RichResponse; + + /** + * Constructs BasicCard with chainable property setters. + * + * @param {string=} bodyText Body text of the card. Can be set using setTitle + * instead. + * @return {BasicCard} Constructed BasicCard. + */ + buildBasicCard(bodyText?: string): BasicCard; + + /** + * Constructs List with chainable property setters. + * + * @param {string=} title A title to set for a new List. + * @return {List} Constructed List. + */ + buildList(title?: string): List; + + /** + * Constructs Carousel with chainable property setters. + * + * @return {Carousel} Constructed Carousel. + */ + buildCarousel(): Carousel; + + /** + * Constructs OptionItem with chainable property setters. + * + * @param {string=} key A unique key to identify this option. This key will + * be returned as an argument in the resulting actions.intent.OPTION + * intent. + * @param {string|Array=} synonyms A list of synonyms which the user may + * use to identify this option instead of the option key. + * @return {OptionItem} Constructed OptionItem. + */ + buildOptionItem(key?: string, synonyms?: string | string[]): OptionItem; + + // --------------------------------------------------------------------------- + // Transaction Builders + // --------------------------------------------------------------------------- + + /** + * Constructs Order with chainable property setters. + * + * @param {string} orderId Unique identifier for the order. + * @return {Order} Constructed Order. + */ + buildOrder(orderId: string): Order; + + /** + * Constructs Cart with chainable property setters. + * + * @param {string=} cartId Unique identifier for the cart. + * @return {Cart} Constructed Cart. + */ + buildCart(cartId?: string): Cart; + + /** + * Constructs LineItem with chainable property setters. + * + * @param {string} id Unique identifier for the item. + * @param {string} name Name of the line item. + * @return {LineItem} Constructed LineItem. + */ + buildLineItem(id: string, name: string): LineItem; + + /** + * Constructs OrderUpdate with chainable property setters. + * + * @param {string} orderId Unique identifier of the order. + * @param {boolean} isGoogleOrderId True if the order ID is provided by + * Google. False if the order ID is app provided. + * @return {OrderUpdate} Constructed OrderUpdate. + */ + buildOrderUpdate(orderId: string, isGoogleOrderId: boolean): OrderUpdate; +} + +export class State { + constructor(name: string); + getName(): string; +} diff --git a/types/actions-on-google/index.d.ts b/types/actions-on-google/index.d.ts new file mode 100644 index 0000000000..3c0daa5a28 --- /dev/null +++ b/types/actions-on-google/index.d.ts @@ -0,0 +1,39 @@ +// Type definitions for actions-on-google 1.4 +// Project: https://github.com/actions-on-google/actions-on-google-nodejs +// Definitions by: Joel Hegg , Pilwon Huh +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.4 + +/** + * Copyright 2016 Google Inc. All Rights Reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +/** + * The Actions on Google client library. + * https://developers.google.com/actions/ + */ + +import * as Transactions from './transactions'; +import * as Responses from './response-builder'; + +export { AssistantApp, AssistantAppOptions, RequestHandler, SessionStartedFunction, State } from './assistant-app'; +export { ActionsSdkApp, ActionsSdkAppOptions } from './actions-sdk-app'; +export { ApiAiApp, ApiAiAppOptions } from './api-ai-app'; +export { Transactions }; +export { Responses }; +// Backwards compatibility +export { AssistantApp as Assistant } from './assistant-app'; +export { ActionsSdkApp as ActionsSdkAssistant } from './actions-sdk-app'; +export { ApiAiApp as ApiAiAssistant } from './api-ai-app'; diff --git a/types/actions-on-google/response-builder.d.ts b/types/actions-on-google/response-builder.d.ts new file mode 100644 index 0000000000..add7b9fc03 --- /dev/null +++ b/types/actions-on-google/response-builder.d.ts @@ -0,0 +1,333 @@ +/** + * Copyright 2017 Google Inc. All Rights Reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +/** + * A collection of response builders. + */ + +import { OrderUpdate } from './transactions'; + +/** + * Simple Response type. + */ +export interface SimpleResponse { + /** Speech to be spoken to user. SSML allowed. */ + speech: string; + /** Optional text to be shown to user */ + displayText?: string; +} + +/** + * Suggestions to show with response. + */ +export interface Suggestion { + /** Text of the suggestion. */ + title: string; +} + +/** + * Link Out Suggestion. Used in rich response as a suggestion chip which, when + * selected, links out to external URL. + */ +export interface LinkOutSuggestion { + /** Text shown on the suggestion chip. */ + title: string; + /** String URL to open. */ + url: string; +} + +/** + * Image type shown on visual elements. + */ +export interface Image { + /** Image source URL. */ + url: string; + /** Text to replace for image for accessibility. */ + accessibilityText: string; + /** Width of the image. */ + width: number; + /** Height of the image. */ + height: number; +} + +/** + * Basic Card Button. Shown below basic cards. Open a URL when selected. + */ +export interface Button { + /** Text shown on the button. */ + title: string; + /** Action to take when selected. */ + openUrlAction: { + /** String URL to open. */ + url: string; + }; +} + +/** + * Option item. Used in actions.intent.OPTION intent. + */ +export interface OptionItem { + /** Option item identifier information. */ + optionInfo: OptionInfo; + /** Name of the item. */ + title: string; + /** Optional text describing the item. */ + description: string; + /** Square image to show for this item. */ + image: Image; +} + +/** + * Option info. Provides unique identifier for a given OptionItem. + */ +export interface OptionInfo { + /** Unique string ID for this option. */ + key: string; + /** Synonyms that can be used by the user to indicate this option if they do not use the key. */ + synonyms: string[]; +} + +/** + * Class for initializing and constructing Rich Responses with chainable interface. + */ +export class RichResponse { + /** + * Constructor for RichResponse. Accepts optional RichResponse to clone. + * + * @param {RichResponse} richResponse + */ + constructor(richResponse: RichResponse); + + /** + * Adds a SimpleResponse to list of items. + * + * @param {string|SimpleResponse} simpleResponse Simple response to present to + * user. If just a string, display text will not be set. + * @return {RichResponse} Returns current constructed RichResponse. + */ + addSimpleResponse(simpleResponse: string | SimpleResponse): RichResponse; + + /** + * Adds a BasicCard to list of items. + * + * @param {BasicCard} basicCard Basic card to include in response. + * @return {RichResponse} Returns current constructed RichResponse. + */ + addBasicCard(basicCard: BasicCard): RichResponse; + + /** + * Adds a single suggestion or list of suggestions to list of items. + * + * @param {string|Array} suggestions Either a single string suggestion + * or list of suggestions to add. + * @return {RichResponse} Returns current constructed RichResponse. + */ + addSuggestions(suggestions: string | string[]): RichResponse; + + /** + * Returns true if the given suggestion text is valid to be added to the suggestion list. A valid + * text string is not longer than 25 characters. + */ + isValidSuggestionText(suggestionText: string): boolean; + + /** + * Sets the suggestion link for this rich response. + * + * @param {string} destinationName Name of the link out destination. + * @param {string} suggestionUrl - String URL to open when suggestion is used. + * @return {RichResponse} Returns current constructed RichResponse. + */ + addSuggestionLink(destinationName: string, suggestionUrl: string): RichResponse; + + /** + * Adds an order update to this response. Use after a successful transaction + * decision to confirm the order. + * + * @param {OrderUpdate} orderUpdate + * @return {RichResponse} Returns current constructed RichResponse. + */ + addOrderUpdate(orderUpdate: OrderUpdate): RichResponse; +} + +/** + * Class for initializing and constructing Basic Cards with chainable interface. + */ +export class BasicCard { + /** + * Constructor for BasicCard. Accepts optional BasicCard to clone. + * + * @param {BasicCard} basicCard + */ + constructor(basicCard: BasicCard); + + /** + * Sets the title for this Basic Card. + * + * @param {string} title Title to show on card. + * @return {BasicCard} Returns current constructed BasicCard. + */ + setTitle(title: string): BasicCard; + + /** + * Sets the subtitle for this Basic Card. + * + * @param {string} subtitle Subtitle to show on card. + * @return {BasicCard} Returns current constructed BasicCard. + */ + setSubtitle(subtitle: string): BasicCard; + + /** + * Sets the body text for this Basic Card. + * + * @param {string} bodyText Body text to show on card. + * @return {BasicCard} Returns current constructed BasicCard. + */ + setBodyText(bodyText: string): BasicCard; + + /** + * Sets the image for this Basic Card. + * + * @param {string} url Image source URL. + * @param {string} accessibilityText Text to replace for image for + * accessibility. + * @param {number=} width Width of the image. + * @param {number=} height Height of the image. + * @return {BasicCard} Returns current constructed BasicCard. + */ + setImage(url: string, accessibilityText: string, width?: number, height?: number): BasicCard; + + /** + * Adds a button below card. + * + * @param {string} text Text to show on button. + * @param {string} url URL to open when button is selected. + * @return {BasicCard} Returns current constructed BasicCard. + */ + addButton(text: string, url: string): BasicCard; +} + +/** + * Class for initializing and constructing Lists with chainable interface. + */ +export class List { + /** + * Constructor for List. Accepts optional List to clone, string title, or + * list of items to copy. + * + * @param {List|string|Array} list Either a list to clone, a title + * to set for a new List, or an array of OptionItem to initialize a new + * list. + */ + constructor(list: List | string | OptionItem[]); + + /** + * Sets the title for this List. + * + * @param {string} title Title to show on list. + * @return {List} Returns current constructed List. + */ + setTitle(title: string): List; + + /** + * Adds a single item or list of items to the list. + * + * @param {OptionItem|Array} optionItems OptionItems to add. + * @return {List} Returns current constructed List. + */ + addItems(optionItems: OptionItem | OptionItem[]): List; +} + +/** + * Class for initializing and constructing Carousel with chainable interface. + */ +export class Carousel { + /** + * Constructor for Carousel. Accepts optional Carousel to clone or list of + * items to copy. + * + * @param {Carousel|Array} carousel Either a carousel to clone, a + * or an array of OptionItem to initialize a new carousel + */ + constructor(carousel: Carousel | OptionItem[]); + + /** + * Adds a single item or list of items to the carousel. + * + * @param {OptionItem|Array} optionItems OptionItems to add. + * @return {Carousel} Returns current constructed Carousel. + */ + addItems(optionItems: OptionItem | OptionItem[]): Carousel; +} + +/** + * Class for initializing and constructing Option Items with chainable interface. + */ +export class OptionItem { + /** + * Constructor for OptionItem. Accepts optional OptionItem to clone. + * + * @param {OptionItem} optionItem + */ + constructor(optionItem: OptionItem); + + /** + * Sets the title for this Option Item. + * + * @param {string} title Title to show on item. + * @return {OptionItem} Returns current constructed OptionItem. + */ + setTitle(title: string): OptionItem; + + /** + * Sets the description for this Option Item. + * + * @param {string} description Description to show on item. + * @return {OptionItem} Returns current constructed OptionItem. + */ + setDescription(description: string): OptionItem; + + /** + * Sets the image for this Option Item. + * + * @param {string} url Image source URL. + * @param {string} accessibilityText Text to replace for image for + * accessibility. + * @param {number=} width Width of the image. + * @param {number=} height Height of the image. + * @return {OptionItem} Returns current constructed OptionItem. + */ + setImage(url: string, accessibilityText: string, width?: number, height?: number): OptionItem; + + /** + * Sets the key for the OptionInfo of this Option Item. This will be returned + * as an argument in the resulting actions.intent.OPTION intent. + * + * @param {string} key Key to uniquely identify this item. + * @return {OptionItem} Returns current constructed OptionItem. + */ + setKey(key: string): OptionItem; + + /** + * Adds a single synonym or list of synonyms to item. + * + * @param {string|Array} synonyms Either a single string synonyms + * or list of synonyms to add. + * @return {OptionItem} Returns current constructed OptionItem. + */ + addSynonyms(synonyms: string | string[]): OptionItem; +} + +export function isSsml(text: string): boolean; diff --git a/types/actions-on-google/transactions.d.ts b/types/actions-on-google/transactions.d.ts new file mode 100644 index 0000000000..e64e69bdf1 --- /dev/null +++ b/types/actions-on-google/transactions.d.ts @@ -0,0 +1,1406 @@ +/** + * Copyright 2017 Google Inc. All Rights Reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +/** + * A collection of Transaction related constants, utility functions, and + * builders. + */ + +import { Image } from './response-builder'; + +/** + * Price type. + */ +export interface Price { + /** One of Transaction.PriceType. */ + type: PriceType; + amount: { + /** Currency code of price. */ + currencyCode: string; + /** Unit count of price. */ + units: number; + /** Partial unit count of price. */ + nanos?: number; + }; +} + +/** + * Order rejection info. + */ +export interface RejectionInfo { + /** One of Transaction.RejectionType. */ + type: RejectionType; + /** Reason for the order rejection. */ + reason: string; +} + +/** + * Order receipt info. + */ +export interface ReceiptInfo { + /** Action provided order ID. Used when the order has been received by the integrator. */ + confirmedActionOrderId: string; +} + +/** + * Order cancellation info. + */ +export interface CancellationInfo { + /** Reason for the cancellation. */ + reason: string; +} + +/** + * Order transit info. + */ +export interface TransitInfo { + /** UTC timestamp of the transit update. */ + updatedTime: { + /** Seconds since Unix epoch. */ + seconds: number; + /** Partial seconds since Unix epoch. */ + nanos?: number; + }; +} + +/** + * Order fulfillment info. + */ +export interface FulfillmentInfo { + /** UTC timestamp of the fulfillment update. */ + deliveryTime: { + /** Seconds since Unix epoch. */ + seconds: number; + /** Partial seconds since Unix epoch. */ + nanos?: number; + }; +} + +/** + * Order return info. + */ +export interface ReturnInfo { + /** Reason for the return. */ + reason: string; +} + +/** + * Transaction config for transactions not involving a Google provided + * payment instrument. + */ +export interface ActionPaymentTransactionConfig { + /** True if delivery address is required for the transaction. */ + deliveryAddressRequired: boolean; + /** One of Transactions.PaymentType. */ + type: PaymentType; + /** The name of the instrument displayed on receipt. For example, for card payment, could be "VISA-1234". */ + displayName: string; + customerInfoOptions?: CustomerInfoOptions; +} + +/** + * Transaction config for transactions involving a Google provided payment + * instrument. + */ +export interface GooglePaymentTransactionConfig { + /** True if delivery address is required for the transaction. */ + deliveryAddressRequired: boolean; + /** Tokenization parameters provided by payment gateway. */ + tokenizationParameters: object; + /** List of accepted card networks. Must be any number of Transactions.CardNetwork. */ + cardNetworks: CardNetwork[]; + /** True if prepaid cards are not allowed for transaction. */ + prepaidCardDisallowed: boolean; + customerInfoOptions?: CustomerInfoOptions; +} + +/** + * Customer information requested as part of the transaction + */ +export interface CustomerInfoOptions { + /** one of Transactions.CustomerInfoProperties */ + customerInfoProperties: string[]; +} + +/** + * Generic Location type. + */ +export interface Location { + postalAddress: { + regionCode: string; + languageCode: string; + postalCode: string; + administrativeArea: string; + locality: string; + addressLines: string[]; + recipients: string; + }; + phoneNumber: string; + notes: string; +} + +/** + * Decision and order information returned when calling getTransactionDecision(). + */ +export interface TransactionDecision { + /** One of Transactions.ConfirmationDecision. */ + userDecision: ConfirmationDecision; + checkResult: { + /** One of Transactions.ResultType. */ + resultType: string; + }; + order: { + /** The proposed order used in the transaction decision. */ + finalOrder: Order; + /** Order ID assigned by Google. */ + googleOrderId: string; + /** User visible order ID set in proposed order. */ + actionOrderId: string; + /** The date and time the order was created */ + orderDate: { + seconds: string; + nanos: number; + }; + /** The details regarding the payment method that must be used to charge the user. */ + paymentInfo: { + /** One of Transactions.PaymentType. */ + paymentType: PaymentType; + googleProvidedPaymentInstrument: { + /** + * Contains a Base64-encoded payment token provided by a third-party payment processor + * Returned for Google-provided payment methods only + */ + instrumentToken: string; + }; + /** + * Name of the instrument displayed on the receipt + * Returned for payment methods provided by your app only + */ + displayName: string; + }; + // Any customer information (e.g. email address) requested + customerInfo: { + /** Customer email. */ + email: string; + }; + }; + /** + * The delivery address if user requested. + * Will appear if userDecision is Transactions.DELIVERY_ADDRESS_UPDATED. + */ + deliveryAddress: Location; +} + +/** + * List of transaction card networks available when paying with Google. + */ +export type CardNetwork = + /** + * Unspecified. + */ + 'UNSPECIFIED' | + /** + * American Express. + */ + 'AMEX' | + /** + * Discover. + */ + 'DISCOVER' | + /** + * Master Card. + */ + 'MASTERCARD' | + /** + * Visa. + */ + 'VISA' | + /** + * JCB. + */ + 'JCB'; + +/** + * List of possible item types. + * @enum {string} + */ +export type ItemType = + /** + * Unspecified. + */ + 'UNSPECIFIED' | + /** + * Regular. + */ + 'REGULAR' | + /** + * Tax. + */ + 'TAX' | + /** + * Discount + */ + 'DISCOUNT' | + /** + * Gratuity + */ + 'GRATUITY' | + /** + * Delivery + */ + 'DELIVERY' | + /** + * Subtotal + */ + 'SUBTOTAL' | + /** + * Fee. For everything else, there's fee. + */ + 'FEE'; + +/** + * List of price types. + * @enum {string} + */ +export type PriceType = + /** + * Unknown. + */ + 'UNKNOWN' | + /** + * Estimate. + */ + 'ESTIMATE' | + /** + * Actual. + */ + 'ACTUAL'; + +/** + * List of possible item types. + * @enum {string} + */ +export type PaymentType = + /** + * Unspecified. + */ + 'UNSPECIFIED' | + /** + * Payment card. + */ + 'PAYMENT_CARD' | + /** + * Bank. + */ + 'BANK' | + /** + * Loyalty program. + */ + 'LOYALTY_PROGRAM' | + /** + * On order fulfillment, such as cash on delivery. + */ + 'ON_FULFILLMENT' | + /** + * Gift card. + */ + 'GIFT_CARD'; + +/** + * List of customer information properties that can be requested. + */ +export type CustomerInfoProperties = 'EMAIL'; + +/** + * List of possible order confirmation user decisions + * @enum {string} + */ +export type ConfirmationDecision = + /** + * Order was approved by user. + */ + 'ORDER_ACCEPTED' | + /** + * Order was declined by user. + */ + 'ORDER_REJECTED' | + /** + * Order was not declined, but the delivery address was updated during + * confirmation. + */ + 'DELIVERY_ADDRESS_UPDATED' | + /** + * Order was not declined, but the cart was updated during confirmation. + */ + 'CART_CHANGE_REQUESTED'; + +/** + * List of possible order states. + * @enum {string} + */ +export type OrderState = + /** + * Order was rejected. + */ + 'REJECTED' | + /** + * Order was confirmed by integrator and is active. + */ + 'CONFIRMED' | + /** + * User cancelled the order. + */ + 'CANCELLED' | + /** + * Order is being delivered. + */ + 'IN_TRANSIT' | + /** + * User performed a return. + */ + 'RETURNED' | + /** + * User received what was ordered. + */ + 'FULFILLED'; + +/** + * List of possible actions to take on the order. + * @enum {string} + */ +export type OrderAction = + /** + * View details. + */ + 'VIEW_DETAILS' | + /** + * Modify order. + */ + 'MODIFY' | + /** + * Cancel order. + */ + 'CANCEL' | + /** + * Return order. + */ + 'RETURN' | + /** + * Exchange order. + */ + 'EXCHANGE' | + /** + * Email. + */ + 'EMAIL' | + /** + * Call. + */ + 'CALL' | + /** + * Reorder. + */ + 'REORDER' | + /** + * Review. + */ + 'REVIEW'; + +/** + * List of possible types of order rejection. + * @enum {string} + */ +export type RejectionType = + /** + * Unknown + */ + 'UNKNOWN' | + /** + * Payment was declined. + */ + 'PAYMENT_DECLINED'; + +/** + * List of possible order state objects. + * @enum {string} + */ +export type OrderStateInfo = + /** + * Information about order rejection. Used with {@link RejectionInfo}. + */ + 'rejectionInfo' | + /** + * Information about order receipt. Used with {@link ReceiptInfo}. + */ + 'receipt' | + /** + * Information about order cancellation. Used with {@link CancellationInfo}. + */ + 'cancellationInfo' | + /** + * Information about in-transit order. Used with {@link TransitInfo}. + */ + 'inTransitInfo' | + /** + * Information about order fulfillment. Used with {@link FulfillmentInfo}. + */ + 'fulfillmentInfo' | + /** + * Information about order return. Used with {@link ReturnInfo}. + */ + 'returnInfo'; + +/** + * List of possible order transaction requirements check result types. + * @enum {string} + */ +export type ResultType = + /** + * Unspecified. + */ + 'RESULT_TYPE_UNSPECIFIED' | + /** + * OK to continue transaction. + */ + 'OK' | + /** + * User is expected to take action, e.g. enable payments, to continue + * transaction. + */ + 'USER_ACTION_REQUIRED' | + /** + * Transactions are not supported on current device/surface. + */ + 'ASSISTANT_SURFACE_NOT_SUPPORTED' | + /** + * Transactions are not supported for current region/country. + */ + 'REGION_NOT_SUPPORTED'; + +/** + * List of possible user decisions to give delivery address. + * @enum {string} + */ +export type DeliveryAddressDecision = + /** + * Unknown. + */ + 'UNKNOWN_USER_DECISION' | + /** + * User granted delivery address. + */ + 'ACCEPTED' | + /** + * User denied to give delivery address. + */ + 'REJECTED'; + +/** + * List of possible order location types. + * @enum {string} + */ +export type LocationType = + /** + * Unknown. + */ + 'UNKNOWN' | + /** + * Delivery location for an order. + */ + 'DELIVERY' | + /** + * Business location of order provider. + */ + 'BUSINESS' | + /** + * Origin of the order. + */ + 'ORIGIN' | + /** + * Destination of the order. + */ + 'DESTINATION'; + +/** + * List of possible order time types. + * @enum {string} + */ + +export type TimeType = + /** + * Unknown. + */ + 'UNKNOWN' | + /** + * Date of delivery for the order. + */ + 'DELIVERY_DATE' | + /** + * Estimated Time of Arrival for order. + */ + 'ETA' | + /** + * Reservation time. + */ + 'RESERVATION_SLOT'; + +/** + * Values related to supporting transactions. + * @type {Object} + */ +export const TransactionValues: { + /** + * List of transaction card networks available when paying with Google. + * @enum {string} + */ + readonly CardNetwork: { + /** + * Unspecified. + */ + UNSPECIFIED: CardNetwork, + /** + * American Express. + */ + AMEX: CardNetwork, + /** + * Discover. + */ + DISCOVER: CardNetwork, + /** + * Master Card. + */ + MASTERCARD: CardNetwork, + /** + * Visa. + */ + VISA: CardNetwork, + /** + * JCB. + */ + JCB: CardNetwork, + }, + + /** + * List of possible item types. + * @enum {string} + */ + readonly ItemType: { + /** + * Unspecified. + */ + UNSPECIFIED: ItemType, + /** + * Regular. + */ + REGULAR: ItemType, + /** + * Tax. + */ + TAX: ItemType, + /** + * Discount + */ + DISCOUNT: ItemType, + /** + * Gratuity + */ + GRATUITY: ItemType, + /** + * Delivery + */ + DELIVERY: ItemType, + /** + * Subtotal + */ + SUBTOTAL: ItemType, + /** + * Fee. For everything else, there's fee. + */ + FEE: ItemType, + }, + + /** + * List of price types. + * @enum {string} + */ + readonly PriceType: { + /** + * Unknown. + */ + UNKNOWN: PriceType, + /** + * Estimate. + */ + ESTIMATE: PriceType, + /** + * Actual. + */ + ACTUAL: PriceType, + }, + + /** + * List of possible item types. + * @enum {string} + */ + readonly PaymentType: { + /** + * Unspecified. + */ + UNSPECIFIED: PaymentType, + /** + * Payment card. + */ + PAYMENT_CARD: PaymentType, + /** + * Bank. + */ + BANK: PaymentType, + /** + * Loyalty program. + */ + LOYALTY_PROGRAM: PaymentType, + /** + * On order fulfillment, such as cash on delivery. + */ + ON_FULFILLMENT: PaymentType, + /** + * Gift card. + */ + GIFT_CARD: PaymentType, + }, + + /** + * List of possible order confirmation user decisions + * @enum {string} + */ + readonly CustomerInfoProperties: { + EMAIL: CustomerInfoProperties, + }, + + /** + * List of possible order confirmation user decisions + * @enum {string} + */ + readonly ConfirmationDecision: { + /** + * Order was approved by user. + */ + ACCEPTED: ConfirmationDecision, + /** + * Order was declined by user. + */ + REJECTED: ConfirmationDecision, + /** + * Order was not declined, but the delivery address was updated during + * confirmation. + */ + DELIVERY_ADDRESS_UPDATED: ConfirmationDecision, + /** + * Order was not declined, but the cart was updated during confirmation. + */ + CART_CHANGE_REQUESTED: ConfirmationDecision, + }, + + /** + * List of possible order states. + * @enum {string} + */ + readonly OrderState: { + /** + * Order was rejected. + */ + REJECTED: OrderState, + /** + * Order was confirmed by integrator and is active. + */ + CONFIRMED: OrderState, + /** + * User cancelled the order. + */ + CANCELLED: OrderState, + /** + * Order is being delivered. + */ + IN_TRANSIT: OrderState, + /** + * User performed a return. + */ + RETURNED: OrderState, + /** + * User received what was ordered. + */ + FULFILLED: OrderState, + }, + + /** + * List of possible actions to take on the order. + * @enum {string} + */ + readonly OrderAction: { + /** + * View details. + */ + VIEW_DETAILS: OrderAction, + /** + * Modify order. + */ + MODIFY: OrderAction, + /** + * Cancel order. + */ + CANCEL: OrderAction, + /** + * Return order. + */ + RETURN: OrderAction, + /** + * Exchange order. + */ + EXCHANGE: OrderAction, + /** + * Email. + */ + EMAIL: OrderAction, + /** + * Call. + */ + CALL: OrderAction, + /** + * Reorder. + */ + REORDER: OrderAction, + /** + * Review. + */ + REVIEW: OrderAction, + }, + + /** + * List of possible types of order rejection. + * @enum {string} + */ + readonly RejectionType: { + /** + * Unknown + */ + UNKNOWN: RejectionType, + /** + * Payment was declined. + */ + PAYMENT_DECLINED: RejectionType, + }, + + /** + * List of possible order state objects. + * @enum {string} + */ + readonly OrderStateInfo: { + /** + * Information about order rejection. Used with {@link RejectionInfo}. + */ + REJECTION: OrderStateInfo, + /** + * Information about order receipt. Used with {@link ReceiptInfo}. + */ + RECEIPT: OrderStateInfo, + /** + * Information about order cancellation. Used with {@link CancellationInfo}. + */ + CANCELLATION: OrderStateInfo, + /** + * Information about in-transit order. Used with {@link TransitInfo}. + */ + IN_TRANSIT: OrderStateInfo, + /** + * Information about order fulfillment. Used with {@link FulfillmentInfo}. + */ + FULFILLMENT: OrderStateInfo, + /** + * Information about order return. Used with {@link ReturnInfo}. + */ + RETURN: OrderStateInfo, + }, + + /** + * List of possible order transaction requirements check result types. + * @enum {string} + */ + readonly ResultType: { + /** + * Unspecified. + */ + UNSPECIFIED: ResultType, + /** + * OK to continue transaction. + */ + OK: ResultType, + /** + * User is expected to take action, e.g. enable payments, to continue + * transaction. + */ + USER_ACTION_REQUIRED: ResultType, + /** + * Transactions are not supported on current device/surface. + */ + ASSISTANT_SURFACE_NOT_SUPPORTED: ResultType, + /** + * Transactions are not supported for current region/country. + */ + REGION_NOT_SUPPORTED: ResultType, + }, + + /** + * List of possible user decisions to give delivery address. + * @enum {string} + */ + readonly DeliveryAddressDecision: { + /** + * Unknown. + */ + UNKNOWN: DeliveryAddressDecision, + /** + * User granted delivery address. + */ + ACCEPTED: DeliveryAddressDecision, + /** + * User denied to give delivery address. + */ + REJECTED: DeliveryAddressDecision, + }, + + /** + * List of possible user decisions to give delivery address. + * @enum {string} + */ + readonly LocationType: { + /** + * Unknown. + */ + UNKNOWN: LocationType, + /** + * Delivery location for an order. + */ + DELIVERY: LocationType, + /** + * Business location of order provider. + */ + BUSINESS: LocationType, + /** + * Origin of the order. + */ + ORIGIN: LocationType, + /** + * Destination of the order. + */ + DESTINATION: LocationType, + }, + + /** + * List of possible user decisions to give delivery address. + * @enum {string} + */ + readonly TimeType: { + /** + * Unknown. + */ + UNKNOWN: TimeType, + /** + * Date of delivery for the order. + */ + DELIVERY_DATE: TimeType, + /** + * Estimated Time of Arrival for order. + */ + ETA: TimeType, + /** + * Reservation time. + */ + RESERVATION_SLOT: TimeType, + }, +}; + +/** + * Class for initializing and constructing Order with chainable interface. + */ +export class Order { + /** + * ID for the order. Required. + */ + readonly id: string; + + /** + * Cart for the order. + */ + readonly cart: Cart; + + /** + * Items not held in the order cart. + */ + readonly otherItems: LineItem[]; + + /** + * Image for the order. + */ + readonly image: Image; + + /** + * TOS for the order. + */ + readonly termsOfServiceUrl: string; + + /** + * Total price for the order. + * @type {Price} + */ + readonly totalPrice: Price; + + /** + * Extensions for this order. Used for vertical-specific order attributes, + * like times and locations. + */ + readonly extension: object; + + /** + * Constructor for Order. + * + * @param {string} orderId Unique identifier for the order. + */ + constructor(orderId: string); + + /** + * Set the cart for this order. + * + * @param {Cart} cart Cart for this order. + * @return {Order} Returns current constructed Order. + */ + setCart(cart: Cart): Order; + + /** + * Adds a single item or list of items to the non-cart items list. + * + * @param {LineItem|Array} items Line Items to add. + * @return {Order} Returns current constructed Order. + */ + addOtherItems(items: LineItem | LineItem[]): Order; + + /** + * Sets the image for this order. + * + * @param {string} url Image source URL. + * @param {string} accessibilityText Text to replace for image for + * accessibility. + * @param {number=} width Width of the image. + * @param {number=} height Height of the image. + * @return {Order} Returns current constructed Order. + */ + setImage(url: string, accessibilityText: string, width?: number, height?: number): Order; + + /** + * Set the TOS for this order. + * + * @param {string} tos String URL of the TOS. + * @return {Order} Returns current constructed Order. + */ + setTermsOfService(url: string): Order; + + /** + * Sets the total price for this order. + * + * @param {string} priceType One of TransactionValues.PriceType. + * @param {string} currencyCode Currency code of price. + * @param {number} units Unit count of price. + * @param {number=} nanos Partial unit count of price. + * @return {Order} Returns current constructed Order. + */ + setTotalPrice(priceType: PriceType, currencyCode: string, units: number, nanos?: number): Order; + + /** + * Adds an associated location to the order. Up to 2 locations can be added. + * + * @param {string} type One of TransactionValues.LocationType. + * @param {Location} location Location to add. + * @return {Order} Returns current constructed Order. + */ + addLocation(type: string, location: Location): Order; + + /** + * Sets an associated time to the order. + * + * @param {string} type One of TransactionValues.TimeType. + * @param {string} time Time to add. Time should be ISO 8601 representation + * of time value. Could be date, datetime, or duration. + * @return {Order} Returns current constructed Order. + */ + setTime(type: string, time: string): Order; +} + +/** + * Class for initializing and constructing Cart with chainable interface. + */ +export class Cart { + /** + * ID for the cart. Optional. + */ + readonly id: string; + + /** + * Merchant providing the cart. + */ + readonly merchant: object; + + /** + * Optional notes about the cart. + */ + readonly notes: string; + + /** + * Items held in the order cart. + */ + readonly lineItems: LineItem[]; + + /** + * Non-line items. + */ + readonly otherItems: LineItem[]; + + /** + * Constructor for Cart. + * + * @param {string=} cartId Optional unique identifier for the cart. + */ + constructor(cartId?: string); + + /** + * Set the merchant for this cart. + * + * @param {string} id Merchant ID. + * @param {string} name Name of the merchant. + * @return {Cart} Returns current constructed Cart. + */ + setMerchant(id: string, name: string): Cart; + + /** + * Set the notes for this cart. + * + * @param {string} notes Notes. + * @return {Cart} Returns current constructed Cart. + */ + setNotes(notes: string): Cart; + + /** + * Adds a single item or list of items to the cart. + * + * @param {LineItem|Array} items Line Items to add. + * @return {Cart} Returns current constructed Cart. + */ + addLineItems(items: LineItem | LineItem[]): Cart; + + /** + * Adds a single item or list of items to the non-items list of this cart. + * + * @param {LineItem|Array} items Line Items to add. + * @return {Cart} Returns current constructed Cart. + */ + addOtherItems(items: LineItem | LineItem[]): Cart; +} + +/** + * Class for initializing and constructing LineItem with chainable interface. + */ +export class LineItem { + /** + * Item ID. + */ + readonly id: string; + + /** + * Name of the item. + */ + readonly name: string; + + /** + * Item price. + */ + readonly price: Price; + + /** + * Sublines for current item. Only valid if item type is REGULAR. + */ + readonly sublines: string[] | LineItem[]; + + /** + * Image of the item. + */ + readonly image: Image; + + /** + * Type of the item. One of TransactionValues.ItemType. + */ + readonly type: ItemType; + + /** + * Quantity of the item. + */ + readonly quantity: number; + + /** + * Description for the item. + */ + readonly description: string; + + /** + * Offer ID for the item. + */ + readonly offerId: string; + + /** + * Constructor for LineItem. + * + * @param {string} lineItemId Unique identifier for the item. + * @param {string} name Name of the item. + */ + constructor(lineItemId: string, name: string); + + /** + * Adds a single item or list of items or notes to the sublines. Only valid + * if item type is REGULAR. + * + * @param {string|LineItem|Array} items Sublines to add. + * @return {LineItem} Returns current constructed LineItem. + */ + addSublines(items: string | LineItem | string[] | LineItem[]): LineItem; + + /** + * Sets the image for this item. + * + * @param {string} url Image source URL. + * @param {string} accessibilityText Text to replace for image for + * accessibility. + * @param {number=} width Width of the image. + * @param {number=} height Height of the image. + * @return {LineItem} Returns current constructed LineItem. + */ + setImage(url: string, accessibilityText: string, width?: number, height?: number): LineItem; + + /** + * Sets the price of this item. + * + * @param {string} priceType One of TransactionValues.PriceType. + * @param {string} currencyCode Currency code of price. + * @param {number} units Unit count of price. + * @param {number=} nanos Partial unit count of price. + * @return {LineItem} Returns current constructed LineItem. + */ + setPrice(priceType: PriceType, currencyCode: string, units: number, nanos?: number): LineItem; + + /** + * Set the type of the item. + * + * @param {string} type Type of the item. One of TransactionValues.ItemType. + * @return {LineItem} Returns current constructed LineItem. + */ + setType(type: ItemType): LineItem; + + /** + * Set the quantity of the item. + * + * @param {number} quantity Quantity of the item. + * @return {LineItem} Returns current constructed LineItem. + */ + setQuantity(quantity: number): LineItem; + + /** + * Set the description of the item. + * + * @param {string} description Description of the item. + * @return {LineItem} Returns current constructed LineItem. + */ + setDescription(description: string): LineItem; + + /** + * Set the Offer ID of the item. + * + * @param {string} offerId Offer ID of the item. + * @return {LineItem} Returns current constructed LineItem. + */ + setOfferId(offerId: string): LineItem; +} + +/** + * Class for initializing and constructing OrderUpdate with chainable interface. + */ +export class OrderUpdate { + /** + * Google provided identifier of the order. + * @type {string} + */ + readonly googleOrderId?: string; + + /** + * App provided identifier of the order. + * @type {string} + */ + readonly actionOrderId?: string; + + /** + * State of the order. + * @type {Object} + */ + readonly orderState?: OrderState; + + /** + * Updates for items in the order. Mapped by item id to state or price. + * @type {Object} + */ + readonly lineItemUpdates?: object; + + /** + * UTC timestamp of the order update. + * @type {Object} + */ + readonly updateTime?: object; + + /** + * Actionable items presented to the user to manage the order. + * @type {Object} + */ + readonly orderManagementActions: object[]; + + /** + * Notification content to the user for the order update. + * @type {Object} + */ + readonly userNotification: object; + + /** + * Updated total price of the order. + * @type {Price} + */ + readonly totalPrice: Price; + + /** + * Constructor for OrderUpdate. + * + * @param {string} orderId Unique identifier of the order. + * @param {boolean} isGoogleOrderId True if the order ID is provided by + * Google. False if the order ID is app provided. + */ + constructor(orderId: string, isGoogleOrderId: boolean); + + /** + * Set the Google provided order ID of the order. + * + * @param {string} orderId Google provided order ID. + * @return {OrderUpdate} Returns current constructed OrderUpdate. + */ + setGoogleOrderId(orderId: string): OrderUpdate; + + /** + * Set the Action provided order ID of the order. + * + * @param {string} orderId Action provided order ID. + * @return {OrderUpdate} Returns current constructed OrderUpdate. + */ + setActionOrderId(orderId: string): OrderUpdate; + + /** + * Set the state of the order. + * + * @param {string} state One of TransactionValues.OrderState. + * @param {string} label Label for the order state. + * @return {OrderUpdate} Returns current constructed OrderUpdate. + */ + setOrderState(state: OrderState, label: string): OrderUpdate; + + /** + * Set the update time of the order. + * + * @param {number} seconds Seconds since Unix epoch. + * @param {number=} nanos Partial time units. + * @return {OrderUpdate} Returns current constructed OrderUpdate. + */ + setUpdateTime(seconds: number, nanos?: number): OrderUpdate; + + /** + * Set the user notification content of the order update. + * + * @param {string} title Title of the notification. + * @param {text} text Text of the notification. + * @return {OrderUpdate} Returns current constructed OrderUpdate. + */ + setUserNotification(title: string, text: object): OrderUpdate; + + /** + * Sets the total price for this order. + * + * @param {string} priceType One of TransactionValues.PriceType. + * @param {string} currencyCode Currency code of price. + * @param {number} units Unit count of price. + * @param {number=} nanos Partial unit count of price. + * @return {OrderUpdate} Returns current constructed OrderUpdate. + */ + setTotalPrice(priceType: PriceType, currencyCode: string, units: number, nanos?: number): OrderUpdate; + + /** + * Adds an actionable item for the user to manage the order. + * + * @param {string} type One of TransactionValues.OrderActions. + * @param {string} label Button label. + * @param {string} url URL to open when button is clicked. + * @return {OrderUpdate} Returns current constructed OrderUpdate. + */ + addOrderManagementAction(type: OrderAction, label: string, url: string): OrderUpdate; + + /** + * Adds a single price update for a particular line item in the order. + * + * @param {string} itemId Line item ID for the order item updated. + * @param {string} priceType One of TransactionValues.PriceType. + * @param {string} currencyCode Currency code of new price. + * @param {number} units Unit count of new price. + * @param {number=} nanos Partial unit count of new price. + * @param {string=} reason Reason for the price change. Required unless a + * reason for this line item change was already declared in + * addLineItemStateUpdate. + * @return {OrderUpdate} Returns current constructed OrderUpdate. + */ + addLineItemPriceUpdate(itemId: string, priceType: PriceType, currencyCode: string, units: number, nanos?: number, reason?: string): OrderUpdate; + + /** + * Adds a single state update for a particular line item in the order. + * + * @param {string} itemId Line item ID for the order item updated. + * @param {string} state One of TransactionValues.OrderState. + * @param {string} label Label for the new item state. + * @param {string=} reason Reason for the price change. This will overwrite + * any reason given in addLineitemPriceUpdate. + * @return {OrderUpdate} Returns current constructed OrderUpdate. + */ + addLineItemStateUpdate(itemId: string, state: OrderState, label: string, reason?: string): OrderUpdate; + + /** + * Sets some extra information about the order. Takes an order update info + * type, and any accompanying data. This should only be called once per + * order update. + * + * @param {string} type One of TransactionValues.OrderStateInfo. + * @param {Object} data Proper Object matching the data necessary for the info + * type. For instance, for the TransactionValues.OrderStateInfo.RECEIPT info + * type, use the {@link ReceiptInfo} data type. + * @return {OrderUpdate} Returns current constructed OrderUpdate. + */ + setInfo(type: string, data: object): OrderUpdate; +} diff --git a/types/actions-on-google/tsconfig.json b/types/actions-on-google/tsconfig.json new file mode 100644 index 0000000000..cc0a4b24d9 --- /dev/null +++ b/types/actions-on-google/tsconfig.json @@ -0,0 +1,27 @@ +{ + "compilerOptions": { + "module": "commonjs", + "lib": [ + "es6" + ], + "noImplicitAny": true, + "noImplicitThis": true, + "strictNullChecks": true, + "baseUrl": "../", + "typeRoots": [ + "../" + ], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true + }, + "files": [ + "index.d.ts", + "assistant-app.d.ts", + "actions-sdk-app.d.ts", + "api-ai-app.d.ts", + "response-builder.d.ts", + "transactions.d.ts", + "actions-on-google-tests.ts" + ] +} diff --git a/types/actions-on-google/tslint.json b/types/actions-on-google/tslint.json new file mode 100644 index 0000000000..3db14f85ea --- /dev/null +++ b/types/actions-on-google/tslint.json @@ -0,0 +1 @@ +{ "extends": "dtslint/dt.json" } From 5035da30ca8f48c167b3b0c9deba1b617ac48acd Mon Sep 17 00:00:00 2001 From: Joel Hegg Date: Fri, 6 Oct 2017 23:56:24 -0400 Subject: [PATCH 095/828] Remove license headers and add a NOTICE file per PR feedback --- types/actions-on-google/NOTICE | 13 +++++++++++++ .../actions-on-google/actions-on-google-tests.ts | 4 ++-- types/actions-on-google/actions-sdk-app.d.ts | 16 ---------------- types/actions-on-google/api-ai-app.d.ts | 16 ---------------- types/actions-on-google/assistant-app.d.ts | 16 ---------------- types/actions-on-google/index.d.ts | 16 ---------------- types/actions-on-google/response-builder.d.ts | 16 ---------------- types/actions-on-google/transactions.d.ts | 16 ---------------- 8 files changed, 15 insertions(+), 98 deletions(-) create mode 100644 types/actions-on-google/NOTICE diff --git a/types/actions-on-google/NOTICE b/types/actions-on-google/NOTICE new file mode 100644 index 0000000000..262b08db36 --- /dev/null +++ b/types/actions-on-google/NOTICE @@ -0,0 +1,13 @@ +License Notices: + +The API definitions are from Actions on Google reference site [1] and actions-on-google library [2]. +The actions-on-google library is licensed under the Apache 2.0 License [3]. + +The code documentation is reproduced from work created and shared by Google [4] +and used according to terms described in the Creative Commons 3.0 Attribution License [5]. + +[1] https://developers.google.com/actions/ +[2] https://github.com/actions-on-google/actions-on-google-nodejs +[3] http://www.apache.org/licenses/LICENSE-2.0 +[4] https://developers.google.com/readme/policies/ +[5] http://creativecommons.org/licenses/by/3.0/ diff --git a/types/actions-on-google/actions-on-google-tests.ts b/types/actions-on-google/actions-on-google-tests.ts index b7632217e2..dfa431da78 100644 --- a/types/actions-on-google/actions-on-google-tests.ts +++ b/types/actions-on-google/actions-on-google-tests.ts @@ -29,5 +29,5 @@ function testApiAi(request: express.Request, response: express.Response) { } const expressApp = express(); -expressApp.get('/actionssdk', (req, res) => testActionsSdk); -expressApp.get('/apiai', (req, res) => testApiAi); +expressApp.get('/actionssdk', testActionsSdk); +expressApp.get('/apiai', testApiAi); diff --git a/types/actions-on-google/actions-sdk-app.d.ts b/types/actions-on-google/actions-sdk-app.d.ts index be399b4783..6511ed7f6d 100644 --- a/types/actions-on-google/actions-sdk-app.d.ts +++ b/types/actions-on-google/actions-sdk-app.d.ts @@ -1,19 +1,3 @@ -/** - * Copyright 2017 Google Inc. All Rights Reserved. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - import { Request, Response } from 'express'; import { AssistantApp, DeviceLocation, SessionStartedFunction, User } from './assistant-app'; diff --git a/types/actions-on-google/api-ai-app.d.ts b/types/actions-on-google/api-ai-app.d.ts index b7dc28b86a..13f5f852dd 100644 --- a/types/actions-on-google/api-ai-app.d.ts +++ b/types/actions-on-google/api-ai-app.d.ts @@ -1,19 +1,3 @@ -/** - * Copyright 2017 Google Inc. All Rights Reserved. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - import { Request, Response } from 'express'; import { AssistantApp, DeviceLocation, SessionStartedFunction, User } from './assistant-app'; diff --git a/types/actions-on-google/assistant-app.d.ts b/types/actions-on-google/assistant-app.d.ts index 01d3bcf046..d964940c54 100644 --- a/types/actions-on-google/assistant-app.d.ts +++ b/types/actions-on-google/assistant-app.d.ts @@ -1,19 +1,3 @@ -/** - * Copyright 2017 Google Inc. All Rights Reserved. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - import { Request, Response } from 'express'; import { BasicCard, Carousel, List, OptionItem, RichResponse } from './response-builder'; diff --git a/types/actions-on-google/index.d.ts b/types/actions-on-google/index.d.ts index 3c0daa5a28..997ae3a7e8 100644 --- a/types/actions-on-google/index.d.ts +++ b/types/actions-on-google/index.d.ts @@ -4,22 +4,6 @@ // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped // TypeScript Version: 2.4 -/** - * Copyright 2016 Google Inc. All Rights Reserved. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - /** * The Actions on Google client library. * https://developers.google.com/actions/ diff --git a/types/actions-on-google/response-builder.d.ts b/types/actions-on-google/response-builder.d.ts index add7b9fc03..1133879819 100644 --- a/types/actions-on-google/response-builder.d.ts +++ b/types/actions-on-google/response-builder.d.ts @@ -1,19 +1,3 @@ -/** - * Copyright 2017 Google Inc. All Rights Reserved. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - /** * A collection of response builders. */ diff --git a/types/actions-on-google/transactions.d.ts b/types/actions-on-google/transactions.d.ts index e64e69bdf1..d2773896b8 100644 --- a/types/actions-on-google/transactions.d.ts +++ b/types/actions-on-google/transactions.d.ts @@ -1,19 +1,3 @@ -/** - * Copyright 2017 Google Inc. All Rights Reserved. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - /** * A collection of Transaction related constants, utility functions, and * builders. From f277b21d513336ad9b4e5d6a27fe2dacd9dee539 Mon Sep 17 00:00:00 2001 From: Joel Hegg Date: Sat, 7 Oct 2017 00:23:17 -0400 Subject: [PATCH 096/828] Add strictFunctionTypes parameter now required by Travis --- types/actions-on-google/tsconfig.json | 1 + 1 file changed, 1 insertion(+) diff --git a/types/actions-on-google/tsconfig.json b/types/actions-on-google/tsconfig.json index cc0a4b24d9..79fed964d6 100644 --- a/types/actions-on-google/tsconfig.json +++ b/types/actions-on-google/tsconfig.json @@ -7,6 +7,7 @@ "noImplicitAny": true, "noImplicitThis": true, "strictNullChecks": true, + "strictFunctionTypes": true, "baseUrl": "../", "typeRoots": [ "../" From ec116e2efb133f4efbc8b4925e5055c736dde548 Mon Sep 17 00:00:00 2001 From: Joel Hegg Date: Tue, 10 Oct 2017 14:14:01 -0400 Subject: [PATCH 097/828] Upgrade to actions-on-google 1.5 --- .../actions-on-google-tests.ts | 8 +- types/actions-on-google/assistant-app.d.ts | 104 ++++++++-------- .../{api-ai-app.d.ts => dialogflow-app.d.ts} | 115 ++++++++++-------- types/actions-on-google/index.d.ts | 7 +- types/actions-on-google/tsconfig.json | 2 +- 5 files changed, 125 insertions(+), 111 deletions(-) rename types/actions-on-google/{api-ai-app.d.ts => dialogflow-app.d.ts} (84%) diff --git a/types/actions-on-google/actions-on-google-tests.ts b/types/actions-on-google/actions-on-google-tests.ts index dfa431da78..e57e1e8d98 100644 --- a/types/actions-on-google/actions-on-google-tests.ts +++ b/types/actions-on-google/actions-on-google-tests.ts @@ -1,4 +1,4 @@ -import { ActionsSdkApp, ActionsSdkAppOptions, ApiAiApp, ApiAiAppOptions, AssistantApp, +import { ActionsSdkApp, ActionsSdkAppOptions, DialogflowApp, DialogflowAppOptions, AssistantApp, Responses, Transactions } from 'actions-on-google'; import * as express from 'express'; @@ -14,8 +14,8 @@ function testActionsSdk(request: express.Request, response: express.Response) { app.handleRequest(actionMap); } -function testApiAi(request: express.Request, response: express.Response) { - const app = new ApiAiApp({request, response}); +function testDialogflow(request: express.Request, response: express.Response) { + const app = new DialogflowApp({request, response}); const actionMap = new Map(); actionMap.set(app.StandardIntents.MAIN, () => { const order: Transactions.Order = app.buildOrder('foo'); @@ -30,4 +30,4 @@ function testApiAi(request: express.Request, response: express.Response) { const expressApp = express(); expressApp.get('/actionssdk', testActionsSdk); -expressApp.get('/apiai', testApiAi); +expressApp.get('/dialogflow', testDialogflow); diff --git a/types/actions-on-google/assistant-app.d.ts b/types/actions-on-google/assistant-app.d.ts index d964940c54..3bfd78f514 100644 --- a/types/actions-on-google/assistant-app.d.ts +++ b/types/actions-on-google/assistant-app.d.ts @@ -425,7 +425,7 @@ export class AssistantApp { * Constructor for AssistantApp object. * Should not be instantiated; rather instantiate one of the subclasses * - * {@link ActionsSdkApp} or {@link ApiAiApp}. + * {@link ActionsSdkApp} or {@link DialogflowApp}. * * @param {Object} options JSON configuration. * @param {Object} options.request Express HTTP request object. @@ -473,8 +473,8 @@ export class AssistantApp { * * app.handleRequest(actionMap); * - * // API.AI - * const app = new ApiAiApp({request: req, response: res}); + * // Dialogflow + * const app = new DialogflowApp({request: req, response: res}); * const NAME_ACTION = 'make_name'; * const COLOR_ARGUMENT = 'color'; * const NUMBER_ARGUMENT = 'number'; @@ -493,7 +493,7 @@ export class AssistantApp { * * @param {(Function|Map)} handler The handler (or Map of handlers) for the request. * @actionssdk - * @apiai + * @dialogflow */ handleRequest(handler?: RequestHandler | Map): void; @@ -512,7 +512,7 @@ export class AssistantApp { * equivalent to just asking for DEVICE_PRECISE_LOCATION * * @example - * const app = new ApiAIApp({request: req, response: res}); + * const app = new DialogflowApp({request: req, response: res}); * const REQUEST_PERMISSION_ACTION = 'request_permission'; * const GET_RIDE_ACTION = 'get_ride'; * @@ -549,7 +549,7 @@ export class AssistantApp { * @return A response is sent to Assistant to ask for the user's permission; for any * invalid input, we return null. * @actionssdk - * @apiai + * @dialogflow */ askForPermissions(context: string, permissions: string[], dialogState?: object): object; @@ -557,7 +557,7 @@ export class AssistantApp { * Checks whether user is in transactable state. * * @example - * const app = new ApiAiApp({request: request, response: response}); + * const app = new DialogflowApp({request: request, response: response}); * const WELCOME_INTENT = 'input.welcome'; * const TXN_REQ_COMPLETE = 'txn.req.complete'; * @@ -591,7 +591,7 @@ export class AssistantApp { * will be circulated back by Assistant. Used in {@link ActionsSdkAssistant}. * @return {Object} HTTP response. * @actionssdk - * @apiai + * @dialogflow */ askForTransactionRequirements(transactionConfig?: ActionPaymentTransactionConfig | GooglePaymentTransactionConfig, dialogState?: object): object; @@ -599,7 +599,7 @@ export class AssistantApp { * Asks user to confirm transaction information. * * @example - * const app = new ApiAiApp({request: request, response: response}); + * const app = new DialogflowApp({request: request, response: response}); * const WELCOME_INTENT = 'input.welcome'; * const TXN_COMPLETE = 'txn.complete'; * @@ -631,7 +631,7 @@ export class AssistantApp { * options and order options. * @param {Object=} dialogState JSON object the app uses to hold dialog state that * will be circulated back by Assistant. Used in {@link ActionsSdkAssistant}. - * @apiai + * @dialogflow */ askForTransactionDecision(order: object, transactionConfig?: ActionPaymentTransactionConfig | GooglePaymentTransactionConfig, dialogState?: object): object; @@ -655,7 +655,7 @@ export class AssistantApp { * * {@link AssistantApp#getUserName|getUserName} * * @example - * const app = new ApiAiApp({request: req, response: res}); + * const app = new DialogflowApp({request: req, response: res}); * const REQUEST_PERMISSION_ACTION = 'request_permission'; * const GET_RIDE_ACTION = 'get_ride'; * @@ -687,7 +687,7 @@ export class AssistantApp { * @return A response is sent to the Assistant to ask for the user's permission; * for any invalid input, we return null. * @actionssdk - * @apiai + * @dialogflow */ askForPermission(context: string, permission: string, dialogState?: object): object; @@ -699,7 +699,7 @@ export class AssistantApp { * @example * const app = new ActionsSdkApp({request: request, response: response}); * // or - * const app = new ApiAiApp({request: request, response: response}); + * const app = new DialogflowApp({request: request, response: response}); * app.askForPermissions("To get you a ride", [ * app.SupportedPermissions.NAME, * app.SupportedPermissions.DEVICE_PRECISE_LOCATION @@ -711,7 +711,7 @@ export class AssistantApp { * } * * @return {boolean} true if permissions granted. - * @apiai + * @dialogflow * @actionssdk */ isPermissionGranted(): boolean; @@ -720,8 +720,8 @@ export class AssistantApp { * Asks user for delivery address. * * @example - * // For ApiAiApp: - * const app = new ApiAiApp({request, response}); + * // For DialogflowApp: + * const app = new DialogflowApp({request, response}); * const WELCOME_INTENT = 'input.welcome'; * const DELIVERY_INTENT = 'delivery.address'; * @@ -771,7 +771,7 @@ export class AssistantApp { * will be circulated back by Assistant. * @return {Object} HTTP response. * @actionssdk - * @apiai + * @dialogflow */ askForDeliveryAddress(reason: string, dialogState?: object): object; @@ -779,7 +779,7 @@ export class AssistantApp { * Asks user for a confirmation. * * @example - * const app = new ApiAiApp({ request, response }); + * const app = new DialogflowApp({ request, response }); * const WELCOME_INTENT = 'input.welcome'; * const CONFIRMATION = 'confirmation'; * @@ -806,7 +806,7 @@ export class AssistantApp { * @param {Object=} dialogState JSON object the app uses to hold dialog state that * will be circulated back by Assistant. Used in {@link ActionsSdkAssistant}. * @actionssdk - * @apiai + * @dialogflow */ askForConfirmation(prompt?: string, dialogState?: object): object; @@ -814,7 +814,7 @@ export class AssistantApp { * Asks user for a timezone-agnostic date and time. * * @example - * const app = new ApiAiApp({ request, response }); + * const app = new DialogflowApp({ request, response }); * const WELCOME_INTENT = 'input.welcome'; * const DATETIME = 'datetime'; * @@ -850,7 +850,7 @@ export class AssistantApp { * @param {Object=} dialogState JSON object the app uses to hold dialog state that * will be circulated back by Assistant. Used in {@link ActionsSdkAssistant}. * @actionssdk - * @apiai + * @dialogflow */ askForDateTime(initialPrompt?: string, datePrompt?: string, timePrompt?: string, dialogState?: object): object; @@ -866,7 +866,7 @@ export class AssistantApp { * consent". * * @example - * const app = new ApiAiApp({ request, response }); + * const app = new DialogflowApp({ request, response }); * const WELCOME_INTENT = 'input.welcome'; * const SIGN_IN = 'sign.in'; * @@ -891,7 +891,7 @@ export class AssistantApp { * @param {Object=} dialogState JSON object the app uses to hold dialog state that * will be circulated back by Assistant. Used in {@link ActionsSdkAssistant}. * @actionssdk - * @apiai + * @dialogflow */ askForSignIn(dialogState?: object): object; @@ -899,7 +899,7 @@ export class AssistantApp { * Requests the user to switch to another surface during the conversation. * * @example - * const app = new ApiAiApp({ request, response }); + * const app = new DialogflowApp({ request, response }); * const WELCOME_INTENT = 'input.welcome'; * const SHOW_IMAGE = 'show.image'; * @@ -937,7 +937,7 @@ export class AssistantApp { * the surface. * @param {Object=} dialogState JSON object the app uses to hold dialog state that * will be circulated back by Assistant. Used in {@link ActionsSdkAssistant}. - * @apiai + * @dialogflow * @actionssdk */ askForNewSurface(context: string, notificationTitle: string, capabilities: string[], dialogState?: object): object; @@ -949,14 +949,14 @@ export class AssistantApp { * see {@link AssistantApp#askForPermissions|askForPermissions}). * * @example - * const app = new ApiAiApp({request: request, response: response}); + * const app = new DialogflowApp({request: request, response: response}); * // or * const app = new ActionsSdkApp({request: request, response: response}); * const userId = app.getUser().userId; * * @return {User} Null if no value. * @actionssdk - * @apiai + * @dialogflow */ getUser(): User; @@ -966,7 +966,7 @@ export class AssistantApp { * returns null. * * @example - * const app = new ApiAIApp({request: req, response: res}); + * const app = new DialogflowApp({request: req, response: res}); * const REQUEST_PERMISSION_ACTION = 'request_permission'; * const SAY_NAME_ACTION = 'get_name'; * @@ -989,7 +989,7 @@ export class AssistantApp { * app.handleRequest(actionMap); * @return {UserName} Null if name permission is not granted. * @actionssdk - * @apiai + * @dialogflow */ getUserName(): UserName; @@ -999,12 +999,12 @@ export class AssistantApp { * For example, 'en-US' represents US English. * * @example - * const app = new ApiAiApp({request, response}); + * const app = new DialogflowApp({request, response}); * const locale = app.getUserLocale(); * * @return {string} User's locale, e.g. 'en-US'. Null if no locale given. * @actionssdk - * @apiai + * @dialogflow */ getUserLocale(): string; @@ -1014,7 +1014,7 @@ export class AssistantApp { * If device info is unavailable, returns null. * * @example - * const app = new ApiAiApp({request: req, response: res}); + * const app = new DialogflowApp({request: req, response: res}); * // or * const app = new ActionsSdkApp({request: req, response: res}); * app.askForPermission("To get you a ride", @@ -1027,7 +1027,7 @@ export class AssistantApp { * * @return {DeviceLocation} Null if location permission is not granted. * @actionssdk - * @apiai + * @dialogflow */ getDeviceLocation(): DeviceLocation; @@ -1036,7 +1036,7 @@ export class AssistantApp { * * @return {number} One of AssistantApp.InputTypes. * Null if no input type given. - * @apiai + * @dialogflow * @actionssdk */ getInputType(): number; @@ -1050,7 +1050,7 @@ export class AssistantApp { * the argument object will be in Proto2 format (snake_case, etc). * * @example - * const app = new ApiAiApp({request: request, response: response}); + * const app = new DialogflowApp({request: request, response: response}); * const WELCOME_INTENT = 'input.welcome'; * const NUMBER_INTENT = 'input.number'; * @@ -1071,7 +1071,7 @@ export class AssistantApp { * @param {string} argName Name of the argument. * @return {Object} Argument value matching argName * or null if no matching argument. - * @apiai + * @dialogflow * @actionssdk */ getArgumentCommon(argName: string): object; @@ -1081,7 +1081,7 @@ export class AssistantApp { * askForTransactionRequirements. Null if no result given. * * @return {string} One of Transactions.ResultType. - * @apiai + * @dialogflow * @actionssdk */ getTransactionRequirementsResult(): string; @@ -1091,7 +1091,7 @@ export class AssistantApp { * * @return {DeliveryAddress} Delivery address information. Null if user * denies permission, or no address given. - * @apiai + * @dialogflow * @actionssdk */ getDeliveryAddress(): Location; @@ -1103,7 +1103,7 @@ export class AssistantApp { * @return {TransactionDecision} Transaction decision data. Returns object with * userDecision only if user declines. userDecision will be one of * Transactions.ConfirmationDecision. Null if no decision given. - * @apiai + * @dialogflow * @actionssdk */ getTransactionDecision(): TransactionDecision; @@ -1113,7 +1113,7 @@ export class AssistantApp { * * False if user replied with negative response. Null if no user * confirmation decision given. - * @apiai + * @dialogflow * @actionssdk */ getUserConfirmation(): boolean | null; @@ -1123,7 +1123,7 @@ export class AssistantApp { * * @return {DateTime} Date and time given by the user. Null if no user * date and time given. - * @apiai + * @dialogflow * @actionssdk */ getDateTime(): DateTime; @@ -1132,9 +1132,9 @@ export class AssistantApp { * Gets status of user sign in request. * * @return {string} Result of user sign in request. One of - * ApiAiApp.SignInStatus or ActionsSdkApp.SignInStatus + * DialogflowApp.SignInStatus or ActionsSdkApp.SignInStatus * Null if no sign in status. - * @apiai + * @dialogflow * @actionssdk */ getSignInStatus(): string; @@ -1146,7 +1146,7 @@ export class AssistantApp { * @return {boolean} True if user device has the given capability. * * @example - * const app = new ApiAIApp({request: req, response: res}); + * const app = new DialogflowApp({request: req, response: res}); * const DESCRIBE_SOMETHING = 'DESCRIBE_SOMETHING'; * * function describe (app) { @@ -1160,7 +1160,7 @@ export class AssistantApp { * actionMap.set(DESCRIBE_SOMETHING, describe); * app.handleRequest(actionMap); * - * @apiai + * @dialogflow * @actionssdk */ hasSurfaceCapability(requestedCapability: string): boolean; @@ -1170,7 +1170,7 @@ export class AssistantApp { * * @return {Array} Supported surface capabilities, as defined in * AssistantApp.SurfaceCapabilities. - * @apiai + * @dialogflow * @actionssdk */ getSurfaceCapabilities(): string[]; @@ -1180,7 +1180,7 @@ export class AssistantApp { * * @return {Array} Empty if no available surfaces. * @actionssdk - * @apiai + * @dialogflow */ getAvailableSurfaces(): Surface[]; @@ -1193,7 +1193,7 @@ export class AssistantApp { * {@link SurfaceCapabilities}. * @return {boolean} True if user has a capability available on some surface. * - * @apiai + * @dialogflow * @actionssdk */ hasAvailableSurfaceCapabilities(capabilities: string | string[]): boolean; @@ -1204,7 +1204,7 @@ export class AssistantApp { * @return {boolean} True if user has triggered conversation on a new device * following the NEW_SURFACE intent. * @actionssdk - * @apiai + * @dialogflow */ isNewSurface(): boolean; @@ -1214,7 +1214,7 @@ export class AssistantApp { * transactions. * * @return {boolean} True if app is being used in Sandbox mode. - * @apiai + * @dialogflow * @actionssdk */ isInSandbox(): boolean; @@ -1249,7 +1249,7 @@ export class AssistantApp { * * @return {number} The current reprompt count. Null if no reprompt count * available (e.g. not in the NO_INPUT intent). - * @apiai + * @dialogflow * @actionssdk */ getRepromptCount(): number; @@ -1284,7 +1284,7 @@ export class AssistantApp { * * @return {boolean} True if in a NO_INPUT intent and this is the final turn * of dialog. - * @apiai + * @dialogflow * @actionssdk */ isFinalReprompt(): boolean; diff --git a/types/actions-on-google/api-ai-app.d.ts b/types/actions-on-google/dialogflow-app.d.ts similarity index 84% rename from types/actions-on-google/api-ai-app.d.ts rename to types/actions-on-google/dialogflow-app.d.ts index 13f5f852dd..c63a78f2ee 100644 --- a/types/actions-on-google/api-ai-app.d.ts +++ b/types/actions-on-google/dialogflow-app.d.ts @@ -5,41 +5,41 @@ import { Carousel, List, RichResponse, SimpleResponse } from './response-builder import { TransactionDecision } from './transactions'; // --------------------------------------------------------------------------- -// API.AI support +// Dialogflow support // --------------------------------------------------------------------------- /** - * API.AI {@link https://docs.api.ai/docs/concept-contexts|Context}. + * DialogflowApp {@link https://dialogflow.com/docs/concept-contexts|Context}. */ export interface Context { /** Full name of the context. */ name: string; /** * Parameters carried within this context. - * See {@link https://docs.api.ai/docs/concept-actions#section-extracting-values-from-contexts|here}. + * See {@link https://dialogflow.com/docs/concept-actions#section-extracting-values-from-contexts|here}. */ parameters: object; /** Remaining number of intents */ lifespan: number; } -export interface ApiAiAppOptions { +export interface DialogflowAppOptions { request: Request; response: Response; sessionStarted?: SessionStartedFunction; } /** - * This is the class that handles the communication with API.AI's fulfillment API. + * This is the class that handles the communication with Dialogflow's fulfillment API. */ -export class ApiAiApp extends AssistantApp { +export class DialogflowApp extends AssistantApp { /** - * Constructor for ApiAiApp object. - * To be used in the API.AI fulfillment webhook logic. + * Constructor for DialogflowApp object. + * To be used in the Dialogflow fulfillment webhook logic. * * @example - * const ApiAiApp = require('actions-on-google').ApiAiApp; - * const app = new ApiAiApp({request: request, response: response, + * const DialogflowApp = require('actions-on-google').DialogflowApp; + * const app = new DialogflowApp({request: request, response: response, * sessionStarted:sessionStarted}); * * @param {Object} options JSON configuration. @@ -47,31 +47,44 @@ export class ApiAiApp extends AssistantApp { * @param {Object} options.response Express HTTP response object. * @param {Function=} options.sessionStarted Function callback when session starts. * Only called if webhook is enabled for welcome/triggering intents, and - * called from Web Simulator or Google Home device (i.e., not API.AI simulator). - * @apiai + * called from Web Simulator or Google Home device (i.e., not Dialogflow simulator). + * @dialogflow */ - constructor(options: ApiAiAppOptions); + constructor(options: DialogflowAppOptions); /** - * Verifies whether the request comes from API.AI. + * @deprecated + * Verifies whether the request comes from Dialogflow. * * @param {string} key The header key specified by the developer in the - * API.AI Fulfillment settings of the app. + * Dialogflow Fulfillment settings of the app. * @param {string} value The private value specified by the developer inside the * fulfillment header. - * @return {boolean} True if the request comes from API.AI. - * @apiai + * @return {boolean} True if the request comes from Dialogflow. + * @dialogflow */ isRequestFromApiAi(key: string, value: string): boolean; + /** + * Verifies whether the request comes from Dialogflow. + * + * @param {string} key The header key specified by the developer in the + * Dialogflow Fulfillment settings of the app. + * @param {string} value The private value specified by the developer inside the + * fulfillment header. + * @return {boolean} True if the request comes from Dialogflow. + * @dialogflow + */ + isRequestFromDialogflow(key: string, value: string): boolean; + /** * Get the current intent. Alternatively, using a handler Map with * {@link AssistantApp#handleRequest|handleRequest}, * the client library will automatically handle the incoming intents. - * 'Intent' in the API.ai context translates into the current action. + * 'Intent' in the Dialogflow context translates into the current action. * * @example - * const app = new ApiAiApp({request: request, response: response}); + * const app = new DialogflowApp({request: request, response: response}); * * function responseHandler (app) { * const intent = app.getIntent(); @@ -90,7 +103,7 @@ export class ApiAiApp extends AssistantApp { * app.handleRequest(responseHandler); * * @return {string} Intent id or null if no value (action name). - * @apiai + * @dialogflow */ getIntent(): string; @@ -103,7 +116,7 @@ export class ApiAiApp extends AssistantApp { * the argument object will be in Proto2 format (snake_case, etc). * * @example - * const app = new ApiAiApp({request: request, response: response}); + * const app = new DialogflowApp({request: request, response: response}); * const WELCOME_INTENT = 'input.welcome'; * const NUMBER_INTENT = 'input.number'; * @@ -124,7 +137,7 @@ export class ApiAiApp extends AssistantApp { * @param {string} argName Name of the argument. * @return {Object} Argument value matching argName * or null if no matching argument. - * @apiai + * @dialogflow */ getArgument(argName: string): object; @@ -136,7 +149,7 @@ export class ApiAiApp extends AssistantApp { * as part of the return object. * * @example - * const app = new ApiAiApp({request: request, response: response}); + * const app = new DialogflowApp({request: request, response: response}); * const WELCOME_INTENT = 'input.welcome'; * const NUMBER_INTENT = 'input.number'; * const OUT_CONTEXT = 'output_context'; @@ -164,12 +177,12 @@ export class ApiAiApp extends AssistantApp { * @param {string} argName Name of the argument. * @return {Object} Object containing value property and optional original * property matching context argument. Null if no matching argument. - * @apiai + * @dialogflow */ getContextArgument(contextName: string, argName: string): object; /** - * Returns the RichResponse constructed in API.AI response builder. + * Returns the RichResponse constructed in Dialogflow response builder. * * @example * const app = new App({request: req, response: res}); @@ -192,14 +205,14 @@ export class ApiAiApp extends AssistantApp { * * app.handleRequest(actionMap); * - * @return {RichResponse} RichResponse created in API.AI. If no RichResponse was + * @return {RichResponse} RichResponse created in Dialogflow. If no RichResponse was * created, an empty RichResponse is returned. - * @apiai + * @dialogflow */ getIncomingRichResponse(): RichResponse; /** - * Returns the List constructed in API.AI response builder. + * Returns the List constructed in Dialogflow response builder. * * @example * const app = new App({request: req, response: res}); @@ -220,14 +233,14 @@ export class ApiAiApp extends AssistantApp { * * app.handleRequest(actionMap); * - * @return {List} List created in API.AI. If no List was created, an empty + * @return {List} List created in Dialogflow. If no List was created, an empty * List is returned. - * @apiai + * @dialogflow */ getIncomingList(): List; /** - * Returns the Carousel constructed in API.AI response builder. + * Returns the Carousel constructed in Dialogflow response builder. * * @example * const app = new App({request: req, response: res}); @@ -248,9 +261,9 @@ export class ApiAiApp extends AssistantApp { * * app.handleRequest(actionMap); * - * @return {Carousel} Carousel created in API.AI. If no Carousel was created, + * @return {Carousel} Carousel created in Dialogflow. If no Carousel was created, * an empty Carousel is returned. - * @apiai + * @dialogflow */ getIncomingCarousel(): Carousel; @@ -283,7 +296,7 @@ export class ApiAiApp extends AssistantApp { * * @return {string} Option key of selected item. Null if no option selected or * if current intent is not OPTION intent. - * @apiai + * @dialogflow */ getSelectedOption(): string; @@ -296,7 +309,7 @@ export class ApiAiApp extends AssistantApp { * for a bye message until the bug is fixed. * * @example - * const app = new ApiAiApp({request: request, response: response}); + * const app = new DialogflowApp({request: request, response: response}); * const WELCOME_INTENT = 'input.welcome'; * const NUMBER_INTENT = 'input.number'; * @@ -319,7 +332,7 @@ export class ApiAiApp extends AssistantApp { * response. * @param {Array=} noInputs Array of re-prompts when the user does not respond (max 3). * @return {Object} HTTP response. - * @apiai + * @dialogflow */ ask(inputPrompt: string | SimpleResponse | RichResponse, noInputs?: string[]): object; @@ -327,7 +340,7 @@ export class ApiAiApp extends AssistantApp { * Asks to collect the user's input with a list. * * @example - * const app = new ApiAiApp({request, response}); + * const app = new DialogflowApp({request, response}); * const WELCOME_INTENT = 'input.welcome'; * const OPTION_INTENT = 'option.select'; * @@ -361,7 +374,7 @@ export class ApiAiApp extends AssistantApp { * response. * @param {List} list List built with {@link AssistantApp#buildList|buildList}. * @return {Object} HTTP response. - * @apiai + * @dialogflow */ askWithList(inputPrompt: string | RichResponse | SimpleResponse, list: List): object; @@ -369,7 +382,7 @@ export class ApiAiApp extends AssistantApp { * Asks to collect the user's input with a carousel. * * @example - * const app = new ApiAiApp({request, response}); + * const app = new DialogflowApp({request, response}); * const WELCOME_INTENT = 'input.welcome'; * const OPTION_INTENT = 'option.select'; * @@ -404,7 +417,7 @@ export class ApiAiApp extends AssistantApp { * @param {Carousel} carousel Carousel built with * {@link AssistantApp#buildCarousel|buildCarousel}. * @return {Object} HTTP response. - * @apiai + * @dialogflow */ askWithCarousel(inputPrompt: string | RichResponse | SimpleResponse, carousel: Carousel): object; @@ -412,7 +425,7 @@ export class ApiAiApp extends AssistantApp { * Tells the Assistant to render the speech response and close the mic. * * @example - * const app = new ApiAiApp({request: request, response: response}); + * const app = new DialogflowApp({request: request, response: response}); * const WELCOME_INTENT = 'input.welcome'; * const NUMBER_INTENT = 'input.number'; * @@ -433,7 +446,7 @@ export class ApiAiApp extends AssistantApp { * @param {string|SimpleResponse|RichResponse} textToSpeech Final response. * Spoken response can be SSML. * @return The response that is sent back to Assistant. - * @apiai + * @dialogflow */ tell(speechResponse: string | SimpleResponse | RichResponse): object; @@ -441,7 +454,7 @@ export class ApiAiApp extends AssistantApp { * Set a new context for the current intent. * * @example - * const app = new ApiAiApp({request: request, response: response}); + * const app = new DialogflowApp({request: request, response: response}); * const CONTEXT_NUMBER = 'number'; * const NUMBER_ARGUMENT = 'myNumber'; * @@ -460,10 +473,10 @@ export class ApiAiApp extends AssistantApp { * actionMap.set(NUMBER_INTENT, numberIntent); * app.handleRequest(actionMap); * - * @param {string} name Name of the context. API.AI converts to lowercase. + * @param {string} name Name of the context. Dialogflow converts to lowercase. * @param {int} [lifespan=1] Context lifespan. * @param {Object=} parameters Context JSON parameters. - * @apiai + * @dialogflow */ setContext(name: string, lifespan: number, parameters?: object): void; @@ -471,7 +484,7 @@ export class ApiAiApp extends AssistantApp { * Returns the incoming contexts for this intent. * * @example - * const app = new ApiAiApp({request: request, response: response}); + * const app = new DialogflowApp({request: request, response: response}); * const CONTEXT_NUMBER = 'number'; * const NUMBER_ARGUMENT = 'myNumber'; * @@ -500,7 +513,7 @@ export class ApiAiApp extends AssistantApp { * app.handleRequest(actionMap); * * @return {Context[]} Empty if no active contexts. - * @apiai + * @dialogflow */ getContexts(): Context[]; @@ -508,7 +521,7 @@ export class ApiAiApp extends AssistantApp { * Returns the incoming context by name for this intent. * * @example - * const app = new ApiAiapp({request: request, response: response}); + * const app = new DialogflowApp({request: request, response: response}); * const CONTEXT_NUMBER = 'number'; * const NUMBER_ARGUMENT = 'myNumber'; * @@ -538,7 +551,7 @@ export class ApiAiApp extends AssistantApp { * * @return {Object} Context value matching name * or null if no matching context. - * @apiai + * @dialogflow */ getContext(name: string): object; @@ -546,11 +559,11 @@ export class ApiAiApp extends AssistantApp { * Gets the user's raw input query. * * @example - * const app = new ApiAiApp({request: request, response: response}); + * const app = new DialogflowApp({request: request, response: response}); * app.tell('You said ' + app.getRawInput()); * * @return {string} User's raw query or null if no value. - * @apiai + * @dialogflow */ getRawInput(): string; } diff --git a/types/actions-on-google/index.d.ts b/types/actions-on-google/index.d.ts index 997ae3a7e8..0e8fd831e5 100644 --- a/types/actions-on-google/index.d.ts +++ b/types/actions-on-google/index.d.ts @@ -1,4 +1,4 @@ -// Type definitions for actions-on-google 1.4 +// Type definitions for actions-on-google 1.5 // Project: https://github.com/actions-on-google/actions-on-google-nodejs // Definitions by: Joel Hegg , Pilwon Huh // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped @@ -14,10 +14,11 @@ import * as Responses from './response-builder'; export { AssistantApp, AssistantAppOptions, RequestHandler, SessionStartedFunction, State } from './assistant-app'; export { ActionsSdkApp, ActionsSdkAppOptions } from './actions-sdk-app'; -export { ApiAiApp, ApiAiAppOptions } from './api-ai-app'; +export { DialogflowApp, DialogflowAppOptions } from './dialogflow-app'; export { Transactions }; export { Responses }; // Backwards compatibility export { AssistantApp as Assistant } from './assistant-app'; export { ActionsSdkApp as ActionsSdkAssistant } from './actions-sdk-app'; -export { ApiAiApp as ApiAiAssistant } from './api-ai-app'; +export { DialogflowApp as ApiAiAssistant } from './dialogflow-app'; +export { DialogflowApp as ApiAiApp } from './dialogflow-app'; diff --git a/types/actions-on-google/tsconfig.json b/types/actions-on-google/tsconfig.json index 79fed964d6..6682b5c194 100644 --- a/types/actions-on-google/tsconfig.json +++ b/types/actions-on-google/tsconfig.json @@ -20,7 +20,7 @@ "index.d.ts", "assistant-app.d.ts", "actions-sdk-app.d.ts", - "api-ai-app.d.ts", + "dialogflow-app.d.ts", "response-builder.d.ts", "transactions.d.ts", "actions-on-google-tests.ts" From aad047cd06ffc379a08c1cb35c00925f14defe89 Mon Sep 17 00:00:00 2001 From: Joel Hegg Date: Fri, 20 Oct 2017 02:24:04 -0400 Subject: [PATCH 098/828] Temporarily stage the 1.5.1 .js files --- .../staging/actions-on-google.js | 38 + .../staging/actions-sdk-app.js | 877 +++++++ .../staging/assistant-app.js | 2262 +++++++++++++++++ .../staging/dialogflow-app.js | 1105 ++++++++ .../staging/response-builder.js | 800 ++++++ .../actions-on-google/staging/transactions.js | 1439 +++++++++++ 6 files changed, 6521 insertions(+) create mode 100644 types/actions-on-google/staging/actions-on-google.js create mode 100644 types/actions-on-google/staging/actions-sdk-app.js create mode 100644 types/actions-on-google/staging/assistant-app.js create mode 100644 types/actions-on-google/staging/dialogflow-app.js create mode 100644 types/actions-on-google/staging/response-builder.js create mode 100644 types/actions-on-google/staging/transactions.js diff --git a/types/actions-on-google/staging/actions-on-google.js b/types/actions-on-google/staging/actions-on-google.js new file mode 100644 index 0000000000..81c21dde03 --- /dev/null +++ b/types/actions-on-google/staging/actions-on-google.js @@ -0,0 +1,38 @@ +/** + * Copyright 2016 Google Inc. All Rights Reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +/** + * The Actions on Google client library. + * https://developers.google.com/actions/ + */ + +'use strict'; + +const AssistantApp = require('./assistant-app'); + +module.exports = { + AssistantApp: AssistantApp.AssistantApp, + State: AssistantApp.State, + ActionsSdkApp: require('./actions-sdk-app'), + DialogflowApp: require('./dialogflow-app'), + Transactions: require('./transactions'), + Responses: require('./response-builder'), + // Backwards compatibility + Assistant: AssistantApp.AssistantApp, + ActionsSdkAssistant: require('./actions-sdk-app'), + ApiAiAssistant: require('./dialogflow-app'), + ApiAiApp: require('./dialogflow-app') +}; diff --git a/types/actions-on-google/staging/actions-sdk-app.js b/types/actions-on-google/staging/actions-sdk-app.js new file mode 100644 index 0000000000..f5ef131b24 --- /dev/null +++ b/types/actions-on-google/staging/actions-sdk-app.js @@ -0,0 +1,877 @@ +/** + * Copyright 2017 Google Inc. All Rights Reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +'use strict'; + +const Debug = require('debug'); +const debug = Debug('actions-on-google:debug'); +const error = Debug('actions-on-google:error'); +const app = require('./assistant-app'); +const AssistantApp = app.AssistantApp; +const State = app.State; +const transformToCamelCase = require('./utils/transform').transformToCamelCase; + +// Constants +const CONVERSATION_API_AGENT_VERSION_HEADER = 'Agent-Version-Label'; +const RESPONSE_CODE_OK = 200; +const INPUTS_MAX = 3; +const CONVERSATION_API_SIGNATURE_HEADER = 'authorization'; + +// Configure logging for hosting platforms that only support console.log and console.error +debug.log = console.log.bind(console); +error.log = console.error.bind(console); + +// --------------------------------------------------------------------------- +// Actions SDK support +// --------------------------------------------------------------------------- + +/** + * This is the class that handles the conversation API directly from Assistant, + * providing implementation for all the methods available in the API. + */ +class ActionsSdkApp extends AssistantApp { + /** + * Constructor for ActionsSdkApp object. + * To be used in the Actions SDK HTTP endpoint logic. + * + * @example + * const ActionsSdkApp = require('actions-on-google').ActionsSdkApp; + * const app = new ActionsSdkApp({request: request, response: response, + * sessionStarted:sessionStarted}); + * + * @param {Object} options JSON configuration. + * @param {Object} options.request Express HTTP request object. + * @param {Object} options.response Express HTTP response object. + * @param {Function=} options.sessionStarted Function callback when session starts. + * @actionssdk + */ + constructor (options) { + debug('ActionsSdkApp constructor'); + super(options, () => this.body_); + + // If request is from AoG and in Proto2 format, convert to Proto3. + if (this.body_ && !this.isNotApiVersionOne_()) { + this.body_ = transformToCamelCase(this.body_); + } + + if (this.body_ && + this.body_.conversation && + this.body_.conversation.type && + this.body_.conversation.type === this.ConversationStages.NEW && + this.sessionStarted_ && typeof this.sessionStarted_ === 'function') { + this.sessionStarted_(); + } else if (this.sessionStarted_ && typeof this.sessionStarted_ !== 'function') { + this.handleError_('options.sessionStarted must be a Function'); + } + } + + /** + * Validates whether request is from Assistant through signature verification. + * Uses Google-Auth-Library to verify authorization token against given + * Google Cloud Project ID. Auth token is given in request header with key, + * "Authorization". + * + * @example + * const app = new ActionsSdkApp({request, response}); + * app.isRequestFromAssistant('nodejs-cloud-test-project-1234') + * .then(() => { + * app.ask('Hey there, thanks for stopping by!'); + * }) + * .catch(err => { + * response.status(400).send(); + * }); + * + * @param {string} projectId Google Cloud Project ID for the Assistant app. + * @return {Promise} Promise resolving with google-auth-library LoginTicket + * if request is from a valid source, otherwise rejects with the error reason + * for an invalid token. + * @actionssdk + */ + isRequestFromAssistant (projectId) { + debug('isRequestFromAssistant: projectId=%s', projectId); + const googleAuthClient = require('./utils/auth').googleAuthClient; + const jwtToken = this.request_.get(CONVERSATION_API_SIGNATURE_HEADER); + + return new Promise((resolve, reject) => { + if (!jwtToken) { + const errorMsg = 'No incoming API Signature JWT token'; + error(errorMsg); + reject(errorMsg); + } + googleAuthClient.verifyIdToken(jwtToken, projectId, (err, login) => { + if (err) { + error('ID token verification Failed: ' + err); + reject(err); + } else { + resolve(login); + } + }); + }); + } + + /** + * Gets the request Conversation API version. + * + * @example + * const app = new ActionsSdkApp({request: request, response: response}); + * const apiVersion = app.getApiVersion(); + * + * @return {string} Version value or null if no value. + * @actionssdk + */ + getApiVersion () { + debug('getApiVersion'); + return this.apiVersion_ || this.actionsApiVersion_; + } + + /** + * Gets the user's raw input query. + * + * @example + * const app = new ActionsSdkApp({request: request, response: response}); + * app.tell('You said ' + app.getRawInput()); + * + * @return {string} User's raw query or null if no value. + * @actionssdk + */ + getRawInput () { + debug('getRawInput'); + const input = this.getTopInput_(); + if (!input) { + error('Failed to get top Input.'); + return null; + } + if (!input.rawInputs || input.rawInputs.length === 0) { + error('Missing user raw input'); + return null; + } + const rawInput = input.rawInputs[0]; + if (!rawInput.query) { + error('Missing query for user raw input'); + return null; + } + return rawInput.query; + } + + /** + * Gets previous JSON dialog state that the app sent to Assistant. + * Alternatively, use the app.data field to store JSON values between requests. + * + * @example + * const app = new ActionsSdkApp({request: request, response: response}); + * const dialogState = app.getDialogState(); + * + * @return {Object} JSON object provided to the Assistant in the previous + * user turn or {} if no value. + * @actionssdk + */ + getDialogState () { + debug('getDialogState'); + if (this.body_.conversation && this.body_.conversation.conversationToken) { + return JSON.parse(this.body_.conversation.conversationToken); + } + return {}; + } + + /** + * Gets the "versionLabel" specified inside the Action Package. + * Used by app to do version control. + * + * @example + * const app = new ActionsSdkApp({request: request, response: response}); + * const actionVersionLabel = app.getActionVersionLabel(); + * + * @return {string} The specified version label or null if unspecified. + * @actionssdk + */ + getActionVersionLabel () { + debug('getActionVersionLabel'); + const versionLabel = this.request_.get(CONVERSATION_API_AGENT_VERSION_HEADER); + if (versionLabel) { + return versionLabel; + } else { + return null; + } + } + + /** + * Gets the unique conversation ID. It's a new ID for the initial query, + * and stays the same until the end of the conversation. + * + * @example + * const app = new ActionsSdkApp({request: request, response: response}); + * const conversationId = app.getConversationId(); + * + * @return {string} Conversation ID or null if no value. + * @actionssdk + */ + getConversationId () { + debug('getConversationId'); + if (!this.body_.conversation || !this.body_.conversation.conversationId) { + error('No conversation ID'); + return null; + } + return this.body_.conversation.conversationId; + } + + /** + * Get the current intent. Alternatively, using a handler Map with + * {@link AssistantApp#handleRequest|handleRequest}, the client library will + * automatically handle the incoming intents. + * + * @example + * const app = new ActionsSdkApp({request: request, response: response}); + * + * function responseHandler (app) { + * const intent = app.getIntent(); + * switch (intent) { + * case app.StandardIntents.MAIN: + * const inputPrompt = app.buildInputPrompt(false, 'Welcome to action snippets! Say anything.'); + * app.ask(inputPrompt); + * break; + * + * case app.StandardIntents.TEXT: + * app.tell('You said ' + app.getRawInput()); + * break; + * } + * } + * + * app.handleRequest(responseHandler); + * + * @return {string} Intent id or null if no value. + * @actionssdk + */ + getIntent () { + debug('getIntent'); + const input = this.getTopInput_(); + if (!input) { + error('Missing intent from request body'); + return null; + } + return input.intent; + } + + /** + * Get the argument value by name from the current intent. If the argument + * is not a text argument, the entire argument object is returned. + * + * Note: If incoming request is using an API version under 2 (e.g. 'v1'), + * the argument object will be in Proto2 format (snake_case, etc). + * + * @param {string} argName Name of the argument. + * @return {string} Argument value matching argName + * or null if no matching argument. + * @actionssdk + */ + getArgument (argName) { + return this.getArgumentCommon(argName); + } + + /** + * Returns the option key user chose from options response. + * + * @example + * const app = new App({request: req, response: res}); + * + * function pickOption (app) { + * if (app.hasSurfaceCapability(app.SurfaceCapabilities.SCREEN_OUTPUT)) { + * app.askWithCarousel('Which of these looks good?', + * app.buildCarousel().addItems( + * app.buildOptionItem('another_choice', ['Another choice']). + * setTitle('Another choice').setDescription('Choose me!'))); + * } else { + * app.ask('What would you like?'); + * } + * } + * + * function optionPicked (app) { + * app.ask('You picked ' + app.getSelectedOption()); + * } + * + * const actionMap = new Map(); + * actionMap.set(app.StandardIntents.TEXT, pickOption); + * actionMap.set(app.StandardIntents.OPTION, optionPicked); + * + * app.handleRequest(actionMap); + * + * @return {string} Option key of selected item. Null if no option selected or + * if current intent is not OPTION intent. + * @actionssdk + */ + getSelectedOption () { + debug('getSelectedOption'); + if (this.getArgument(this.BuiltInArgNames.OPTION)) { + return this.getArgument(this.BuiltInArgNames.OPTION); + } + debug('Failed to get selected option'); + return null; + } + + /** + * Asks to collect user's input; all user's queries need to be sent to + * the app. + * {@link https://developers.google.com/actions/policies/general-policies#user_experience|The guidelines when prompting the user for a response must be followed at all times}. + * + * @example + * const app = new ActionsSdkApp({request: request, response: response}); + * + * function mainIntent (app) { + * const inputPrompt = app.buildInputPrompt(true, 'Hi! ' + + * 'I can read out an ordinal like ' + + * '123. Say a number.', + * ['I didn\'t hear a number', 'If you\'re still there, what\'s the number?', 'What is the number?']); + * app.ask(inputPrompt); + * } + * + * function rawInput (app) { + * if (app.getRawInput() === 'bye') { + * app.tell('Goodbye!'); + * } else { + * const inputPrompt = app.buildInputPrompt(true, 'You said, ' + + * app.getRawInput() + '', + * ['I didn\'t hear a number', 'If you\'re still there, what\'s the number?', 'What is the number?']); + * app.ask(inputPrompt); + * } + * } + * + * const actionMap = new Map(); + * actionMap.set(app.StandardIntents.MAIN, mainIntent); + * actionMap.set(app.StandardIntents.TEXT, rawInput); + * + * app.handleRequest(actionMap); + * + * @param {Object|SimpleResponse|RichResponse} inputPrompt Holding initial and + * no-input prompts. + * @param {Object=} dialogState JSON object the app uses to hold dialog state that + * will be circulated back by App. + * @return {(Object|null)} The response that is sent to Assistant to ask user to provide input. + * @actionssdk + */ + ask (inputPrompt, dialogState) { + debug('ask: inputPrompt=%s, dialogState=%s', + JSON.stringify(inputPrompt), JSON.stringify(dialogState)); + const expectedIntent = this.buildExpectedIntent_(this.StandardIntents.TEXT, []); + if (!expectedIntent) { + error('Error in building expected intent'); + return null; + } + return this.buildAskHelper_(inputPrompt, [expectedIntent], dialogState); + } + + /** + * Asks to collect user's input with a list. + * + * @example + * const app = new ActionsSdkApp({request, response}); + * + * function welcomeIntent (app) { + * app.askWithlist('Which of these looks good?', + * app.buildList('List title') + * .addItems([ + * app.buildOptionItem(SELECTION_KEY_ONE, + * ['synonym of KEY_ONE 1', 'synonym of KEY_ONE 2']) + * .setTitle('Number one'), + * app.buildOptionItem(SELECTION_KEY_TWO, + * ['synonym of KEY_TWO 1', 'synonym of KEY_TWO 2']) + * .setTitle('Number two'), + * ])); + * } + * + * function optionIntent (app) { + * if (app.getSelectedOption() === SELECTION_KEY_ONE) { + * app.tell('Number one is a great choice!'); + * } else { + * app.tell('Number two is a great choice!'); + * } + * } + * + * const actionMap = new Map(); + * actionMap.set(app.StandardIntents.TEXT, welcomeIntent); + * actionMap.set(app.StandardIntents.OPTION, optionIntent); + * app.handleRequest(actionMap); + * + * @param {Object|SimpleResponse|RichResponse} inputPrompt Holding initial and + * no-input prompts. Cannot contain basic card. + * @param {List} list List built with {@link AssistantApp#buildList|buildList}. + * @param {Object=} dialogState JSON object the app uses to hold dialog state that + * will be circulated back by Assistant. + * @return {(Object|null)} The response that is sent to Assistant to ask user to provide input. + * @actionssdk + */ + askWithList (inputPrompt, list, dialogState) { + debug('askWithList: inputPrompt=%s, list=%s, dialogState=%s', + JSON.stringify(inputPrompt), JSON.stringify(list), JSON.stringify(dialogState)); + if (!list || typeof list !== 'object') { + this.handleError_('Invalid list'); + return null; + } + if (list.items.length < 2) { + this.handleError_('List requires at least 2 items'); + return null; + } + const expectedIntent = this.buildExpectedIntent_(this.StandardIntents.OPTION, []); + if (!expectedIntent) { + error('Error in building expected intent'); + return null; + } + if (this.isNotApiVersionOne_()) { + expectedIntent.inputValueData = Object.assign({ + [this.ANY_TYPE_PROPERTY_]: this.InputValueDataTypes_.OPTION + }, { + listSelect: list + }); + } else { + expectedIntent.inputValueSpec = { + optionValueSpec: { + listSelect: list + } + }; + } + return this.buildAskHelper_(inputPrompt, [expectedIntent], dialogState); + } + + /** + * Asks to collect user's input with a carousel. + * + * @example + * const app = new ActionsSdkApp({request, response}); + * + * function welcomeIntent (app) { + * app.askWithCarousel('Which of these looks good?', + * app.buildCarousel() + * .addItems([ + * app.buildOptionItem(SELECTION_KEY_ONE, + * ['synonym of KEY_ONE 1', 'synonym of KEY_ONE 2']) + * .setTitle('Number one'), + * app.buildOptionItem(SELECTION_KEY_TWO, + * ['synonym of KEY_TWO 1', 'synonym of KEY_TWO 2']) + * .setTitle('Number two'), + * ])); + * } + * + * function optionIntent (app) { + * if (app.getSelectedOption() === SELECTION_KEY_ONE) { + * app.tell('Number one is a great choice!'); + * } else { + * app.tell('Number two is a great choice!'); + * } + * } + * + * const actionMap = new Map(); + * actionMap.set(app.StandardIntents.TEXT, welcomeIntent); + * actionMap.set(app.StandardIntents.OPTION, optionIntent); + * app.handleRequest(actionMap); + * + * @param {Object|SimpleResponse|RichResponse} inputPrompt Holding initial and + * no-input prompts. Cannot contain basic card. + * @param {Carousel} carousel Carousel built with + * {@link AssistantApp#buildCarousel|buildCarousel}. + * @param {Object=} dialogState JSON object the app uses to hold dialog state that + * will be circulated back by Assistant. + * @return {(Object|null)} The response that is sent to Assistant to ask user to provide input. + * @actionssdk + */ + askWithCarousel (inputPrompt, carousel, dialogState) { + debug('askWithCarousel: inputPrompt=%s, carousel=%s, dialogState=%s', + JSON.stringify(inputPrompt), JSON.stringify(carousel), JSON.stringify(dialogState)); + if (!carousel || typeof carousel !== 'object') { + this.handleError_('Invalid carousel'); + return null; + } + if (carousel.items.length < 2) { + this.handleError_('Carousel requires at least 2 items'); + return null; + } + const expectedIntent = this.buildExpectedIntent_(this.StandardIntents.OPTION, []); + if (!expectedIntent) { + error('Error in building expected intent'); + return null; + } + if (this.isNotApiVersionOne_()) { + expectedIntent.inputValueData = Object.assign({ + [this.ANY_TYPE_PROPERTY_]: this.InputValueDataTypes_.OPTION + }, { + carouselSelect: carousel + }); + } else { + expectedIntent.inputValueSpec = { + optionValueSpec: { + carouselSelect: carousel + } + }; + } + return this.buildAskHelper_(inputPrompt, [expectedIntent], dialogState); + } + + /** + * Tells Assistant to render the speech response and close the mic. + * + * @example + * const app = new ActionsSdkApp({request: request, response: response}); + * + * function mainIntent (app) { + * const inputPrompt = app.buildInputPrompt(true, 'Hi! ' + + * 'I can read out an ordinal like ' + + * '123. Say a number.', + * ['I didn\'t hear a number', 'If you\'re still there, what\'s the number?', 'What is the number?']); + * app.ask(inputPrompt); + * } + * + * function rawInput (app) { + * if (app.getRawInput() === 'bye') { + * app.tell('Goodbye!'); + * } else { + * const inputPrompt = app.buildInputPrompt(true, 'You said, ' + + * app.getRawInput() + '', + * ['I didn\'t hear a number', 'If you\'re still there, what\'s the number?', 'What is the number?']); + * app.ask(inputPrompt); + * } + * } + * + * const actionMap = new Map(); + * actionMap.set(app.StandardIntents.MAIN, mainIntent); + * actionMap.set(app.StandardIntents.TEXT, rawInput); + * + * app.handleRequest(actionMap); + * + * @param {string|SimpleResponse|RichResponse} textToSpeech Final response. + * Spoken response can be SSML. + * @return {(Object|null)} The HTTP response that is sent back to Assistant. + * @actionssdk + */ + tell (textToSpeech) { + debug('tell: textToSpeech=%s', textToSpeech); + if (!textToSpeech) { + this.handleError_('Invalid speech response'); + return null; + } + const finalResponse = {}; + if (typeof textToSpeech === 'string') { + if (this.isSsml_(textToSpeech)) { + finalResponse.speechResponse = { + ssml: textToSpeech + }; + } else { + finalResponse.speechResponse = { + textToSpeech: textToSpeech + }; + } + } else { + if (textToSpeech.items) { + finalResponse.richResponse = textToSpeech; + } else if (textToSpeech.speech) { + finalResponse.richResponse = this.buildRichResponse() + .addSimpleResponse(textToSpeech); + } else { + this.handleError_('Invalid speech response. Must be string, ' + + 'RichResponse or SimpleResponse.'); + return null; + } + } + const response = this.buildResponseHelper_(null, false, null, finalResponse); + return this.doResponse_(response, RESPONSE_CODE_OK); + } + + /** + * Builds the {@link https://developers.google.com/actions/reference/conversation#InputPrompt|InputPrompt object} + * from initial prompt and no-input prompts. + * + * The App needs one initial prompt to start the conversation. If there is no user response, + * the App re-opens the mic and renders the no-input prompts three times + * (one for each no-input prompt that was configured) to help the user + * provide the right response. + * + * Note: we highly recommend app to provide all the prompts required here in order to ensure a + * good user experience. + * + * @example + * const inputPrompt = app.buildInputPrompt(false, 'Welcome to action snippets! Say a number.', + * ['Say any number', 'Pick a number', 'What is the number?']); + * app.ask(inputPrompt); + * + * @param {boolean} isSsml Indicates whether the text to speech is SSML or not. + * @param {string} initialPrompt The initial prompt the App asks the user. + * @param {Array=} noInputs Array of re-prompts when the user does not respond (max 3). + * @return {Object} An {@link https://developers.google.com/actions/reference/conversation#InputPrompt|InputPrompt object}. + * @actionssdk + */ + buildInputPrompt (isSsml, initialPrompt, noInputs) { + debug('buildInputPrompt: isSsml=%s, initialPrompt=%s, noInputs=%s', + isSsml, initialPrompt, noInputs); + const initials = []; + + if (noInputs) { + if (noInputs.length > INPUTS_MAX) { + error('Invalid number of no inputs'); + return null; + } + } else { + noInputs = []; + } + + this.maybeAddItemToArray_(initialPrompt, initials); + if (isSsml) { + return { + initialPrompts: this.buildPromptsFromSsmlHelper_(initials), + noInputPrompts: this.buildPromptsFromSsmlHelper_(noInputs) + }; + } else { + return { + initialPrompts: this.buildPromptsFromPlainTextHelper_(initials), + noInputPrompts: this.buildPromptsFromPlainTextHelper_(noInputs) + }; + } + } + +// --------------------------------------------------------------------------- +// Private Helpers +// --------------------------------------------------------------------------- + + /** + * Get the top most Input object. + * + * @return {Object} Input object. + * @private + * @actionssdk + */ + getTopInput_ () { + debug('getTopInput_'); + if (!this.body_.inputs || this.body_.inputs.length === 0) { + error('Missing inputs from request body'); + return null; + } + return this.body_.inputs[0]; + } + + /** + * Builds the response to send back to Assistant. + * + * @param {string} conversationToken The dialog state. + * @param {boolean} expectUserResponse The expected user response. + * @param {Object} expectedInput The expected response. + * @param {boolean} finalResponse The final response. + * @return {Object} Final response returned to server. + * @private + * @actionssdk + */ + buildResponseHelper_ (conversationToken, expectUserResponse, expectedInput, finalResponse) { + debug('buildResponseHelper_: conversationToken=%s, expectUserResponse=%s, ' + + 'expectedInput=%s, finalResponse=%s', + conversationToken, expectUserResponse, JSON.stringify(expectedInput), + JSON.stringify(finalResponse)); + const response = {}; + if (conversationToken) { + response.conversationToken = conversationToken; + } + response.expectUserResponse = expectUserResponse; + if (expectedInput) { + response.expectedInputs = expectedInput; + } + if (!expectUserResponse && finalResponse) { + response.finalResponse = finalResponse; + } + return response; + } + + /** + * Helper to add item to an array. + * + * @param {*} item Item to add to the array. + * @param {Array} array Target array. + * @return {undefined} + * @private + * @actionssdk + */ + maybeAddItemToArray_ (item, array) { + debug('maybeAddItemToArray_: item=%s, array=%s', item, array); + if (!array) { + error('Invalid array'); + return; + } + if (!item) { + // ignore add + return; + } + array.push(item); + } + + /** + * Extract session data from the incoming JSON request. + * + * @return {undefined} + * @private + * @actionssdk + */ + extractData_ () { + debug('extractData_'); + if (this.body_.conversation && + this.body_.conversation.conversationToken) { + const json = JSON.parse(this.body_.conversation.conversationToken); + this.data = json.data; + this.state = json.state; + } else { + this.data = {}; + } + } + + /** + * Uses a PermissionsValueSpec object to construct and send a + * permissions request to user. + * + * @param {Object} permissionsSpec PermissionsValueSpec object containing + * the permissions prefix and the permissions requested. + * @param {Object} dialogState JSON object the app uses to hold dialog state that + * will be circulated back by Assistant. + * @return {Object} HTTP response object. + * @private + * @actionssdk + */ + fulfillPermissionsRequest_ (permissionsSpec, dialogState) { + debug('fulfillPermissionsRequest_: permissionsSpec=%s, dialogState=%s', + JSON.stringify(permissionsSpec), JSON.stringify(dialogState)); + if (this.isNotApiVersionOne_()) { + return this.fulfillSystemIntent_(this.StandardIntents.PERMISSION, + this.InputValueDataTypes_.PERMISSION, permissionsSpec, + 'PLACEHOLDER_FOR_PERMISSION', dialogState); + } else { + // Build an Expected Intent object. + const expectedIntent = { + intent: this.StandardIntents.PERMISSION + }; + expectedIntent.inputValueSpec = { + permissionValueSpec: permissionsSpec + }; + const inputPrompt = this.buildInputPrompt(false, + 'PLACEHOLDER_FOR_PERMISSION'); + return this.buildAskHelper_(inputPrompt, [expectedIntent], dialogState); + } + } + + /** + * Uses a given intent spec to construct and send a non-TEXT intent response + * to Google. + * + * @param {string} intent Name of the intent to fulfill. One of + * {@link AssistantApp#StandardIntents|StandardIntents}. + * @param {string} specType Type of the related intent spec. One of + * {@link AssistantApp#InputValueDataTypes_|InputValueDataTypes_}. + * @param {Object} intentSpec Intent Spec object. Pass null to leave empty. + * @param {string=} promptPlaceholder Some placeholder text for the response + * prompt. + * @param {Object=} dialogState JSON object the app uses to hold dialog state that + * will be circulated back by Assistant. + * @return {Object} HTTP response. + * @private + * @actionssdk + */ + fulfillSystemIntent_ (intent, specType, intentSpec, promptPlaceholder, + dialogState) { + debug('fulfillSystemIntent_: intent=%s, specType=%s, intentSpec=%s, ' + + 'promptPlaceholder=%s dialogState=%s', intent, specType, + JSON.stringify(intentSpec), promptPlaceholder, JSON.stringify(dialogState)); + // Build an Expected Intent object. + const expectedIntent = this.buildExpectedIntent_(intent); + if (!expectedIntent) { + error('Error in building expected intent'); + return null; + } + expectedIntent.inputValueData = {}; + if (intentSpec) { + expectedIntent.inputValueData = Object.assign({ + [this.ANY_TYPE_PROPERTY_]: specType + }, intentSpec); + } + // Send an Ask request to Assistant. + const inputPrompt = this.buildInputPrompt(false, promptPlaceholder || + 'PLACEHOLDER_FOR_INTENT'); + return this.buildAskHelper_(inputPrompt, [expectedIntent], dialogState); + } + + /** + * Builds the ask response to send back to Assistant. + * + * @param {Object} inputPrompt Holding initial and no-input prompts. + * @param {Array} possibleIntents Array of ExpectedIntents. + * @param {Object} dialogState JSON object the app uses to hold dialog state that + * will be circulated back by Assistant. + * @return {(Object|null)} The response that is sent to Assistant to ask user to provide input. + * @private + * @actionssdk + */ + buildAskHelper_ (inputPrompt, possibleIntents, dialogState) { + debug('buildAskHelper_: inputPrompt=%s, possibleIntents=%s, dialogState=%s', + inputPrompt, possibleIntents, JSON.stringify(dialogState)); + if (!inputPrompt) { + error('Invalid input prompt'); + return null; + } + if (typeof inputPrompt === 'string') { + inputPrompt = this.buildInputPrompt(this.isSsml_(inputPrompt), inputPrompt); + } else { + if (inputPrompt.speech) { + inputPrompt = { richInitialPrompt: this.buildRichResponse() + .addSimpleResponse(inputPrompt) }; + } else if (inputPrompt.items) { + inputPrompt = { richInitialPrompt: inputPrompt }; + } + } + if (!dialogState) { + dialogState = { + 'state': (this.state instanceof State ? this.state.getName() : this.state), + 'data': this.data + }; + } else if (Array.isArray(dialogState)) { + error('Invalid dialog state'); + return null; + } + const expectedInputs = [{ + inputPrompt: inputPrompt, + possibleIntents: possibleIntents + }]; + const response = this.buildResponseHelper_( + JSON.stringify(dialogState), + true, // expectedUserResponse + expectedInputs, + null // finalResponse is null b/c dialog is active + ); + return this.doResponse_(response, RESPONSE_CODE_OK); + } + + /** + * Builds an ExpectedIntent object. Refer to {@link ActionsSdkApp#newRuntimeEntity} to create the list + * of runtime entities required by this method. Runtime entities need to be defined in + * the Action Package. + * + * @param {string} intent Developer specified in-dialog intent inside the Action + * Package or an App built-in intent like + * 'assistant.intent.action.TEXT'. + * @return {Object} An {@link https://developers.google.com/actions/reference/conversation#ExpectedIntent|ExpectedIntent object} + encapsulating the intent and the runtime entities. + * @private + * @actionssdk + */ + buildExpectedIntent_ (intent) { + debug('buildExpectedIntent_: intent=%s', intent); + if (!intent || intent === '') { + error('Invalid intent'); + return null; + } + const expectedIntent = { intent }; + return expectedIntent; + } +} + +module.exports = ActionsSdkApp; diff --git a/types/actions-on-google/staging/assistant-app.js b/types/actions-on-google/staging/assistant-app.js new file mode 100644 index 0000000000..0237c0c921 --- /dev/null +++ b/types/actions-on-google/staging/assistant-app.js @@ -0,0 +1,2262 @@ +/** + * Copyright 2017 Google Inc. All Rights Reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +'use strict'; + +const Debug = require('debug'); +const debug = Debug('actions-on-google:debug'); +const error = Debug('actions-on-google:error'); + +// Response Builder classes +const RichResponse = require('./response-builder').RichResponse; +const BasicCard = require('./response-builder').BasicCard; +const List = require('./response-builder').List; +const Carousel = require('./response-builder').Carousel; +const OptionItem = require('./response-builder').OptionItem; +const isSsml = require('./response-builder').isSsml; + +// Transaction classes +const TransactionValues = require('./transactions').TransactionValues; +const Order = require('./transactions').Order; +const Cart = require('./transactions').Cart; +const LineItem = require('./transactions').LineItem; +const OrderUpdate = require('./transactions').OrderUpdate; + +const transformToSnakeCase = require('./utils/transform').transformToSnakeCase; + +// Constants +const ERROR_MESSAGE = 'Sorry, I am unable to process your request.'; +const API_ERROR_MESSAGE_PREFIX = 'Action Error: '; +const CONVERSATION_API_VERSION_HEADER = 'Google-Assistant-API-Version'; +const ACTIONS_CONVERSATION_API_VERSION_HEADER = 'Google-Actions-API-Version'; +const ACTIONS_CONVERSATION_API_VERSION_TWO = 2; +const RESPONSE_CODE_OK = 200; +const RESPONSE_CODE_BAD_REQUEST = 400; +const HTTP_CONTENT_TYPE_HEADER = 'Content-Type'; +const HTTP_CONTENT_TYPE_JSON = 'application/json'; + +// Configure logging for hosting platforms that only support console.log and console.error +debug.log = console.log.bind(console); +error.log = console.error.bind(console); + +/** + * The Actions on Google client library AssistantApp base class. + * + * This class contains the methods that are shared between platforms to support the conversation API + * protocol from Assistant. It also exports the 'State' class as a helper to represent states by + * name. + */ +class AssistantApp { + /** + * Constructor for AssistantApp object. + * Should not be instantiated; rather instantiate one of the subclasses + * {@link ActionsSdkApp} or {@link DialogflowApp}. + * + * @param {Object} options JSON configuration. + * @param {Object} options.request Express HTTP request object. + * @param {Object} options.response Express HTTP response object. + * @param {Function=} options.sessionStarted Function callback when session starts. + * @param {function(): *} requestData Function that returns the + * request data object to be processed. + */ + constructor (options, requestData) { + debug('AssistantApp constructor'); + + if (!options) { + // ignore for JavaScript inheritance to work + + // As a workaround for pre-existing sample code which incorrectly + // initializes this class without an options object. + this.StandardIntents = { + MAIN: 'assistant.intent.action.MAIN', + TEXT: 'assistant.intent.action.TEXT', + PERMISSION: 'assistant.intent.action.PERMISSION' + }; + return; + } + if (!options.request) { + this.handleError_('Request can NOT be empty.'); + return; + } + if (!options.response) { + this.handleError_('Response can NOT be empty.'); + return; + } + + /** + * The Express HTTP request that the endpoint receives from the Assistant. + * @private + * @type {Object} + */ + this.request_ = options.request; + + /** + * The Express HTTP response the endpoint will return to Assistant. + * @private + * @type {Object} + */ + this.response_ = options.response; + + /** + * 'sessionStarted' callback (optional). + * @private + * @type {Function} + */ + this.sessionStarted_ = options.sessionStarted; + + debug('Request from Assistant: %s', JSON.stringify(this.request_.body)); + + /** + * The request body contains query JSON and previous session variables. + * Assignment using JSON parse/stringify ensures manipulation of this.body_ + * does not affect passed in request body structure. + * @private + * @type {Object} + */ + this.body_ = JSON.parse(JSON.stringify(this.request_.body)); + + /** + * API version describes version of the Actions API request. + * @private + * @type {string} + */ + this.actionsApiVersion_ = null; + // Populates API version from either request header or Dialogflow orig request. + if (this.request_.get(ACTIONS_CONVERSATION_API_VERSION_HEADER)) { + this.actionsApiVersion_ = this.request_.get(ACTIONS_CONVERSATION_API_VERSION_HEADER); + debug('Actions API version from header: ' + this.actionsApiVersion_); + } + if (this.body_.originalRequest && + this.body_.originalRequest.version) { + this.actionsApiVersion_ = this.body_.originalRequest.version; + debug('Actions API version from Dialogflow: ' + this.actionsApiVersion_); + } + + /** + * Intent handling data structure. + * @private + * @type {Object} + */ + this.handler_ = null; + + /** + * Intent mapping data structure. + * @private + * @type {Object} + */ + this.intentMap_ = null; + + /** + * Intent state data structure. + * @private + * @type {Object} + */ + this.stateMap_ = null; + + /** + * The session state. + * @public + * @type {string} + */ + this.state = null; + + /** + * The session data in JSON format. + * @public + * @type {Object} + */ + this.data = {}; + + /** + * The Dialogflow context. + * @private + * @type {Object} + */ + this.contexts_ = {}; + + /** + * The last error message. + * @private + * @type {string} + */ + this.lastErrorMessage_ = null; + + /** + * Track if an HTTP response has been sent already. + * @private + * @type {boolean} + */ + this.responded_ = false; + + /** + * List of standard intents that the app provides. + * @readonly + * @enum {string} + * @actionssdk + * @dialogflow + */ + this.StandardIntents = { + /** App fires MAIN intent for queries like [talk to $app]. */ + MAIN: this.isNotApiVersionOne_() ? 'actions.intent.MAIN' : 'assistant.intent.action.MAIN', + /** App fires TEXT intent when action issues ask intent. */ + TEXT: this.isNotApiVersionOne_() ? 'actions.intent.TEXT' : 'assistant.intent.action.TEXT', + /** App fires PERMISSION intent when action invokes askForPermission. */ + PERMISSION: this.isNotApiVersionOne_() ? 'actions.intent.PERMISSION' : 'assistant.intent.action.PERMISSION', + /** App fires OPTION intent when user chooses from options provided. */ + OPTION: 'actions.intent.OPTION', + /** App fires TRANSACTION_REQUIREMENTS_CHECK intent when action sets up transaction. */ + TRANSACTION_REQUIREMENTS_CHECK: 'actions.intent.TRANSACTION_REQUIREMENTS_CHECK', + /** App fires DELIVERY_ADDRESS intent when action asks for delivery address. */ + DELIVERY_ADDRESS: 'actions.intent.DELIVERY_ADDRESS', + /** App fires TRANSACTION_DECISION intent when action asks for transaction decision. */ + TRANSACTION_DECISION: 'actions.intent.TRANSACTION_DECISION', + /** App fires CONFIRMATION intent when requesting affirmation from user. */ + CONFIRMATION: 'actions.intent.CONFIRMATION', + /** App fires DATETIME intent when requesting date/time from user. */ + DATETIME: 'actions.intent.DATETIME', + /** App fires SIGN_IN intent when requesting sign-in from user. */ + SIGN_IN: 'actions.intent.SIGN_IN', + /** App fires NO_INPUT intent when user doesn't provide input. */ + NO_INPUT: 'actions.intent.NO_INPUT', + /** App fires CANCEL intent when user exits app mid-dialog. */ + CANCEL: 'actions.intent.CANCEL', + /** App fires NEW_SURFACE intent when requesting handoff to a new surface from user. */ + NEW_SURFACE: 'actions.intent.NEW_SURFACE' + }; + + /** + * List of supported permissions the app supports. + * @readonly + * @enum {string} + * @actionssdk + * @dialogflow + */ + this.SupportedPermissions = { + /** + * The user's name as defined in the + * {@link https://developers.google.com/actions/reference/conversation#UserProfile|UserProfile object} + */ + NAME: 'NAME', + /** + * The location of the user's current device, as defined in the + * {@link https://developers.google.com/actions/reference/conversation#Location|Location object}. + */ + DEVICE_PRECISE_LOCATION: 'DEVICE_PRECISE_LOCATION', + /** + * City and zipcode corresponding to the location of the user's current device, as defined in the + * {@link https://developers.google.com/actions/reference/conversation#Location|Location object}. + */ + DEVICE_COARSE_LOCATION: 'DEVICE_COARSE_LOCATION' + }; + + /** + * List of built-in argument names. + * @readonly + * @enum {string} + * @actionssdk + * @dialogflow + */ + this.BuiltInArgNames = { + /** Permission granted argument. */ + PERMISSION_GRANTED: this.isNotApiVersionOne_() ? 'PERMISSION' : 'permission_granted', + /** Option selected argument. */ + OPTION: 'OPTION', + /** Transaction requirements check result argument. */ + TRANSACTION_REQ_CHECK_RESULT: 'TRANSACTION_REQUIREMENTS_CHECK_RESULT', + /** Delivery address value argument. */ + DELIVERY_ADDRESS_VALUE: 'DELIVERY_ADDRESS_VALUE', + /** Transactions decision argument. */ + TRANSACTION_DECISION_VALUE: 'TRANSACTION_DECISION_VALUE', + /** Confirmation argument. */ + CONFIRMATION: 'CONFIRMATION', + /** DateTime argument. */ + DATETIME: 'DATETIME', + /** Sign in status argument. */ + SIGN_IN: 'SIGN_IN', + /** Reprompt count for consecutive NO_INPUT intents. */ + REPROMPT_COUNT: 'REPROMPT_COUNT', + /** Flag representing finality of NO_INPUT intent. */ + IS_FINAL_REPROMPT: 'IS_FINAL_REPROMPT', + /** New surface value argument. */ + NEW_SURFACE: 'NEW_SURFACE' + }; + + /** + * The property name used when specifying an input value data spec. + * @readonly + * @type {string} + * @actionssdk + * @dialogflow + */ + this.ANY_TYPE_PROPERTY_ = '@type'; + + /** + * List of built-in value type names. + * @private + * @readonly + * @enum {string} + * @actionssdk + * @dialogflow + */ + this.InputValueDataTypes_ = { + /** Permission Value Spec. */ + PERMISSION: 'type.googleapis.com/google.actions.v2.PermissionValueSpec', + /** Option Value Spec. */ + OPTION: 'type.googleapis.com/google.actions.v2.OptionValueSpec', + /** Transaction Requirements Check Value Spec. */ + TRANSACTION_REQ_CHECK: 'type.googleapis.com/google.actions.v2.TransactionRequirementsCheckSpec', + /** Delivery Address Value Spec. */ + DELIVERY_ADDRESS: 'type.googleapis.com/google.actions.v2.DeliveryAddressValueSpec', + /** Transaction Decision Value Spec. */ + TRANSACTION_DECISION: 'type.googleapis.com/google.actions.v2.TransactionDecisionValueSpec', + /** Confirmation Value Spec. */ + CONFIRMATION: 'type.googleapis.com/google.actions.v2.ConfirmationValueSpec', + /** DateTime Value Spec. */ + DATETIME: 'type.googleapis.com/google.actions.v2.DateTimeValueSpec', + /** New Surface Value Spec. */ + NEW_SURFACE: 'type.googleapis.com/google.actions.v2.NewSurfaceValueSpec' + }; + + /** + * List of possible conversation stages, as defined in the + * {@link https://developers.google.com/actions/reference/conversation#Conversation|Conversation object}. + * @readonly + * @enum {number} + * @actionssdk + * @dialogflow + */ + this.ConversationStages = { + /** + * Unspecified conversation state. + */ + UNSPECIFIED: this.isNotApiVersionOne_() ? 'UNSPECIFIED' : 0, + /** + * A new conversation. + */ + NEW: this.isNotApiVersionOne_() ? 'NEW' : 1, + /** + * An active (ongoing) conversation. + */ + ACTIVE: this.isNotApiVersionOne_() ? 'ACTIVE' : 2 + }; + + /** + * List of surface capabilities supported by the app. + * @readonly + * @enum {string} + * @actionssdk + * @dialogflow + */ + this.SurfaceCapabilities = { + /** + * The ability to output audio. + */ + AUDIO_OUTPUT: 'actions.capability.AUDIO_OUTPUT', + /** + * The ability to output on a screen + */ + SCREEN_OUTPUT: 'actions.capability.SCREEN_OUTPUT' + }; + + /** + * List of possible user input types. + * @readonly + * @enum {number} + * @actionssdk + * @dialogflow + */ + this.InputTypes = { + /** + * Unspecified. + */ + UNSPECIFIED: this.isNotApiVersionOne_() ? 'UNSPECIFIED' : 0, + /** + * Input given by touch. + */ + TOUCH: this.isNotApiVersionOne_() ? 'TOUCH' : 1, + /** + * Input given by voice (spoken). + */ + VOICE: this.isNotApiVersionOne_() ? 'VOICE' : 2, + /** + * Input given by keyboard (typed). + */ + KEYBOARD: this.isNotApiVersionOne_() ? 'KEYBOARD' : 3 + }; + + /** + * List of possible sign in result status values. + * @readonly + * @enum {string} + * @actionssdk + * @dialogflow + */ + this.SignInStatus = { + // Unknown status. + UNSPECIFIED: 'SIGN_IN_STATUS_UNSPECIFIED', + // User successfully completed the account linking. + OK: 'OK', + // Cancelled or dismissed account linking. + CANCELLED: 'CANCELLED', + // System or network error. + ERROR: 'ERROR' + }; + + /** + * API version describes version of the Assistant request. + * @deprecated + * @private + * @type {string} + */ + this.apiVersion_ = null; + // Populates API version. + if (this.request_.get(CONVERSATION_API_VERSION_HEADER)) { + this.apiVersion_ = this.request_.get(CONVERSATION_API_VERSION_HEADER); + debug('Assistant API version: ' + this.apiVersion_); + } + + /** + * Values related to supporting {@link Transactions}. + * @readonly + * @type {object} + */ + this.Transactions = TransactionValues; + + this.requestData = requestData; + + // Extracts the data from the request + this.extractData_(); + } + + // --------------------------------------------------------------------------- + // Public APIs + // --------------------------------------------------------------------------- + + /** + * Handles the incoming Assistant request using a handler or Map of handlers. + * Each handler can be a function callback or Promise. + * + * @example + * // Actions SDK + * const app = new ActionsSdkApp({request: request, response: response}); + * + * function mainIntent (app) { + * const inputPrompt = app.buildInputPrompt(true, 'Hi! ' + + * 'I can read out an ordinal like ' + + * '123. Say a number.', + * ['I didn\'t hear a number', 'If you\'re still there, what\'s the number?', 'What is the number?']); + * app.ask(inputPrompt); + * } + * + * function rawInput (app) { + * if (app.getRawInput() === 'bye') { + * app.tell('Goodbye!'); + * } else { + * const inputPrompt = app.buildInputPrompt(true, 'You said, ' + + * app.getRawInput() + '', + * ['I didn\'t hear a number', 'If you\'re still there, what\'s the number?', 'What is the number?']); + * app.ask(inputPrompt); + * } + * } + * + * const actionMap = new Map(); + * actionMap.set(app.StandardIntents.MAIN, mainIntent); + * actionMap.set(app.StandardIntents.TEXT, rawInput); + * + * app.handleRequest(actionMap); + * + * // Dialogflow + * const app = new DialogflowApp({request: req, response: res}); + * const NAME_ACTION = 'make_name'; + * const COLOR_ARGUMENT = 'color'; + * const NUMBER_ARGUMENT = 'number'; + * + * function makeName (app) { + * const number = app.getArgument(NUMBER_ARGUMENT); + * const color = app.getArgument(COLOR_ARGUMENT); + * app.tell('Alright, your silly name is ' + + * color + ' ' + number + + * '! I hope you like it. See you next time.'); + * } + * + * const actionMap = new Map(); + * actionMap.set(NAME_ACTION, makeName); + * app.handleRequest(actionMap); + * + * @param {(Function|Map)} handler The handler (or Map of handlers) for the request. + * @return {undefined} + * @actionssdk + * @dialogflow + */ + handleRequest (handler) { + debug('handleRequest: handler=%s', handler); + if (!handler) { + this.handleError_('request handler can NOT be empty.'); + return; + } + if (typeof handler === 'function') { + debug('handleRequest: function'); + // simple function handler + this.handler_ = handler; + const promise = handler(this); + if (promise instanceof Promise) { + promise.then( + (result) => { + debug(result); + }) + .catch( + (reason) => { + this.handleError_('function failed: %s', reason.message); + this.tell(!reason.message ? ERROR_MESSAGE : reason.message); + }); + } else { + // Handle functions + return; + } + return; + } else if (handler instanceof Map) { + debug('handleRequest: map'); + const intent = this.getIntent(); + const result = this.invokeIntentHandler_(handler, intent); + if (!result) { + this.tell(!this.lastErrorMessage_ ? ERROR_MESSAGE : this.lastErrorMessage_); + } + return; + } + // Could not handle intent + this.handleError_('invalid intent handler type: ' + (typeof handler)); + this.tell(ERROR_MESSAGE); + } + + /** + * Equivalent to {@link AssistantApp#askForPermission|askForPermission}, + * but allows you to prompt the user for more than one permission at once. + * + * Notes: + * + * * The order in which you specify the permission prompts does not matter - + * it is controlled by the Assistant to provide a consistent user experience. + * * The user will be able to either accept all permissions at once, or none. + * If you wish to allow them to selectively accept one or other, make several + * dialog turns asking for each permission independently with askForPermission. + * * Asking for DEVICE_COARSE_LOCATION and DEVICE_PRECISE_LOCATION at once is + * equivalent to just asking for DEVICE_PRECISE_LOCATION + * + * @example + * const app = new DialogflowApp({request: req, response: res}); + * const REQUEST_PERMISSION_ACTION = 'request_permission'; + * const GET_RIDE_ACTION = 'get_ride'; + * + * function requestPermission (app) { + * const permission = [ + * app.SupportedPermissions.NAME, + * app.SupportedPermissions.DEVICE_PRECISE_LOCATION + * ]; + * app.askForPermissions('To pick you up', permissions); + * } + * + * function sendRide (app) { + * if (app.isPermissionGranted()) { + * const displayName = app.getUserName().displayName; + * const address = app.getDeviceLocation().address; + * app.tell('I will tell your driver to pick up ' + displayName + + * ' at ' + address); + * } else { + * // Response shows that user did not grant permission + * app.tell('Sorry, I could not figure out where to pick you up.'); + * } + * } + * const actionMap = new Map(); + * actionMap.set(REQUEST_PERMISSION_ACTION, requestPermission); + * actionMap.set(GET_RIDE_ACTION, sendRide); + * app.handleRequest(actionMap); + * + * @param {string} context Context why the permission is being asked; it's the TTS + * prompt prefix (action phrase) we ask the user. + * @param {Array} permissions Array of permissions App supports, each of + * which comes from AssistantApp.SupportedPermissions. + * @param {Object=} dialogState JSON object the app uses to hold dialog state that + * will be circulated back by Assistant. Used in {@link ActionsSdkAssistant}. + * @return {(Object|null)} A response is sent to Assistant to ask for the user's permission; for any + * invalid input, we return null. + * @actionssdk + * @dialogflow + */ + askForPermissions (context, permissions, dialogState) { + debug('askForPermissions: context=%s, permissions=%s, dialogState=%s', + context, permissions, JSON.stringify(dialogState)); + if (!context || context === '') { + this.handleError_('Assistant context can NOT be empty.'); + return null; + } + if (!permissions || permissions.length === 0) { + this.handleError_('At least one permission needed.'); + return null; + } + for (let i = 0; i < permissions.length; i++) { + const permission = permissions[i]; + if (permission !== this.SupportedPermissions.NAME && + permission !== this.SupportedPermissions.DEVICE_PRECISE_LOCATION && + permission !== this.SupportedPermissions.DEVICE_COARSE_LOCATION) { + this.handleError_('Assistant permission must be one of ' + + '[NAME, DEVICE_PRECISE_LOCATION, DEVICE_COARSE_LOCATION]'); + return null; + } + } + if (!dialogState) { + dialogState = { + 'state': (this.state instanceof State ? this.state.getName() : this.state), + 'data': this.data + }; + } + return this.fulfillPermissionsRequest_({ + optContext: context, + permissions: permissions + }, dialogState); + } + + /** + * Checks whether user is in transactable state. + * + * @example + * const app = new DialogflowApp({request: request, response: response}); + * const WELCOME_INTENT = 'input.welcome'; + * const TXN_REQ_COMPLETE = 'txn.req.complete'; + * + * let transactionConfig = { + * deliveryAddressRequired: false, + * type: app.Transactions.PaymentType.BANK, + * displayName: 'Checking-1234' + * }; + * function welcomeIntent (app) { + * app.askForTransactionRequirements(transactionConfig); + * } + * + * function txnReqCheck (app) { + * if (app.getTransactionRequirementsResult() === app.Transactions.ResultType.OK) { + * // continue cart building flow + * } else { + * // don't continue cart building + * } + * } + * + * const actionMap = new Map(); + * actionMap.set(WELCOME_INTENT, welcomeIntent); + * actionMap.set(TXN_REQ_COMPLETE, txnReqCheck); + * app.handleRequest(actionMap); + * + * @param {ActionPaymentTransactionConfig|GooglePaymentTransactionConfig=} + * transactionConfig Configuration for the transaction. Includes payment + * options and order options. Optional if order has no payment or + * delivery. + * @param {Object=} dialogState JSON object the app uses to hold dialog state that + * will be circulated back by Assistant. Used in {@link ActionsSdkAssistant}. + * @return {(Object|null)} HTTP response. + * @actionssdk + * @dialogflow + */ + askForTransactionRequirements (transactionConfig, dialogState) { + debug('checkForTransactionRequirements: transactionConfig=%s,' + + ' dialogState=%s', + JSON.stringify(transactionConfig), JSON.stringify(dialogState)); + if (transactionConfig && transactionConfig.type && + transactionConfig.cardNetworks) { + this.handleError_('Invalid transaction configuration. Must be of type' + + 'ActionPaymentTransactionConfig or GooglePaymentTransactionConfig'); + return null; + } + const transactionRequirementsCheckSpec = {}; + if (transactionConfig && transactionConfig.deliveryAddressRequired) { + transactionRequirementsCheckSpec.orderOptions = { + requestDeliveryAddress: transactionConfig.deliveryAddressRequired + }; + } + if (transactionConfig && (transactionConfig.type || + transactionConfig.cardNetworks)) { + transactionRequirementsCheckSpec.paymentOptions = + this.buildPaymentOptions_(transactionConfig); + } + return this.fulfillSystemIntent_(this.StandardIntents.TRANSACTION_REQUIREMENTS_CHECK, + this.InputValueDataTypes_.TRANSACTION_REQ_CHECK, transactionRequirementsCheckSpec, + 'PLACEHOLDER_FOR_TXN_REQUIREMENTS', dialogState); + } + + /** + * Asks user to confirm transaction information. + * + * @example + * const app = new DialogflowApp({request: request, response: response}); + * const WELCOME_INTENT = 'input.welcome'; + * const TXN_COMPLETE = 'txn.complete'; + * + * let transactionConfig = { + * deliveryAddressRequired: false, + * type: app.Transactions.PaymentType.BANK, + * displayName: 'Checking-1234' + * }; + * + * let order = app.buildOrder(); + * // fill order cart + * + * function welcomeIntent (app) { + * app.askForTransaction(order, transactionConfig); + * } + * + * function txnComplete (app) { + * // respond with order update + * } + * + * const actionMap = new Map(); + * actionMap.set(WELCOME_INTENT, welcomeIntent); + * actionMap.set(TXN_COMPLETE, txnComplete); + * app.handleRequest(actionMap); + * + * @param {Object} order Order built with buildOrder(). + * @param {ActionPaymentTransactionConfig|GooglePaymentTransactionConfig} + * transactionConfig Configuration for the transaction. Includes payment + * options and order options. + * @param {Object=} dialogState JSON object the app uses to hold dialog state that + * will be circulated back by Assistant. Used in {@link ActionsSdkAssistant}. + * @return {(Object|null)} HTTP response + * @dialogflow + */ + askForTransactionDecision (order, transactionConfig, dialogState) { + debug('askForTransactionDecision: order=%s, transactionConfig=%s,' + + ' dialogState=%s', JSON.stringify(order), + JSON.stringify(transactionConfig), JSON.stringify(dialogState)); + if (!order) { + this.handleError_('Invalid order'); + return null; + } + if (transactionConfig && transactionConfig.type && + transactionConfig.cardNetworks) { + this.handleError_('Invalid transaction configuration. Must be of type' + + 'ActionPaymentTransactionConfig or GooglePaymentTransactionConfig'); + return null; + } + const transactionDecisionValueSpec = { + proposedOrder: order + }; + if (transactionConfig && transactionConfig.deliveryAddressRequired) { + transactionDecisionValueSpec.orderOptions = { + requestDeliveryAddress: transactionConfig.deliveryAddressRequired + }; + } + if (transactionConfig && (transactionConfig.type || + transactionConfig.cardNetworks)) { + transactionDecisionValueSpec.paymentOptions = + this.buildPaymentOptions_(transactionConfig); + } + if (transactionConfig && transactionConfig.customerInfoOptions) { + if (!transactionDecisionValueSpec.orderOptions) { + transactionDecisionValueSpec.orderOptions = {}; + } + transactionDecisionValueSpec.orderOptions.customerInfoOptions = + transactionConfig.customerInfoOptions; + } + return this.fulfillSystemIntent_(this.StandardIntents.TRANSACTION_DECISION, + this.InputValueDataTypes_.TRANSACTION_DECISION, transactionDecisionValueSpec, + 'PLACEHOLDER_FOR_TXN_DECISION', dialogState); + } + + /** + * Asks the Assistant to guide the user to grant a permission. For example, + * if you want your app to get access to the user's name, you would invoke + * the askForPermission method with a context containing the reason for the request, + * and the AssistantApp.SupportedPermissions.NAME permission. With this, the Assistant will ask + * the user, in your agent's voice, the following: '[Context with reason for the request], + * I'll just need to get your name from Google, is that OK?'. + * + * Once the user accepts or denies the request, the Assistant will fire another intent: + * assistant.intent.action.PERMISSION with a boolean argument: AssistantApp.BuiltInArgNames.PERMISSION_GRANTED + * and, if granted, the information that you requested. + * + * Read more: + * + * * {@link https://developers.google.com/actions/reference/conversation#ExpectedIntent|Supported Permissions} + * * Check if the permission has been granted with {@link AssistantApp#isPermissionGranted|isPermissionsGranted} + * * {@link AssistantApp#getDeviceLocation|getDeviceLocation} + * * {@link AssistantApp#getUserName|getUserName} + * + * @example + * const app = new DialogflowApp({request: req, response: res}); + * const REQUEST_PERMISSION_ACTION = 'request_permission'; + * const GET_RIDE_ACTION = 'get_ride'; + * + * function requestPermission (app) { + * const permission = app.SupportedPermissions.NAME; + * app.askForPermission('To pick you up', permission); + * } + * + * function sendRide (app) { + * if (app.isPermissionGranted()) { + * const displayName = app.getUserName().displayName; + * app.tell('I will tell your driver to pick up ' + displayName); + * } else { + * // Response shows that user did not grant permission + * app.tell('Sorry, I could not figure out who to pick up.'); + * } + * } + * const actionMap = new Map(); + * actionMap.set(REQUEST_PERMISSION_ACTION, requestPermission); + * actionMap.set(GET_RIDE_ACTION, sendRide); + * app.handleRequest(actionMap); + * + * @param {string} context Context why permission is asked; it's the TTS + * prompt prefix (action phrase) we ask the user. + * @param {string} permission One of the permissions Assistant supports, each of + * which comes from AssistantApp.SupportedPermissions. + * @param {Object=} dialogState JSON object the app uses to hold dialog state that + * will be circulated back by Assistant. + * @return {(Object|null)} A response is sent to the Assistant to ask for the user's permission; + * for any invalid input, we return null. + * @actionssdk + * @dialogflow + */ + askForPermission (context, permission, dialogState) { + debug('askForPermission: context=%s, permission=%s, dialogState=%s', + context, permission, JSON.stringify(dialogState)); + return this.askForPermissions(context, [permission], dialogState); + } + + /** + * Returns true if the request follows a previous request asking for + * permission from the user and the user granted the permission(s). Otherwise, + * false. Use with {@link AssistantApp#askForPermissions|askForPermissions}. + * + * @example + * const app = new ActionsSdkApp({request: request, response: response}); + * // or + * const app = new DialogflowApp({request: request, response: response}); + * app.askForPermissions("To get you a ride", [ + * app.SupportedPermissions.NAME, + * app.SupportedPermissions.DEVICE_PRECISE_LOCATION + * ]); + * // ... + * // In response handler for subsequent intent: + * if (app.isPermissionGranted()) { + * // Use the requested permission(s) to get the user a ride + * } + * + * @return {boolean} true if permissions granted. + * @dialogflow + * @actionssdk + */ + isPermissionGranted () { + debug('isPermissionGranted'); + return this.getArgumentCommon(this.BuiltInArgNames.PERMISSION_GRANTED) === 'true'; + } + + /** + * Asks user for delivery address. + * + * @example + * // For DialogflowApp: + * const app = new DialogflowApp({request, response}); + * const WELCOME_INTENT = 'input.welcome'; + * const DELIVERY_INTENT = 'delivery.address'; + * + * function welcomeIntent (app) { + * app.askForDeliveryAddress('To make sure I can deliver to you'); + * } + * + * function addressIntent (app) { + * const postalCode = app.getDeliveryAddress().postalAddress.postalCode; + * if (isInDeliveryZone(postalCode)) { + * app.tell('Great looks like you\'re in our delivery area!'); + * } else { + * app.tell('I\'m sorry it looks like we can\'t deliver to you.'); + * } + * } + * + * const actionMap = new Map(); + * actionMap.set(WELCOME_INTENT, welcomeIntent); + * actionMap.set(DELIVERY_INTENT, addressIntent); + * app.handleRequest(actionMap); + * + * // For ActionsSdkApp: + * const app = new ActionsSdkApp({request, response}); + * const WELCOME_INTENT = app.StandardIntents.MAIN; + * const DELIVERY_INTENT = app.StandardIntents.DELIVERY_ADDRESS; + * + * function welcomeIntent (app) { + * app.askForDeliveryAddress('To make sure I can deliver to you'); + * } + * + * function addressIntent (app) { + * const postalCode = app.getDeliveryAddress().postalAddress.postalCode; + * if (isInDeliveryZone(postalCode)) { + * app.tell('Great looks like you\'re in our delivery area!'); + * } else { + * app.tell('I\'m sorry it looks like we can\'t deliver to you.'); + * } + * } + * + * const actionMap = new Map(); + * actionMap.set(WELCOME_INTENT, welcomeIntent); + * actionMap.set(DELIVERY_INTENT, addressIntent); + * app.handleRequest(actionMap); + * + * @param {string} reason Reason given to user for asking delivery address. + * @param {Object=} dialogState JSON object the app uses to hold dialog state that + * will be circulated back by Assistant. + * @return {Object} HTTP response. + * @actionssdk + * @dialogflow + */ + askForDeliveryAddress (reason, dialogState) { + debug('askForDeliveryAddress: reason=%s, dialogState=%s', reason, dialogState); + if (!reason) { + this.handleError_('reason cannot be empty'); + return null; + } + const deliveryValueSpec = { + addressOptions: { + reason: reason + } + }; + return this.fulfillSystemIntent_(this.StandardIntents.DELIVERY_ADDRESS, + this.InputValueDataTypes_.DELIVERY_ADDRESS, deliveryValueSpec, + 'PLACEHOLDER_FOR_DELIVERY_ADDRESS', dialogState); + } + + /** + * Asks user for a confirmation. + * + * @example + * const app = new DialogflowApp({ request, response }); + * const WELCOME_INTENT = 'input.welcome'; + * const CONFIRMATION = 'confirmation'; + * + * function welcomeIntent (app) { + * app.askForConfirmation('Are you sure you want to do that?'); + * } + * + * function confirmation (app) { + * if (app.getUserConfirmation()) { + * app.tell('Great! I\'m glad you want to do it!'); + * } else { + * app.tell('That\'s okay. Let\'s not do it now.'); + * } + * } + * + * const actionMap = new Map(); + * actionMap.set(WELCOME_INTENT, welcomeIntent); + * actionMap.set(CONFIRMATION, confirmation); + * app.handleRequest(actionMap); + * + * @param {string=} prompt The confirmation prompt presented to the user to + * query for an affirmative or negative response. If undefined or null, + * Google will use a generic yes/no prompt. + * @param {Object=} dialogState JSON object the app uses to hold dialog state that + * will be circulated back by Assistant. Used in {@link ActionsSdkAssistant}. + * @return {(Object|null)} HTTP response. + * @actionssdk + * @dialogflow + */ + askForConfirmation (prompt, dialogState) { + debug('askForConfirmation: prompt=%s, dialogState=%s', prompt, + JSON.stringify(dialogState)); + let confirmationValueSpec = {}; + if (prompt) { + confirmationValueSpec.dialogSpec = { + requestConfirmationText: prompt + }; + } + return this.fulfillSystemIntent_(this.StandardIntents.CONFIRMATION, + this.InputValueDataTypes_.CONFIRMATION, confirmationValueSpec, + 'PLACEHOLDER_FOR_CONFIRMATION', dialogState); + } + + /** + * Asks user for a timezone-agnostic date and time. + * + * @example + * const app = new DialogflowApp({ request, response }); + * const WELCOME_INTENT = 'input.welcome'; + * const DATETIME = 'datetime'; + * + * function welcomeIntent (app) { + * app.askForDateTime('When do you want to come in?', + * 'Which date works best for you?', + * 'What time of day works best for you?'); + * } + * + * function datetime (app) { + * app.tell({speech: 'Great see you at your appointment!', + * displayText: 'Great, we will see you on ' + * + app.getDateTime().date.month + * + '/' + app.getDateTime().date.day + * + ' at ' + app.getDateTime().time.hours + * + (app.getDateTime().time.minutes || '')}); + * } + * + * const actionMap = new Map(); + * actionMap.set(WELCOME_INTENT, welcomeIntent); + * actionMap.set(DATETIME, datetime); + * app.handleRequest(actionMap); + * + * @param {string=} initialPrompt The initial prompt used to ask for a + * date and time. If undefined or null, Google will use a generic + * prompt. + * @param {string=} datePrompt The prompt used to specifically ask for the + * date if not provided by user. If undefined or null, Google will use a + * generic prompt. + * @param {string=} timePrompt The prompt used to specifically ask for the + * time if not provided by user. If undefined or null, Google will use a + * generic prompt. + * @param {Object=} dialogState JSON object the app uses to hold dialog state that + * will be circulated back by Assistant. Used in {@link ActionsSdkAssistant}. + * @return {(Object|null)} HTTP response. + * @actionssdk + * @dialogflow + */ + askForDateTime (initialPrompt, datePrompt, timePrompt, dialogState) { + debug('askForDateTime: initialPrompt=%s, datePrompt=%s, ' + + 'timePrompt=%s, dialogState=%s', initialPrompt, datePrompt, timePrompt, + JSON.stringify(dialogState)); + let dateTimeValueSpec = {}; + if (initialPrompt || datePrompt || timePrompt) { + dateTimeValueSpec.dialogSpec = { + requestDatetimeText: initialPrompt || undefined, + requestDateText: datePrompt || undefined, + requestTimeText: timePrompt || undefined + }; + } + return this.fulfillSystemIntent_(this.StandardIntents.DATETIME, + this.InputValueDataTypes_.DATETIME, dateTimeValueSpec, + 'PLACEHOLDER_FOR_DATETIME', dialogState); + } + + /** + * Hands the user off to a web sign in flow. App sign in and OAuth credentials + * are set in the {@link https://console.actions.google.com|Actions Console}. + * Retrieve the access token in subsequent intents using + * app.getUser().accessToken. + * + * Note: Currently this API requires enabling the app for Transactions APIs. + * To do this, fill out the App Info section of the Actions Console project + * and check the box indicating the use of Transactions under "Privacy and + * consent". + * + * @example + * const app = new DialogflowApp({ request, response }); + * const WELCOME_INTENT = 'input.welcome'; + * const SIGN_IN = 'sign.in'; + * + * function welcomeIntent (app) { + * app.askForSignIn(); + * } + * + * function signIn (app) { + * if (app.getSignInStatus() === app.SignInstatus.OK) { + * let accessToken = app.getUser().accessToken; + * app.ask('Great, thanks for signing in!'); + * } else { + * app.ask('I won\'t be able to save your data, but let\'s continue!'); + * } + * } + * + * const actionMap = new Map(); + * actionMap.set(WELCOME_INTENT, welcomeIntent); + * actionMap.set(SIGN_IN, signIn); + * app.handleRequest(actionMap); + * + * @param {Object=} dialogState JSON object the app uses to hold dialog state that + * will be circulated back by Assistant. Used in {@link ActionsSdkAssistant}. + * @return {(Object|null)} HTTP response. + * @actionssdk + * @dialogflow + */ + askForSignIn (dialogState) { + debug('askForSignIn: dialogState=%s', JSON.stringify(dialogState)); + return this.fulfillSystemIntent_(this.StandardIntents.SIGN_IN, + this.InputValueDataTypes_.SIGN_IN, null, + 'PLACEHOLDER_FOR_SIGN_IN', dialogState); + } + + /** + * Requests the user to switch to another surface during the conversation. + * + * @example + * const app = new DialogflowApp({ request, response }); + * const WELCOME_INTENT = 'input.welcome'; + * const SHOW_IMAGE = 'show.image'; + * + * function welcomeIntent (app) { + * if (app.hasSurfaceCapability(app.SurfaceCapabilities.SCREEN_OUTPUT)) { + * showPicture(app); + * } else if (app.hasAvailableSurfaceCapabilities(app.SurfaceCapabilities.SCREEN_OUTPUT)) { + * app.askForNewSurface('To show you an image', + * 'Check out this image', + * [app.SurfaceCapabilities.SCREEN_OUTPUT] + * ); + * } else { + * app.tell('This part of the app only works on screen devices. Sorry about that'); + * } + * } + * + * function showImage (app) { + * if (!app.isNewSurface()) { + * app.tell('Ok, I understand. You don't want to see pictures. Bye'); + * } else { + * showPicture(app, pictureType); + * } + * } + * + * const actionMap = new Map(); + * actionMap.set(WELCOME_INTENT, welcomeIntent); + * actionMap.set(SHOW_IMAGE, showImage); + * app.handleRequest(actionMap); + * + * @param {string} context Context why new surface is requested; it's the TTS + * prompt prefix (action phrase) we ask the user. + * @param {string} notificationTitle Title of the notification appearing on + * new surface device. + * @param {Array} capabilities The list of capabilities required in + * the surface. + * @param {Object=} dialogState JSON object the app uses to hold dialog state that + * will be circulated back by Assistant. Used in {@link ActionsSdkAssistant}. + * @return {(Object|null)} HTTP response. + * @dialogflow + * @actionssdk + */ + askForNewSurface (context, notificationTitle, capabilities, dialogState) { + debug('askForNewSurface: context=%s, notificationTitle=%s, ' + + 'capabilities=%s, dialogState=%s', context, notificationTitle, + JSON.stringify(capabilities), dialogState); + let newSurfaceValueSpec = { context, notificationTitle, capabilities }; + return this.fulfillSystemIntent_(this.StandardIntents.NEW_SURFACE, + this.InputValueDataTypes_.NEW_SURFACE, newSurfaceValueSpec, + 'PLACEHOLDER_FOR_NEW_SURFACE', dialogState); + } + + /** + * User provided date/time info. + * @typedef {Object} DateTime + * @property {Object} date + * @property {number} date.year + * @property {number} date.month + * @property {number} date.day + * @property {Object} time + * @property {number} time.hours + * @property {number} time.minutes + * @property {number} time.seconds + * @property {number} time.nanos + */ + /** + * User's permissioned name info. + * @typedef {Object} UserName + * @property {string} displayName - User's display name. + * @property {string} givenName - User's given name. + * @property {string} familyName - User's family name. + */ + + /** + * User's permissioned device location. + * @typedef {Object} DeviceLocation + * @property {Object} coordinates - {latitude, longitude}. Requested with + * SupportedPermissions.DEVICE_PRECISE_LOCATION. + * @property {string} address - Full, formatted street address. Requested with + * SupportedPermissions.DEVICE_PRECISE_LOCATION. + * @property {string} zipCode - Zip code. Requested with + * SupportedPermissions.DEVICE_COARSE_LOCATION. + * @property {string} city - Device city. Requested with + * SupportedPermissions.DEVICE_COARSE_LOCATION. + */ + + /** + * User object. + * @typedef {Object} User + * @property {string} userId - Random string ID for Google user. + * @property {UserName} userName - User name information. Null if not + * requested with {@link AssistantApp#askForPermission|askForPermission(SupportedPermissions.NAME)}. + * @property {string} accessToken - Unique Oauth2 token. Only available with + * account linking. + */ + + /** + * Actions on Google Surface. + * @typedef {Object} Surface + * @property {Array} capabilities - Capabilities of the surface. + */ + + /** + * Surface capability. + * @typedef {Object} Capability + * @property {string} name - Name of the capability. + */ + + /** + * Gets the {@link User} object. + * The user object contains information about the user, including + * a string identifier and personal information (requires requesting permissions, + * see {@link AssistantApp#askForPermissions|askForPermissions}). + * + * @example + * const app = new DialogflowApp({request: request, response: response}); + * // or + * const app = new ActionsSdkApp({request: request, response: response}); + * const userId = app.getUser().userId; + * + * @return {User} Null if no value. + * @actionssdk + * @dialogflow + */ + getUser () { + debug('getUser'); + const data = this.requestData(); + + if (!data || !data.user) { + error('No user object'); + return null; + } + + const requestUser = data.user; + + // User object includes original API properties + const user = Object.assign({}, requestUser); + + // Backwards compatibility + user.user_id = user.userId; + user.access_token = user.accessToken; + + const profile = user.profile; + user.userName = profile ? Object.assign({}, profile) : null; + + return user; + } + + /** + * If granted permission to user's name in previous intent, returns user's + * display name, family name, and given name. If name info is unavailable, + * returns null. + * + * @example + * const app = new DialogflowApp({request: req, response: res}); + * const REQUEST_PERMISSION_ACTION = 'request_permission'; + * const SAY_NAME_ACTION = 'get_name'; + * + * function requestPermission (app) { + * const permission = app.SupportedPermissions.NAME; + * app.askForPermission('To know who you are', permission); + * } + * + * function sayName (app) { + * if (app.isPermissionGranted()) { + * app.tell('Your name is ' + app.getUserName().displayName)); + * } else { + * // Response shows that user did not grant permission + * app.tell('Sorry, I could not get your name.'); + * } + * } + * const actionMap = new Map(); + * actionMap.set(REQUEST_PERMISSION_ACTION, requestPermission); + * actionMap.set(SAY_NAME_ACTION, sayName); + * app.handleRequest(actionMap); + * @return {UserName} Null if name permission is not granted. + * @actionssdk + * @dialogflow + */ + getUserName () { + debug('getUserName'); + return this.getUser() && this.getUser().userName + ? this.getUser().userName : null; + } + + /** + * Gets the user locale. Returned string represents the regional language + * information of the user set in their Assistant settings. + * For example, 'en-US' represents US English. + * + * @example + * const app = new DialogflowApp({request, response}); + * const locale = app.getUserLocale(); + * + * @return {string} User's locale, e.g. 'en-US'. Null if no locale given. + * @actionssdk + * @dialogflow + */ + getUserLocale () { + debug('getUserLocale'); + return this.getUser() && this.getUser().locale + ? this.getUser().locale : null; + } + + /** + * If granted permission to device's location in previous intent, returns device's + * location (see {@link AssistantApp#askForPermissions|askForPermissions}). + * If device info is unavailable, returns null. + * + * @example + * const app = new DialogflowApp({request: req, response: res}); + * // or + * const app = new ActionsSdkApp({request: req, response: res}); + * app.askForPermission("To get you a ride", + * app.SupportedPermissions.DEVICE_PRECISE_LOCATION); + * // ... + * // In response handler for permissions fallback intent: + * if (app.isPermissionGranted()) { + * sendCarTo(app.getDeviceLocation().coordinates); + * } + * + * @return {DeviceLocation} Null if location permission is not granted. + * @actionssdk + * @dialogflow + */ + getDeviceLocation () { + debug('getDeviceLocation'); + const data = this.requestData(); + if (!data || !data.device || !data.device.location) { + return null; + } + const deviceLocation = Object.assign({}, data.device.location); + deviceLocation.address = deviceLocation.formattedAddress; + return deviceLocation; + } + + /** + * Gets type of input used for this request. + * + * @return {number} One of AssistantApp.InputTypes. + * Null if no input type given. + * @dialogflow + * @actionssdk + */ + getInputType () { + debug('getInputType'); + const data = this.requestData(); + if (data && data.inputs) { + for (const input of data.inputs) { + if (input.rawInputs) { + for (const rawInput of input.rawInputs) { + if (rawInput.inputType) { + return rawInput.inputType; + } + } + } + } + } + error('No input type in incoming request'); + return null; + } + + /** + * Get the argument value by name from the current intent. + * If the argument is included in originalRequest, and is not a text argument, + * the entire argument object is returned. + * + * Note: If incoming request is using an API version under 2 (e.g. 'v1'), + * the argument object will be in Proto2 format (snake_case, etc). + * + * @example + * const app = new DialogflowApp({request: request, response: response}); + * const WELCOME_INTENT = 'input.welcome'; + * const NUMBER_INTENT = 'input.number'; + * + * function welcomeIntent (app) { + * app.ask('Welcome to action snippets! Say a number.'); + * } + * + * function numberIntent (app) { + * const number = app.getArgument(NUMBER_ARGUMENT); + * app.tell('You said ' + number); + * } + * + * const actionMap = new Map(); + * actionMap.set(WELCOME_INTENT, welcomeIntent); + * actionMap.set(NUMBER_INTENT, numberIntent); + * app.handleRequest(actionMap); + * + * @param {string} argName Name of the argument. + * @return {Object} Argument value matching argName + * or null if no matching argument. + * @dialogflow + * @actionssdk + */ + getArgumentCommon (argName) { + debug('getArgument: argName=%s', argName); + if (!argName) { + error('Invalid argument name'); + return null; + } + const argument = this.findArgument_(argName); + if (!argument) { + debug('Failed to get argument value: %s', argName); + return null; + } else if (argument.textValue) { + return argument.textValue; + } else { + if (!this.isNotApiVersionOne_()) { + return transformToSnakeCase(argument); + } else { + return argument; + } + } + } + + /** + * Gets transactability of user. Only use after calling + * askForTransactionRequirements. Null if no result given. + * + * @return {string} One of Transactions.ResultType. + * @dialogflow + * @actionssdk + */ + getTransactionRequirementsResult () { + debug('getTransactionRequirementsResult'); + const argument = this.findArgument_(this.BuiltInArgNames.TRANSACTION_REQ_CHECK_RESULT); + if (argument && argument.extension && argument.extension.resultType) { + return argument.extension.resultType; + } + debug('Failed to get transaction requirements result'); + return null; + } + + /** + * Gets order delivery address. Only use after calling askForDeliveryAddress. + * + * @return {DeliveryAddress} Delivery address information. Null if user + * denies permission, or no address given. + * @dialogflow + * @actionssdk + */ + getDeliveryAddress () { + debug('getDeliveryAddress'); + const { + DELIVERY_ADDRESS_VALUE, + TRANSACTION_DECISION_VALUE + } = this.BuiltInArgNames; + const argument = this.findArgument_(DELIVERY_ADDRESS_VALUE, TRANSACTION_DECISION_VALUE); + if (argument && argument.extension) { + if (argument.extension.userDecision === this.Transactions.DeliveryAddressDecision.ACCEPTED) { + const { location } = argument.extension; + if (!location.postalAddress) { + debug('User accepted, but may not have configured address in app'); + return null; + } + return location; + } else { + debug('User rejected giving delivery address'); + return null; + } + } + debug('Failed to get order delivery address'); + return null; + } + + /** + * Gets transaction decision information. Only use after calling + * askForTransactionDecision. + * + * @return {TransactionDecision} Transaction decision data. Returns object with + * userDecision only if user declines. userDecision will be one of + * Transactions.ConfirmationDecision. Null if no decision given. + * @dialogflow + * @actionssdk + */ + getTransactionDecision () { + debug('getTransactionDecision'); + const argument = this.findArgument_(this.BuiltInArgNames.TRANSACTION_DECISION_VALUE); + if (argument && argument.extension) { + return argument.extension; + } + debug('Failed to get order decision information'); + return null; + } + + /** + * Gets confirmation decision. Use after askForConfirmation. + * + * @return {(boolean|null)} False if user replied with negative response. Null if no user + * confirmation decision given. + * @dialogflow + * @actionssdk + */ + getUserConfirmation () { + debug('getUserConfirmation'); + const argument = this.findArgument_(this.BuiltInArgNames.CONFIRMATION); + if (argument) { + return argument.boolValue; + } + debug('Failed to get confirmation decision information'); + return null; + } + + /** + * Gets user provided date and time. Use after askForDateTime. + * + * @return {DateTime} Date and time given by the user. Null if no user + * date and time given. + * @dialogflow + * @actionssdk + */ + getDateTime () { + debug('getDateTime'); + const argument = this.findArgument_(this.BuiltInArgNames.DATETIME); + if (argument) { + return argument.datetimeValue; + } + debug('Failed to get date/time information'); + return null; + } + + /** + * Gets status of user sign in request. + * + * @return {string} Result of user sign in request. One of + * DialogflowApp.SignInStatus or ActionsSdkApp.SignInStatus + * Null if no sign in status. + * @dialogflow + * @actionssdk + */ + getSignInStatus () { + debug('getSignInStatus'); + const argument = this.findArgument_(this.BuiltInArgNames.SIGN_IN); + if (argument && argument.extension && argument.extension.status) { + return argument.extension.status; + } + debug('Failed to get sign in status'); + return null; + } + + /** + * Returns true if user device has a given surface capability. + * + * @param {string} requestedCapability Must be one of {@link SurfaceCapabilities}. + * @return {boolean} True if user device has the given capability. + * + * @example + * const app = new DialogflowApp({request: req, response: res}); + * const DESCRIBE_SOMETHING = 'DESCRIBE_SOMETHING'; + * + * function describe (app) { + * if (app.hasSurfaceCapability(app.SurfaceCapabilities.SCREEN_OUTPUT)) { + * app.tell(richResponseWithBasicCard); + * } else { + * app.tell('Let me tell you about ...'); + * } + * } + * const actionMap = new Map(); + * actionMap.set(DESCRIBE_SOMETHING, describe); + * app.handleRequest(actionMap); + * + * @dialogflow + * @actionssdk + */ + hasSurfaceCapability (requestedCapability) { + debug('hasSurfaceCapability: requestedCapability=%s', requestedCapability); + const capabilities = this.getSurfaceCapabilities(); + if (!capabilities) { + error('No incoming capabilities to search ' + + 'for request capability: %s', requestedCapability); + return false; + } + return capabilities.includes(requestedCapability); + } + + /** + * Gets surface capabilities of user device. + * + * @return {Array} Supported surface capabilities, as defined in + * AssistantApp.SurfaceCapabilities. + * @dialogflow + * @actionssdk + */ + getSurfaceCapabilities () { + debug('getSurfaceCapabilities'); + const data = this.requestData(); + if (!data || !data.surface || !data.surface.capabilities) { + error('No surface capabilities in incoming request'); + return null; + } + if (data && data.surface && data.surface.capabilities) { + return data.surface.capabilities.map(capability => capability.name); + } else { + error('No surface capabilities in incoming request'); + return null; + } + } + + /** + * Returns the set of other available surfaces for the user. + * + * @return {Array} Empty if no available surfaces. + * @actionssdk + * @dialogflow + */ + getAvailableSurfaces () { + debug('getAvailableSurfaces'); + return this.requestData().availableSurfaces || []; + } + + /** + * Returns true if user has an available surface which includes all given + * capabilities. Available surfaces capabilities may exist on surfaces other + * than that used for an ongoing conversation. + * + * @param {string|Array} capabilities Must be one of + * {@link SurfaceCapabilities}. + * @return {boolean} True if user has a capability available on some surface. + * + * @dialogflow + * @actionssdk + */ + hasAvailableSurfaceCapabilities (capabilities) { + debug('hasAvailableSurfaceCapabilities: capabilities=%s', capabilities); + const capabilitiesArray = Array.isArray(capabilities) ? capabilities + : [capabilities]; + const availableSurfaces = this.requestData().availableSurfaces; + if (availableSurfaces) { + for (let surface of availableSurfaces) { + const availableCapabilities = surface.capabilities.map(capability => capability.name); + const unavailableCapabilities = capabilitiesArray + .filter(capability => !availableCapabilities.includes(capability)); + if (!unavailableCapabilities.length) { + return true; + } + } + } + return false; + } + + /** + * Returns the result of the AskForNewSurface helper. + * + * @return {boolean} True if user has triggered conversation on a new device + * following the NEW_SURFACE intent. + * @actionssdk + * @dialogflow + */ + isNewSurface () { + debug('isNewSurface'); + const argument = this.findArgument_(this.BuiltInArgNames.NEW_SURFACE); + return argument && argument.extension && argument.extension.status && + argument.extension.status === 'OK'; + } + + /** + * Returns true if the app is being tested in sandbox mode. Enable sandbox + * mode in the (Actions console)[console.actions.google.com] to test + * transactions. + * + * @return {boolean} True if app is being used in Sandbox mode. + * @dialogflow + * @actionssdk + */ + isInSandbox () { + debug('isInSandbox'); + const data = this.requestData(); + return data && data.isInSandbox; + } + + /** + * Returns the number of subsequent reprompts related to silent input from the + * user. This should be used along with the NO_INPUT intent to reprompt the + * user for input in cases where the Google Assistant could not pick up any + * speech. + * + * @example + * const app = new ActionsSdkApp({request, response}); + * + * function welcome (app) { + * app.ask('Welcome to your app!'); + * } + * + * function noInput (app) { + * if (app.getRepromptCount() === 0) { + * app.ask(`What was that?`); + * } else if (app.getRepromptCount() === 1) { + * app.ask(`Sorry I didn't catch that. Could you repeat yourself?`); + * } else if (app.isFinalReprompt()) { + * app.tell(`Okay let's try this again later.`); + * } + * } + * + * const actionMap = new Map(); + * actionMap.set(app.StandardIntents.MAIN, welcome); + * actionMap.set(app.StandardIntents.NO_INPUT, noInput); + * app.handleRequest(actionMap); + * + * @return {number} The current reprompt count. Null if no reprompt count + * available (e.g. not in the NO_INPUT intent). + * @dialogflow + * @actionssdk + */ + getRepromptCount () { + debug('getRepromptCount'); + const repromptCount = this.getArgumentCommon(this.BuiltInArgNames.REPROMPT_COUNT); + return repromptCount !== null ? parseInt(repromptCount, 10) : null; + } + + /** + * Returns true if it is the final reprompt related to silent input from the + * user. This should be used along with the NO_INPUT intent to give the final + * response to the user after multiple silences and should be an app.tell + * which ends the conversation. + * + * @example + * const app = new ActionsSdkApp({request, response}); + * + * function welcome (app) { + * app.ask('Welcome to your app!'); + * } + * + * function noInput (app) { + * if (app.getRepromptCount() === 0) { + * app.ask(`What was that?`); + * } else if (app.getRepromptCount() === 1) { + * app.ask(`Sorry I didn't catch that. Could you repeat yourself?`); + * } else if (app.isFinalReprompt()) { + * app.tell(`Okay let's try this again later.`); + * } + * } + * + * const actionMap = new Map(); + * actionMap.set(app.StandardIntents.MAIN, welcome); + * actionMap.set(app.StandardIntents.NO_INPUT, noInput); + * app.handleRequest(actionMap); + * + * @return {boolean} True if in a NO_INPUT intent and this is the final turn + * of dialog. + * @dialogflow + * @actionssdk + */ + isFinalReprompt () { + debug('isFinalReprompt'); + const finalReprompt = this.getArgumentCommon(this.BuiltInArgNames.IS_FINAL_REPROMPT); + return finalReprompt === '1'; + } + + // --------------------------------------------------------------------------- + // Response Builders + // --------------------------------------------------------------------------- + + /** + * Constructs RichResponse with chainable property setters. + * + * @param {RichResponse=} richResponse RichResponse to clone. + * @return {RichResponse} Constructed RichResponse. + */ + buildRichResponse (richResponse) { + return new RichResponse(richResponse); + } + + /** + * Constructs BasicCard with chainable property setters. + * + * @param {string=} bodyText Body text of the card. Can be set using setTitle + * instead. + * @return {BasicCard} Constructed BasicCard. + */ + buildBasicCard (bodyText) { + const card = new BasicCard(); + if (bodyText) { + card.setBodyText(bodyText); + } + return card; + } + + /** + * Constructs List with chainable property setters. + * + * @param {string=} title A title to set for a new List. + * @return {List} Constructed List. + */ + buildList (title) { + return new List(title); + } + + /** + * Constructs Carousel with chainable property setters. + * + * @return {Carousel} Constructed Carousel. + */ + buildCarousel () { + return new Carousel(); + } + + /** + * Constructs OptionItem with chainable property setters. + * + * @param {string=} key A unique key to identify this option. This key will + * be returned as an argument in the resulting actions.intent.OPTION + * intent. + * @param {string|Array=} synonyms A list of synonyms which the user may + * use to identify this option instead of the option key. + * @return {OptionItem} Constructed OptionItem. + */ + buildOptionItem (key, synonyms) { + let optionItem = new OptionItem(); + if (key) { + optionItem.setKey(key); + } + if (synonyms) { + optionItem.addSynonyms(synonyms); + } + return optionItem; + } + + // --------------------------------------------------------------------------- + // Transaction Builders + // --------------------------------------------------------------------------- + + /** + * Constructs Order with chainable property setters. + * + * @param {string} orderId Unique identifier for the order. + * @return {Order} Constructed Order. + */ + buildOrder (orderId) { + return new Order(orderId); + } + + /** + * Constructs Cart with chainable property setters. + * + * @param {string=} cartId Unique identifier for the cart. + * @return {Cart} Constructed Cart. + */ + buildCart (cartId) { + return new Cart(cartId); + } + + /** + * Constructs LineItem with chainable property setters. + * Because of a previous bug, the parameters are swapped compared to + * the LineItem constructor to prevent a breaking change. + * + * @param {string} name Name of the line item. + * @param {string} id Unique identifier for the item. + * @return {LineItem} Constructed LineItem. + */ + buildLineItem (name, id) { + return new LineItem(id, name); + } + + /** + * Constructs OrderUpdate with chainable property setters. + * + * @param {string} orderId Unique identifier of the order. + * @param {boolean} isGoogleOrderId True if the order ID is provided by + * Google. False if the order ID is app provided. + * @return {OrderUpdate} Constructed OrderUpdate. + */ + buildOrderUpdate (orderId, isGoogleOrderId) { + return new OrderUpdate(orderId, isGoogleOrderId); + } + + // --------------------------------------------------------------------------- + // Private Helpers + // --------------------------------------------------------------------------- + + /** + * Utility function to invoke an intent handler. + * + * @param {Object} handler The handler for the request. + * @param {string} intent The intent to handle. + * @return {boolean} true if the handler was invoked. + * @private + */ + invokeIntentHandler_ (handler, intent) { + debug('invokeIntentHandler_: handler=%s, intent=%s', handler, intent); + this.lastErrorMessage_ = null; + // map of intents or states + for (let key of handler.keys()) { + const value = handler.get(key); + let name; + if (key instanceof Intent) { + debug('key is intent'); + name = key.getName(); + } else if (key instanceof State) { + debug('key is state'); + name = key.getName(); + } else { + debug('key is id'); + // String id + name = key; + } + debug('name=' + name); + if (value instanceof Map) { + debug('state=' + (this.state instanceof State ? this.state.getName() : this.state)); + // map of states + if (!this.state && name === null) { + debug('undefined state'); + return this.invokeIntentHandler_(value, intent); + } else if (this.state instanceof State && name === this.state.getName()) { + return this.invokeIntentHandler_(value, intent); + } else if (name === this.state) { + return this.invokeIntentHandler_(value, intent); + } + } + // else map of intents + if (name === intent) { + debug('map of intents'); + const promise = value(this); + if (promise instanceof Promise) { + promise.then( + (result) => { + // No-op + }) + .catch( + (reason) => { + error(reason.message); + this.handleError_('intent handler failed: %s', reason.message); + this.lastErrorMessage_ = reason.message; + return false; + }); + } else { + // Handle functions + return true; + } + return true; + } + } + this.handleError_('no matching intent handler for: ' + intent); + return false; + } + + /** + * Find argument with requirements + * @param {Array} targets Argument to find + * @return {*} The argument + */ + findArgument_ (...targets) { + const data = this.requestData(); + if (data && data.inputs) { + for (const input of data.inputs) { + if (input.arguments) { + for (const argument of input.arguments) { + for (const target of targets) { + if (argument.name === target) { + return argument; + } + } + } + } + } + } + return null; + } + + /** + * Utility function to detect SSML markup. + * + * @param {string} text The text to be checked. + * @return {boolean} true if text is SSML markup. + * @private + */ + isSsml_ (text) { + debug('isSsml_: text=%s', text); + if (!text) { + error('Text can NOT be empty'); + return false; + } + return isSsml(text); + } + + /** + * Utility function to detect incoming request format. + * + * @return {boolean} true if request is not Action API Version 1. + * @private + */ + isNotApiVersionOne_ () { + debug('isNotApiVersionOne_'); + return this.actionsApiVersion_ !== null && + parseInt(this.actionsApiVersion_, 10) >= ACTIONS_CONVERSATION_API_VERSION_TWO; + } + + /** + * Utility function to handle error messages. + * + * @param {string} text The error message. + * @return {undefined} + * @private + */ + handleError_ (text) { + debug('handleError_: text=%s', text); + if (!text) { + error('Missing text'); + return; + } + // Log error + error.apply(text, Array.prototype.slice.call(arguments, 1)); + // Tell app to say error + if (this.responded_) { + return; + } + if (this.response_) { + // Don't call other methods; just do directly + this.response_.status(RESPONSE_CODE_BAD_REQUEST).send(API_ERROR_MESSAGE_PREFIX + text); + this.responded_ = true; + } + } + + /** + * Utility method to send an HTTP response. + * + * @param {string} response The JSON response. + * @param {string} responseCode The HTTP response code. + * @return {(Object|null)} HTTP response. + * @private + */ + doResponse_ (response, responseCode) { + debug('doResponse_: response=%s, responseCode=%d', JSON.stringify(response), responseCode); + if (this.responded_) { + return; + } + if (!response) { + this.handleError_('Response can NOT be empty.'); + return null; + } + let code = RESPONSE_CODE_OK; + if (responseCode) { + code = responseCode; + } + if (this.apiVersion_ !== null) { + this.response_.append(CONVERSATION_API_VERSION_HEADER, this.apiVersion_); + } + this.response_.append(HTTP_CONTENT_TYPE_HEADER, HTTP_CONTENT_TYPE_JSON); + // If request was in Proto2 format, convert response to Proto2 + if (!this.isNotApiVersionOne_()) { + if (response.data) { + response.data = transformToSnakeCase(response.data); + } else { + response = transformToSnakeCase(response); + } + } + debug('Response %s', JSON.stringify(response)); + const httpResponse = this.response_.status(code).send(response); + this.responded_ = true; + return httpResponse; + } + + /** + * Extract session data from the incoming JSON request. + * + * Used in subclasses for Actions SDK and Dialogflow. + * @return {undefined} + * @private + */ + extractData_ () { + debug('extractData_'); + this.data = {}; + } + + /** + * Uses a PermissionsValueSpec object to construct and send a + * permissions request to user. + * + * Used in subclasses for Actions SDK and Dialogflow. + * @return {Object} HTTP response. + * @private + */ + fulfillPermissionsRequest_ () { + debug('fulfillPermissionsRequest_'); + return {}; + } + + /** + * Uses a ConfirmationValueSpec object to construct and send a + * confirmation request to user. + * + * Used in subclasses for Actions SDK and Dialogflow. + * @return {Object} HTTP response. + * @private + */ + fulfillConfirmationRequest_ () { + debug('fulfillConfirmationRequest_'); + return {}; + } + + /** + * Uses a DateTimeValueSpec object to construct and send a + * date time request to user. + * + * Used in subclasses for Actions SDK and Dialogflow. + * @return {Object} HTTP response. + * @private + */ + fulfillDateTimeRequest_ () { + debug('fulfillDateTimeRequest_'); + return {}; + } + + /** + * Construct and send a sign in request to user. + * + * Used in subclasses for Actions SDK and Dialogflow. + * @return {Object} HTTP response. + * @private + */ + fulfillSignInRequest_ () { + debug('fulfillSignInRequest_'); + return {}; + } + + /** + * Uses a TransactionRequirementsCheckValueSpec object to construct and send a + * transaction requirements request to user. + * + * Used in subclasses for Actions SDK and Dialogflow. + * @return {Object} HTTP response. + * @private + */ + fulfillTransactionRequirementsCheck_ () { + debug('fulfillTransactionRequirementsCheck_'); + return {}; + } + + /** + * Uses a TransactionDecisionValueSpec object to construct and send a + * transaction confirmation request to user. + * + * Used in subclasses for Actions SDK and Dialogflow. + * @return {Object} HTTP response. + * @private + */ + fulfillTransactionDecision_ () { + debug('fulfillTransactionDecision_'); + return {}; + } + + /** + * Helper to build prompts from SSML's. + * + * @param {Array} ssmls Array of ssml. + * @return {Array} Array of SpeechResponse objects. + * @private + */ + buildPromptsFromSsmlHelper_ (ssmls) { + debug('buildPromptsFromSsmlHelper_: ssmls=%s', ssmls); + const prompts = []; + for (let i = 0; i < ssmls.length; i++) { + const prompt = { + ssml: ssmls[i] + }; + prompts.push(prompt); + } + return prompts; + } + + /** + * Helper to build prompts from plain texts. + * + * @param {Array} plainTexts Array of plain text to speech. + * @return {Array} Array of SpeechResponse objects. + * @private + */ + buildPromptsFromPlainTextHelper_ (plainTexts) { + debug('buildPromptsFromPlainTextHelper_: plainTexts=%s', plainTexts); + const prompts = []; + for (let i = 0; i < plainTexts.length; i++) { + const prompt = { + textToSpeech: plainTexts[i] + }; + prompts.push(prompt); + } + return prompts; + } + + /** + * Helper to process a transaction config and create a payment options object. + * + * @param {ActionPaymentTransactionConfig|GooglePaymentTransactionConfig} + * transactionConfig Configuration for the transaction. Includes payment + * options and order options. + * @return {Object} paymentOptions + * @private + */ + buildPaymentOptions_ (transactionConfig) { + debug('buildPromptsFromPlainTextHelper_: transactionConfig=%s', + JSON.stringify(transactionConfig)); + let paymentOptions = {}; + if (transactionConfig.type) { // Action payment + paymentOptions.actionProvidedOptions = { + paymentType: transactionConfig.type, + displayName: transactionConfig.displayName + }; + } else { // Google payment + paymentOptions.googleProvidedOptions = { + supportedCardNetworks: transactionConfig.cardNetworks, + prepaidCardDisallowed: transactionConfig.prepaidCardDisallowed + }; + if (transactionConfig.tokenizationParameters) { + paymentOptions.googleProvidedOptions.tokenizationParameters = { + tokenizationType: 'PAYMENT_GATEWAY', + parameters: transactionConfig.tokenizationParameters + }; + } + } + return paymentOptions; + } +} + +/** + * Utility class for representing intents by name. + * + * @private + */ +const Intent = class { + /** + * Constructor for Intent object. + * + * @param {string} name The name of the intent. + */ + constructor (name) { + this.name_ = name; + } + + /** + * Getter for the Intent name. + * + * @return {string} The name of the intent. + */ + getName () { + return this.name_; + } +}; + +/** + * Utility class for representing states by name. + * + * @private + */ +const State = class { + /** + * Constructor for State object. + * + * @param {string} name The name of the state. + */ + constructor (name) { + this.name_ = name; + } + + /** + * Getter for the State name. + * + * @return {string} The name of the state. + */ + getName () { + return this.name_; + } +}; + +module.exports = { + AssistantApp: AssistantApp, + State: State +}; diff --git a/types/actions-on-google/staging/dialogflow-app.js b/types/actions-on-google/staging/dialogflow-app.js new file mode 100644 index 0000000000..9c4336195e --- /dev/null +++ b/types/actions-on-google/staging/dialogflow-app.js @@ -0,0 +1,1105 @@ +/** + * Copyright 2017 Google Inc. All Rights Reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +'use strict'; + +const Debug = require('debug'); +const debug = Debug('actions-on-google:debug'); +const error = Debug('actions-on-google:error'); +const app = require('./assistant-app'); +const AssistantApp = app.AssistantApp; +const State = app.State; +const transformToCamelCase = require('./utils/transform').transformToCamelCase; + +// Constants +const RESPONSE_CODE_OK = 200; +const ACTIONS_DIALOGFLOW_CONTEXT = '_actions_on_google_'; +const MAX_LIFESPAN = 100; +const INPUTS_MAX = 3; +const ORIGINAL_SUFFIX = '.original'; +const SELECT_EVENT = 'actions_intent_option'; + +// Dialogflow Rich Response item types +const SIMPLE_RESPONSE = 'simple_response'; +const BASIC_CARD = 'basic_card'; +const LIST = 'list_card'; +const CAROUSEL = 'carousel_card'; +const SUGGESTIONS = 'suggestion_chips'; +const LINK_OUT_SUGGESTION = 'link_out_chip'; +const TYPE = 'type'; +const PLATFORM = 'platform'; + +// Configure logging for hosting platforms that only support console.log and console.error +debug.log = console.log.bind(console); +error.log = console.error.bind(console); + +// --------------------------------------------------------------------------- +// Dialogflow support +// --------------------------------------------------------------------------- + +/** + * This is the class that handles the communication with Dialogflow's fulfillment API. + */ +class DialogflowApp extends AssistantApp { + /** + * Constructor for DialogflowApp object. + * To be used in the Dialogflow fulfillment webhook logic. + * + * @example + * const DialogflowApp = require('actions-on-google').DialogflowApp; + * const app = new DialogflowApp({request: request, response: response, + * sessionStarted:sessionStarted}); + * + * @param {Object} options JSON configuration. + * @param {Object} options.request Express HTTP request object. + * @param {Object} options.response Express HTTP response object. + * @param {Function=} options.sessionStarted Function callback when session starts. + * Only called if webhook is enabled for welcome/triggering intents, and + * called from Web Simulator or Google Home device (i.e., not Dialogflow simulator). + * @dialogflow + */ + constructor (options) { + debug('DialogflowApp constructor'); + super(options, () => { + const originalRequest = this.body_.originalRequest; + if (!(originalRequest && originalRequest.data)) { + return null; + } + return originalRequest.data; + }); + + // If request contains originalRequest, convert to Proto3. + if (this.body_ && this.body_.originalRequest && !this.isNotApiVersionOne_()) { + this.body_.originalRequest = transformToCamelCase(this.body_.originalRequest); + } + + if (this.body_ && + this.body_.originalRequest && + this.body_.originalRequest.data && + this.body_.originalRequest.data.conversation) { + if (this.body_.originalRequest.data.conversation.type === + this.ConversationStages.NEW && this.sessionStarted_ && + typeof this.sessionStarted_ === 'function') { + this.sessionStarted_(); + } else if (this.sessionStarted_ && typeof this.sessionStarted_ !== 'function') { + this.handleError_('options.sessionStarted must be a Function'); + } + } + } + + /** + * @deprecated + * Verifies whether the request comes from Dialogflow. + * + * @param {string} key The header key specified by the developer in the + * Dialogflow Fulfillment settings of the app. + * @param {string} value The private value specified by the developer inside the + * fulfillment header. + * @return {boolean} True if the request comes from Dialogflow. + * @dialogflow + */ + isRequestFromApiAi (key, value) { + debug('isRequestFromApiAi: key=%s, value=%s', key, value); + console.log('isRequestFromApiAi is *DEPRECATED*, use isRequestFromDialogflow'); + return this.isRequestFromDialogflow(key, value); + } + + /** + * Verifies whether the request comes from Dialogflow. + * + * @param {string} key The header key specified by the developer in the + * Dialogflow Fulfillment settings of the app. + * @param {string} value The private value specified by the developer inside the + * fulfillment header. + * @return {boolean} True if the request comes from Dialogflow. + * @dialogflow + */ + isRequestFromDialogflow (key, value) { + debug('isRequestFromDialogflow: key=%s, value=%s', key, value); + if (!key || key === '') { + error('Key must be specified'); + return false; + } + if (!value || value === '') { + error('Value must be specified'); + return false; + } + return this.request_.get(key) === value; + } + + /** + * Get the current intent. Alternatively, using a handler Map with + * {@link AssistantApp#handleRequest|handleRequest}, + * the client library will automatically handle the incoming intents. + * 'Intent' in the Dialogflow context translates into the current action. + * + * @example + * const app = new DialogflowApp({request: request, response: response}); + * + * function responseHandler (app) { + * const intent = app.getIntent(); + * switch (intent) { + * case WELCOME_INTENT: + * app.ask('Welcome to action snippets! Say a number.'); + * break; + * + * case NUMBER_INTENT: + * const number = app.getArgument(NUMBER_ARGUMENT); + * app.tell('You said ' + number); + * break; + * } + * } + * + * app.handleRequest(responseHandler); + * + * @return {string} Intent id or null if no value (action name). + * @dialogflow + */ + getIntent () { + debug('getIntent'); + const intent = this.getIntent_(); + if (!intent) { + error('The current action name could not be found in request body'); + return null; + } + return intent; + } + + /** + * Get the argument value by name from the current intent. If the argument + * is included in originalRequest, and is not a text argument, the entire + * argument object is returned. + * + * Note: If incoming request is using an API version under 2 (e.g. 'v1'), + * the argument object will be in Proto2 format (snake_case, etc). + * + * @example + * const app = new DialogflowApp({request: request, response: response}); + * const WELCOME_INTENT = 'input.welcome'; + * const NUMBER_INTENT = 'input.number'; + * + * function welcomeIntent (app) { + * app.ask('Welcome to action snippets! Say a number.'); + * } + * + * function numberIntent (app) { + * const number = app.getArgument(NUMBER_ARGUMENT); + * app.tell('You said ' + number); + * } + * + * const actionMap = new Map(); + * actionMap.set(WELCOME_INTENT, welcomeIntent); + * actionMap.set(NUMBER_INTENT, numberIntent); + * app.handleRequest(actionMap); + * + * @param {string} argName Name of the argument. + * @return {Object} Argument value matching argName + * or null if no matching argument. + * @dialogflow + */ + getArgument (argName) { + debug('getArgument: argName=%s', argName); + if (!argName) { + error('Invalid argument name'); + return null; + } + const { parameters } = this.body_.result; + if (parameters && parameters[argName]) { + return parameters[argName]; + } + return this.getArgumentCommon(argName); + } + + /** + * Get the context argument value by name from the current intent. Context + * arguments include parameters collected in previous intents during the + * lifespan of the given context. If the context argument has an original + * value, usually representing the underlying entity value, that will be given + * as part of the return object. + * + * @example + * const app = new DialogflowApp({request: request, response: response}); + * const WELCOME_INTENT = 'input.welcome'; + * const NUMBER_INTENT = 'input.number'; + * const OUT_CONTEXT = 'output_context'; + * const NUMBER_ARG = 'myNumberArg'; + * + * function welcomeIntent (app) { + * const parameters = {}; + * parameters[NUMBER_ARG] = '42'; + * app.setContext(OUT_CONTEXT, 1, parameters); + * app.ask('Welcome to action snippets! Ask me for your number.'); + * } + * + * function numberIntent (app) { + * const number = app.getContextArgument(OUT_CONTEXT, NUMBER_ARG); + * // number === { value: 42 } + * app.tell('Your number is ' + number.value); + * } + * + * const actionMap = new Map(); + * actionMap.set(WELCOME_INTENT, welcomeIntent); + * actionMap.set(NUMBER_INTENT, numberIntent); + * app.handleRequest(actionMap); + * + * @param {string} contextName Name of the context. + * @param {string} argName Name of the argument. + * @return {Object} Object containing value property and optional original + * property matching context argument. Null if no matching argument. + * @dialogflow + */ + getContextArgument (contextName, argName) { + debug('getContextArgument: contextName=%s, argName=%s', contextName, argName); + if (!contextName) { + error('Invalid context name'); + return null; + } + if (!argName) { + error('Invalid argument name'); + return null; + } + if (!this.body_.result || + !this.body_.result.contexts) { + error('No contexts included in request'); + return null; + } + for (let context of this.body_.result.contexts) { + if (context.name === contextName && context.parameters[argName]) { + let argument = { value: context.parameters[argName] }; + if (context.parameters[argName + ORIGINAL_SUFFIX]) { + argument.original = context.parameters[argName + ORIGINAL_SUFFIX]; + } + return argument; + } + } + debug('Failed to get context argument value: %s', argName); + return null; + } + + /** + * Returns the RichResponse constructed in Dialogflow response builder. + * + * @example + * const app = new App({request: req, response: res}); + * + * function tellFact (app) { + * let fact = 'Google was founded in 1998'; + * + * if (app.hasSurfaceCapability(app.SurfaceCapabilities.SCREEN_OUTPUT)) { + * app.ask(app.getIncomingRichResponse().addSimpleResponse('Here\'s a ' + + * 'fact for you. ' + fact + ' Which one do you want to hear about ' + + * 'next, Google\'s history or headquarters?')); + * } else { + * app.ask('Here\'s a fact for you. ' + fact + ' Which one ' + + * 'do you want to hear about next, Google\'s history or headquarters?'); + * } + * } + * + * const actionMap = new Map(); + * actionMap.set('tell.fact', tellFact); + * + * app.handleRequest(actionMap); + * + * @return {RichResponse} RichResponse created in Dialogflow. If no RichResponse was + * created, an empty RichResponse is returned. + * @dialogflow + */ + getIncomingRichResponse () { + debug('getIncomingRichResponse'); + let response = this.buildRichResponse(); + if (this.body_.result && + this.body_.result.fulfillment && + this.body_.result.fulfillment.messages) { + for (let message of this.body_.result.fulfillment.messages) { + if (!message.type) { + continue; + } + if (message.type === SIMPLE_RESPONSE) { + let item = { + simpleResponse: {} + }; + Object.assign(item.simpleResponse, message); + delete item.simpleResponse[TYPE]; + delete item.simpleResponse[PLATFORM]; + response.items.push(item); + } else if (message.type === BASIC_CARD) { + let item = { + basicCard: {} + }; + Object.assign(item.basicCard, message); + delete item.basicCard[TYPE]; + delete item.basicCard[PLATFORM]; + response.items.push(item); + } else if (message.type === SUGGESTIONS) { + response.suggestions = message.suggestions; + } else if (message.type === LINK_OUT_SUGGESTION) { + response.linkOutSuggestion = Object.assign({}, message); + delete response.linkOutSuggestion[TYPE]; + delete response.linkOutSuggestion[PLATFORM]; + } + } + } + return response; + } + + /** + * Returns the List constructed in Dialogflow response builder. + * + * @example + * const app = new App({request: req, response: res}); + * + * function pickOption (app) { + * if (app.hasSurfaceCapability(app.SurfaceCapabilities.SCREEN_OUTPUT)) { + * app.askWithList('Which of these looks good?', + * app.getIncomingList().addItems( + * app.buildOptionItem('another_choice', ['Another choice']). + * setTitle('Another choice'))); + * } else { + * app.ask('What would you like?'); + * } + * } + * + * const actionMap = new Map(); + * actionMap.set('pick.option', pickOption); + * + * app.handleRequest(actionMap); + * + * @return {List} List created in Dialogflow. If no List was created, an empty + * List is returned. + * @dialogflow + */ + getIncomingList () { + debug('getIncomingList'); + let list = this.buildList(); + if (this.body_.result && + this.body_.result.fulfillment && + this.body_.result.fulfillment.messages) { + for (let message of this.body_.result.fulfillment.messages) { + if (!message.type) { + continue; + } + if (message.type === LIST) { + Object.assign(list, message); + delete list[TYPE]; + delete list[PLATFORM]; + } + } + } + return list; + } + + /** + * Returns the Carousel constructed in Dialogflow response builder. + * + * @example + * const app = new App({request: req, response: res}); + * + * function pickOption (app) { + * if (app.hasSurfaceCapability(app.SurfaceCapabilities.SCREEN_OUTPUT)) { + * app.askWithCarousel('Which of these looks good?', + * app.getIncomingCarousel().addItems( + * app.buildOptionItem('another_choice', ['Another choice']). + * setTitle('Another choice').setDescription('Choose me!'))); + * } else { + * app.ask('What would you like?'); + * } + * } + * + * const actionMap = new Map(); + * actionMap.set('pick.option', pickOption); + * + * app.handleRequest(actionMap); + * + * @return {Carousel} Carousel created in Dialogflow. If no Carousel was created, + * an empty Carousel is returned. + * @dialogflow + */ + getIncomingCarousel () { + debug('getIncomingCarousel'); + let carousel = this.buildCarousel(); + if (this.body_.result && + this.body_.result.fulfillment && + this.body_.result.fulfillment.messages) { + for (let message of this.body_.result.fulfillment.messages) { + if (!message.type) { + continue; + } + if (message.type === CAROUSEL) { + Object.assign(carousel, message); + delete carousel[TYPE]; + delete carousel[PLATFORM]; + } + } + } + return carousel; + } + + /** + * Returns the option key user chose from options response. + * + * @example + * const app = new App({request: req, response: res}); + * + * function pickOption (app) { + * if (app.hasSurfaceCapability(app.SurfaceCapabilities.SCREEN_OUTPUT)) { + * app.askWithCarousel('Which of these looks good?', + * app.getIncomingCarousel().addItems( + * app.buildOptionItem('another_choice', ['Another choice']). + * setTitle('Another choice').setDescription('Choose me!'))); + * } else { + * app.ask('What would you like?'); + * } + * } + * + * function optionPicked (app) { + * app.ask('You picked ' + app.getSelectedOption()); + * } + * + * const actionMap = new Map(); + * actionMap.set('pick.option', pickOption); + * actionMap.set('option.picked', optionPicked); + * + * app.handleRequest(actionMap); + * + * @return {string} Option key of selected item. Null if no option selected or + * if current intent is not OPTION intent. + * @dialogflow + */ + getSelectedOption () { + debug('getSelectedOption'); + if (this.getContextArgument(SELECT_EVENT, this.BuiltInArgNames.OPTION) && + this.getContextArgument(SELECT_EVENT, this.BuiltInArgNames.OPTION).value) { + return this.getContextArgument(SELECT_EVENT, this.BuiltInArgNames.OPTION).value; + } else if (this.getArgument(this.BuiltInArgNames.OPTION)) { + return this.getArgument(this.BuiltInArgNames.OPTION); + } + debug('Failed to get selected option'); + return null; + } + + /** + * Asks to collect the user's input. + * {@link https://developers.google.com/actions/policies/general-policies#user_experience|The guidelines when prompting the user for a response must be followed at all times}. + * + * NOTE: Due to a bug, if you specify the no-input prompts, + * the mic is closed after the 3rd prompt, so you should use the 3rd prompt + * for a bye message until the bug is fixed. + * + * @example + * const app = new DialogflowApp({request: request, response: response}); + * const WELCOME_INTENT = 'input.welcome'; + * const NUMBER_INTENT = 'input.number'; + * + * function welcomeIntent (app) { + * app.ask('Welcome to action snippets! Say a number.', + * ['Say any number', 'Pick a number', 'We can stop here. See you soon.']); + * } + * + * function numberIntent (app) { + * const number = app.getArgument(NUMBER_ARGUMENT); + * app.tell('You said ' + number); + * } + * + * const actionMap = new Map(); + * actionMap.set(WELCOME_INTENT, welcomeIntent); + * actionMap.set(NUMBER_INTENT, numberIntent); + * app.handleRequest(actionMap); + * + * @param {string|SimpleResponse|RichResponse} inputPrompt The input prompt + * response. + * @param {Array=} noInputs Array of re-prompts when the user does not respond (max 3). + * @return {Object} HTTP response. + * @dialogflow + */ + ask (inputPrompt, noInputs) { + debug('ask: inputPrompt=%s, noInputs=%s', inputPrompt, noInputs); + if (!inputPrompt) { + this.handleError_('Invalid input prompt'); + return null; + } + const response = this.buildResponse_(inputPrompt, true, noInputs); + if (!response) { + this.handleError_('Error in building response'); + return null; + } + return this.doResponse_(response, RESPONSE_CODE_OK); + } + + /** + * Asks to collect the user's input with a list. + * + * @example + * const app = new DialogflowApp({request, response}); + * const WELCOME_INTENT = 'input.welcome'; + * const OPTION_INTENT = 'option.select'; + * + * function welcomeIntent (app) { + * app.askWithList('Which of these looks good?', + * app.buildList('List title') + * .addItems([ + * app.buildOptionItem(SELECTION_KEY_ONE, + * ['synonym of KEY_ONE 1', 'synonym of KEY_ONE 2']) + * .setTitle('Title of First List Item'), + * app.buildOptionItem(SELECTION_KEY_TWO, + * ['synonym of KEY_TWO 1', 'synonym of KEY_TWO 2']) + * .setTitle('Title of Second List Item'), + * ])); + * } + * + * function optionIntent (app) { + * if (app.getSelectedOption() === SELECTION_KEY_ONE) { + * app.tell('Number one is a great choice!'); + * } else { + * app.tell('Number two is a great choice!'); + * } + * } + * + * const actionMap = new Map(); + * actionMap.set(WELCOME_INTENT, welcomeIntent); + * actionMap.set(OPTION_INTENT, optionIntent); + * app.handleRequest(actionMap); + * + * @param {string|RichResponse|SimpleResponse} inputPrompt The input prompt + * response. + * @param {List} list List built with {@link AssistantApp#buildList|buildList}. + * @return {Object} HTTP response. + * @dialogflow + */ + askWithList (inputPrompt, list) { + debug('askWithList: inputPrompt=%s, list=%s', + inputPrompt, JSON.stringify(list)); + if (!inputPrompt) { + this.handleError_('Invalid input prompt'); + return null; + } + if (!list || typeof list !== 'object') { + this.handleError_('Invalid list'); + return null; + } + if (list.items.length < 2) { + this.handleError_('List requires at least 2 items'); + return null; + } + const response = this.buildResponse_(inputPrompt, true); + if (!response) { + error('Error in building response'); + return null; + } + response.data.google.systemIntent = { + intent: this.StandardIntents.OPTION + }; + if (this.isNotApiVersionOne_()) { + response.data.google.systemIntent.data = Object.assign({ + [this.ANY_TYPE_PROPERTY_]: this.InputValueDataTypes_.OPTION + }, { + listSelect: list + }); + } else { + response.data.google.systemIntent.spec = { + optionValueSpec: { + listSelect: list + } + }; + } + return this.doResponse_(response, RESPONSE_CODE_OK); + } + + /** + * Asks to collect the user's input with a carousel. + * + * @example + * const app = new DialogflowApp({request, response}); + * const WELCOME_INTENT = 'input.welcome'; + * const OPTION_INTENT = 'option.select'; + * + * function welcomeIntent (app) { + * app.askWithCarousel('Which of these looks good?', + * app.buildCarousel() + * .addItems([ + * app.buildOptionItem(SELECTION_KEY_ONE, + * ['synonym of KEY_ONE 1', 'synonym of KEY_ONE 2']) + * .setTitle('Number one'), + * app.buildOptionItem(SELECTION_KEY_TWO, + * ['synonym of KEY_TWO 1', 'synonym of KEY_TWO 2']) + * .setTitle('Number two'), + * ])); + * } + * + * function optionIntent (app) { + * if (app.getSelectedOption() === SELECTION_KEY_ONE) { + * app.tell('Number one is a great choice!'); + * } else { + * app.tell('Number two is a great choice!'); + * } + * } + * + * const actionMap = new Map(); + * actionMap.set(WELCOME_INTENT, welcomeIntent); + * actionMap.set(OPTION_INTENT, optionIntent); + * app.handleRequest(actionMap); + * + * @param {string|RichResponse|SimpleResponse} inputPrompt The input prompt + * response. + * @param {Carousel} carousel Carousel built with + * {@link AssistantApp#buildCarousel|buildCarousel}. + * @return {Object} HTTP response. + * @dialogflow + */ + askWithCarousel (inputPrompt, carousel) { + debug('askWithCarousel: inputPrompt=%s, carousel=%s', + inputPrompt, JSON.stringify(carousel)); + if (!inputPrompt) { + this.handleError_('Invalid input prompt'); + return null; + } + if (!carousel || typeof carousel !== 'object') { + this.handleError_('Invalid carousel'); + return null; + } + if (carousel.items.length < 2) { + this.handleError_('Carousel requires at least 2 items'); + return null; + } + const response = this.buildResponse_(inputPrompt, true); + if (!response) { + error('Error in building response'); + return null; + } + response.data.google.systemIntent = { + intent: this.StandardIntents.OPTION + }; + if (this.isNotApiVersionOne_()) { + response.data.google.systemIntent.data = Object.assign({ + [this.ANY_TYPE_PROPERTY_]: this.InputValueDataTypes_.OPTION + }, { + carouselSelect: carousel + }); + } else { + response.data.google.systemIntent.spec = { + optionValueSpec: { + carouselSelect: carousel + } + }; + } + return this.doResponse_(response, RESPONSE_CODE_OK); + } + + /** + * Tells the Assistant to render the speech response and close the mic. + * + * @example + * const app = new DialogflowApp({request: request, response: response}); + * const WELCOME_INTENT = 'input.welcome'; + * const NUMBER_INTENT = 'input.number'; + * + * function welcomeIntent (app) { + * app.ask('Welcome to action snippets! Say a number.'); + * } + * + * function numberIntent (app) { + * const number = app.getArgument(NUMBER_ARGUMENT); + * app.tell('You said ' + number); + * } + * + * const actionMap = new Map(); + * actionMap.set(WELCOME_INTENT, welcomeIntent); + * actionMap.set(NUMBER_INTENT, numberIntent); + * app.handleRequest(actionMap); + * + * @param {string|SimpleResponse|RichResponse} speechResponse Final response. + * Spoken response can be SSML. + * @return {(Object|null)} The response that is sent back to Assistant. + * @dialogflow + */ + tell (speechResponse) { + debug('tell: speechResponse=%s', speechResponse); + if (!speechResponse) { + this.handleError_('Invalid speech response'); + return null; + } + const response = this.buildResponse_(speechResponse, false); + return this.doResponse_(response, RESPONSE_CODE_OK); + } + + /** + * Set a new context for the current intent. + * + * @example + * const app = new DialogflowApp({request: request, response: response}); + * const CONTEXT_NUMBER = 'number'; + * const NUMBER_ARGUMENT = 'myNumber'; + * + * function welcomeIntent (app) { + * app.setContext(CONTEXT_NUMBER); + * app.ask('Welcome to action snippets! Say a number.'); + * } + * + * function numberIntent (app) { + * const number = app.getArgument(NUMBER_ARGUMENT); + * app.tell('You said ' + number); + * } + * + * const actionMap = new Map(); + * actionMap.set(WELCOME_INTENT, welcomeIntent); + * actionMap.set(NUMBER_INTENT, numberIntent); + * app.handleRequest(actionMap); + * + * @param {string} name Name of the context. Dialogflow converts to lowercase. + * @param {int} [lifespan=1] Context lifespan. + * @param {Object=} parameters Context JSON parameters. + * @return {null|undefined} Null if the context name is not defined. + * @dialogflow + */ + setContext (name, lifespan, parameters) { + debug('setContext: context=%s, lifespan=%d, parameters=%s', name, lifespan, + JSON.stringify(parameters)); + if (!name) { + error('Empty context name'); + return null; + } + const newContext = { + name: name, + lifespan: 1 + }; + if (lifespan !== null && lifespan !== undefined) { + newContext.lifespan = lifespan; + } + if (parameters) { + newContext.parameters = parameters; + } + this.contexts_[name] = newContext; + } + + /** + * Dialogflow {@link https://dialogflow.com/docs/concept-contexts|Context}. + * @typedef {Object} Context + * @property {string} name - Full name of the context. + * @property {Object} parameters - Parameters carried within this context. + See {@link https://dialogflow.com/docs/concept-actions#section-extracting-values-from-contexts|here}. + * @property {number} lifespan - Remaining number of intents + */ + + /** + * Returns the incoming contexts for this intent. + * + * @example + * const app = new DialogflowApp({request: request, response: response}); + * const CONTEXT_NUMBER = 'number'; + * const NUMBER_ARGUMENT = 'myNumber'; + * + * function welcomeIntent (app) { + * app.setContext(CONTEXT_NUMBER); + * app.ask('Welcome to action snippets! Say a number.'); + * } + * + * function numberIntent (app) { + * let contexts = app.getContexts(); + * // contexts === [{ + * // name: 'number', + * // lifespan: 0, + * // parameters: { + * // myNumber: '23', + * // myNumber.original: '23' + * // } + * // }] + * const number = app.getArgument(NUMBER_ARGUMENT); + * app.tell('You said ' + number); + * } + * + * const actionMap = new Map(); + * actionMap.set(WELCOME_INTENT, welcomeIntent); + * actionMap.set(NUMBER_INTENT, numberIntent); + * app.handleRequest(actionMap); + * + * @return {Context[]} Empty if no active contexts. + * @dialogflow + */ + getContexts () { + debug('getContexts'); + if (!this.body_.result || + !this.body_.result.contexts) { + error('No contexts included in request'); + return null; + } + return this.body_.result.contexts.filter((context) => { + return context.name !== ACTIONS_DIALOGFLOW_CONTEXT; + }); + } + + /** + * Returns the incoming context by name for this intent. + * + * @example + * const app = new DialogflowApp({request: request, response: response}); + * const CONTEXT_NUMBER = 'number'; + * const NUMBER_ARGUMENT = 'myNumber'; + * + * function welcomeIntent (app) { + * app.setContext(CONTEXT_NUMBER); + * app.ask('Welcome to action snippets! Say a number.'); + * } + * + * function numberIntent (app) { + * let context = app.getContext(CONTEXT_NUMBER); + * // context === { + * // name: 'number', + * // lifespan: 0, + * // parameters: { + * // myNumber: '23', + * // myNumber.original: '23' + * // } + * // } + * const number = app.getArgument(NUMBER_ARGUMENT); + * app.tell('You said ' + number); + * } + * + * const actionMap = new Map(); + * actionMap.set(WELCOME_INTENT, welcomeIntent); + * actionMap.set(NUMBER_INTENT, numberIntent); + * app.handleRequest(actionMap); + * + * @param {string} name The name of the Context to retrieve. + * @return {Object} Context value matching name + * or null if no matching context. + * @dialogflow + */ + getContext (name) { + debug('getContext: name=%s', name); + if (!this.body_.result || + !this.body_.result.contexts) { + error('No contexts included in request'); + return null; + } + for (let context of this.body_.result.contexts) { + if (context.name === name) { + return context; + } + } + debug('Failed to get context: %s', name); + return null; + } + + /** + * Gets the user's raw input query. + * + * @example + * const app = new DialogflowApp({request: request, response: response}); + * app.tell('You said ' + app.getRawInput()); + * + * @return {string} User's raw query or null if no value. + * @dialogflow + */ + getRawInput () { + debug('getRawInput'); + if (!this.body_.result || + !this.body_.result.resolvedQuery) { + error('No raw input'); + return null; + } + return this.body_.result.resolvedQuery; + } + + // --------------------------------------------------------------------------- + // Private Helpers + // --------------------------------------------------------------------------- + + /** + * Get the current intent. + * + * @return {string} The intent id. + * @private + * @dialogflow + */ + getIntent_ () { + debug('getIntent_'); + if (this.body_.result) { + return this.body_.result.action; + } else { + error('Missing result from request body'); + return null; + } + } + + /** + * Builds a response for Dialogflow to send back to the Assistant. + * + * @param {string|RichResponse|SimpleResponse} textToSpeech TTS/response + * spoken/shown to end user. + * @param {boolean} expectUserResponse true if the user response is expected. + * @param {Array=} noInputs Array of re-prompts when the user does not respond (max 3). + * @return {Object} The final response returned to Assistant. + * @private + * @dialogflow + */ + buildResponse_ (textToSpeech, expectUserResponse, noInputs) { + debug('buildResponse_: textToSpeech=%s, expectUserResponse=%s, noInputs=%s', + textToSpeech, expectUserResponse, noInputs); + if (!textToSpeech === undefined || !textToSpeech) { + error('Empty text to speech'); + return null; + } + let isStringResponse = typeof textToSpeech === 'string'; + if (!isStringResponse) { + if (textToSpeech.speech) { + // Convert SimpleResponse to RichResponse + textToSpeech = this.buildRichResponse().addSimpleResponse(textToSpeech); + } else if (!(textToSpeech.items && + textToSpeech.items[0] && + textToSpeech.items[0].simpleResponse)) { + error('Invalid RichResponse. First item must be SimpleResponse'); + return null; + } + } + const dialogState = { + 'state': (this.state instanceof State ? this.state.getName() : this.state), + 'data': this.data + }; + if (noInputs) { + if (noInputs.length > INPUTS_MAX) { + error('Invalid number of no inputs'); + return null; + } + if (this.isSsml_(textToSpeech)) { + noInputs = this.buildPromptsFromSsmlHelper_(noInputs); + } else { + noInputs = this.buildPromptsFromPlainTextHelper_(noInputs); + } + } else { + noInputs = []; + } + const response = { + speech: isStringResponse ? textToSpeech + : textToSpeech.items[0].simpleResponse.textToSpeech, + contextOut: [] + }; + response.data = isStringResponse ? { + google: { + expectUserResponse: expectUserResponse, + isSsml: this.isSsml_(textToSpeech), + noInputPrompts: noInputs + } + } : { + google: { + expectUserResponse: expectUserResponse, + richResponse: textToSpeech, + noInputPrompts: noInputs + } + }; + if (expectUserResponse) { + response.contextOut.push({ + name: ACTIONS_DIALOGFLOW_CONTEXT, + lifespan: MAX_LIFESPAN, + parameters: dialogState.data + }); + } + for (let context of Object.keys(this.contexts_)) { + response.contextOut.push(this.contexts_[context]); + } + return response; + } + + /** + * Extract the session data from the incoming JSON request. + * + * @return {undefined} + * @private + * @dialogflow + */ + extractData_ () { + debug('extractData_'); + if (this.body_.result && this.body_.result.contexts.length > 0) { + for (let i = 0; i < this.body_.result.contexts.length; i++) { + if (this.body_.result.contexts[i].name === ACTIONS_DIALOGFLOW_CONTEXT) { + const parameters = this.body_.result.contexts[i].parameters; + if (parameters) { + this.data = parameters; + } else { + this.data = {}; + } + break; + } + } + } else { + this.data = {}; + } + } + + /** + * Uses a PermissionsValueSpec object to construct and send a + * permissions request to the user. + * + * @param {Object} permissionsSpec PermissionsValueSpec object containing + * the permissions prefix and permissions requested. + * @return {Object} The HTTP response. + * @private + * @dialogflow + */ + fulfillPermissionsRequest_ (permissionsSpec) { + debug('fulfillPermissionsRequest_: permissionsSpec=%s', + JSON.stringify(permissionsSpec)); + const inputPrompt = 'PLACEHOLDER_FOR_PERMISSION'; + if (this.isNotApiVersionOne_()) { + return this.fulfillSystemIntent_(this.StandardIntents.PERMISSION, + this.InputValueDataTypes_.PERMISSION, permissionsSpec, + inputPrompt); + } else { + const response = this.buildResponse_(inputPrompt, true); + response.data.google.systemIntent = { + intent: this.StandardIntents.PERMISSION + }; + response.data.google.systemIntent.spec = { + permissionValueSpec: permissionsSpec + }; + return this.doResponse_(response, RESPONSE_CODE_OK); + } + } + + /** + * Uses a given intent spec to construct and send a non-TEXT intent response + * to Google. + * + * @param {string} intent Name of the intent to fulfill. One of + * {@link AssistantApp#StandardIntents|StandardIntents}. + * @param {string} specType Type of the related intent spec. One of + * {@link AssistantApp#InputValueDataTypes_|InputValueDataTypes_}. + * @param {Object} intentSpec Intent Spec object. Pass {} to leave empty. + * @param {string=} promptPlaceholder Some placeholder text for the response + * prompt. Default is 'PLACEHOLDER_FOR_INTENT'. + * @param {Object=} dialogState JSON object the app uses to hold dialog state that + * will be circulated back by Assistant. + * @return {Object} HTTP response. + * @private + * @dialogflow + */ + fulfillSystemIntent_ (intent, specType, intentSpec, promptPlaceholder, + dialogState) { + debug('fulfillSystemIntent_: intent=%s, specType=%s, intentSpec=%s, ' + + 'promptPlaceholder=%s dialogState=%s', intent, specType, + JSON.stringify(intentSpec), promptPlaceholder, JSON.stringify(dialogState)); + const response = this.buildResponse_(promptPlaceholder || + 'PLACEHOLDER_FOR_INTENT', true); + response.data.google.systemIntent = { intent }; + response.data.google.systemIntent.data = {}; + if (intentSpec) { + response.data.google.systemIntent.data = Object.assign({ + [this.ANY_TYPE_PROPERTY_]: specType + }, intentSpec); + } + return this.doResponse_(response, RESPONSE_CODE_OK); + } +} + +module.exports = DialogflowApp; diff --git a/types/actions-on-google/staging/response-builder.js b/types/actions-on-google/staging/response-builder.js new file mode 100644 index 0000000000..6e6238eeee --- /dev/null +++ b/types/actions-on-google/staging/response-builder.js @@ -0,0 +1,800 @@ +/** + * Copyright 2017 Google Inc. All Rights Reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +/** + * A collection of response builders. + */ + +'use strict'; + +const Debug = require('debug'); +const debug = Debug('actions-on-google:debug'); +const warn = Debug('actions-on-google:warn'); +const error = Debug('actions-on-google:error'); + +const LIST_ITEM_LIMIT = 30; +const CAROUSEL_ITEM_LIMIT = 10; + +/** + * Simple Response type. + * @typedef {Object} SimpleResponse + * @property {string} speech - Speech to be spoken to user. SSML allowed. + * @property {string} displayText - Optional text to be shown to user + */ + +/** + * Suggestions to show with response. + * @typedef {Object} Suggestion + * @property {string} title - Text of the suggestion. + */ + +/** + * Link Out Suggestion. Used in rich response as a suggestion chip which, when + * selected, links out to external URL. + * @typedef {Object} LinkOutSuggestion + * @property {string} title - Text shown on the suggestion chip. + * @property {string} url - String URL to open. + */ + +/** + * Image type shown on visual elements. + * @typedef {Object} Image + * @property {string} url - Image source URL. + * @property {string} accessibilityText - Text to replace for image for + * accessibility. + * @property {number} width - Width of the image. + * @property {number} height - Height of the image. + */ + +/** + * Basic Card Button. Shown below basic cards. Open a URL when selected. + * @typedef {Object} Button + * @property {string} title - Text shown on the button. + * @property {Object} openUrlAction - Action to take when selected. + * @property {string} openUrlAction.url - String URL to open. + */ + +/** + * Option item. Used in actions.intent.OPTION intent. + * @typedef {Object} OptionItem + * @property {OptionInfo} optionInfo - Option item identifier information. + * @property {string} title - Name of the item. + * @property {string} description - Optional text describing the item. + * @property {Image} image - Square image to show for this item. + */ + +/** + * Option info. Provides unique identifier for a given OptionItem. + * @typedef {Object} OptionInfo + * @property {string} key - Unique string ID for this option. + * @property {Array} synonyms - Synonyms that can be used by the user + * to indicate this option if they do not use the key. + */ + +/** + * Class for initializing and constructing Rich Responses with chainable interface. + */ +const RichResponse = class { + /** + * Constructor for RichResponse. Accepts optional RichResponse to clone. + * + * @param {RichResponse=} richResponse Optional RichResponse to clone. + */ + constructor (richResponse) { + /** + * Ordered list of either SimpleResponse objects or BasicCard objects. + * First item must be SimpleResponse. There can be at most one card. + * @type {Array} + */ + this.items = []; + + /** + * Ordered list of text suggestions to display. Optional. + * @type {Array} + */ + this.suggestions = []; + + /** + * Link Out Suggestion chip for this rich response. Optional. + * @type {LinkOutSuggestion} + */ + this.linkOutSuggestion = undefined; + + if (richResponse) { + if (richResponse.items) { + this.items = richResponse.items; + for (let item of this.items) { + if (item.basicCard) { + item.basicCard = new BasicCard(item.basicCard); + } + } + } + if (richResponse.suggestions) { + this.suggestions = richResponse.suggestions; + } + if (richResponse.linkOutSuggestion) { + this.linkOutSuggestion = richResponse.linkOutSuggestion; + } + } + } + + /** + * Adds a SimpleResponse to list of items. + * + * @param {string|SimpleResponse} simpleResponse Simple response to present to + * user. If just a string, display text will not be set. + * @return {RichResponse} Returns current constructed RichResponse. + */ + addSimpleResponse (simpleResponse) { + if (!simpleResponse) { + error('Invalid simpleResponse'); + return this; + } + // Validate if RichResponse already contains two SimpleResponse objects + let simpleResponseCount = 0; + for (let item of this.items) { + if (item.simpleResponse) { + simpleResponseCount++; + } + if (simpleResponseCount >= 2) { + error('Cannot include >2 SimpleResponses in RichResponse'); + return this; + } + } + const simpleResponseObj = { + simpleResponse: this.buildSimpleResponseHelper_(simpleResponse) + }; + // Check first if needs to replace BasicCard at beginning of items list + if (this.items.length > 0 && (this.items[0].basicCard || + this.items[0].structuredResponse)) { + this.items.unshift(simpleResponseObj); + } else { + this.items.push(simpleResponseObj); + } + return this; + } + + /** + * Adds a BasicCard to list of items. + * + * @param {BasicCard} basicCard Basic card to include in response. + * @return {RichResponse} Returns current constructed RichResponse. + */ + addBasicCard (basicCard) { + if (!basicCard) { + error('Invalid basicCard'); + return this; + } + // Validate if basic card is already present + for (let item of this.items) { + if (item.basicCard) { + error('Cannot include >1 BasicCard in RichResponse'); + return this; + } + } + this.items.push({ + basicCard: basicCard + }); + return this; + } + + /** + * Adds a single suggestion or list of suggestions to list of items. + * + * @param {string|Array} suggestions Either a single string suggestion + * or list of suggestions to add. + * @return {RichResponse} Returns current constructed RichResponse. + */ + addSuggestions (suggestions) { + if (!suggestions) { + error('Invalid suggestions'); + return this; + } + if (Array.isArray(suggestions)) { + for (let suggestion of suggestions) { + if (this.isValidSuggestionText(suggestion)) { + this.suggestions.push({title: suggestion}); + } else { + warn('Suggestion text can\'t be longer than 25 characters: ' + suggestion + + '. This suggestion won\'t be added to the list.'); + } + } + } else { + if (this.isValidSuggestionText(suggestions)) { + this.suggestions.push({title: suggestions}); + } else { + warn('Suggestion text can\'t be longer than 25 characters: ' + suggestions + + '. This suggestion won\'t be added to the list.'); + } + } + return this; + } + + /** + * Returns true if the given suggestion text is valid to be added to the suggestion list. A valid + * text string is not longer than 25 characters. + * + * @param {string} suggestionText Text to validate as suggestion. + * @return {boolean} True if the text is valid, false otherwise.s + */ + isValidSuggestionText (suggestionText) { + return suggestionText && suggestionText.length && suggestionText.length <= 25; + } + + /** + * Sets the suggestion link for this rich response. + * + * @param {string} destinationName Name of the link out destination. + * @param {string} suggestionUrl - String URL to open when suggestion is used. + * @return {RichResponse} Returns current constructed RichResponse. + */ + addSuggestionLink (destinationName, suggestionUrl) { + if (!destinationName) { + error('destinationName cannot be empty'); + return this; + } + if (!suggestionUrl) { + error('suggestionUrl cannot be empty'); + return this; + } + this.linkOutSuggestion = { + destinationName: destinationName, + url: suggestionUrl + }; + return this; + } + + /** + * Adds an order update to this response. Use after a successful transaction + * decision to confirm the order. + * + * @param {OrderUpdate} orderUpdate OrderUpdate object to add. + * @return {RichResponse} Returns current constructed RichResponse. + */ + addOrderUpdate (orderUpdate) { + if (!orderUpdate) { + error('Invalid orderUpdate'); + return this; + } + // Validate if RichResponse already contains StructuredResponse object + for (let item of this.items) { + if (item.structuredResponse) { + debug('Cannot include >1 StructuredResponses in RichResponse'); + return this; + } + } + this.items.push({ + structuredResponse: { + orderUpdate: orderUpdate + } + }); + return this; + } + + /** + * Helper to build SimpleResponse from speech and display text. + * + * @param {string|SimpleResponse} response String to speak, or SimpleResponse. + * SSML allowed. + * @param {string} response.speech If using SimpleResponse, speech to be spoken + * to user. + * @param {string=} response.displayText If using SimpleResponse, text to be shown + * to user. + * @return {Object} Appropriate SimpleResponse object. + * @private + */ + buildSimpleResponseHelper_ (response) { + if (!response) { + error('Invalid response'); + return null; + } + debug('buildSimpleResponseHelper_: response=%s', JSON.stringify(response)); + let simpleResponseObj = {}; + if (typeof response === 'string') { + simpleResponseObj = isSsml(response) + ? { ssml: response } : { textToSpeech: response }; + } else if (response.speech) { + simpleResponseObj = isSsml(response.speech) + ? { ssml: response.speech } : { textToSpeech: response.speech }; + simpleResponseObj.displayText = response.displayText; + } else { + error('SimpleResponse requires a speech parameter.'); + return null; + } + return simpleResponseObj; + } +}; + +/** + * Class for initializing and constructing Basic Cards with chainable interface. + */ +const BasicCard = class { + /** + * Constructor for BasicCard. Accepts optional BasicCard to clone. + * + * @param {BasicCard=} basicCard Optional BasicCard to clone. + */ + constructor (basicCard) { + /** + * Title of the card. Optional. + * @type {string} + */ + this.title = undefined; + + /** + * Body text to show on the card. Required, unless image is present. + * @type {string} + */ + this.formattedText = ''; + + /** + * Subtitle of the card. Optional. + * @type {string} + */ + this.subtitle = undefined; + + /** + * Image to show on the card. Optional. + * @type {Image} + */ + this.image = undefined; + + /** + * Ordered list of buttons to show below card. Optional. + * @type {Array