Skip to main content

Replicache

Classes

Interfaces

Type Aliases

ClientGroupID

Ƭ ClientGroupID: string

The ID describing a group of clients. All clients in the same group share a persistent storage (IDB).


ClientID

Ƭ ClientID: string

The ID describing a client.


ClientStateNotFoundResponse

Ƭ ClientStateNotFoundResponse: Object

In certain scenarios the server can signal that it does not know about the client. For example, the server might have lost all of its state (this might happen during the development of the server).

Type declaration

NameType
error"ClientStateNotFound"

Ƭ Cookie: null | string | number | ReadonlyJSONValue & { order: number | string }

A cookie is a value that is used to determine the order of snapshots. It needs to be comparable. This can be a string, number or if you want to use a more complex value, you can use an object with an order property. The value null is considered to be less than any other cookie and it is used for the first pull when no cookie has been set.

The order is the natural order of numbers and strings. If one of the cookies is an object then the value of the order property is treated as the cookie when doing comparison.

If one of the cookies is a string and the other is a number, the number is fist converted to a string (using toString()).


CreateIndexDefinition

Ƭ CreateIndexDefinition: IndexDefinition & { name: string }


CreateKVStore

Ƭ CreateKVStore: (name: string) => KVStore

Type declaration

▸ (name): KVStore

Factory function for creating KVStore instances.

The name is used to identify the store. If the same name is used for multiple stores, they should share the same data. It is also desirable to have these stores share an RWLock.

Parameters
NameType
namestring
Returns

KVStore


DeepReadonly

Ƭ DeepReadonly<T>: T extends null | boolean | string | number | undefined ? T : DeepReadonlyObject<T>

Basic deep readonly type. It works for JSONValue.

Type parameters

Name
T

DeepReadonlyObject

Ƭ DeepReadonlyObject<T>: { readonly [K in keyof T]: DeepReadonly<T[K]> }

Type parameters

Name
T

DropDatabaseOptions

Ƭ DropDatabaseOptions: Object

Options for dropDatabase and dropAllDatabases.

Type declaration

NameTypeDescription
kvStore?"idb" | "mem" | KVStoreProviderAllows providing a custom implementation of the underlying storage layer. Default is 'idb'.
logLevel?LogLevelDetermines how much logging to do. When this is set to 'debug', Replicache will also log 'info' and 'error' messages. When set to 'info' we log 'info' and 'error' but not 'debug'. When set to 'error' we only log 'error' messages. Default is 'info'.
logSinks?LogSink[]Enables custom handling of logs. By default logs are logged to the console. If you would like logs to be sent elsewhere (e.g. to a cloud logging service like DataDog) you can provide an array of LogSinks. Logs at or above logLevel are sent to each of these LogSinks. If you would still like logs to go to the console, include consoleLogSink in the array. ts logSinks: [consoleLogSink, myCloudLogSink], Default is [consoleLogSink].

DropKVStore

Ƭ DropKVStore: (name: string) => Promise<void>

Type declaration

▸ (name): Promise<void>

Function for deleting KVStore instances.

The name is used to identify the store. If the same name is used for multiple stores, they should share the same data.

Parameters
NameType
namestring
Returns

Promise<void>


ExperimentalDiff

Ƭ ExperimentalDiff: ExperimentalIndexDiff | ExperimentalNoIndexDiff

Describes the changes that happened to Replicache after a WriteTransaction was committed.

This type is experimental and may change in the future.


ExperimentalDiffOperation

Ƭ ExperimentalDiffOperation<Key>: ExperimentalDiffOperationAdd<Key> | ExperimentalDiffOperationDel<Key> | ExperimentalDiffOperationChange<Key>

The individual parts describing the changes that happened to the Replicache data. There are three different kinds of operations:

  • add: A new entry was added.

  • del: An entry was deleted.

  • change: An entry was changed.

    This type is experimental and may change in the future.

Type parameters

Name
Key

ExperimentalDiffOperationAdd

Ƭ ExperimentalDiffOperationAdd<Key, Value>: Object

Type parameters

NameType
KeyKey
ValueReadonlyJSONValue

