import { Twilsock, InitRegistration } from "twilsock"; import { ConnectionState as TwilsockConnectionState } from "twilsock"; import { ReplayEventEmitter } from "@twilio/replay-event-emitter"; /** * Routes all incoming messages to the consumers. */ interface Router { /** * Subscribe to events */ _subscribe(sid: string, entity: any): any; /** * Unsubscribe from events */ _unsubscribe(sid: string): any; /** * Entry point for all incoming messages * @param {String} type - Type of incoming message * @param {Object} message - Message to route */ _routeMessage(type: string, message: any): any; } interface Network { get(uri: string): any; post(uri: string, body: Object, revision?: string, retryWhenThrottled?: boolean): any; put(uri: string, body: Object, revision: string): any; delete(uri: string): any; } interface Storage { store(type: string, id: string, value: Object): any; read(type: string, id: string): Object; update(type: string, id: string, uniqueName: string, patch: Object): any; remove(type: string, sid: string, uniqueName: string): any; updateStorageId(storageId: string): any; } /** * Generic SyncLibrary error class */ declare class SyncError extends Error { name: string; message: string; status: number; code: number; constructor(message: string, status?: number, code?: number); } // Response body to `POST /v3/Streams` and `GET /v3/Streams/TOxx` interface StreamDescriptor { sid: string; unique_name: string; url: string; date_expires: string; links: StreamLinks; } interface StreamLinks { messages: string; } interface SyncStreamServices extends EntityServices { } /** * Stream message descriptor. */ interface SyncStreamMessage { /** * Stream message SID. */ sid: string; /** * Stream message data. */ data: object; } declare class SyncStreamImpl extends SyncEntity { private readonly descriptor; /** * @internal */ constructor(services: SyncStreamServices, descriptor: StreamDescriptor, removalHandler: RemovalHandler); // private props get uri(): string; get links(): any; static get type(): string; get dateExpires(): string; get type(): string; get lastEventId(): any; // below properties are specific to Insights only get indexName(): string; get queryString(): string; // public props, documented along with class description get sid(): string; get uniqueName(): string; publishMessage(data: object): Promise; setTtl(ttl: number): Promise; removeStream(): Promise; /** * Handle event from the server * @private */ _update(update: any): void; private _handleMessagePublished; protected onRemoved(isLocal: boolean): void; } /** * A Sync primitive for pub-sub messaging. Stream Messages are not persisted, exist * only in transit, and will be dropped if (due to congestion or network anomalies) they * cannot be delivered promptly. Use the {@link SyncClient.stream} method to obtain a reference to a Sync Message Stream. * Information about rate limits can be found [here](https://www.twilio.com/docs/sync/limits). */ declare class SyncStream extends Closeable { private readonly syncStreamImpl; // private props get uri(): string; get links(): any; static get type(): string; get dateExpires(): string; get type(): string; get lastEventId(): any; /** * The immutable system-assigned identifier of this stream. Never null. */ get sid(): string; /** * A unique identifier optionally assigned to the stream on creation. */ get uniqueName(): string; /** * @internal */ constructor(syncStreamImpl: SyncStreamImpl); /** * Fired when a message is published to the stream either locally or by a remote actor. * * Parameters: * 1. object `args` - info object provided with the event. It has the following properties: * * {@link SyncStreamMessage} `message` - Published message * * boolean `isLocal` - equals true if the message was published by a local actor, false otherwise * @example * ```typescript * stream.on('messagePublished', (args) => { * console.log('Stream message published'); * console.log('Message SID:', args.message.sid); * console.log('Message data: ', args.message.data); * console.log('args.isLocal:', args.isLocal); * }); * ``` * @event */ static readonly messagePublished = "messagePublished"; /** * Fired when a stream is removed entirely, regardless of whether the remover was local or remote. * * Parameters: * 1. object `args` - info object provided with the event. It has the following properties: * * boolean `isLocal` - equals true if the stream was removed by a local actor, false otherwise * @example * ```typescript * stream.on('removed', (args) => { * console.log(`Stream ${stream.sid} was removed`); * console.log('args.isLocal:', args.isLocal); * }); * ``` * @event */ static readonly removed = "removed"; /** * Publish a message to the stream. The system will attempt delivery to all online subscribers. * @param data The body of the dispatched message. Maximum size in serialized JSON: 4KB. * A rate limit applies to this operation, refer to the [Sync API documentation](https://www.twilio.com/docs/api/sync) for details. * @return A promise which resolves after the message is successfully published * to the Sync service. Resolves irrespective of ultimate delivery to any subscribers. * @example * ```typescript * stream.publishMessage({ x: 42, y: 123 }) * .then((message) => { * console.log('Stream publishMessage() successful, message SID:', message.sid); * }) * .catch((error) => { * console.error('Stream publishMessage() failed', error); * }); * ``` */ publishMessage(data: object): Promise; /** * Update the time-to-live of the stream. * @param ttl Specifies the TTL in seconds after which the stream is subject to automatic deletion. The value 0 means infinity. * @return A promise that resolves after the TTL update was successful. * @example * ```typescript * stream.setTtl(3600) * .then(() => { * console.log('Stream setTtl() successful'); * }) * .catch((error) => { * console.error('Stream setTtl() failed', error); * }); * ``` */ setTtl(ttl: number): Promise; /** * Permanently delete this Stream. * @return A promise which resolves after the Stream is successfully deleted. * @example * ```typescript * stream.removeStream() * .then(() => { * console.log('Stream removeStream() successful'); * }) * .catch((error) => { * console.error('Stream removeStream() failed', error); * }); * ``` */ removeStream(): Promise; /** * Conclude work with the stream instance and remove all event listeners attached to it. * Any subsequent operation on this object will be rejected with error. * Other local copies of this stream will continue operating and receiving events normally. * @example * ```typescript * stream.close(); * ``` */ close(): void; } type CloseableEvents = { updated: (eventData: { data: any; previousData: any; isLocal: boolean; }) => void; removed: (eventData: { previousData?: any; isLocal: boolean; }) => void; itemUpdated: (eventData: any) => void; itemAdded: (eventData: any) => void; itemRemoved: (eventData: any) => void; contextUpdated: (eventData: { context: any; isLocal: boolean; }) => void; messagePublished: (eventData: { message: SyncStreamMessage; isLocal: boolean; }) => void; failure: (error: SyncError) => void; _subscriptionStateChanged: (state: SubscriptionState) => void; }; declare abstract class Closeable extends ReplayEventEmitter { private readonly uuid; private closed; constructor(); get listenerUuid(): string; protected close(): void; protected ensureNotClosed(): void; } interface EntityServices { network: Network; router: Router; storage: Storage; } type RemovalHandler = (type: string, sid: string, uniqueName: string) => void; type SubscriptionState = "none" | "request_in_flight" | "response_in_flight" | "established"; declare abstract class SyncEntity { protected readonly services: EntityServices; protected readonly removalHandler: RemovalHandler; private subscriptionState; private readonly _attachedListeners; protected constructor(services: EntityServices, removalHandler: RemovalHandler); abstract get sid(): string; abstract get uniqueName(): string; abstract get type(): string; abstract get lastEventId(): number; abstract get indexName(): string; abstract get queryString(): string; abstract _update(update: any, isStrictlyOrdered: boolean): void; _advanceLastEventId(eventId: number, revision?: string): void; protected abstract onRemoved(locally: boolean): void; reportFailure(err: SyncError): void; /** * Subscribe to changes of data entity * @private */ _subscribe(): void; /** * Unsubscribe from changes of current data entity * @private */ _unsubscribe(): void; _setSubscriptionState(newState: SubscriptionState): void; /** * @public */ close(): void; attach(closeable: Closeable): void; detach(listenerUuid: string): void; protected broadcastEventToListeners>(eventName: E, ...args: Parameters): void; } /** * Applies a transformation to the data of a Sync entity. May be called multiple times on the * same datum in case of collisions with remote code. * * @param currentValue Current data of the Sync entity in the cloud. * @return Desired new data for the item or `null` to gracefully cancel the mutation. */ type Mutator = (currentValue: Object) => Object; interface DocumentServices extends EntityServices { } interface DocumentDescriptor { url: string; sid: string; revision: string; last_event_id: number; unique_name: string; data: Object; date_updated: Date; date_expires: string; } /** * Document metadata. */ interface SyncDocumentMetadata { /** * Specifies the time-to-live in seconds after which the document is subject to automatic deletion. * The value 0 means infinity. */ ttl?: number; } declare class SyncDocumentImpl extends SyncEntity { private readonly updateMergingQueue; private readonly descriptor; private isDeleted; /** * @internal */ constructor(services: DocumentServices, descriptor: DocumentDescriptor, removalHandler: RemovalHandler); // private props get uri(): string; get revision(): string; get lastEventId(): number; get dateExpires(): string; static get type(): string; get type(): string; // below properties are specific to Insights only get indexName(): string; get queryString(): string; // public props, documented along with class description get sid(): string; get data(): Object; get dateUpdated(): Date; get uniqueName(): string; /** * Update data entity with new data * @private */ _update(update: any): void; set(value: Object, metadataUpdates?: SyncDocumentMetadata): Promise; mutate(mutator: Mutator, metadataUpdates?: SyncDocumentMetadata): Promise; update(obj: Object, metadataUpdates?: SyncDocumentMetadata): Promise; setTtl(ttl: number): Promise; /** * @private */ private _setUnconditionally; /** * @private */ private _setWithIfMatch; /** * @private */ private _handleSuccessfulUpdateResult; /** * @private */ private _postUpdateToServer; /** * Get new data from server * @private */ private _softSync; protected onRemoved(locally: boolean): void; removeDocument(): Promise; } /** * Represents a Sync document, the contents of which is a single JSON object. * Use the {@link SyncClient.document} method to obtain a reference to a Sync document. * Information about rate limits can be found [here](https://www.twilio.com/docs/sync/limits). */ declare class SyncDocument extends Closeable { private readonly syncDocumentImpl; // private props get uri(): string; get revision(): string; get lastEventId(): number; get dateExpires(): string; static get type(): string; get type(): string; /** * The immutable identifier of this document, assigned by the system. */ get sid(): string; /** * The contents of this document. */ get data(): Object; /** * Date when the document was last updated. */ get dateUpdated(): Date; /** * An optional immutable identifier that may be assigned by the programmer * to this document during creation. Globally unique among other documents. */ get uniqueName(): string; /** * @internal */ constructor(syncDocumentImpl: SyncDocumentImpl); /** * Fired when the document is removed, regardless of whether the remover was local or remote. * * Parameters: * 1. object `args` - info object provided with the event. It has following properties: * * boolean `isLocal` - is true if document was removed by a local actor, false otherwise * * object `previousData` - contains a snapshot of the document data before removal * @example * ```typescript * document.on('removed', (args) => { * console.log(`Document ${document.sid} was removed`); * console.log('args.isLocal:', args.isLocal); * console.log('args.previousData:', args.previousData); * }); * ``` * @event */ static readonly removed = "removed"; /** * Fired when the document's contents have changed, regardless of whether the updater was local or remote. * * Parameters: * 1. object `args` - info object provided with the event. It has the following properties: * * boolean `isLocal` - is true if document was updated by a local actor, false otherwise * * object `data` - a snapshot of the document's new contents * * object `previousData` - contains a snapshot of the document data before the update * @example * ```typescript * document.on('updated', (args) => { * console.log(`Document ${document.sid} was updated`); * console.log('args.data:', args.data); * console.log('args.isLocal:', args.isLocal); * console.log('args.previousData:', args.previousData); * }); * ``` * @event */ static readonly updated = "updated"; /** * Assign new contents to this document. The current data will be overwritten. * @param data The new contents to assign. * @param metadataUpdates New document metadata. * @return A promise resolving to the new data of the document. * @example * ```typescript * // Say, the Document data is `{ name: 'John Smith', age: 34 }` * document.set({ name: 'Barbara Oaks' }, { ttl: 86400 }) * .then((newValue) => { * // Now the Document data is `{ name: 'Barbara Oaks' }` * console.log('Document set() successful, new data:', newValue); * }) * .catch((error) => { * console.error('Document set() failed', error); * }); * ``` */ set(data: Object, metadataUpdates?: SyncDocumentMetadata): Promise; /** * Schedules a modification to this document that will apply a mutation function. * @param mutator A function that outputs new data based on the existing data. * May be called multiple times, particularly if this document is modified concurrently by remote code. * If the mutation ultimately succeeds, the document will have made the particular transition described * by this function. * @param metadataUpdates New document metadata. * @return Resolves with the most recent Document state, whether the output of a * successful mutation or a state that prompted graceful cancellation (mutator returned `null`). * @example * ```typescript * const mutatorFunction = (currentValue) => { * currentValue.viewCount = (currentValue.viewCount ?? 0) + 1; * return currentValue; * }; * document.mutate(mutatorFunction, { ttl: 86400 })) * .then((newValue) => { * console.log('Document mutate() successful, new data:', newValue); * }) * .catch((error) => { * console.error('Document mutate() failed', error); * }); * ``` */ mutate(mutator: Mutator, metadataUpdates?: SyncDocumentMetadata): Promise; /** * Modify a document by appending new fields (or by overwriting existing ones) with the values from the provided Object. * This is equivalent to: * ```typescript * document.mutate((currentValue) => Object.assign(currentValue, obj)); * ``` * @param obj Specifies the particular (top-level) attributes that will receive new values. * @param metadataUpdates New document metadata. * @return A promise resolving to the new data of the document. * @example * ```typescript * // Say, the Document data is `{ name: 'John Smith' }` * document.update({ age: 34 }, { ttl: 86400 }) * .then((newValue) => { * // Now the Document data is `{ name: 'John Smith', age: 34 }` * console.log('Document update() successful, new data:', newValue); * }) * .catch((error) => { * console.error('Document update() failed', error); * }); * ``` */ update(obj: Object, metadataUpdates?: SyncDocumentMetadata): Promise; /** * Update the time-to-live of the document. * @param ttl Specifies the time-to-live in seconds after which the document is subject to automatic deletion. The value 0 means infinity. * @return A promise that resolves after the TTL update was successful. * @example * ```typescript * document.setTtl(3600) * .then(() => { * console.log('Document setTtl() successful'); * }) * .catch((error) => { * console.error('Document setTtl() failed', error); * }); * ``` */ setTtl(ttl: number): Promise; /** * Delete a document. * @return A promise which resolves if (and only if) the document is ultimately deleted. * @example * ```typescript * document.removeDocument() * .then(() => { * console.log('Document removeDocument() successful'); * }) * .catch((error) => { * console.error('Document removeDocument() failed', error); * }); * ``` */ removeDocument(): Promise; /** * Conclude work with the document instance and remove all event listeners attached to it. * Any subsequent operation on this object will be rejected with error. * Other local copies of this document will continue operating and receiving events normally. * @example * ```typescript * document.close(); * ``` */ close(): void; } interface SyncListItemDescriptor { index: number; url: string; data: Record; revision: string; lastEventId: number; dateUpdated: Date; dateExpires: string; } /** * Represents an individual element in a Sync list. */ declare class SyncListItem { private readonly descriptor; /** * @param descriptor Item descriptor * @internal */ constructor(descriptor: SyncListItemDescriptor); get url(): string; get revision(): string; get lastEventId(): number; /** * Date when the list item was last updated. */ get dateUpdated(): Date; get dateExpires(): string; /** * The index, within the containing list, of this item. This index is stable; * even if lower-indexed items are removed, this index will remain as is. */ get index(): number; /** * The contents of the item. */ get data(): Object; /** * CachedValue interface. */ get cacheKey(): number; /** * @internal */ update(eventId: number, revision: string, data: Record, dateUpdated: Date): SyncListItem; /** * @internal */ updateDateExpires(dateExpires: string): void; } /** * Pagination helper class. */ declare class Paginator { private prevPageItemId; private nextPageItemId; private source; /** * Array of elements on current page. */ readonly items: Item[]; /** * @internal */ constructor(items: any, source: any, prevItemId?: string | number | null, nextItemId?: string | number | null); /** * Request next page. * Does not modify existing object. */ nextPage(): Promise>; /** * Request previous page. * Does not modify existing object. */ prevPage(): Promise>; /** * Indicates the existence of the next page. */ get hasNextPage(): boolean; /** * Indicates the existence of the previous page. */ get hasPrevPage(): boolean; } interface SyncListServices extends EntityServices { } interface SyncListDescriptor { sid: string; url: string; revision: string; last_event_id: number; links: any; unique_name: string; date_updated: Date; date_expires: string; } /** * List item metadata. */ interface SyncListItemMetadata { /** * Specifies the time-to-live in seconds after which the list item is subject to automatic deletion. * The value 0 means infinity. */ ttl?: number; } /** * List item query options. */ interface SyncListItemQueryOptions { index?: number; /** * Item index, which should be used as the offset. * If undefined, starts from the beginning or end depending on queryOptions.order. */ from?: number; /** * Results page size. Default is 50. */ pageSize?: number; /** * Numeric order of results. Default is "asc". */ order?: "asc" | "desc"; /** * Query limit. */ limit?: number; } declare class SyncListImpl extends SyncEntity { private descriptor; private updateMergingQueue; private cache; private context; private contextEventId; /** * @private */ constructor(services: SyncListServices, descriptor: SyncListDescriptor, removalHandler: RemovalHandler); // private props get uri(): string; get revision(): string; get lastEventId(): number; get links(): any; get dateExpires(): string; static get type(): string; get type(): string; // below properties are specific to Insights only get indexName(): string; get queryString(): string; // public props, documented along with class description get sid(): string; get uniqueName(): string; get dateUpdated(): Date; private _addOrUpdateItemOnServer; push(value: any, itemMetadata?: SyncListItemMetadata): Promise; set(index: number, value: Record, itemMetadataUpdates?: SyncListItemMetadata): Promise; private _updateItemUnconditionally; private _updateItemWithIfMatch; mutate(index: number, mutator: Mutator, itemMetadataUpdates?: SyncListItemMetadata): Promise; update(index: number, obj: Object, itemMetadataUpdates?: SyncListItemMetadata): Promise; remove(index: number): Promise; get(index: number): Promise; private _getItemFromServer; /** * Query items from the List * @param args Argument pack for the query. * May include the following parameters: * * - index -- Returns the Item with the specified index or an empty items array, if one doesn't exist. * - from -- Item index offset specifying the starting point of the query (inclusive). If not specified, * the query starts from either the first or the last item in the List (by index), * depending on the Order query parameter. * - order -- String(Optional) -- Determines the order of the query. Items are ordered numerically by index. * One of {asc, desc}, defaults to asc. * - pageSize -- Maximum number of Items in the response (i.e. in this page). Defaults to 50. * The max page size is 1000. Note: PageSize between 100 and 1000 returns at most 100 items. * - pageToken - Direct paging token, for starting from a specific page. * - Metadata - May have the value list. If specified, returns the state of the List in the list attribute of the response. * - HideExpired - Determines whether expired List items are filtered out from the result list. By default, is false. * * Stuff not accepted by the service, internal to SDK: * * - limit * * Valid query parameter combinations * These are the valid query parameter combinations. [x] should be read as “if x is not provided, the default value is assumed”. * The combinations are in order of precedence - e.g., if both Index and PageToken are provided, PageToken is ignored. * +-----------------------------------------+------------------------------------------------------------------------------+ * | Index, [Metadata] | Returns 0-1 Items with the given Index | * | PageToken, [Metadata] | Returns a page based on the PageToken returned from a previous query, | * | | with this and all following pages modified by any provided query parameters. | * | [From], [Order], [Pagesize], [Metadata] | Performs an initial query from a specified offset. | * | | Returned PageTokens in the meta block should be used for pagination. | * +-----------------------------------------+------------------------------------------------------------------------------+ * @private */ protected queryItems(args?: any): Promise>; private _prevPageAllowed; private _nextPageAllowed; // Paginator depends on: // - items listed // - was there a previous token (prevPage) // - was there a next token (nextPage) // - order of items asc/desc private makePaginator; protected _querySingleItemFromServer(index: number): Promise>; protected _queryItemsFromServer(args: any): Promise>; getItems(args?: any): Promise>; /** * @return {Promise} Context of List * @private */ getContext(): Promise; setTtl(ttl: number): Promise; setItemTtl(index: number, ttl: number): Promise; removeList(): Promise; protected onRemoved(locally: boolean): void; private shouldIgnoreEvent; /** * Handle update, which came from the server. * @private */ _update(update: any, isStrictlyOrdered: boolean): void; _advanceLastEventId(eventId: number, revision?: string): void; private _updateRootDateUpdated; private _handleItemMutated; /** * @private */ private emitItemMutationEvent; /** * @private */ private _handleItemRemoved; /** * @private */ private _handleContextUpdate; /** * @private */ private _updateContextIfRequired; } /** * Represents a Sync list, which stores an ordered list of values. * Use the {@link SyncClient.list} method to obtain a reference to a Sync list. * Information about rate limits can be found [here](https://www.twilio.com/docs/sync/limits). */ declare class SyncList extends Closeable { private readonly syncListImpl; // private props get uri(): string; get revision(): string; get lastEventId(): number; get links(): any; get dateExpires(): string; static get type(): string; get type(): string; /** * Unique ID of the list, immutable identifier assigned by the system. */ get sid(): string; /** * Unique name of the list, immutable identifier that can be assigned to the list during creation. */ get uniqueName(): string; /** * Date when the list was last updated, given in UTC ISO 8601 format (e.g., '2018-04-26T15:23:19.732Z'). */ get dateUpdated(): Date; /** * @internal */ constructor(syncListImpl: SyncListImpl); /** * Fired when a new item appears in the list, regardless of whether its creator was local or remote. * * Parameters: * 1. object `args` - info object provided with the event. It has the following properties: * * {@link SyncListItem} `item` - added item * * boolean `isLocal` - equals true if the item was added by a local actor, false otherwise * @example * ```typescript * list.on('itemAdded', (args) => { * console.log(`List item ${args.item.index} was added`); * console.log('args.item.data:', args.item.data); * console.log('args.isLocal:', args.isLocal); * }); * ``` * @event */ static readonly itemAdded = "itemAdded"; /** * Fired when a list item is updated (not added or removed, but changed), regardless of whether the updater was local or remote. * * Parameters: * 1. object `args` - info object provided with the event. It has the following properties: * * {@link SyncListItem} `item` - updated item * * boolean `isLocal` - equals true if the item was updated by a local actor, false otherwise * * object `previousItemData` - contains a snapshot of the item data before the update * @example * ```typescript * list.on('itemUpdated', (args) => { * console.log(`List item ${args.item.index} was updated`); * console.log('args.item.data:', args.item.data); * console.log('args.isLocal:', args.isLocal); * console.log('args.previousItemData:', args.previousItemData); * }); * ``` * @event */ static readonly itemUpdated = "itemUpdated"; /** * Fired when a list item is removed, regardless of whether the remover was local or remote. * * Parameters: * 1. object `args` - info object provided with the event. It has the following properties: * * number `index` - index of the removed item * * boolean `isLocal` - equals true if the item was removed by a local actor, false otherwise * * object `previousItemData` - contains a snapshot of the item data before the removal * @example * ```typescript * list.on('itemRemoved', (args) => { * console.log(`List item ${args.index} was removed`); * console.log('args.previousItemData:', args.previousItemData); * console.log('args.isLocal:', args.isLocal); * }); * ``` * @event */ static readonly itemRemoved = "itemRemoved"; /** * Fired when a list is deleted entirely, by any actor local or remote. * * Parameters: * 1. object `args` - info object provided with the event. It has the following properties: * * boolean `isLocal` - equals true if the list was removed by a local actor, false otherwise * @example * ```typescript * list.on('removed', (args) => { * console.log(`List ${list.sid} was removed`); * console.log('args.isLocal:', args.isLocal); * }); * ``` * @event */ static readonly removed = "removed"; /** * Add a new item to the list. * @param data Data to be added. * @param itemMetadata Item metadata. * @return The newly added item. * @example * ```typescript * list.push({ name: 'John Smith' }, { ttl: 86400 }) * .then((item) => { * console.log(`List Item push() successful, item index: ${item.index}, data:`, item.data) * }) * .catch((error) => { * console.error('List Item push() failed', error); * }); * ``` */ push(data: any, itemMetadata?: SyncListItemMetadata): Promise; /** * Assign new data to an existing item, given its index. * @param index Index of the item to be updated. * @param value New data to be assigned to an item. * @param itemMetadataUpdates New item metadata. * @return A promise with the updated item containing latest known data. * The promise will be rejected if the item does not exist. * @example * ```typescript * list.set(42, { name: 'John Smith' }, { ttl: 86400 }) * .then((item) => { * console.log('List Item set() successful, item data:', item.data) * }) * .catch((error) => { * console.error('List Item set() failed', error); * }); * ``` */ set(index: number, value: Record, itemMetadataUpdates?: SyncListItemMetadata): Promise; /** * Modify an existing item by applying a mutation function to it. * @param index Index of the item to be changed. * @param mutator A function that outputs a new data based on the existing data. * @param itemMetadataUpdates New item metadata. * @return Resolves with the most recent item state, the output of a successful * mutation or a state that prompted graceful cancellation (mutator returned `null`). This promise * will be rejected if the indicated item does not already exist. * @example * ```typescript * const mutatorFunction = (currentValue) => { * currentValue.viewCount = (currentValue.viewCount || 0) + 1; * return currentValue; * }; * list.mutate(42, mutatorFunction, { ttl: 86400 }) * .then((item) => { * console.log('List Item mutate() successful, new data:', item.data) * }) * .catch((error) => { * console.error('List Item mutate() failed', error); * }); * ``` */ mutate(index: number, mutator: Mutator, itemMetadataUpdates?: SyncListItemMetadata): Promise; /** * Modify an existing item by appending new fields (or overwriting existing ones) with the values from the object. * This is equivalent to * ```typescript * list.mutate(42, (currentValue) => Object.assign(currentValue, obj)); * ``` * @param index Index of an item to be changed. * @param obj Set of fields to update. * @param itemMetadataUpdates New item metadata. * @return A promise with a modified item containing latest known data. * The promise will be rejected if the item was not found. * @example * ```typescript * // Say, the List Item (index: 42) data is `{ name: 'John Smith' }` * list.update(42, { age: 34 }, { ttl: 86400 }) * .then((item) => { * // Now the List Item data is `{ name: 'John Smith', age: 34 }` * console.log('List Item update() successful, new data:', item.data); * }) * .catch((error) => { * console.error('List Item update() failed', error); * }); * ``` */ update(index: number, obj: Record, itemMetadataUpdates?: SyncListItemMetadata): Promise; /** * Delete an item given its index. * @param index Index of the item to be removed. * @return A promise to remove the item. * The promise will be rejected if the item was not found. * @example * ```typescript * list.remove(42) * .then(() => { * console.log('List Item remove() successful'); * }) * .catch((error) => { * console.error('List Item remove() failed', error); * }); * ``` */ remove(index: number): Promise; /** * Retrieve an item by List index. * @param index Item index in the list. * @return A promise with the item containing latest known data. * The promise will be rejected if the item was not found. * @example * ```typescript * list.get(42) * .then((item) => { * console.log('List Item get() successful, item data:', item.data) * }) * .catch((error) => { * console.error('List Item get() failed', error); * }); * ``` */ get(index: number): Promise; /** * Retrieve a list context * @return A promise with the list's context * @internal */ getContext(): Promise; /** * Query a list of items from collection. * Information about the query limits can be found {@link https://www.twilio.com/docs/sync/limits|here}. * @param queryOptions Query options. * @example * ```typescript * const pageHandler = (paginator) => { * paginator.items.forEach((item) => { * console.log(`Item ${item.index}:`, item.data); * }); * return paginator.hasNextPage * ? paginator.nextPage().then(pageHandler) * : null; * }; * list.getItems({ from: 0, order: 'asc' }) * .then(pageHandler) * .catch((error) => { * console.error('List getItems() failed', error); * }); * ``` */ getItems(queryOptions: SyncListItemQueryOptions): Promise>; /** * Update the time-to-live of the list. * @param ttl Specifies the TTL in seconds after which the list is subject to automatic deletion. The value 0 means infinity. * @return A promise that resolves after the TTL update was successful. * @example * ```typescript * list.setTtl(3600) * .then(() => { * console.log('List setTtl() successful'); * }) * .catch((error) => { * console.error('List setTtl() failed', error); * }); * ``` */ setTtl(ttl: number): Promise; /** * Update the time-to-live of a list item. * @param index Item index. * @param ttl Specifies the TTL in seconds after which the list item is subject to automatic deletion. The value 0 means infinity. * @return A promise that resolves after the TTL update was successful. * @example * ```typescript * list.setItemTtl(42, 86400) * .then(() => { * console.log('List setItemTtl() successful'); * }) * .catch((error) => { * console.error('List setItemTtl() failed', error); * }); * ``` */ setItemTtl(index: number, ttl: number): Promise; /** * Delete this list. It will be impossible to restore it. * @return A promise that resolves when the list has been deleted. * @example * list.removeList() * .then(() => { * console.log('List removeList() successful'); * }) * .catch((error) => { * console.error('List removeList() failed', error); * }); */ removeList(): Promise; /** * Conclude work with the list instance and remove all event listeners attached to it. * Any subsequent operation on this object will be rejected with error. * Other local copies of this list will continue operating and receiving events normally. * @example * ```typescript * list.close(); * ``` */ close(): void; } interface SyncMapItemDescriptor { key: string; url: string; revision: string; last_event_id: number; date_updated: Date; date_expires: string; data: Record; } /** * Represents an individual element in a Sync map. */ declare class SyncMapItem { private readonly descriptor; /** * @internal */ constructor(descriptor: SyncMapItemDescriptor); get uri(): string; get revision(): string; get lastEventId(): number; get dateExpires(): string; /** * The identifier that maps to this item within the containing Map. */ get key(): string; /** * The contents of the item. */ get data(): Object; /** * Date when the map item was last updated. */ get dateUpdated(): Date; /** * CachedValue interface. */ get cacheKey(): string; /** * @internal */ update(eventId: number, revision: string, value: Record, dateUpdated: Date): SyncMapItem; /** * @internal */ updateDateExpires(dateExpires: string): void; } interface SyncMapServices extends EntityServices { } interface SyncMapDescriptor { sid: string; url: string; revision: string; last_event_id: number; links: any; unique_name: string; date_updated: Date; date_expires: string; items?: SyncMapItemDescriptor[]; } /** * Map item metadata. */ interface SyncMapItemMetadata { /** * Specifies the time-to-live in seconds after which the map item is subject to automatic deletion. * The value 0 means infinity. */ ttl?: number; } /** * Map item query options. */ interface SyncMapItemQueryOptions { /** * SyncMapItem key, which should be used as the offset. If undefined, starts from the beginning or end depending * on queryOptions.order. */ from?: string; /** * Result page size. */ pageSize?: number | string; /** * Lexicographical order of results. */ order?: "asc" | "desc"; key?: string; limit?: number; } declare class SyncMapImpl extends SyncEntity { private readonly descriptor; private readonly updateMergingQueue; private readonly cache; /** * @private */ constructor(services: SyncMapServices, descriptor: SyncMapDescriptor, removalHandler: RemovalHandler); // private props get uri(): string; get links(): any; get revision(): string; get lastEventId(): number; get dateExpires(): string; static get type(): string; get type(): string; // below properties are specific to Insights only get indexName(): string; get queryString(): string; // public props, documented along with class description get sid(): string; get uniqueName(): string; get dateUpdated(): Date; set(key: string, value: Record, itemMetadataUpdates?: SyncMapItemMetadata): Promise; get(key: string): Promise; private _getItemFromServer; mutate(key: string, mutator: Mutator, itemMetadataUpdates?: SyncMapItemMetadata): Promise; update(key: string, obj: Record, itemMetadataUpdates?: SyncMapItemMetadata): Promise; private _putItemUnconditionally; private _putItemWithIfMatch; private _putItemToServer; remove(key: string): Promise; /** * @param args Argument pack for the query. * May include the following parameters: * * - key -- Returns the Item with the specified key or an empty items array, if one doesn't exist. * - from -- Item index offset specifying the starting point of the query (inclusive). If not specified, * the query starts from either the first or the last item in the List (by index), * depending on the Order query parameter. * - order -- String(Optional) -- Determines the order of the query. Items are ordered numerically by index. * One of {asc, desc}, defaults to asc. * - pageSize -- Maximum number of Items in the response (i.e. in this page). Defaults to 50. * The max page size is 1000. Note: PageSize between 100 and 1000 returns at most 100 items. * - pageToken - Direct paging token, for starting from a specific page. * - Metadata - May have the value list. If specified, returns the state of the List in the list attribute of the response. * - HideExpired - Determines whether expired List items are filtered out from the result list. By default, is false. * * Stuff not accepted by the service, internal to SDK: * * - limit * - isNextPage * * Valid query parameter combinations * These are the valid query parameter combinations. [x] should be read as “if x is not provided, the default value is assumed”. * The combinations are in order of precedence - e.g., if both Key and PageToken are provided, PageToken is ignored. * +-----------------------------------------+------------------------------------------------------------------------------+ * | Key, [Metadata] | Returns 0-1 Items with the given Key | * | PageToken, [Metadata] | Returns a page based on the PageToken returned from a previous query, | * | | with this and all following pages modified by any provided query parameters. | * | [From], [Order], [Pagesize], [Metadata] | Performs an initial query from a specified offset. | * | | Returned PageTokens in the meta block should be used for pagination. | * +-----------------------------------------+------------------------------------------------------------------------------+ * @private */ protected queryItems(args?: any): Promise>; private _prevPageAllowed; private _nextPageAllowed; // Paginator depends on: // - items listed // - was there a previous token (prevPage) // - was there a next token (nextPage) // - order of items asc/desc private makePaginator; protected _querySingleItemFromServer(key: string): Promise>; protected _queryItemsFromServer(args: any): Promise>; getItems(args?: any): Promise>; private shouldIgnoreEvent; /** * Handle update from the server * @private */ _update(update: any, isStrictlyOrdered: boolean): void; _advanceLastEventId(eventId: number, revision?: string): void; private _updateRootDateUpdated; private _handleItemMutated; private emitItemMutationEvent; /** * @private */ protected _handleItemRemoved(key: any, eventId: any, oldData: any, dateUpdated: Date, remote: boolean): void; protected onRemoved(locally: boolean): void; setTtl(ttl: number): Promise; setItemTtl(key: string, ttl: number): Promise; removeMap(): Promise; } /** * Represents a Sync map, which is a data structure that stores an unordered set of key-value pairs. * Use the {@link SyncClient.map} method to obtain a reference to a Sync map. * Information about rate limits can be found [here](https://www.twilio.com/docs/sync/limits). */ declare class SyncMap extends Closeable { private readonly syncMapImpl; // private props get uri(): string; get links(): any; get revision(): string; get lastEventId(): number; get dateExpires(): string; static get type(): string; get type(): string; /** * An immutable identifier (a SID) assigned by the system on creation. */ get sid(): string; /** * An optional immutable identifier that may be assigned by the * programmer to this map on creation. Unique among other Maps. */ get uniqueName(): string; /** * Date when the map was last updated. */ get dateUpdated(): Date; /** * @internal */ constructor(syncMapImpl: SyncMapImpl); /** * Fired when a new item appears in the map, regardless of whether its creator was local or remote. * * Parameters: * 1. object `args` - info object provided with the event. It has the following properties: * * {@link SyncMapItem} `item` - added item * * boolean `isLocal` - equals true if the item was added by a local actor, false otherwise * @example * ```typescript * map.on('itemAdded', (args) => { * console.log(`Map item ${args.item.key} was added`); * console.log('args.item.data:', args.item.data); * console.log('args.isLocal:', args.isLocal); * }); * ``` * @event */ static readonly itemAdded = "itemAdded"; /** * Fired when a map item is updated (not added or removed, but changed), regardless of whether the updater was local or remote. * * Parameters: * 1. object `args` - info object provided with the event. It has the following properties: * * {@link SyncMapItem} `item` - updated item * * boolean `isLocal` - equals true if the item was updated by a local actor, false otherwise * * object `previousItemData` - contains a snapshot of the item data before the update * @example * ```typescript * map.on('itemUpdated', (args) => { * console.log(`Map item ${args.item.key} was updated`); * console.log('args.item.data:', args.item.data); * console.log('args.isLocal:', args.isLocal); * console.log('args.previousItemData:', args.previousItemData); * }); * ``` * @event */ static readonly itemUpdated = "itemUpdated"; /** * Fired when a map item is removed, regardless of whether the remover was local or remote. * * Parameters: * 1. object `args` - info object provided with the event. It has the following properties: * * string `key` - the key of the removed item * * boolean `isLocal` - equals true if the item was added by a local actor, false otherwise * * object `previousItemData` - contains a snapshot of the item data before removal * @example * ```typescript * map.on('itemRemoved', (args) => { * console.log(`Map item ${args.key} was removed`); * console.log('args.previousItemData:', args.previousItemData); * console.log('args.isLocal:', args.isLocal); * }); * ``` * @event */ static readonly itemRemoved = "itemRemoved"; /** * Fired when a map is deleted entirely, by any actor local or remote. * * Parameters: * 1. object `args` - info object provided with the event. It has the following properties: * * boolean `isLocal` - equals true if the map was removed by a local actor, false otherwise * @example * ```typescript * map.on('removed', (args) => { * console.log(`Map ${map.sid} was removed`); * console.log('args.isLocal:', args.isLocal); * }); * ``` * @event */ static readonly removed = "removed"; /** * Add a new item to the map with the given key-value pair. Overwrites any data that might already exist with that key. * @param key Unique item identifier. * @param data Data to be set. * @param itemMetadataUpdates New item metadata. * @return Newly added item, or modified one if already exists, with the latest known data. * @example * ```typescript * map.set('myKey', { name: 'John Smith' }, { ttl: 86400 }) * .then((item) => { * console.log('Map SyncMapItem set() successful, item data:', item.data); * }) * .catch((error) => { * console.error('Map SyncMapItem set() failed', error); * }); * ``` */ set(key: string, data: Record, itemMetadataUpdates?: SyncMapItemMetadata): Promise; /** * Retrieve an item by key. * @param key Identifies the desired item. * @return A promise that resolves when the item has been fetched. * This promise will be rejected if item was not found. * @example * ```typescript * map.get('myKey') * .then((item) => { * console.log('Map SyncMapItem get() successful, item data:', item.data) * }) * .catch((error) => { * console.error('Map SyncMapItem get() failed', error); * }); * ``` */ get(key: string): Promise; /** * Schedules a modification to this Map SyncMapItem that will apply a mutation function. * If no SyncMapItem with the given key exists, it will first be created, having the default data (`{}`). * @param key Selects the map item to be mutated. * @param mutator A function that outputs a new data based on the existing data. * May be called multiple times, particularly if this Map SyncMapItem is modified concurrently by remote code. * If the mutation ultimately succeeds, the Map SyncMapItem will have made the particular transition described * by this function. * @param itemMetadataUpdates New item metadata. * @return Resolves with the most recent item state, the output of a successful * mutation or a state that prompted graceful cancellation (mutator returned `null`). * @example * ```typescript * const mutatorFunction = (currentData) => { * currentData.viewCount = (currentData.viewCount || 0) + 1; * return currentData; * }; * map.mutate('myKey', mutatorFunction, { ttl: 86400 }) * .then((item) => { * console.log('Map SyncMapItem mutate() successful, new data:', item.data) * }) * .catch((error) => { * console.error('Map SyncMapItem mutate() failed', error); * }); * ``` */ mutate(key: string, mutator: Mutator, itemMetadataUpdates?: SyncMapItemMetadata): Promise; /** * Modify a map item by appending new fields (or by overwriting existing ones) with the values from * the provided Object. Creates a new item if no item by this key exists, copying all given fields and values * into it. * This is equivalent to * ```typescript * map.mutate('myKey', (currentData) => Object.assign(currentData, obj)); * ``` * @param key Selects the map item to update. * @param obj Specifies the particular (top-level) attributes that will receive new values. * @param itemMetadataUpdates New item metadata. * @return A promise resolving to the modified item in its new state. * @example * ```typescript * // Say, the Map SyncMapItem (key: `'myKey'`) data is `{ name: 'John Smith' }` * map.update('myKey', { age: 34 }, { ttl: 86400 }) * .then((item) => { * // Now the Map SyncMapItem data is `{ name: 'John Smith', age: 34 }` * console.log('Map SyncMapItem update() successful, new data:', item.data); * }) * .catch((error) => { * console.error('Map SyncMapItem update() failed', error); * }); * ``` */ update(key: string, obj: Record, itemMetadataUpdates?: SyncMapItemMetadata): Promise; /** * Delete an item, given its key. * @param key Selects the item to delete. * @return A promise to remove an item. * The promise will be rejected if 'key' is undefined or an item was not found. * @example * ```typescript * map.remove('myKey') * .then(() => { * console.log('Map SyncMapItem remove() successful'); * }) * .catch((error) => { * console.error('Map SyncMapItem remove() failed', error); * }); * ``` */ remove(key: string): Promise; /** * Get a complete list of items from the map. * Information about the query limits can be found [here](https://www.twilio.com/docs/sync/limits). * @param queryOptions Query options. * @example * ```typescript * const pageHandler = (paginator) => { * paginator.items.forEach((item) => { * console.log(`SyncMapItem ${item.key}: `, item.data); * }); * return paginator.hasNextPage * ? paginator.nextPage().then(pageHandler) * : null; * }; * map.getItems({ from: 'myKey', order: 'asc' }) * .then(pageHandler) * .catch((error) => { * console.error('Map getItems() failed', error); * }); * ``` */ getItems(queryOptions?: SyncMapItemQueryOptions): Promise>; /** * Update the time-to-live of the map. * @param ttl Specifies the TTL in seconds after which the map is subject to automatic deletion. The value 0 means infinity. * @return A promise that resolves after the TTL update was successful. * @example * ```typescript * map.setTtl(3600) * .then(() => { * console.log('Map setTtl() successful'); * }) * .catch((error) => { * console.error('Map setTtl() failed', error); * }); * ``` */ setTtl(ttl: number): Promise; /** * Update the time-to-live of a map item. * @param key SyncMapItem key. * @param ttl Specifies the TTL in seconds after which the map item is subject to automatic deletion. The value 0 means infinity. * @return A promise that resolves after the TTL update was successful. * @example * ```typescript * map.setItemTtl('myKey', 86400) * .then(() => { * console.log('Map setItemTtl() successful'); * }) * .catch((error) => { * console.error('Map setItemTtl() failed', error); * }); * ``` */ setItemTtl(key: string, ttl: number): Promise; /** * Delete this map. It will be impossible to restore it. * @return A promise that resolves when the map has been deleted. * @example * ```typescript * map.removeMap() * .then(() => { * console.log('Map removeMap() successful'); * }) * .catch((error) => { * console.error('Map removeMap() failed', error); * }); * ``` */ removeMap(): Promise; /** * Conclude work with the map instance and remove all event listeners attached to it. * Any subsequent operation on this object will be rejected with error. * Other local copies of this map will continue operating and receiving events normally. * @example * ```typescript * map.close(); * ```` */ close(): void; } interface InsightsServices extends EntityServices { } /** * An individual result from a LiveQuery or InstantQuery result set. */ declare class InsightsItem { /** * @internal */ constructor(key: string, value: Record, lastEventId: number); /** * The identifier that maps to this item within the search result. */ key: string; /** * The contents of the item. */ value: Record; /** * The revision of the item. */ lastEventId: number; /** * CachedValue interface. */ get cacheKey(): string; } /** * A result set, i.e. a collection of items that matched a LiveQuery or InstantQuery expression. * Each result is a key-value pair, where each key identifies its object uniquely. These * results are equivalent to a set of InsightsItem-s. */ interface ItemsSnapshot { [key: string]: object; } interface LiveQueryDescriptor { indexName: string; sid: string; queryExpression: string; queryUri: string; last_event_id: number; } declare class LiveQueryImpl extends SyncEntity { private readonly descriptor; private readonly cache; constructor(descriptor: LiveQueryDescriptor, services: InsightsServices, removalHandler: RemovalHandler, items?: any); // public get sid(): string; // private extension of SyncEntity get uniqueName(): any; get type(): string; static get type(): string; get lastEventId(): number; get indexName(): string; get queryString(): string; // custom private props get queryUri(): string; get liveQueryDescriptor(): LiveQueryDescriptor; // dummy stub from iface protected onRemoved(): void; getItems(): ItemsSnapshot; /** * @internal */ _update(message: any, isStrictlyOrdered: boolean): void; private handleItemMutated; private handleItemRemoved; private handleBatchUpdate; private shouldIgnoreEvent; /** * @internal */ _advanceLastEventId(eventId: number, revision?: string): void; } /** * Represents a long-running query against Flex data wherein the returned result set * subsequently receives pushed updates whenever new (or updated) records would match the * given expression. Updated results are presented row-by-row until this query is explicitly * closed. * * Use the {@link SyncClient.liveQuery} method to create a live query. */ declare class LiveQuery extends Closeable { private readonly liveQueryImpl; // private props static get type(): string; get type(): string; get lastEventId(): number; /** * The immutable identifier of this query object, assigned by the system. */ get sid(): string; /** * @internal */ constructor(liveQueryImpl: LiveQueryImpl); /** * Fired when an item has been added or updated. * * Parameters: * 1. {@link InsightsItem} `item` - updated item * @example * ```typescript * liveQuery.on('itemUpdated', (item) => { * console.log(`Item ${item.key} was updated`'`); * console.log('Item value:', item.value); * }); * ``` * @event */ static readonly itemUpdated = "itemUpdated"; /** * Fired when an existing item has been removed. * * Parameters: * 1. object `args` - info object provided with the event. It has the following properties: * * object `key` - the key of the removed item * @example * ```typescript * liveQuery.on('itemRemoved', (args) => { * console.log(`Item ${args.key} was removed`); * }); * ``` * @event */ static readonly itemRemoved = "itemRemoved"; /** * Closes this query instance and unsubscribes from further service events. * This will eventually stop the physical inflow of updates over the network, * when all other instances of this query are closed as well. */ close(): void; /** * @return A snapshot of items matching the current query expression. */ getItems(): ItemsSnapshot; } type InstantQueryEvents = { searchResult: (snapshot: ItemsSnapshot) => void; }; /** * Allows repetitive quick searches against specific Flex data. * Unlike a LiveQuery, this result set does not subscribe to any updates and therefore * receives no events beyond the initial result set. * * Use the {@link SyncClient.instantQuery} method to create an Instant Query. */ declare class InstantQuery extends ReplayEventEmitter { private indexName; private queryUri; private readonly insightsUri; private readonly liveQueryCreator; private readonly network; private queryExpression; private items; // private props static get type(): string; get type(): string; /** * @internal */ constructor(params: any); /** * Fired when a search result is ready. * * Parameters: * 1. {@link ItemsSnapshot} `items` - a snapshot of items matching current query expression. * @example * ```typescript * instantQuery.on('searchResult', (items) => { * Object.entries(items).forEach(([key, value]) => { * console.log('Search result item key:', key); * console.log('Search result item value:', value); * }); * }); * ``` * @event */ static readonly searchResult = "searchResult"; /** * Spawns a new search request. The result will be provided asynchronously via the {@link InstantQuery.searchResult} * event. * @param queryExpression A query expression to be executed against the given data index. For more information * on the syntax read {@link SyncClient.liveQuery}. * @return A promise that resolves when query result has been received. */ search(queryExpression: string): Promise; /** * Instantiates a LiveQuery object based on the last known query expression that was passed to the * {@link InstantQuery.search} method. This LiveQuery will start receiving updates with new results, * while current object can be still used to execute repetitive searches. * @return A promise which resolves when the LiveQuery object is ready. */ subscribe(): Promise; /** * @return A snapshot of items matching current query expression. */ getItems(): ItemsSnapshot; /** * Set new index name * @param indexName New index name to set */ updateIndexName(indexName: string): void; private generateQueryUri; } type json = { [key: string]: any; }; /** * Mode for opening the Sync object: * * `'open_or_create'` - reads a Sync object or creates one if it does not exist. * * `'open_existing'` - reads an existing Sync object. The promise is rejected if the object does not exist. * * `'create_new'` - creates a new Sync object. If the *id* property is specified, it will be used as the unique name. */ type OpenMode = "open_or_create" | "open_existing" | "create_new"; /** * Client connection state. * Directly reflects connection state of the underlying websocket transport. * Possible values are as follows: * * 'connecting' - client is offline and connection attempt is in process. * * 'connected' - client is online and ready. * * 'disconnecting' - client is going offline as disconnection is in process. * * 'disconnected' - client is offline and no connection attempt is in process. * * 'denied' - client connection is denied because of invalid JWT access token. User must refresh token in order to proceed. * * 'error' - client connection is in a permanent erroneous state. Client re-initialization is required. */ type ConnectionState = TwilsockConnectionState; /** * Client options. */ interface SyncClientOptions { /** * The level of logging to enable. */ logLevel?: "silent" | "error" | "warn" | "info" | "debug" | "trace"; twilsockClient?: Twilsock; [key: string]: any; } /** * Options for opening a Sync object. * * @example The following example is applicable to all Sync objects * (i.e., `syncClient.document()`, `syncClient.list()`,` syncClient.map()`, `syncClient.stream()`) * ```typescript * // Attempts to open an existing document with a unique name of 'MyDocument' * // If no such document exists, the promise is rejected * syncClient.document({ * id: 'MyDocument', * mode: 'open_existing' * }) * .then(...) * .catch(...); * * // Attempts to create a new document with a unique name of 'MyDocument', TTL of 24 hours and initial data `{ name: 'John Smith' }` * // If such a document already exists, the promise is rejected * syncClient.document({ * id: 'MyDocument', * mode: 'create_new', * ttl: 86400 * data: { name: 'John Smith' } // the `data` property is only applicable for Documents * }) * .then(...) * .catch(...); * ``` */ interface OpenOptions { /** * Sync object SID or unique name. */ id?: string; /** * Mode for opening the Sync object. */ mode?: OpenMode; /** * The time-to-live of the Sync object in seconds. This is applied only if the object is created. */ ttl?: number; } /** * Options for opening a document. */ interface OpenDocumentOptions extends OpenOptions { /** * The initial data of the Sync document. */ data?: json; } /** * List options. */ interface OpenListOptions extends OpenOptions { purpose?: string; context?: json; includeItems?: boolean; } /** * Map options. */ interface OpenMapOptions extends OpenOptions { includeItems?: boolean; } /** * Stream options. */ interface OpenStreamOptions extends OpenOptions { } type ConnectionError = { terminal: boolean; message: string; }; type ClientEvents = { tokenAboutToExpire: () => void; tokenExpired: () => void; connectionError: (error: ConnectionError) => void; connectionStateChanged: (state: ConnectionState) => void; }; /** * Client for the Twilio Sync service. * * @example * ```typescript * // Using NPM resolution * const SyncClient = require('twilio-sync'); * const syncClient = new SyncClient(token, { loglevel: 'debug' }); * * // Using CDN * const syncClient = new Twilio.Sync.Client(token, { logLevel: 'debug' }); * ``` */ declare class Client extends ReplayEventEmitter { private readonly services; private readonly entities; /** * @param fpaToken Twilio access token. * @param options Options to customize the client. */ constructor(fpaToken: string, options?: SyncClientOptions); /** * Fired when connection state has been changed. * * Parameters: * 1. {@link ConnectionState} `connectionState` - contains current service connection state. * @example * ```typescript * syncClient.on('connectionStateChanged', (newState) => { * console.log('Received a new connection state:', newState); * }); * ``` * @event */ static readonly connectionStateChanged = "connectionStateChanged"; /** * Fired when connection is interrupted by unexpected reason. * * Parameters: * 1. object `connectionError` - connection error details. It has following properties: * * boolean `terminal` - twilsock will stop connection attempts * * string `message` - root cause * * number? `httpStatusCode` - HTTP status code if available * * number? `errorCode` - Twilio public error code if available * @example * ```typescript * syncClient.on('connectionError', (connectionError) => { * console.error('Connection was interrupted:', connectionError.message); * console.error('Is terminal:', connectionError.terminal); * }); * ``` * @event */ static readonly connectionError = "connectionError"; /** * Fired when the access token is about to expire and needs to be updated. * The trigger takes place three minutes before the JWT access token expiry. * For long living applications, you should refresh the token when either * {@link SyncClient.tokenAboutToExpire | tokenAboutToExpire} or * {@link SyncClient.tokenExpired | tokenExpire} events occur; handling just * one of them is sufficient. * @example * The following example illustrates access token refresh. * ```typescript * syncClient.on('tokenAboutToExpire', () => { * // Obtain a JWT access token: https://www.twilio.com/docs/sync/identity-and-access-tokens * const token = ''; * syncClient.updateToken(token); * }); * ``` * @event */ static readonly tokenAboutToExpire = "tokenAboutToExpire"; /** * Fired when the access token is expired. * In case the token is not refreshed, all subsequent Sync operations will fail and the client will disconnect. * For long living applications, you should refresh the token when either * {@link SyncClient.tokenAboutToExpire | tokenAboutToExpire} or * {@link SyncClient.tokenExpired | tokenExpire} events occur; handling just * one of them is sufficient. * @event */ static readonly tokenExpired = "tokenExpired"; static populateInitRegistrations(reg: InitRegistration): void; /** * Entry point for all the incoming messages (Router). * * @param type Type of the incoming message * @param message Message to route * @internal */ _routeMessage(type: string, message: any): void; /** * Subscribe for events (Router) * * @internal */ _subscribe(sid: string, entity: any): void; /** * Unsubscribe from events (Router) * * @internal */ _unsubscribe(sid: string): void; /** * Current version of the Sync client. */ static get version(): string; /** * Current service connection state. */ get connectionState(): ConnectionState; /** * Returns a promise which resolves when library is correctly initialized * Or throws if initialization is impossible * * @internal */ private ensureReady; private storeRootInSessionCache; private readRootFromSessionCache; private _get; private _createDocument; private _getDocument; private _createList; private _getList; private _createMap; private _getMap; private _getStream; private _createStream; private _getLiveQuery; private getCached; private removeFromCacheAndSession; /** * Read or create a Sync document. * @param arg Could be any of the following: * * Unique name or SID identifying the Sync document - opens the document with the given identifier or creates one if it does not exist. * * none - creates a new document with a randomly assigned SID and no unique name. * * {@link OpenDocumentOptions} object for more granular control. * @return A promise which resolves after the document is successfully read (or created). * This promise may reject if the document could not be created or if this endpoint lacks the necessary permissions to access it. * @example * ```typescript * syncClient.document('MyDocument') * .then((document) => { * console.log('Successfully opened a document. SID:', document.sid); * document.on('updated', (event) => { * console.log('Received an "updated" event: ', event); * }); * }) * .catch((error) => { * console.error('Unexpected error', error); * }); * ``` */ document(arg?: string | OpenDocumentOptions): Promise; /** * Read or create a Sync map. * @param arg Could be any of the following: * * Unique name or SID identifying the Sync map - opens the map with the given identifier or creates one if it does not exist. * * none - creates a new map with a randomly assigned SID and no unique name. * * {@link OpenMapOptions} object for more granular control. * @return A promise which resolves after the map is successfully read (or created). * This promise may reject if the map could not be created or if this endpoint lacks the necessary permissions to access it. * @example * ```typescript * syncClient.map('MyMap') * .then((map) => { * console.log('Successfully opened a map. SID:', map.sid); * map.on('itemUpdated', (event) => { * console.log('Received an "itemUpdated" event:', event); * }); * }) * .catch((error) => { * console.error('Unexpected error', error); * }); * ``` */ map(arg?: string | OpenMapOptions): Promise; /** * Read or create a Sync list. * @param arg Could be any of the following: * * Unique name or SID identifying a Sync list - opens the list with the given identifier or creates one if it does not exist. * * none - creates a new list with a randomly assigned SID and no unique name. * * {@link OpenListOptions} object for more granular control. * @return A promise which resolves after the list is successfully read (or created). * This promise may reject if the list could not be created or if this endpoint lacks the necessary permissions to access it. * @example * ```typescript * syncClient.list('MyList') * .then((list) => { * console.log('Successfully opened a List. SID:', list.sid); * list.on('itemAdded', (event) => { * console.log('Received an "itemAdded" event:', event); * }); * }) * .catch((error) => { * console.error('Unexpected error', error); * }); * ``` */ list(arg?: string | OpenListOptions): Promise; /** * Read or create a Sync message stream. * @param arg Could be any of the following: * * Unique name or SID identifying a stream - opens the stream with the given identifier or creates one if it does not exist. * * none - creates a new stream with a randomly assigned SID and no unique name. * * {@link OpenStreamOptions} object for more granular control. * @return A promise which resolves after the stream is successfully read (or created). * The flow of messages will begin imminently (but not necessarily immediately) upon resolution. * This promise may reject if the stream could not be created or if this endpoint lacks the necessary permissions to access it. * @example * ```typescript * syncClient.stream('MyStream') * .then((stream) => { * console.log('Successfully opened a message stream. SID:', stream.sid); * stream.on('messagePublished', (event) => { * console.log('Received a "messagePublished" event:', event); * }); * }) * .catch((error) => { * console.error('Unexpected error', error); * }); * ``` */ stream(arg?: string | OpenStreamOptions): Promise; /** * Gracefully shuts the Sync client down. */ shutdown(): Promise; /** * Set the authentication token. * @param token New token to set. */ updateToken(token: string): Promise; /** * For Flex customers only. Establishes a long-running query against Flex data wherein the returned * result set is updated whenever new (or updated) records match the given expression. Updated results * are presented row-by-row according to the lifetime of the returned LiveQuery object. * * @param indexName Must specify one of the Flex data classes for which Live Queries are available. * @param queryExpression A query expression to be executed against the given data index. * Please review the [Live Query Language](https://www.twilio.com/docs/sync/live-query) * page for Sync client limits and a full list of operators currently supported in query expressions. * * @return A promise that resolves when the query has been successfully executed. * @example * ```typescript * syncClient.liveQuery('tr-worker', 'data.attributes.worker_name == "Bob"') * .then((args) => { * console.log('Subscribed to live data updates for worker Bob'); * const items = args.getItems(); * Object.entries(items).forEach(([key, value]) => { * console.log('Search result item key:', key); * console.log('Search result item value:', value); * }); * }) * .catch((err) => { * console.error('Error when subscribing to live updates for worker Bob', err); * }); * ``` */ liveQuery(indexName: string, queryExpression: string): Promise; /** * For Flex customers only. Creates a query object that can be used to issue one-time queries repeatedly * against the target index. * * @param indexName Must specify one of the Flex data classes for which live queries are available. * @return A promise which resolves after the instance of InstantQuery is successfully created. * @example * ```typescript * syncClient.instantQuery('tr-worker') * .then((q) => { * q.on('searchResult', (items) => { * Object.entries(items).forEach(([key, value]) => { * console.log('Search result item key:', key); * console.log('Search result item value:', value); * }); * }); * }); * ``` */ instantQuery(indexName: string): Promise; } export { SyncDocument, SyncDocumentMetadata, SyncList, SyncListItemMetadata, SyncListItemQueryOptions, SyncListItem, SyncMap, SyncMapItemMetadata, SyncMapItemQueryOptions, SyncMapItem, Client as SyncClient, Client, SyncClientOptions, ConnectionState, OpenMode, OpenOptions, OpenDocumentOptions, OpenListOptions, OpenMapOptions, OpenStreamOptions, InsightsItem, ItemsSnapshot, LiveQuery, InstantQuery, Mutator, Paginator, SyncStream, SyncStreamMessage };