Type declaration

NameType
keyKey
newValueValue
op"add"

ExperimentalDiffOperationChange

Ƭ ExperimentalDiffOperationChange<Key, Value>: Object

Type parameters

NameType
KeyKey
ValueReadonlyJSONValue

Type declaration

NameType
keyKey
newValueValue
oldValueValue
op"change"

ExperimentalDiffOperationDel

Ƭ ExperimentalDiffOperationDel<Key, Value>: Object

Type parameters

NameType
KeyKey
ValueReadonlyJSONValue

Type declaration

NameType
keyKey
oldValueValue
op"del"

ExperimentalIndexDiff

Ƭ ExperimentalIndexDiff: readonly ExperimentalDiffOperation<IndexKey>[]

This type is experimental and may change in the future.


ExperimentalNoIndexDiff

Ƭ ExperimentalNoIndexDiff: readonly ExperimentalDiffOperation<string>[]

This type is experimental and may change in the future.


ExperimentalWatchCallbackForOptions

Ƭ ExperimentalWatchCallbackForOptions<Options>: Options extends ExperimentalWatchIndexOptions ? ExperimentalWatchIndexCallback : ExperimentalWatchNoIndexCallback

Type parameters

NameType
Optionsextends ExperimentalWatchOptions

ExperimentalWatchIndexCallback

Ƭ ExperimentalWatchIndexCallback: (diff: ExperimentalIndexDiff) => void

Type declaration

▸ (diff): void

Function that gets passed into experimentalWatch when doing a watch on a secondary index map and gets called when the data in Replicache changes.

This type is experimental and may change in the future.

Parameters
NameType
diffExperimentalIndexDiff
Returns

void


ExperimentalWatchIndexOptions

Ƭ ExperimentalWatchIndexOptions: ExperimentalWatchNoIndexOptions & { indexName: string }

Options object passed to experimentalWatch. This is for an index watch.


ExperimentalWatchNoIndexCallback

Ƭ ExperimentalWatchNoIndexCallback: (diff: ExperimentalNoIndexDiff) => void

Type declaration

▸ (diff): void

Function that gets passed into experimentalWatch and gets called when the data in Replicache changes.

This type is experimental and may change in the future.

Parameters
NameType
diffExperimentalNoIndexDiff
Returns

void


ExperimentalWatchNoIndexOptions

Ƭ ExperimentalWatchNoIndexOptions: Object

Options object passed to experimentalWatch. This is for a non index watch.

Type declaration

NameTypeDescription
initialValuesInFirstDiff?booleanWhen this is set to true (default is false), the watch callback will be called once asynchronously when watch is called. The arguments in that case is a diff where we consider all the existing values in Replicache as being added.
prefix?stringWhen provided, the watch is limited to changes where the key starts with prefix.

ExperimentalWatchOptions

Ƭ ExperimentalWatchOptions: ExperimentalWatchIndexOptions | ExperimentalWatchNoIndexOptions

Options for experimentalWatch.

This interface is experimental and may change in the future.


GetIndexScanIterator

Ƭ GetIndexScanIterator: (indexName: string, fromSecondaryKey: string, fromPrimaryKey: string | undefined) => IterableUnion<readonly [key: IndexKey, value: ReadonlyJSONValue]>

Type declaration

▸ (indexName, fromSecondaryKey, fromPrimaryKey): IterableUnion<readonly [key: IndexKey, value: ReadonlyJSONValue]>

When using makeScanResult this is the type used for the function called when doing a scan with an indexName.

Parameters
NameTypeDescription
indexNamestringThe name of the index we are scanning over.
fromSecondaryKeystringThe fromSecondaryKey is computed by scan and is the secondary key of the first entry to return in the iterator. It is based on prefix and start.key of the ScanIndexOptions.
fromPrimaryKeystring | undefinedThe fromPrimaryKey is computed by scan and is the primary key of the first entry to return in the iterator. It is based on prefix and start.key of the ScanIndexOptions.
Returns

IterableUnion<readonly [key: IndexKey, value: ReadonlyJSONValue]>


GetScanIterator

Ƭ GetScanIterator: (fromKey: string) => IterableUnion<Entry<ReadonlyJSONValue>>

Type declaration

▸ (fromKey): IterableUnion<Entry<ReadonlyJSONValue>>

This is called when doing a scan without an indexName.

Parameters
NameTypeDescription
fromKeystringThe fromKey is computed by scan and is the key of the first entry to return in the iterator. It is based on prefix and start.key of the ScanNoIndexOptions.
Returns

IterableUnion<Entry<ReadonlyJSONValue>>


HTTPRequestInfo

Ƭ HTTPRequestInfo: Object

Type declaration

NameType
errorMessagestring
httpStatusCodenumber

IndexDefinition

Ƭ IndexDefinition: Object

The definition of a single index.

Type declaration

NameTypeDescription
allowEmpty?booleanIf true, indexing empty values will not emit a warning. Defaults to false.
jsonPointerstringA JSON Pointer pointing at the sub value inside each value to index over. For example, one might index over users' ages like so: {prefix: '/user/', jsonPointer: '/age'}
prefix?stringThe prefix, if any, to limit the index over. If not provided the values of all keys are indexed.

IndexDefinitions

Ƭ IndexDefinitions: Object

An object as a map defining the indexes. The keys are the index names and the values are the index definitions.

Index signature

[name: string]: IndexDefinition


IndexKey

Ƭ IndexKey: readonly [secondary: string, primary: string]

When using indexes the key is a tuple of the secondary key and the primary key.


IterableUnion

Ƭ IterableUnion<T>: AsyncIterable<T> | Iterable<T>

Type parameters

Name
T

JSONObject

Ƭ JSONObject: Object

A JSON object. This is a map from strings to JSON values or undefined. We allow undefined values as a convenience... but beware that the undefined values do not round trip to the server. For example:

// Time t1
await tx.set('a', {a: undefined});

// time passes, in a new transaction
const v = await tx.get('a');
console.log(v); // either {a: undefined} or {}

Index signature

[key: string]: JSONValue | undefined


JSONValue

Ƭ JSONValue: null | string | boolean | number | JSONValue[] | JSONObject

The values that can be represented in JSON


KVStoreProvider

Ƭ KVStoreProvider: Object

Provider for creating and deleting KVStore instances.

Type declaration

NameType
createCreateKVStore
dropDropKVStore

KeyTypeForScanOptions

Ƭ KeyTypeForScanOptions<O>: O extends ScanIndexOptions ? IndexKey : string

If the options contains an indexName then the key type is a tuple of secondary and primary.

Type parameters

NameType
Oextends ScanOptions

LogLevel

Ƭ LogLevel: "error" | "info" | "debug"

The different log levels. This is used to determine how much logging to do. 'error' > 'info' > 'debug'... meaning 'error' has highest priority and 'debug' lowest.


MaybePromise

Ƭ MaybePromise<T>: T | Promise<T>

Type parameters

Name
T

MutationV0

Ƭ MutationV0: Object

Mutation describes a single mutation done on the client. This is the legacy version (V0) and it is used when recovering mutations from old clients.

Type declaration

NameType
argsReadonlyJSONValue
idnumber
namestring
timestampnumber

MutationV1

Ƭ MutationV1: Object

Mutation describes a single mutation done on the client.

Type declaration

NameType
argsReadonlyJSONValue
clientIDClientID
idnumber
namestring
timestampnumber

MutatorDefs

Ƭ MutatorDefs: Object

Index signature

[key: string]: (tx: WriteTransaction, args?: any) => MutatorReturn


MutatorReturn

Ƭ MutatorReturn<T>: MaybePromise<T | void>

Type parameters

NameType
Textends ReadonlyJSONValue = ReadonlyJSONValue

PatchOperation

Ƭ PatchOperation: { key: string ; op: "put" ; value: ReadonlyJSONValue } | { key: string ; op: "del" } | { op: "clear" }

This type describes the patch field in a PullResponse and it is used to describe how to update the Replicache key-value store.


PendingMutation

Ƭ PendingMutation: Object

Type declaration

NameType
argsReadonlyJSONValue
clientIDClientID
idnumber
namestring

Poke

Ƭ Poke: Object

Type declaration

NameType
baseCookieReadonlyJSONValue
pullResponsePullResponseV1

PullRequest

Ƭ PullRequest: PullRequestV1 | PullRequestV0

The JSON value used as the body when doing a POST to the pull endpoint.


PullRequestV0

Ƭ PullRequestV0: Object

The JSON value used as the body when doing a POST to the pull endpoint. This is the legacy version (V0) and it is still used when recovering mutations from old clients.

Type declaration

NameType
clientIDClientID
cookieReadonlyJSONValue
lastMutationIDnumber
profileIDstring
pullVersion0
schemaVersionstring

PullRequestV1

Ƭ PullRequestV1: Object

The JSON value used as the body when doing a POST to the pull endpoint.

Type declaration

NameType
clientGroupIDClientGroupID
cookieCookie
profileIDstring
pullVersion1
schemaVersionstring

PullResponse

Ƭ PullResponse: PullResponseV1 | PullResponseV0


PullResponseOKV0

Ƭ PullResponseOKV0: Object

The shape of a pull response under normal circumstances.

Type declaration

NameType
cookie?ReadonlyJSONValue
lastMutationIDnumber
patchPatchOperation[]

PullResponseOKV1

Ƭ PullResponseOKV1: Object

The shape of a pull response under normal circumstances.

Type declaration

NameType
cookieCookie
lastMutationIDChangesRecord<ClientID, number>
patchPatchOperation[]

PullResponseV0

Ƭ PullResponseV0: PullResponseOKV0 | ClientStateNotFoundResponse | VersionNotSupportedResponse

PullResponse defines the shape and type of the response of a pull. This is the JSON you should return from your pull server endpoint.


PullResponseV1

Ƭ PullResponseV1: PullResponseOKV1 | ClientStateNotFoundResponse | VersionNotSupportedResponse

PullResponse defines the shape and type of the response of a pull. This is the JSON you should return from your pull server endpoint.


Puller

Ƭ Puller: (requestBody: PullRequest, requestID: string) => Promise<PullerResult>

Type declaration

▸ (requestBody, requestID): Promise<PullerResult>

Puller is the function type used to do the fetch part of a pull.

Puller needs to support dealing with pull request of version 0 and 1. Version 0 is used when doing mutation recovery of old clients. If a PullRequestV1 is passed in the n a PullerResultV1 should be returned. We do a runtime assert to make this is the case.

If you do not support old clients you can just throw if pullVersion is 0,

Parameters
NameType
requestBodyPullRequest
requestIDstring
Returns

Promise<PullerResult>


PullerResult

Ƭ PullerResult: PullerResultV1 | PullerResultV0


PullerResultV0

Ƭ PullerResultV0: Object

Type declaration

NameType
httpRequestInfoHTTPRequestInfo
response?PullResponseV0

PullerResultV1

Ƭ PullerResultV1: Object

Type declaration

NameType
httpRequestInfoHTTPRequestInfo
response?PullResponseV1

PushRequest

Ƭ PushRequest: PushRequestV0 | PushRequestV1


PushRequestV0

Ƭ PushRequestV0: Object

The JSON value used as the body when doing a POST to the push endpoint. This is the legacy version (V0) and it is still used when recovering mutations from old clients.

Type declaration

NameTypeDescription
clientIDClientID-
mutationsMutationV0[]-
profileIDstring-
pushVersion0-
schemaVersionstringschemaVersion can optionally be used to specify to the push endpoint version information about the mutators the app is using (e.g., format of mutator args).

PushRequestV1

Ƭ PushRequestV1: Object

The JSON value used as the body when doing a POST to the push endpoint.

Type declaration

NameTypeDescription
clientGroupIDClientGroupID-
mutationsMutationV1[]-
profileIDstring-
pushVersion1-
schemaVersionstringschemaVersion can optionally be used to specify to the push endpoint version information about the mutators the app is using (e.g., format of mutator args).

PushResponse

Ƭ PushResponse: ClientStateNotFoundResponse | VersionNotSupportedResponse

The response from a push can contain information about error conditions.


Pusher

Ƭ Pusher: (requestBody: PushRequest, requestID: string) => Promise<PusherResult>

Type declaration

▸ (requestBody, requestID): Promise<PusherResult>

Pusher is the function type used to do the fetch part of a push. The request is a POST request where the body is JSON with the type PushRequest.

The return value should either be a HTTPRequestInfo or a PusherResult. The reason for the two different return types is that we didn't use to care about the response body of the push request. The default pusher implementation checks if the response body is JSON and if it matches the type PusherResponse. If it does, it is included in the return value.

Parameters
NameType
requestBodyPushRequest
requestIDstring
Returns

Promise<PusherResult>


PusherResult

Ƭ PusherResult: Object

Type declaration

NameType
httpRequestInfoHTTPRequestInfo
response?PushResponse

ReadonlyJSONObject

Ƭ ReadonlyJSONObject: Object

Like JSONObject but deeply readonly

Index signature

[key: string]: ReadonlyJSONValue | undefined


ReadonlyJSONValue

Ƭ ReadonlyJSONValue: null | string | boolean | number | ReadonlyArray<ReadonlyJSONValue> | ReadonlyJSONObject

Like JSONValue but deeply readonly


ScanIndexOptions

Ƭ ScanIndexOptions: Object

Options for scan when scanning over an index. When scanning over and index you need to provide the indexName and the start key is now a tuple consisting of secondary and primary key

Type declaration

NameTypeDescription
indexNamestringDo a scan over a named index. The indexName is the name of an index defined when creating the Replicache instance using indexes.
limit?numberOnly include up to limit results.
prefix?stringOnly include results starting with the secondary keys starting with prefix.
start?{ exclusive?: boolean ; key: ScanOptionIndexedStartKey }When provided the scan starts at this key.
start.exclusive?booleanWhether the key is exclusive or inclusive.
start.keyScanOptionIndexedStartKey-

ScanNoIndexOptions

Ƭ ScanNoIndexOptions: Object

Options for scan when scanning over the entire key space.

Type declaration

NameTypeDescription
limit?numberOnly include up to limit results.
prefix?stringOnly include keys starting with prefix.
start?{ exclusive?: boolean ; key: string }When provided the scan starts at this key.
start.exclusive?booleanWhether the key is exclusive or inclusive.
start.keystring-

ScanOptionIndexedStartKey

Ƭ ScanOptionIndexedStartKey: readonly [secondary: string, primary?: string | undefined] | string

The key to start scanning at.

If you are scanning the primary index (i.e., you did not specify indexName), then pass a single string for this field, which is the key in the primary index to scan at.

If you are scanning a secondary index (i.e., you specified indexName), then use the tuple form. In that case, secondary is the secondary key to start scanning at, and primary (if any) is the primary key to start scanning at.


ScanOptions

Ƭ ScanOptions: ScanIndexOptions | ScanNoIndexOptions

Options for scan


TransactionEnvironment

Ƭ TransactionEnvironment: "client" | "server"


TransactionLocation

Ƭ TransactionLocation: TransactionEnvironment


TransactionReason

Ƭ TransactionReason: "initial" | "rebase" | "authoritative"


UpdateNeededReason

Ƭ UpdateNeededReason: { type: "NewClientGroup" } | { type: "VersionNotSupported" ; versionType?: "push" | "pull" | "schema" }


VersionNotSupportedResponse

Ƭ VersionNotSupportedResponse: Object

The server endpoint may respond with a VersionNotSupported error if it does not know how to handle the pullVersion, pushVersion or the schemaVersion.

Type declaration

NameType
error"VersionNotSupported"
versionType?"pull" | "push" | "schema"

Variables

TEST_LICENSE_KEY

Const TEST_LICENSE_KEY: "This key only good for automated testing"


consoleLogSink

Const consoleLogSink: LogSink

An implementation of [[LogSink]] that logs using console.log etc


version

Const version: string = REPLICACHE_VERSION

The current version of Replicache.

Functions

deleteAllReplicacheData

deleteAllReplicacheData(opts?): Promise<{ dropped: string[] ; errors: unknown[] }>

Deletes all IndexedDB data associated with Replicache.

Returns an object with the names of the successfully dropped databases and any errors encountered while dropping.

Parameters

NameType
opts?DropDatabaseOptions

Returns

Promise<{ dropped: string[] ; errors: unknown[] }>

Deprecated

Use dropAllDatabases instead.


dropAllDatabases

dropAllDatabases(opts?): Promise<{ dropped: string[] ; errors: unknown[] }>

Deletes all IndexedDB data associated with Replicache.

Returns an object with the names of the successfully dropped databases and any errors encountered while dropping.

Parameters

NameType
opts?DropDatabaseOptions

Returns

Promise<{ dropped: string[] ; errors: unknown[] }>


dropDatabase

dropDatabase(dbName, opts?): Promise<void>

Deletes a single Replicache database.

Parameters

NameType
dbNamestring
opts?DropDatabaseOptions

Returns

Promise<void>


filterAsyncIterable

filterAsyncIterable<V>(iter, predicate): AsyncIterable<V>

Filters an async iterable.

This utility function is provided because it is useful when using makeScanResult. It can be used to filter out tombstones (delete entries) for example.

Type parameters

Name
V

Parameters

NameType
iterIterableUnion<V>
predicate(v: V) => boolean

Returns

AsyncIterable<V>


getDefaultPuller

getDefaultPuller(rep): Puller

This creates a default puller which uses HTTP POST to send the pull request.

Parameters

NameType
repObject
rep.authstring
rep.pullURLstring

Returns

Puller


isScanIndexOptions

isScanIndexOptions(options): options is ScanIndexOptions

Type narrowing of ScanOptions.

Parameters

NameType
optionsScanOptions

Returns

options is ScanIndexOptions


makeIDBName

makeIDBName(name, schemaVersion?): string

Returns the name of the IDB database that will be used for a particular Replicache instance.

Parameters

NameTypeDescription
namestringThe name of the Replicache instance (i.e., the name field of ReplicacheOptions).
schemaVersion?stringThe schema version of the database (i.e., the schemaVersion field of ReplicacheOptions).

Returns

string


makeScanResult

makeScanResult<Options>(options, getScanIterator): ScanResult<KeyTypeForScanOptions<Options>, ReadonlyJSONValue>

A helper function that makes it easier to implement scan with a custom backend.

If you are implementing a custom backend and have an in memory pending async iterable we provide two helper functions to make it easier to merge these together. mergeAsyncIterables and filterAsyncIterable.

For example:

const scanResult = makeScanResult(
options,
options.indexName
? () => {
throw Error('not implemented');
}
: fromKey => {
const persisted: AsyncIterable<Entry<ReadonlyJSONValue>> = ...;
const pending: AsyncIterable<Entry<ReadonlyJSONValue | undefined>> = ...;
const iter = await mergeAsyncIterables(persisted, pending);
const filteredIter = await filterAsyncIterable(
iter,
entry => entry[1] !== undefined,
);
return filteredIter;
},
);

Type parameters

NameType
Optionsextends ScanOptions

Parameters

NameType
optionsOptions
getScanIteratorOptions extends ScanIndexOptions ? GetIndexScanIterator : GetScanIterator

Returns

ScanResult<KeyTypeForScanOptions<Options>, ReadonlyJSONValue>


mergeAsyncIterables

mergeAsyncIterables<A, B>(iterableBase, iterableOverlay, compare): AsyncIterable<A | B>

Merges an iterable on to another iterable.

The two iterables need to be ordered and the compare function is used to compare two different elements.

If two elements are equal (compare returns 0) then the element from the second iterable is picked.

This utility function is provided because it is useful when using makeScanResult. It can be used to merge an in memory pending async iterable on to a persistent async iterable for example.

Type parameters

Name
A
B

Parameters

NameType
iterableBaseIterableUnion<A>
iterableOverlayIterableUnion<B>
compare(a: A, b: B) => number

Returns

AsyncIterable<A | B>