From 973630d685a9688da621d73c93407af8bd4a8e1e Mon Sep 17 00:00:00 2001 From: amerllica Date: Sun, 25 Oct 2026 17:55:59 +0330 Subject: [PATCH 01/14] build: depend on tinode-sdk from the tinode-js devel branch --- package.json | 13 ++++++++++--- tsconfig.json | 3 ++- yarn.lock | 14 +++++++++++--- 3 files changed, 23 insertions(+), 7 deletions(-) diff --git a/package.json b/package.json index 8fd9281..03d3d70 100644 --- a/package.json +++ b/package.json @@ -1,7 +1,7 @@ { "name": "react-native-tinode", "version": "0.1.1", - "description": "Tinode chat SDK for React Native and web, rewritten in TypeScript, with React hooks", + "description": "React and React Native hooks for Tinode chat, on top of the official tinode-sdk", "main": "./lib/module/index.js", "types": "./lib/typescript/src/index.d.ts", "exports": { @@ -53,6 +53,9 @@ "publishConfig": { "registry": "https://registry.npmjs.org/" }, + "dependencies": { + "tinode-sdk": "github:tinode/tinode-js#commit=70436161b61efb1087de69f612692019f13fb2de" + }, "devDependencies": { "@commitlint/config-conventional": "^21.2.0", "@eslint/compat": "^2.1.0", @@ -105,7 +108,8 @@ "project": "tsconfig.build.json" } ] - ] + ], + "exclude": "{**/{__tests__,__fixtures__,__mocks__}/**,**/*.d.ts}" }, "jest": { "preset": "@react-native/jest-preset", @@ -143,5 +147,8 @@ ], "version": "0.63.1" }, - "sideEffects": false + "sideEffects": [ + "./src/platform/**", + "./lib/module/platform/**" + ] } diff --git a/tsconfig.json b/tsconfig.json index 4108c45..7ae2029 100644 --- a/tsconfig.json +++ b/tsconfig.json @@ -27,5 +27,6 @@ "strict": true, "target": "ESNext", "verbatimModuleSyntax": true - } + }, + "exclude": ["lib"] } diff --git a/yarn.lock b/yarn.lock index 0e545b2..66c55f0 100644 --- a/yarn.lock +++ b/yarn.lock @@ -5705,9 +5705,9 @@ __metadata: linkType: hard "fake-indexeddb@npm:^6.2.5": - version: 6.2.5 - resolution: "fake-indexeddb@npm:6.2.5" - checksum: 10c0/6c5e2fe84a61daa06d7ad63699d1041fe61847f15f92db12415634b3db94f363a64be9e08a3c3c4434af9c3c0132086b85c4d5dc5e8e06edae1e7daf70ce1f3c + version: 6.2.6 + resolution: "fake-indexeddb@npm:6.2.6" + checksum: 10c0/d55b3155548f08da1c9d7552314eed30fd1880c1f7643654c8b0c1fdf80591682d9f88e7a5c481113f48b994cb09820d61eee0dd8b966ca4f4497fce0eb748de languageName: node linkType: hard @@ -9305,6 +9305,7 @@ __metadata: react-native: "npm:0.86.3" react-native-builder-bob: "npm:^0.43.0" react-test-renderer: "npm:19.2.3" + tinode-sdk: "github:tinode/tinode-js#commit=70436161b61efb1087de69f612692019f13fb2de" turbo: "npm:^2.10.8" typescript: "npm:^6.0.3" peerDependencies: @@ -10314,6 +10315,13 @@ __metadata: languageName: node linkType: hard +"tinode-sdk@github:tinode/tinode-js#commit=70436161b61efb1087de69f612692019f13fb2de": + version: 0.25.4 + resolution: "tinode-sdk@https://github.com/tinode/tinode-js.git#commit=70436161b61efb1087de69f612692019f13fb2de" + checksum: 10c0/faf4aa6cedb36df0166452667ff8c0ba0f34306674ff5b094fb25b819d491e98ca74e9efd1196c4709eafbcad4da3764e77aa6c1191d141b35e39c512f92dfba + languageName: node + linkType: hard + "tinyexec@npm:^1.0.0": version: 1.3.1 resolution: "tinyexec@npm:1.3.1" From 62080bbc2c8d05395ac1d6767cfd5ef6c31c266f Mon Sep 17 00:00:00 2001 From: amerllica Date: Sun, 25 Oct 2026 17:56:07 +0330 Subject: [PATCH 02/14] feat: type the tinode-sdk surface --- src/sdk/__tests__/sdk.test.ts | 112 ++ src/sdk/index.ts | 55 + src/sdk/tinode-sdk.d.ts | 12 + src/sdk/types.ts | 1956 +++++++++++++++++++++++++++++++++ 4 files changed, 2135 insertions(+) create mode 100644 src/sdk/__tests__/sdk.test.ts create mode 100644 src/sdk/index.ts create mode 100644 src/sdk/tinode-sdk.d.ts create mode 100644 src/sdk/types.ts diff --git a/src/sdk/__tests__/sdk.test.ts b/src/sdk/__tests__/sdk.test.ts new file mode 100644 index 0000000..eb817a8 --- /dev/null +++ b/src/sdk/__tests__/sdk.test.ts @@ -0,0 +1,112 @@ +import { describe, expect, test } from '@jest/globals'; +import { + DEL_CHAR, + Drafty, + fromMMKV, + isCommError, + KeyValueAdapter, + MemoryAdapter, + MESSAGE_STATUS_READ, + MESSAGE_STATUS_SENT, + Tinode, + type KeyValueStore, +} from '..'; + +class FakeWebSocket { + readyState = 0; + onopen = null; + onclose = null; + onerror = null; + onmessage = null; + close(): void {} + send(): void {} +} + +class MapStore implements KeyValueStore { + data = new Map(); + getItem(key: string): string | null { + return this.data.get(key) ?? null; + } + setItem(key: string, value: string): void { + this.data.set(key, value); + } + removeItem(key: string): void { + this.data.delete(key); + } + getAllKeys(): string[] { + return [...this.data.keys()]; + } +} + +function createClient(storage: MemoryAdapter): Promise { + return new Promise((resolve, reject) => { + const client = new Tinode( + { + appName: 'Test/1.0', + host: 'localhost:6060', + apiKey: 'key', + network: { WebSocket: FakeWebSocket }, + storage, + }, + (err) => (err ? reject(err) : resolve(client)) + ); + }); +} + +describe('tinode-sdk facade', () => { + test('re-exports the Tinode statics as constants', () => { + expect(MESSAGE_STATUS_READ).toBe(Tinode.MESSAGE_STATUS_READ); + expect(MESSAGE_STATUS_SENT).toBe(50); + expect(DEL_CHAR).toBe('␡'); + expect(Tinode.getLibrary()).toMatch(/^tinodejs\//); + }); + + test('passes the storage adapter to the client', async () => { + const client = await createClient(new MemoryAdapter()); + expect(client._db.isReady()).toBe(true); + expect(client._connection).toBeDefined(); + }); + + test('keeps the cache in a key-value store', async () => { + const store = new MapStore(); + const adapter = new KeyValueAdapter(store); + await adapter.open(); + await adapter.putTopic({ name: 'grpA', seq: 3 }); + + const reopened = new KeyValueAdapter(store); + await reopened.open(); + await expect(reopened.getTopic('grpA')).resolves.toMatchObject({ + name: 'grpA', + seq: 3, + }); + }); + + test('wraps MMKV v3 and v4 stores', () => { + const removed: string[] = []; + const store = fromMMKV({ + getString: () => undefined, + set: () => {}, + getAllKeys: () => [], + remove: (key: string) => { + removed.push(key); + return true; + }, + }); + store.removeItem('a'); + expect(removed).toEqual(['a']); + }); + + test('parses Drafty with graphemes', () => { + expect(Drafty.parse('*bold* 👍🏽')?.txt).toBe('bold 👍🏽'); + }); + + test('recognises CommError by name and code', () => { + const err = Object.assign(new Error('not found'), { + name: 'CommError', + code: 404, + }); + expect(isCommError(err)).toBe(true); + expect(isCommError(new Error('plain'))).toBe(false); + expect(isCommError({ name: 'CommError', code: 404 })).toBe(false); + }); +}); diff --git a/src/sdk/index.ts b/src/sdk/index.ts new file mode 100644 index 0000000..c6ab8a2 --- /dev/null +++ b/src/sdk/index.ts @@ -0,0 +1,55 @@ +/// +import * as sdk from 'tinode-sdk'; +import type { + AccessMode as AccessModeClass, + CommError, + Drafty as DraftyClass, + IndexedDBAdapter as IndexedDBAdapterClass, + KeyValueAdapter as KeyValueAdapterClass, + KeyValueStore, + MemoryAdapter as MemoryAdapterClass, + MMKVLike, + TheCard as TheCardClass, + Tinode as TinodeClass, +} from './types'; + +export type * from './types'; + +export const Tinode: typeof TinodeClass = sdk.Tinode; +export type Tinode = TinodeClass; +export const Drafty: typeof DraftyClass = sdk.Drafty; +export type Drafty = DraftyClass; +export const TheCard: typeof TheCardClass = sdk.TheCard; +export type TheCard = TheCardClass; +export const AccessMode: typeof AccessModeClass = sdk.AccessMode; +export type AccessMode = AccessModeClass; +export const MemoryAdapter: typeof MemoryAdapterClass = sdk.MemoryAdapter; +export type MemoryAdapter = MemoryAdapterClass; +export const IndexedDBAdapter: typeof IndexedDBAdapterClass = + sdk.IndexedDBAdapter; +export type IndexedDBAdapter = IndexedDBAdapterClass; +export const KeyValueAdapter: typeof KeyValueAdapterClass = sdk.KeyValueAdapter; +export type KeyValueAdapter = KeyValueAdapterClass; + +export function fromMMKV(mmkv: MMKVLike): KeyValueStore { + return sdk.fromMMKV(mmkv); +} + +export const MESSAGE_STATUS_NONE = Tinode.MESSAGE_STATUS_NONE; +export const MESSAGE_STATUS_QUEUED = Tinode.MESSAGE_STATUS_QUEUED; +export const MESSAGE_STATUS_SENDING = Tinode.MESSAGE_STATUS_SENDING; +export const MESSAGE_STATUS_FAILED = Tinode.MESSAGE_STATUS_FAILED; +export const MESSAGE_STATUS_FATAL = Tinode.MESSAGE_STATUS_FATAL; +export const MESSAGE_STATUS_SENT = Tinode.MESSAGE_STATUS_SENT; +export const MESSAGE_STATUS_RECEIVED = Tinode.MESSAGE_STATUS_RECEIVED; +export const MESSAGE_STATUS_READ = Tinode.MESSAGE_STATUS_READ; +export const MESSAGE_STATUS_TO_ME = Tinode.MESSAGE_STATUS_TO_ME; +export const DEL_CHAR = Tinode.DEL_CHAR; + +export function isCommError(err: unknown): err is CommError { + return ( + err instanceof Error && + err.name === 'CommError' && + typeof Reflect.get(err, 'code') === 'number' + ); +} diff --git a/src/sdk/tinode-sdk.d.ts b/src/sdk/tinode-sdk.d.ts new file mode 100644 index 0000000..f6b4af8 --- /dev/null +++ b/src/sdk/tinode-sdk.d.ts @@ -0,0 +1,12 @@ +declare module 'tinode-sdk' { + export const Tinode: typeof import('./types').Tinode; + export const Drafty: typeof import('./types').Drafty; + export const TheCard: typeof import('./types').TheCard; + export const AccessMode: typeof import('./types').AccessMode; + export const MemoryAdapter: typeof import('./types').MemoryAdapter; + export const IndexedDBAdapter: typeof import('./types').IndexedDBAdapter; + export const KeyValueAdapter: typeof import('./types').KeyValueAdapter; + export function fromMMKV( + mmkv: import('./types').MMKVLike + ): import('./types').KeyValueStore; +} diff --git a/src/sdk/types.ts b/src/sdk/types.ts new file mode 100644 index 0000000..a057622 --- /dev/null +++ b/src/sdk/types.ts @@ -0,0 +1,1956 @@ +type AccessValue = number | string | null | undefined; +export interface AccessModeInput { + given?: AccessValue; + want?: AccessValue; + mode?: AccessValue; +} +export interface AccessModeJson { + mode: string | null; + given: string | null; + want: string | null; +} +export declare class AccessMode { + #private; + static readonly _NONE = 0; + static readonly _JOIN = 1; + static readonly _READ = 2; + static readonly _WRITE = 4; + static readonly _PRES = 8; + static readonly _APPROVE = 16; + static readonly _SHARE = 32; + static readonly _DELETE = 64; + static readonly _OWNER = 128; + static readonly _BITMASK: number; + static readonly _INVALID = 1048576; + given?: number | null; + want?: number | null; + mode?: number | null; + constructor(acs?: AccessModeInput | null); + static decode(str: AccessValue): number | null; + static encode(val: number | null | undefined): string | null; + static update( + val: number | null | undefined, + upd: AccessValue + ): number | null | undefined; + static diff(a1: AccessValue, a2: AccessValue): number; + toString(): string; + jsonHelper(): AccessModeJson; + setMode(m: AccessValue): this; + updateMode(u: AccessValue): this; + getMode(): string | null; + setGiven(g: AccessValue): this; + updateGiven(u: AccessValue): this; + getGiven(): string | null; + setWant(w: AccessValue): this; + updateWant(u: AccessValue): this; + getWant(): string | null; + getMissing(): string | null; + getExcessive(): string | null; + updateAll(val?: AccessModeInput | null): this; + isOwner(side?: string): boolean; + isPresencer(side?: string): boolean; + isMuted(side?: string): boolean; + isJoiner(side?: string): boolean; + isReader(side?: string): boolean; + isWriter(side?: string): boolean; + isApprover(side?: string): boolean; + isAdmin(side?: string): boolean; + isSharer(side?: string): boolean; + isDeleter(side?: string): boolean; +} + +type CardCommProto = 'tel' | 'email' | 'tinode' | 'http' | 'impp'; +export interface CardName { + surname?: string; + given?: string; + additional?: string; + prefix?: string; + suffix?: string; +} +export interface CardOrg { + fn?: string; + title?: string; +} +export interface CardPhoto { + type?: string; + data?: string; + ref?: string; +} +interface CardBirthday { + y?: number; + m: number; + d: number; +} +export interface CardComm { + proto: CardCommProto; + des: string[]; + value: string; +} +export interface CardData { + fn?: string; + n?: CardName; + org?: CardOrg; + note?: string; + bday?: CardBirthday; + photo?: CardPhoto | '\u2421'; + comm?: CardComm[]; +} +type MaybeCard = CardData | null | undefined; +export interface TheCard extends CardData {} +export declare class TheCard { + static contentType: string; + constructor( + fn?: string, + imageUrl?: string, + imageMimeType?: string, + note?: string + ); + merge(other: CardData): void; + get contentType(): string; + get size(): number; + static setFn(card: MaybeCard, fn?: string | null): CardData; + static getFn(card: MaybeCard): string | null; + static setNote(card: MaybeCard, note?: string | null): CardData; + static setPhoto( + card: MaybeCard, + imageUrl?: string | null, + imageMimeType?: string | null + ): CardData; + static getPhotoUrl(card: MaybeCard): string | null; + static getOrg(card: MaybeCard): string | null; + static setPhone(card: MaybeCard, phone: string, type?: string): CardData; + static setEmail(card: MaybeCard, email: string, type?: string): CardData; + static setTinodeID( + card: MaybeCard, + tinodeID: string, + type?: string + ): CardData; + static addPhone(card: MaybeCard, phone: string, type?: string): CardData; + static addEmail(card: MaybeCard, email: string, type?: string): CardData; + static addTinodeID( + card: MaybeCard, + tinodeID: string, + type?: string + ): CardData; + static clearPhone( + card: T, + phone?: string, + type?: string + ): T; + static clearEmail( + card: T, + email?: string, + type?: string + ): T; + static clearTinodeID( + card: T, + tinodeID?: string, + type?: string + ): T; + static getComm(card: MaybeCard, proto: string): CardComm[]; + static getEmails(card: MaybeCard): string[]; + static getPhones(card: MaybeCard): string[]; + static getFirstTinodeID(card: MaybeCard): string | null; + static exportVCard(card: MaybeCard): string | null; + static importVCard(vcardStr: unknown): CardData | null; + static isFileSupported(type?: string | null, name?: string | null): boolean; +} + +type DraftyEntityType = + 'AU' | 'BN' | 'EX' | 'HT' | 'IM' | 'LN' | 'MN' | 'TC' | 'VC' | 'VD'; +type DraftyStyleType = + | DraftyEntityType + | 'BR' + | 'CO' + | 'DL' + | 'EM' + | 'FM' + | 'HD' + | 'HL' + | 'QQ' + | 'RW' + | 'ST'; +type DraftyJsonObject = { + readonly [key: string]: unknown; +}; +export interface DraftyEntData extends CardData { + act?: string; + aonly?: boolean; + duration?: number; + height?: number; + incoming?: boolean; + mime?: string; + name?: string; + premime?: string; + preref?: string; + preview?: string; + ref?: string; + size?: number; + state?: string; + title?: string; + url?: string; + val?: string | DraftyJsonObject; + vc?: boolean; + width?: number; + _tempPreview?: string; + _processing?: boolean; +} +export interface DraftyFmt { + at?: number; + len?: number; + tp?: DraftyStyleType; + key?: number; +} +export interface DraftyEnt { + tp: DraftyStyleType; + data?: DraftyEntData; +} +export interface DraftyDoc { + txt?: string; + fmt?: DraftyFmt[]; + ent?: DraftyEnt[]; +} +export type DraftySource = DraftyDoc | string | null | undefined; +export interface DraftyNode { + type?: DraftyStyleType; + text?: string; + data?: DraftyEntData; + key?: number; + att?: boolean; + children?: DraftyNode[] | null; + parent?: DraftyNode; +} +export type DraftyFormatter = ( + style: DraftyStyleType | undefined, + data: DraftyEntData | undefined, + values: (R | string)[] | null, + index: number, + stack: DraftyStyleType[] | undefined +) => R | null | undefined; +type DraftyEntityCallback = ( + data: DraftyEntData | undefined, + index: number, + tp: DraftyStyleType +) => unknown; +type DraftyStyleCallback = ( + tp: DraftyStyleType | undefined, + at: number | undefined, + len: number | undefined, + key: number | undefined, + index: number +) => unknown; +type DraftyLogger = (message: string, ...args: unknown[]) => void; +type DraftyAttributes = Record< + string, + string | number | boolean | null | undefined +>; +interface ImageDesc { + mime?: string; + refurl?: string; + bits?: string; + preview?: string; + width?: number; + height?: number; + filename?: string; + size?: number; + _tempPreview?: string; + urlPromise?: Promise; +} +interface VideoDesc { + mime?: string; + refurl?: string; + bits?: string; + preview?: string; + preref?: string; + width?: number; + height?: number; + duration?: number; + filename?: string; + size?: number; + _tempPreview?: string; + urlPromise?: Promise<[string | undefined, string | undefined]>; +} +interface AudioDesc { + mime?: string; + refurl?: string; + bits?: string; + duration?: number; + preview?: string; + filename?: string; + size?: number; + urlPromise?: Promise; +} +interface AttachmentDesc { + mime?: string; + data?: string; + filename?: string; + size?: number; + refurl?: string; + urlPromise?: Promise; +} +interface LinkData { + txt: string; + url: string; +} +interface VideoCallUpdate { + state?: string; + duration?: number; + incoming?: boolean; + vc?: boolean; +} +type ButtonActionType = 'url' | 'pub'; +export declare class Drafty implements DraftyDoc { + txt: string; + fmt: DraftyFmt[]; + ent: DraftyEnt[]; + static logger?: DraftyLogger | null; + static readonly contentType = 'text/x-drafty'; + static init(plainText?: unknown): DraftyDoc | null; + static parse(content: string): DraftyDoc; + static parse(content: unknown): DraftyDoc | null; + static append(first: DraftyDoc, second: DraftySource): DraftyDoc; + static append( + first: DraftyDoc | null | undefined, + second: DraftySource + ): DraftySource; + static insertImage( + content: DraftyDoc | null | undefined, + at: number, + imageDesc: ImageDesc + ): DraftyDoc; + static insertVideo( + content: DraftyDoc | null | undefined, + at: number, + videoDesc: VideoDesc + ): DraftyDoc; + static insertAudio( + content: DraftyDoc | null | undefined, + at: number, + audioDesc: AudioDesc + ): DraftyDoc; + static videoCall(audioOnly?: boolean): DraftyDoc; + static updateVideoCall( + content: T, + params: VideoCallUpdate + ): T; + static quote(header: string, uid: string, body: DraftySource): DraftyDoc; + static mention(name: string | null | undefined, uid: string): DraftyDoc; + static appendLink( + content: DraftyDoc | null | undefined, + linkData: LinkData + ): DraftyDoc; + static appendImage( + content: DraftyDoc | null | undefined, + imageDesc: ImageDesc + ): DraftyDoc; + static appendAudio( + content: DraftyDoc | null | undefined, + audioDesc: AudioDesc + ): DraftyDoc; + static attachFile( + content: DraftyDoc | null | undefined, + attachmentDesc: AttachmentDesc + ): DraftyDoc; + static wrapInto( + content: DraftyDoc | string, + style: DraftyStyleType, + at?: number, + len?: number + ): DraftyDoc; + static wrapAsForm( + content: DraftyDoc | string, + at?: number, + len?: number + ): DraftyDoc; + static insertButton( + content: DraftySource, + at: number, + len: number, + name: string | undefined, + actionType: ButtonActionType, + actionValue?: string, + refUrl?: string + ): DraftyDoc | null; + static appendButton( + content: DraftyDoc | null | undefined, + title: string, + name: string | undefined, + actionType: ButtonActionType, + actionValue?: string, + refUrl?: string + ): DraftyDoc | null; + static attachJSON( + content: DraftyDoc | null | undefined, + data: DraftyJsonObject + ): DraftyDoc; + static appendLineBreak(content: DraftyDoc | null | undefined): DraftyDoc; + static appendTheCard( + content: DraftyDoc | null | undefined, + theCardData: CardData + ): DraftyDoc; + static UNSAFE_toHTML(doc: DraftySource): string | null; + static format( + original: DraftySource, + formatter: DraftyFormatter, + context?: unknown + ): R | null | undefined; + static shorten( + original: DraftySource, + limit: number, + light?: boolean + ): DraftyDoc; + static forwardedContent(original: DraftySource): DraftyDoc; + static replyContent(original: DraftySource, limit: number): DraftySource; + static preview( + original: DraftySource, + limit: number, + forwarding?: boolean + ): DraftyDoc; + static toPlainText(content: DraftyDoc | string): string | undefined; + static isPlainText(content: DraftyDoc | string): boolean; + static toMarkdown(content: DraftySource): string | null; + static isValid(content: unknown): boolean; + static hasAttachments(content: DraftyDoc): boolean; + static attachments( + content: DraftyDoc, + callback: DraftyEntityCallback, + context?: unknown + ): void; + static hasEntities(content: DraftySource): boolean; + static entities( + content: DraftyDoc, + callback: DraftyEntityCallback, + context?: unknown + ): void; + static styles( + content: DraftyDoc, + callback: DraftyStyleCallback, + context?: unknown + ): void; + static sanitizeEntities( + content: T + ): T; + static getDownloadUrl(entData: DraftyEntData): string | null; + static isProcessing(entData: DraftyEntData): boolean; + static getPreviewUrl(entData: DraftyEntData): string | null; + static getEntitySize(entData: DraftyEntData): number; + static getEntityMimeType(entData: DraftyEntData): string; + static tagName(style: DraftyStyleType | undefined): string | undefined; + static attrValue( + style: DraftyStyleType | undefined, + data: DraftyEntData | null | undefined + ): DraftyAttributes | null | undefined; + static getContentType(): string; + static isFormResponseType(mimeType: string | null | undefined): boolean; +} + +type Comparator = (a: T, b: T) => number; +type ForEachCallback = ( + elem: T, + prev: T | undefined, + next: T | undefined, + index: number +) => void; +type FilterCallback = (elem: T, index: number) => boolean; +declare class CBuffer { + #private; + buffer: T[]; + constructor(compare?: Comparator | null, unique?: boolean); + getAt(at: number): T | undefined; + getLast(filter?: FilterCallback | null): T | undefined; + put(items: T[]): void; + put(...items: T[]): void; + delAt(at: number): T | undefined; + delRange(since: number, before: number): T[]; + length(): number; + reset(): void; + forEach( + callback: ForEachCallback, + startIdx?: number, + beforeIdx?: number, + context?: unknown + ): void; + find(elem: T, nearest?: boolean): number; + filter(callback: FilterCallback, context?: unknown): void; + isEmpty(): boolean; +} + +export interface SeqRange$1 { + low: number; + hi?: number; +} +export interface TopicRecord { + name: string; + created?: Date; + updated?: Date; + deleted?: Date; + touched?: Date; + read?: number; + recv?: number; + seq?: number; + clear?: number; + defacs?: unknown; + creds?: unknown; + public?: unknown; + trusted?: unknown; + private?: unknown; + _aux?: unknown; + _deleted?: boolean; + tags?: string[]; + acs?: unknown; +} +export interface UserRecord { + uid: string; + public: unknown; +} +export interface SubscriptionRecord { + topic: string; + uid: string; + updated?: Date; + mode?: string; + read?: number; + recv?: number; + clear?: number; + lastSeen?: unknown; + userAgent?: string; +} +export interface MessageRecord { + topic: string; + seq: number; + ts?: Date; + _status?: number; + from?: string; + head?: unknown; + content?: unknown; +} +export interface DelLogRecord { + topic: string; + clear: number; + low: number; + hi: number; +} +export interface DelLogRange { + low: number; + hi: number; +} +export interface SeqWindow { + since: number; + before: number; + limit: number; +} +export interface StorageAdapter { + open(): Promise; + close(): Promise; + destroy(): Promise; + isOpen(): boolean; + getTopics(): Promise; + getTopic(name: string): Promise; + putTopic(record: TopicRecord): Promise; + removeTopic(name: string): Promise; + getUsers(): Promise; + getUser(uid: string): Promise; + putUser(record: UserRecord): Promise; + removeUser(uid: string): Promise; + getSubscriptions(topic: string): Promise; + getSubscription( + topic: string, + uid: string + ): Promise; + putSubscription(record: SubscriptionRecord): Promise; + removeSubscription(topic: string, uid: string): Promise; + putMessage(record: MessageRecord): Promise; + updateMessageStatus( + topic: string, + seq: number, + status: number + ): Promise; + removeMessages(topic: string, low: number, hi: number): Promise; + readMessages(topic: string, window: SeqWindow): Promise; + readMessageRanges( + topic: string, + ranges: SeqRange$1[] + ): Promise; + addDelLog(records: DelLogRecord[]): Promise; + readDelLog(topic: string, window: SeqWindow): Promise; + readDelLogRanges(topic: string, ranges: SeqRange$1[]): Promise; + maxDelId(topic: string): Promise; +} + +type PersistentCacheLogger = (...args: unknown[]) => void; +type PersistentCacheErrorHandler = (error: unknown) => void; +interface CacheableTopic { + name: string; + seq: number; + read: number; + unread: number; + acs?: unknown; + _tags?: unknown; + getAccessMode(): { + jsonHelper(): unknown; + }; + setAccessMode(acs: unknown): unknown; +} +interface MessageQuery { + since?: number; + before?: number; + limit?: number; + ranges?: SeqRange$1[]; +} +interface CacheableMessage { + topic: string; + seq: number; +} +type CachedSubscription = SubscriptionRecord & { + user: string; +}; +interface CachedUser { + user: string; + public: unknown; +} +type EachCallback = (this: unknown, item: T) => void; +declare class PersistentCache { + #private; + constructor( + onError: PersistentCacheErrorHandler | null | undefined, + logger: PersistentCacheLogger | null | undefined, + adapter: StorageAdapter | null + ); + get disabled(): boolean; + initDatabase(): Promise; + deleteDatabase(): Promise; + isReady(): boolean; + updTopic(topic: CacheableTopic): Promise; + markTopicAsDeleted(name: string, deleted: boolean): Promise; + remTopic(name: string): Promise; + mapTopics( + callback?: EachCallback, + context?: unknown + ): Promise; + deserializeTopic(topic: CacheableTopic, src: TopicRecord): void; + updUser(uid: string, pub?: unknown): Promise; + remUser(uid: string): Promise; + mapUsers( + callback?: EachCallback, + context?: unknown + ): Promise; + getUser(uid: string): Promise; + updSubscription(topicName: string, uid: string, sub: object): Promise; + remSubscription(topicName: string, uid: string): Promise; + mapSubscriptions( + topicName: string, + callback?: EachCallback, + context?: unknown + ): Promise; + addMessage(msg: CacheableMessage): Promise; + updMessageStatus( + topicName: string, + seq: number, + status: number + ): Promise; + remMessages(topicName: string, from?: number, to?: number): Promise; + readMessages( + topicName: string, + query?: MessageQuery | null, + callback?: EachCallback, + context?: unknown + ): Promise; + addDelLog( + topicName: string, + delId: number, + ranges: SeqRange$1[] + ): Promise; + readDelLog( + topicName: string, + query?: MessageQuery | null + ): Promise; + maxDelId(topicName: string): Promise; +} + +export interface SeqRange { + low: number; + hi?: number; +} + +export type MessageCallback = ( + data: Message, + prev: Message | undefined, + next: Message | undefined, + idx: number +) => void; +export type SubscriberCallback = ( + sub: TopicSubscription, + key: string, + all: Record +) => void; +type ReceiptKind = 'recv' | 'read'; +export interface TopicCallbacks { + onData?: (data?: Message) => void; + onMeta?: (meta: MetaMessage) => void; + onPres?: (pres: PresMessage) => void; + onInfo?: (info: InfoMessage) => void; + onMetaDesc?: (topic: Topic) => void; + onMetaSub?: (sub: TopicSubscription) => void; + onSubsUpdated?: (keys: string[], count?: number) => void; + onTagsUpdated?: (tags: string[]) => void; + onCredsUpdated?: (creds: Credential[]) => void; + onAuxUpdated?: (aux: Record) => void; + onDeleteTopic?: () => void; + onAllMessagesReceived?: (count: number) => void; +} +export declare class Topic { + #private; + name: string; + created: Date | undefined; + updated: Date | undefined; + touched: Date; + deleted: Date | undefined; + acs: AccessMode; + defacs: DefAcs | undefined; + private: TopicPrivate | null; + public: unknown; + trusted: unknown; + seq: number; + read: number; + recv: number; + unread: number; + clear: number; + subcnt: number; + online: boolean | undefined; + seen: LastSeen | undefined; + topic: string | undefined; + _users: Record; + _queuedSeqId: number; + _maxSeq: number; + _minSeq: number; + _noEarlierMsgs: boolean; + _maxDel: number; + _recvNotificationTimer: ReturnType | null; + _tags: string[]; + _credentials: Credential[]; + _aux: Record; + _messageVersions: Record>; + _messages: CBuffer; + _attached: boolean; + _lastSubsUpdate: Date; + _new?: boolean; + _deleted: boolean; + _delayedLeaveTimer: ReturnType | null; + onData: TopicCallbacks['onData']; + onMeta: TopicCallbacks['onMeta']; + onPres: TopicCallbacks['onPres']; + onInfo: TopicCallbacks['onInfo']; + onMetaDesc: TopicCallbacks['onMetaDesc']; + onMetaSub: TopicCallbacks['onMetaSub']; + onSubsUpdated: TopicCallbacks['onSubsUpdated']; + onTagsUpdated: TopicCallbacks['onTagsUpdated']; + onCredsUpdated: TopicCallbacks['onCredsUpdated']; + onAuxUpdated: TopicCallbacks['onAuxUpdated']; + onDeleteTopic: TopicCallbacks['onDeleteTopic']; + onAllMessagesReceived: TopicCallbacks['onAllMessagesReceived']; + _cacheGetUser: (uid: string) => TopicSubscription | undefined; + _cachePutUser: (uid: string, user: TopicSubscription) => void; + _cacheDelUser: (uid: string) => void; + _cachePutSelf: () => void; + _cacheDelSelf: () => void; + constructor(name: string, callbacks?: TopicCallbacks); + get _tinode(): Tinode; + set _tinode(tinode: Tinode); + static topicType(name: string | null | undefined): TopicType | undefined; + static isMeTopicName(name: string | null | undefined): boolean; + static isSelfTopicName(name: string | null | undefined): boolean; + static isGroupTopicName(name: string | null | undefined): boolean; + static isP2PTopicName(name: string | null | undefined): boolean; + static isCommTopicName(name: string | null | undefined): boolean; + static isNewGroupTopicName(name: string | null | undefined): boolean; + static isChannelTopicName(name: string | null | undefined): boolean; + isSubscribed(): boolean; + subscribe( + getParams?: GetQuery, + setParams?: SetParams + ): Promise; + createMessage(data: DraftyDoc | string, noEcho?: boolean): PubMessage; + publish( + data: DraftyDoc | string, + noEcho?: boolean + ): Promise; + publishMessage(pub: PubMessage): Promise; + publishDraft( + pub: PubMessage, + prom?: Promise | null + ): Promise; + leave(unsub?: boolean): Promise; + leaveDelayed(unsub: boolean, delay: number): void; + getMeta(params?: GetQuery): Promise; + getMessagesPage( + limit: number, + gaps: SeqRange[] | null | undefined, + min: number, + max: number, + newer: boolean + ): Promise; + getPinnedMessages(): Promise; + setMeta(params: SetParams): Promise; + updateMode(uid: string | null, update: string): Promise; + invite(uid: string, mode?: string | null): Promise; + archive(arch: boolean): Promise; + pinMessage(seq: number, pin: boolean): Promise; + pinTopic(_topic: string, _pin?: boolean): Promise; + pinnedTopicRank(_topic: string): number; + delMessages(ranges: SeqRange[], hard?: boolean): Promise; + delMessagesAll(hardDel?: boolean): Promise; + delMessagesList(list: number[], hardDel?: boolean): Promise; + delMessagesEdits(seq: number, hardDel?: boolean): Promise; + delTopic(hard?: boolean): Promise; + delSubscription(user: string): Promise; + note(what: ReceiptKind, seq: number): void; + noteRecv(seq: number): void; + noteRead(seq?: number): void; + noteKeyPress(): void; + noteRecording(audioOnly?: boolean): void; + videoCall(evt: string, seq: number, payload?: unknown): void; + _updateMyReadRecv( + what: ReceiptKind | 'msg', + seq?: number, + ts?: Date + ): boolean; + userDesc(uid: string): TopicSubscription | undefined; + p2pPeerDesc(): TopicSubscription | undefined; + subscribers(callback?: SubscriberCallback, context?: unknown): void; + tags(): string[]; + aux(key: string): unknown; + alias(): string | undefined; + subscriber(uid: string): TopicSubscription | undefined; + messageVersions( + origSeq: number, + callback?: MessageCallback, + context?: unknown + ): void; + messages( + callback?: MessageCallback, + sinceId?: number, + beforeId?: number, + context?: unknown + ): void; + findMessage(seq: number): Message | undefined; + latestMessage(): Message | undefined; + latestMsgVersion(seq: number): Message | null; + maxMsgSeq(): number; + minMsgSeq(): number; + maxClearId(): number; + messageCount(): number; + queuedMessages(callback: MessageCallback, context?: unknown): void; + msgReceiptCount(what: ReceiptKind, seq: number): number; + msgReadCount(seq: number): number; + msgRecvCount(seq: number): number; + msgHasMoreMessages(min: number, max: number, newer: boolean): SeqRange[]; + isNewMessage(seqId: number): boolean; + flushMessage(seqId: number): Message | undefined; + flushMessageRange(fromId: number, untilId: number): Message[]; + swapMessageId(pub: Message, newSeqId: number): void; + cancelSend(seqId: number): boolean; + getType(): TopicType | undefined; + getAccessMode(): AccessMode; + setAccessMode(acs?: AccessModeInput | null): AccessMode; + getDefaultAccess(): DefAcs | undefined; + startMetaQuery(): MetaGetBuilder; + isArchived(): boolean; + isMeType(): boolean; + isSelfType(): boolean; + isChannelType(): boolean; + isGroupType(): boolean; + isP2PType(): boolean; + isCommType(): boolean; + msgStatus(msg: Message, upd?: boolean): number; + _maybeUpdateMessageVersionsCache(msg: Message): void; + _routeData(data: Message): void; + _routeMeta(meta: MetaMessage): void; + _routePres(pres: PresMessage): void; + _routeInfo(info: InfoMessage): void; + _processMetaDesc(desc: TopicDesc): void; + _processMetaSubs(subs: TopicSubscription[], skipSubcnt?: boolean): void; + _processMetaTags(tags: string[] | string): void; + _processMetaCreds(_creds: Credential[], _upd?: boolean): void; + _processMetaAux(aux: Record | string | null): void; + _processDelMessages(clear: number, delseq?: SeqRange[]): void; + _allMessagesReceived(count: number): void; + _resetSub(): void; + _gone(): void; + _updateCachedUser(uid: string, obj: TopicSubscription): TopicSubscription; + _getQueuedSeqId(): number; + _loadMessages(db: PersistentCache, query?: GetDataType): Promise; + _updateReceived(seq: number | undefined, act?: string): void; +} + +export interface GetOptsType { + ims?: Date; + limit?: number; +} +interface GetSubType extends GetOptsType { + user?: string; + topic?: string; +} +export interface GetDataType { + since?: number; + before?: number; + limit?: number; + ranges?: SeqRange[]; +} +interface GetDelType { + since?: number; + limit?: number; +} +export interface GetQuery { + what?: string; + desc?: GetOptsType; + sub?: GetSubType; + data?: GetDataType; + del?: GetDelType; +} +interface MetaWhat { + data?: GetDataType; + sub?: GetSubType; + desc?: GetOptsType; + tags?: true; + cred?: true; + aux?: true; + del?: GetDelType; +} +type MetaWhatKey = keyof MetaWhat; +export declare class MetaGetBuilder { + #private; + topic: Topic; + what: MetaWhat; + constructor(parent: Topic); + withData(since?: number, before?: number, limit?: number): this; + withLaterData(limit?: number): this; + withDataRanges(ranges: SeqRange[], limit?: number): this; + withDataList(list: number[]): this; + withEarlierData(limit?: number): this; + withDesc(ims?: Date): this; + withLaterDesc(): this; + withSub(ims?: Date, limit?: number, userOrTopic?: string): this; + withOneSub(ims?: Date, userOrTopic?: string): this; + withLaterOneSub(userOrTopic?: string): this; + withLaterSub(limit?: number): this; + withTags(): this; + withCred(): this; + withAux(): this; + withDel(since?: number, limit?: number): this; + withLaterDel(limit?: number): this; + extract(what: K): MetaWhat[K]; + build(): GetQuery | undefined; +} + +export type TopicType = 'me' | 'fnd' | 'grp' | 'p2p' | 'sys' | 'slf'; +export interface DefAcs { + auth?: string; + anon?: string; +} +export interface AuthToken { + token: string; + expires: Date; +} +export interface Credential { + meth: string; + val?: string; + resp?: string; + params?: unknown; + done?: boolean; +} +export interface LastSeen { + when?: Date; + ua?: string; +} +export interface TopicPrivate { + arch?: boolean; + tpin?: string[]; + comment?: string; + [key: string]: unknown; +} +export interface TopicDesc { + created?: Date; + updated?: Date; + touched?: Date; + deleted?: Date; + defacs?: DefAcs; + acs?: AccessMode; + seq?: number; + read?: number; + recv?: number; + clear?: number; + unread?: number; + subcnt?: number; + online?: boolean; + seen?: LastSeen; + public?: unknown; + private?: unknown; + trusted?: unknown; + _noForwarding?: boolean; +} +export interface TopicSubscription { + user?: string; + topic?: string; + created?: Date; + updated?: Date; + touched?: Date; + deleted?: Date; + acs?: AccessMode; + mode?: string; + seq?: number; + read?: number; + recv?: number; + clear?: number; + unread?: number; + online?: boolean; + seen?: LastSeen; + public?: unknown; + private?: unknown; + trusted?: unknown; + _noForwarding?: boolean; +} +export interface MessageHead { + 'mime'?: string; + 'replace'?: string; + 'forwarded'?: string; + 'webrtc'?: string; + 'webrtc-duration'?: number; + 'vc'?: boolean; + [key: string]: unknown; +} +export interface Message { + id?: string; + topic: string; + seq: number; + from?: string; + ts?: Date; + head?: MessageHead | null; + content?: DraftyDoc | string; + noecho?: boolean; + low?: number; + hi?: number; + _deleted?: boolean; + _sending?: boolean; + _failed?: boolean; + _fatal?: boolean; + _cancelled?: boolean; + _status?: number; + _noForwarding?: boolean; + _origTs?: Date; + _origSeq?: number; +} +export interface PubMessage extends Omit { + seq?: number; +} +export interface CtrlParams { + what?: string; + count?: number; + seq?: number; + del?: number; + acs?: AccessMode; + user?: string; + token?: string; + expires?: Date; + unsub?: boolean; + ver?: string; + build?: string; + sid?: string; + [key: string]: unknown; +} +export interface CtrlMessage { + id?: string; + topic?: string; + code: number; + text?: string; + ts?: Date; + params?: CtrlParams; +} +export interface DataMessage { + topic: string; + from?: string; + ts: Date; + seq: number; + head?: MessageHead; + content?: DraftyDoc | string; +} +export interface DelValues { + clear: number; + delseq: SeqRange[]; +} +export interface MetaMessage { + id?: string; + topic: string; + ts?: Date; + desc?: TopicDesc; + sub?: TopicSubscription[]; + tags?: string[]; + cred?: Credential[]; + del?: DelValues; + aux?: Record; +} +export type PresWhat = + | 'on' + | 'off' + | 'ua' + | 'upd' + | 'gone' + | 'acs' + | 'term' + | 'msg' + | 'read' + | 'recv' + | 'del' + | 'tags' + | 'aux'; +export interface PresMessage { + topic?: string; + src?: string; + what: PresWhat; + seq?: number; + clear?: number; + delseq?: SeqRange[]; + ua?: string; + act?: string; + tgt?: string; + dacs?: AccessModeInput; + _noForwarding?: boolean; +} +export type InfoWhat = 'kp' | 'kpa' | 'kpv' | 'recv' | 'read' | 'call'; +export interface InfoMessage { + topic?: string; + src?: string; + from?: string; + what: InfoWhat; + seq?: number; + event?: string; + payload?: unknown; + _noForwarding?: boolean; +} +export interface ServerMessage { + ctrl?: CtrlMessage; + data?: DataMessage; + meta?: MetaMessage; + pres?: PresMessage; + info?: InfoMessage; +} +export interface ServerParams { + ver?: string; + build?: string; + sid?: string; + [key: string]: unknown; +} +export interface SetDesc { + defacs?: DefAcs; + public?: unknown; + private?: unknown; + trusted?: unknown; + acs?: AccessMode; + updated?: Date; + _noForwarding?: boolean; +} +export interface SetSub { + user?: string | null; + mode?: string | null; + topic?: string; + acs?: AccessMode; + updated?: Date; + _noForwarding?: boolean; +} +export interface SetParams { + desc?: SetDesc; + sub?: SetSub; + tags?: string[]; + cred?: Credential; + aux?: Record; + attachments?: string[]; +} +export interface AccountParams { + defacs?: DefAcs; + public?: unknown; + private?: unknown; + trusted?: unknown; + tags?: string[]; + cred?: Credential[]; + scheme?: string; + secret?: string; + attachments?: string[]; +} +export interface HiPacket { + id?: string; + ver?: string; + ua?: string; + dev?: string | null; + lang?: string; + platf?: string; +} +export interface AccPacket { + id?: string; + user: string | null; + scheme: string | null; + secret: string | null; + tmpscheme?: string; + tmpsecret?: string; + login?: boolean; + tags?: string[]; + desc: SetDesc; + cred?: Credential[]; +} +export interface LoginPacket { + id?: string; + scheme: string; + secret: string; + cred?: Credential[] | null; +} +export interface SubPacket { + id?: string; + topic: string; + get?: GetQuery; + set: { + desc?: SetDesc; + sub?: SetSub; + tags?: string[]; + aux?: Record; + }; +} +export interface LeavePacket { + id?: string; + topic: string; + unsub?: boolean; +} +export interface GetPacket extends GetQuery { + id?: string; + topic: string; +} +export interface SetPacket { + id?: string; + topic: string; + desc?: SetDesc; + sub?: SetSub; + tags?: string[]; + cred?: Credential; + aux?: Record; +} +export type DelWhat = 'msg' | 'topic' | 'sub' | 'cred' | 'user'; +export interface DelPacket { + id?: string; + topic: string | null; + what: DelWhat; + delseq?: SeqRange[]; + user?: string; + cred?: { + meth: string; + val: string; + }; + hard?: boolean; +} +export type NoteWhat = 'recv' | 'read' | 'kp' | 'kpa' | 'kpv' | 'call'; +export interface NotePacket { + id?: string; + topic: string; + what: NoteWhat; + seq?: number; + event?: string; + payload?: unknown; +} +export interface ClientMessage { + hi?: HiPacket; + acc?: AccPacket; + login?: LoginPacket; + sub?: SubPacket; + leave?: LeavePacket; + pub?: PubMessage; + get?: GetPacket; + set?: SetPacket; + del?: DelPacket; + note?: NotePacket; + extra?: { + attachments: string[]; + }; +} +export interface PushPayload { + what: string; + topic?: string; + seq?: number; + xfrom?: string; + modeGiven?: string; + modeWant?: string; +} + +export declare class CommError extends Error { + code: number; + constructor(message: string, code: number); +} + +type Handler$1 = { + bivarianceHack(evt: E): void; +}['bivarianceHack']; +export interface WebSocketLike { + readonly OPEN?: number; + readyState: number; + onopen: ((evt: unknown) => void) | null; + onclose: ((evt: unknown) => void) | null; + onerror: ((evt: unknown) => void) | null; + onmessage: ((evt: { data: unknown }) => void) | null; + send(data: string): void; + close(): void; +} +export interface LongPollRequestLike { + readyState: number; + status: number; + responseText: string; + onreadystatechange: Handler$1 | null; + open(method: string, url: string, async: boolean): void; + send(body?: string | null): void; + abort(): void; +} +export type WebSocketProviderType = new (url: string) => WebSocketLike; +export type XHRProviderType$2 = new () => LongPollRequestLike; +type ConnectionTransport = 'ws' | 'lp'; +type ConnectionLogger = (...args: unknown[]) => void; +interface ConnectionConfig { + host: string; + apiKey: string; + transport: string; + secure?: boolean; +} +export type AutoreconnectIterationCallback = ( + timeout: number, + promise?: Promise +) => void; +declare class Connection { + #private; + static readonly NETWORK_ERROR = 503; + static readonly NETWORK_ERROR_TEXT = 'Connection failed'; + static readonly NETWORK_USER = 418; + static readonly NETWORK_USER_TEXT = 'Disconnected by client'; + host: string; + secure: boolean | undefined; + apiKey: string; + version: string; + autoreconnect: boolean; + initialized: ConnectionTransport | undefined; + onMessage: ((message: string) => void) | undefined; + onDisconnect: ((err: CommError, code: number) => void) | undefined; + onOpen: (() => void) | undefined; + onAutoreconnectIteration: AutoreconnectIterationCallback | undefined; + connect: (host_?: string | null, force?: boolean) => Promise; + reconnect: (force?: boolean) => void; + disconnect: () => void; + sendText: (msg: string) => void; + isConnected: () => boolean; + constructor( + config: ConnectionConfig, + version_: string, + autoreconnect_: boolean + ); + static setNetworkProviders( + wsProvider?: WebSocketProviderType, + xhrProvider?: XHRProviderType$2 + ): void; + static set logger(l: ConnectionLogger); + transport(): ConnectionTransport | undefined; + probe(): void; + backoffReset(): void; + retryNow(): void; +} + +export type FoundContactCallback = ( + contact: TopicSubscription, + key: string, + all: Record +) => void; +export declare class TopicFnd extends Topic { + _contacts: Record; + constructor(callbacks?: TopicCallbacks); + _processMetaSubs(subs: TopicSubscription[]): void; + publish(): Promise; + setMeta(params: SetParams): Promise; + checkTagUniqueness(tag: string, caller: string): Promise; + contacts(callback?: FoundContactCallback, context?: unknown): void; +} + +type Handler = { + bivarianceHack(evt: E): void; +}['bivarianceHack']; +interface UploadProgressEventLike { + lengthComputable: boolean; + loaded: number; + total: number; +} +interface XHRLike { + readyState: number; + status: number; + statusText: string; + response: unknown; + responseType: string; + upload: { + onprogress: Handler | null; + }; + onload: Handler | null; + onerror: Handler | null; + onabort: Handler | null; + onprogress: Handler<{ + loaded: number; + }> | null; + open(method: string, url: string, async: boolean): void; + setRequestHeader(name: string, value: string): void; + send(body?: FormData | null): void; + abort(): void; +} +export type XHRProviderType$1 = new () => XHRLike; +type LargeFileTinode = Pick< + Tinode, + | '_apiKey' + | '_secure' + | '_host' + | 'getAuthToken' + | 'getNextUniqueId' + | 'logger' +>; +export interface ReactNativeFileDescriptor { + uri: string; + name: string; + type: string; +} +export type UploadData = Blob | ReactNativeFileDescriptor; +interface ServerCtrl { + code: number; + text: string; + params?: Record; +} +type ProgressCallback = (progress: number) => void; +type SuccessCallback = (ctrl: ServerCtrl) => void; +type FailureCallback = (ctrl: ServerCtrl | null) => void; +type DownloadErrorCallback = (err: unknown) => void; +export declare class LargeFileHelper { + _tinode: LargeFileTinode; + _version: string; + _apiKey: string; + _authToken: ReturnType; + xhr: XHRLike[]; + onProgress: ProgressCallback | undefined; + constructor(tinode: LargeFileTinode, version: string); + uploadWithBaseUrl( + baseUrl: string | null | undefined, + data: UploadData, + avatarFor?: string | null, + onProgress?: ProgressCallback | null, + onSuccess?: SuccessCallback | null, + onFailure?: FailureCallback | null + ): Promise; + upload( + data: UploadData, + avatarFor?: string | null, + onProgress?: ProgressCallback | null, + onSuccess?: SuccessCallback | null, + onFailure?: FailureCallback | null + ): Promise; + download( + relativeUrl: string, + filename?: string, + mimetype?: string, + onProgress?: ProgressCallback | null, + onError?: DownloadErrorCallback | null + ): Promise | undefined; + cancel(): void; + static setNetworkProvider(xhrProvider?: XHRProviderType$1): void; +} + +export type ContactCallback = (contact: Topic, key: string) => void; +export interface TopicMeCallbacks extends TopicCallbacks { + onContactUpdate?: (what: PresWhat, cont: Topic) => void; +} +export declare class TopicMe extends Topic { + onContactUpdate: TopicMeCallbacks['onContactUpdate']; + constructor(callbacks?: TopicMeCallbacks); + _processMetaDesc(desc: TopicDesc): void; + _processMetaSubs(subs: TopicSubscription[]): void; + _processMetaCreds(creds: Credential[], upd?: boolean): void; + _routePres(pres: PresMessage): void; + _refreshContact(what: PresWhat, cont: Topic): void; + publish(): Promise; + delCredential(method: string, value: string): Promise; + contacts( + callback: ContactCallback, + filter?: ((contact: Topic) => boolean) | null, + context?: unknown + ): void; + getContact(name: string): Topic | undefined; + getAccessMode(): AccessMode; + getAccessMode(name?: string): AccessMode | null; + isArchived(name?: string): boolean; + getCredentials(): Credential[]; + pinTopic(topic: string, pin?: boolean): Promise; + pinnedTopicRank(topic: string): number; +} + +export interface NetInfoStateLike { + isConnected: boolean | null; +} +export interface NetInfoLike { + addEventListener(listener: (state: NetInfoStateLike) => void): () => void; +} + +export type XHRProviderType = XHRProviderType$2 & XHRProviderType$1; +export interface TinodeNetwork { + WebSocket?: WebSocketProviderType; + XMLHttpRequest?: XHRProviderType; +} +export interface TinodeConfig { + appName?: string; + host: string; + apiKey: string; + transport?: 'ws' | 'lp' | null; + secure?: boolean; + platform?: 'ios' | 'android' | 'web'; + persist?: boolean; + storage?: StorageAdapter | null; + netInfo?: NetInfoLike | null; + network?: TinodeNetwork; +} +interface PendingPromise { + resolve(ctrl: CtrlMessage): void; + resolveMeta?(meta: MetaMessage): void; + reject(err: Error): void; + ts: Date; +} +export declare class Tinode { + #private; + static readonly MESSAGE_STATUS_NONE = 0; + static readonly MESSAGE_STATUS_QUEUED = 10; + static readonly MESSAGE_STATUS_SENDING = 20; + static readonly MESSAGE_STATUS_FAILED = 30; + static readonly MESSAGE_STATUS_FATAL = 40; + static readonly MESSAGE_STATUS_SENT = 50; + static readonly MESSAGE_STATUS_RECEIVED = 60; + static readonly MESSAGE_STATUS_READ = 70; + static readonly MESSAGE_STATUS_TO_ME = 80; + static readonly DEL_CHAR = '\u2421'; + static readonly MAX_MESSAGE_SIZE = 'maxMessageSize'; + static readonly MAX_SUBSCRIBER_COUNT = 'maxSubscriberCount'; + static readonly MIN_TAG_LENGTH = 'minTagLength'; + static readonly MAX_TAG_LENGTH = 'maxTagLength'; + static readonly MAX_TAG_COUNT = 'maxTagCount'; + static readonly MAX_FILE_UPLOAD_SIZE = 'maxFileUploadSize'; + static readonly REQ_CRED_VALIDATORS = 'reqCred'; + static readonly MSG_DELETE_AGE = 'msgDelAge'; + static readonly URI_TOPIC_ID_PREFIX = 'tinode:///id/'; + static readonly URI_TOPIC_ALIAS_PREFIX = 'tinode:///alias/'; + static readonly TAG_ALIAS = 'alias:'; + static readonly TAG_EMAIL = 'email:'; + static readonly TAG_PHONE = 'tel:'; + _host: string; + _secure: boolean | undefined; + _appName: string; + _apiKey: string; + _browser: string; + _platform: string; + _hwos: string; + _humanLanguage: string; + _loggingEnabled: boolean; + _trimLongStrings: boolean; + _myUID: string | null; + _authenticated: boolean; + _login: string | null; + _authToken: AuthToken | null; + _inPacketCount: number; + _messageId: number; + _serverInfo: ServerParams | null; + _deviceToken: string | null; + _pendingPromises: Record; + _expirePromises: ReturnType | null; + _connection: Connection; + _persist: boolean; + _db: PersistentCache; + _cache: Record; + onWebsocketOpen: (() => void) | undefined; + onConnect: (() => void) | undefined; + onDisconnect: ((err?: Error | null) => void) | undefined; + onLogin: ((code: number, text: string | undefined) => void) | undefined; + onCtrlMessage: ((ctrl: CtrlMessage) => void) | undefined; + onDataMessage: ((data: DataMessage) => void) | undefined; + onPresMessage: ((pres: PresMessage) => void) | undefined; + onMetaMessage: ((meta: MetaMessage) => void) | undefined; + onInfoMessage: ((info: InfoMessage) => void) | undefined; + onMessage: ((pkt: ServerMessage) => void) | undefined; + onRawMessage: ((text: string) => void) | undefined; + onNetworkProbe: (() => void) | undefined; + onAutoreconnectIteration: AutoreconnectIterationCallback | undefined; + constructor(config: TinodeConfig, onComplete?: (err?: unknown) => void); + logger: (str: unknown, ...args: unknown[]) => void; + static credential( + meth?: string | Credential | null, + val?: string | null, + params?: unknown, + resp?: string | null + ): Credential[] | null; + static topicType(name: string | null | undefined): TopicType | undefined; + static isMeTopicName(name: string | null | undefined): boolean; + static isSelfTopicName(name: string | null | undefined): boolean; + static isGroupTopicName(name: string | null | undefined): boolean; + static isP2PTopicName(name: string | null | undefined): boolean; + static isCommTopicName(name: string | null | undefined): boolean; + static isNewGroupTopicName(name: string | null | undefined): boolean; + static isChannelTopicName(name: string | null | undefined): boolean; + static getVersion(): string; + /** @deprecated Pass `network: { WebSocket, XMLHttpRequest }` in the config instead. */ + static setNetworkProviders( + wsProvider?: WebSocketProviderType | null, + xhrProvider?: XHRProviderType | null + ): void; + /** @deprecated Pass `storage: new IndexedDBAdapter(provider)` in the config instead. */ + static setDatabaseProvider(idbProvider?: unknown): void; + static getLibrary(): string; + static isNullValue(str: unknown): boolean; + static isServerAssignedSeq(seq: number): boolean; + static parseTinodeUrl(tinodeUrl: unknown): string | null; + static isValidTagValue(tag: unknown): boolean; + static tagSplit(tag: string | null | undefined): { + prefix: string; + value: string; + } | null; + static setUniqueTag( + tags: string[] | null | undefined, + uniqueTag: string + ): string[]; + static clearTagPrefix( + tags: (string | null | undefined)[] | null | undefined, + prefix: string + ): string[]; + static tagByPrefix( + tags: (string | null | undefined)[] | null | undefined, + prefix: string + ): string | undefined; + getNextUniqueId(): string | undefined; + connect(host_?: string | null): Promise; + reconnect(force?: boolean): void; + disconnect(): void; + clearStorage(): Promise; + initStorage(): Promise; + networkProbe(): void; + isConnected(): boolean; + isAuthenticated(): boolean; + authorizeURL(url: T): T | string; + account( + uid: string | null, + scheme: string | null, + secret: string | null, + login?: boolean, + params?: AccountParams + ): Promise; + createAccount( + scheme: string, + secret: string, + login?: boolean, + params?: AccountParams + ): Promise; + createAccountBasic( + username: string | null | undefined, + password: string | null | undefined, + params?: AccountParams + ): Promise; + updateAccountBasic( + uid: string | null, + username: string | null | undefined, + password: string | null | undefined, + params?: AccountParams + ): Promise; + hello(): Promise; + setDeviceToken(dt: string | null | undefined | false): boolean; + login( + scheme: string, + secret: string, + cred?: Credential[] | null + ): Promise; + loginBasic( + uname: string, + password: string, + cred?: Credential[] | null + ): Promise; + loginToken(token: string, cred?: Credential[] | null): Promise; + requestResetAuthSecret( + scheme: string, + method: string, + value: string + ): Promise; + getAuthToken(): AuthToken | null; + setAuthToken(token: AuthToken | null): void; + subscribe( + topicName: string, + getParams?: GetQuery, + setParams?: SetParams + ): Promise; + leave(topic: string, unsub?: boolean): Promise; + createMessage( + topic: string, + content: DraftyDoc | string, + noEcho?: boolean + ): PubMessage; + publish( + topicName: string, + content: DraftyDoc | string, + noEcho?: boolean + ): Promise; + publishMessage( + pub: PubMessage, + attachments?: string[] | null + ): Promise; + oobNotification(data: PushPayload): void; + getMeta(topic: string, params?: GetQuery): Promise; + setMeta(topic: string, params: SetParams): Promise; + delMessages( + topic: string, + ranges: SeqRange[], + hard?: boolean + ): Promise; + delTopic(topicName: string, hard?: boolean): Promise; + delSubscription(topicName: string, user: string): Promise; + delCredential(method: string, value: string): Promise; + delCurrentUser(hard?: boolean): Promise; + note(topicName: string, what: 'recv' | 'read', seq: number): void; + noteKeyPress(topicName: string, type?: 'kp' | 'kpa' | 'kpv'): void; + videoCall( + topicName: string, + seq: number, + evt: string, + payload?: unknown + ): void; + getTopic(topicName: 'me'): TopicMe; + getTopic(topicName: 'fnd'): TopicFnd; + getTopic(topicName: string | null | undefined): Topic | undefined; + cacheGetTopic(topicName: string | null | undefined): Topic | undefined; + cacheRemTopic(topicName: string): void; + mapTopics( + func: (topic: Topic, key: string) => boolean | void, + context?: unknown + ): void; + isTopicCached(topicName: string): boolean; + newGroupTopicName(isChan?: boolean): string; + getMeTopic(): TopicMe; + getFndTopic(): TopicFnd; + getLargeFileHelper(): LargeFileHelper; + getCurrentUserID(): string | null; + isMe(uid: string | null | undefined): boolean; + getCurrentLogin(): string | null; + getServerInfo(): ServerParams | null; + report(action: string, target: string): Promise; + getServerParam(name: string, defaultValue?: unknown): unknown; + enableLogging(enabled: boolean, trimLongStrings?: boolean): void; + setHumanLanguage(hl: string | null | undefined): void; + isTopicOnline(name: string): boolean; + getTopicAccessMode(name: string): AccessMode | null; + wantAkn(status: boolean): void; +} + +export declare class MemoryAdapter implements StorageAdapter { + #private; + open(): Promise; + close(): Promise; + destroy(): Promise; + isOpen(): boolean; + getTopics(): Promise; + getTopic(name: string): Promise; + putTopic(record: TopicRecord): Promise; + removeTopic(name: string): Promise; + getUsers(): Promise; + getUser(uid: string): Promise; + putUser(record: UserRecord): Promise; + removeUser(uid: string): Promise; + getSubscriptions(topic: string): Promise; + getSubscription( + topic: string, + uid: string + ): Promise; + putSubscription(record: SubscriptionRecord): Promise; + removeSubscription(topic: string, uid: string): Promise; + putMessage(record: MessageRecord): Promise; + updateMessageStatus( + topic: string, + seq: number, + status: number + ): Promise; + removeMessages(topic: string, low: number, hi: number): Promise; + readMessages(topic: string, window: SeqWindow): Promise; + readMessageRanges( + topic: string, + ranges: SeqRange$1[] + ): Promise; + addDelLog(records: DelLogRecord[]): Promise; + readDelLog(topic: string, window: SeqWindow): Promise; + readDelLogRanges(topic: string, ranges: SeqRange$1[]): Promise; + maxDelId(topic: string): Promise; +} + +interface IdbRequest { + result: T; + error: unknown; + onsuccess: (() => void) | null; + onerror: (() => void) | null; +} +interface IdbOpenRequest extends IdbRequest { + onupgradeneeded: (() => void) | null; + onblocked: (() => void) | null; +} +interface IdbCursor { + value: T; + continue(): void; +} +interface IdbIndex { + openCursor( + range: unknown, + direction: 'prev' + ): IdbRequest | null>; +} +interface IdbObjectStore { + indexNames: { + contains(name: string): boolean; + }; + get(key: unknown): IdbRequest; + getAll(range?: unknown): IdbRequest; + put(value: object): IdbRequest; + delete(key: unknown): IdbRequest; + openCursor( + range: unknown, + direction: 'prev' + ): IdbRequest | null>; + index(name: string): IdbIndex; + createIndex( + name: string, + keyPath: string[], + options: { + unique: boolean; + } + ): unknown; +} +interface IdbTransaction { + error: unknown; + oncomplete: (() => void) | null; + onerror: (() => void) | null; + onabort: (() => void) | null; + objectStore(name: string): IdbObjectStore; +} +interface IdbDatabase { + objectStoreNames: { + contains(name: string): boolean; + }; + onversionchange: (() => void) | null; + transaction(stores: string[], mode?: 'readwrite'): IdbTransaction; + createObjectStore( + name: string, + options: { + keyPath: string | string[]; + } + ): IdbObjectStore; + close(): void; +} +interface IdbFactory { + open(name: string, version: number): IdbOpenRequest; + deleteDatabase(name: string): IdbRequest & { + onblocked: (() => void) | null; + }; +} +interface IdbKeyRangeStatic { + only(value: unknown): unknown; + bound( + lower: unknown, + upper: unknown, + lowerOpen?: boolean, + upperOpen?: boolean + ): unknown; +} +interface IndexedDBProvider { + factory: IdbFactory; + keyRange: IdbKeyRangeStatic; +} +export declare class IndexedDBAdapter implements StorageAdapter { + #private; + constructor(provider?: IndexedDBProvider); + static isSupported(): boolean; + open(): Promise; + close(): Promise; + destroy(): Promise; + isOpen(): boolean; + getTopics(): Promise; + getTopic(name: string): Promise; + putTopic(record: TopicRecord): Promise; + removeTopic(name: string): Promise; + getUsers(): Promise; + getUser(uid: string): Promise; + putUser(record: UserRecord): Promise; + removeUser(uid: string): Promise; + getSubscriptions(topic: string): Promise; + getSubscription( + topic: string, + uid: string + ): Promise; + putSubscription(record: SubscriptionRecord): Promise; + removeSubscription(topic: string, uid: string): Promise; + putMessage(record: MessageRecord): Promise; + updateMessageStatus( + topic: string, + seq: number, + status: number + ): Promise; + removeMessages(topic: string, low: number, hi: number): Promise; + readMessages(topic: string, window: SeqWindow): Promise; + readMessageRanges( + topic: string, + ranges: SeqRange$1[] + ): Promise; + addDelLog(records: DelLogRecord[]): Promise; + readDelLog(topic: string, window: SeqWindow): Promise; + readDelLogRanges(topic: string, ranges: SeqRange$1[]): Promise; + maxDelId(topic: string): Promise; +} + +type Awaitable = T | Promise; +export interface KeyValueStore { + getItem(key: string): Awaitable; + setItem(key: string, value: string): unknown; + removeItem(key: string): unknown; + getAllKeys(): Awaitable; + getMany?( + keys: string[] + ): Awaitable>; + multiGet?( + keys: string[] + ): Awaitable; +} +interface MMKVReadWrite { + getString(key: string): string | undefined; + set(key: string, value: string): void; + getAllKeys(): string[]; +} +export type MMKVLike = MMKVReadWrite & + ( + | { + remove(key: string): unknown; + } + | { + delete(key: string): unknown; + } + ); +export interface KeyValueAdapterOptions { + prefix?: string; +} +export declare class KeyValueAdapter extends MemoryAdapter { + #private; + constructor(store: KeyValueStore, options?: KeyValueAdapterOptions); + open(): Promise; + destroy(): Promise; + putTopic(record: TopicRecord): Promise; + removeTopic(name: string): Promise; + putUser(record: UserRecord): Promise; + removeUser(uid: string): Promise; + putSubscription(record: SubscriptionRecord): Promise; + removeSubscription(topic: string, uid: string): Promise; + putMessage(record: MessageRecord): Promise; + updateMessageStatus( + topic: string, + seq: number, + status: number + ): Promise; + removeMessages(topic: string, low: number, hi: number): Promise; + addDelLog(records: DelLogRecord[]): Promise; +} From 33461f604d2e57973cd67f92928b949f90445990 Mon Sep 17 00:00:00 2001 From: amerllica Date: Sun, 25 Oct 2026 17:56:09 +0330 Subject: [PATCH 03/14] feat: polyfill Intl.Segmenter and TextDecoder for Hermes --- src/platform/__tests__/graphemes.test.ts | 85 ++++++++++ src/platform/__tests__/intl-segmenter.test.ts | 49 ++++++ src/platform/__tests__/text-decoder.test.ts | 52 +++++++ src/platform/graphemes.ts | 147 ++++++++++++++++++ src/platform/index.ts | 5 + src/platform/intl-segmenter.ts | 32 ++++ src/platform/text-decoder.ts | 36 +++++ src/platform/utf8.ts | 45 ++++++ 8 files changed, 451 insertions(+) create mode 100644 src/platform/__tests__/graphemes.test.ts create mode 100644 src/platform/__tests__/intl-segmenter.test.ts create mode 100644 src/platform/__tests__/text-decoder.test.ts create mode 100644 src/platform/graphemes.ts create mode 100644 src/platform/index.ts create mode 100644 src/platform/intl-segmenter.ts create mode 100644 src/platform/text-decoder.ts create mode 100644 src/platform/utf8.ts diff --git a/src/platform/__tests__/graphemes.test.ts b/src/platform/__tests__/graphemes.test.ts new file mode 100644 index 0000000..962a45e --- /dev/null +++ b/src/platform/__tests__/graphemes.test.ts @@ -0,0 +1,85 @@ +import { describe, expect, test } from '@jest/globals'; + +import { splitGraphemesFallback } from '../graphemes'; + +const segmentsOf = (str: string) => + splitGraphemesFallback(str).map(({ segment }) => segment); + +describe('splitGraphemesFallback', () => { + test('plain ASCII and Cyrillic', () => { + expect(segmentsOf('abc')).toEqual(['a', 'b', 'c']); + expect(segmentsOf('жЫр')).toEqual(['ж', 'Ы', 'р']); + expect(segmentsOf('')).toEqual([]); + }); + + test('surrogate pairs', () => { + expect(segmentsOf('a😀b')).toEqual(['a', '😀', 'b']); + expect(segmentsOf('𝒳𝒴')).toEqual(['𝒳', '𝒴']); + }); + + test('combining marks', () => { + expect(segmentsOf('éx')).toEqual(['é', 'x']); + expect(segmentsOf('ạ̈b')).toEqual(['ạ̈', 'b']); + }); + + test('variation selectors', () => { + expect(segmentsOf('❤️!')).toEqual(['❤️', '!']); + expect(segmentsOf('🕯️ x')).toEqual(['🕯️', ' ', 'x']); + }); + + test('skin tone modifiers', () => { + expect(segmentsOf('Hi👋🏼Hi')).toEqual(['H', 'i', '👋🏼', 'H', 'i']); + }); + + test('ZWJ sequences', () => { + expect(segmentsOf('b1👩🏽‍✈️b2')).toEqual(['b', '1', '👩🏽‍✈️', 'b', '2']); + expect(segmentsOf('👨‍👩‍👧‍👦')).toEqual(['👨‍👩‍👧‍👦']); + }); + + test('ZWJ before a letter does not glue the letter', () => { + expect(segmentsOf('a‍b')).toEqual(['a‍', 'b']); + }); + + test('regional indicator flags pair up', () => { + expect(segmentsOf('🇺🇸🇫🇷')).toEqual(['🇺🇸', '🇫🇷']); + expect(segmentsOf('🇺🇸🇫')).toEqual(['🇺🇸', '🇫']); + }); + + test('tag sequence flags', () => { + const england = '🏴\u{E0067}\u{E0062}\u{E0065}\u{E006E}\u{E0067}\u{E007F}'; + expect(segmentsOf(england + 'x')).toEqual([england, 'x']); + }); + + test('keycaps', () => { + expect(segmentsOf('1️⃣#️⃣')).toEqual(['1️⃣', '#️⃣']); + }); + + test('CRLF stays together, other controls split', () => { + expect(segmentsOf('a\r\nb')).toEqual(['a', '\r\n', 'b']); + expect(segmentsOf('\ń')).toEqual(['\n', '́']); + }); + + test('segment index is the UTF-16 offset', () => { + expect(splitGraphemesFallback('a😀👋🏼b')).toEqual([ + { segment: 'a', index: 0 }, + { segment: '😀', index: 1 }, + { segment: '👋🏼', index: 3 }, + { segment: 'b', index: 7 }, + ]); + }); + + test('matches Intl.Segmenter on mixed text', () => { + const samples = [ + 'Это *жЫрный*, `код` и _наклонный_', + '😀 b1👩🏽‍✈️b2 smile 123', + 'Hi 👋🏼 Visit http://localhost:6060', + '🔴Hello🔴 🟠Hello🟠 🇩🇪🇯🇵', + 'café 1️⃣ 👨‍👩‍👧‍👦 ❤️', + ]; + const segmenter = new Intl.Segmenter(); + for (const sample of samples) { + const expected = Array.from(segmenter.segment(sample), (s) => s.segment); + expect(segmentsOf(sample)).toEqual(expected); + } + }); +}); diff --git a/src/platform/__tests__/intl-segmenter.test.ts b/src/platform/__tests__/intl-segmenter.test.ts new file mode 100644 index 0000000..c0799ad --- /dev/null +++ b/src/platform/__tests__/intl-segmenter.test.ts @@ -0,0 +1,49 @@ +import { describe, expect, jest, test } from '@jest/globals'; +import { installIntlSegmenter } from '../intl-segmenter'; + +const nativeSegmenter = Intl.Segmenter; + +function withoutNativeSegmenter(run: () => void): void { + Reflect.deleteProperty(Intl, 'Segmenter'); + try { + run(); + } finally { + Object.defineProperty(Intl, 'Segmenter', { + value: nativeSegmenter, + configurable: true, + writable: true, + }); + } +} + +describe('installIntlSegmenter', () => { + test('adds a grapheme segmenter when Intl has none', () => { + withoutNativeSegmenter(() => { + installIntlSegmenter(); + const input = 'a👍🏽b'; + expect(Array.from(new Intl.Segmenter().segment(input))).toEqual([ + { segment: 'a', index: 0, input }, + { segment: '👍🏽', index: 1, input }, + { segment: 'b', index: 5, input }, + ]); + expect(new Intl.Segmenter().resolvedOptions().granularity).toBe( + 'grapheme' + ); + }); + }); + + test('keeps the native segmenter', () => { + installIntlSegmenter(); + expect(Intl.Segmenter).toBe(nativeSegmenter); + }); + + test('lets tinode-sdk load before Intl.Segmenter exists natively', () => { + withoutNativeSegmenter(() => { + jest.isolateModules(() => { + require('..'); + const { Drafty } = require('tinode-sdk'); + expect(Drafty.parse('*bold* 👍🏽').txt).toBe('bold 👍🏽'); + }); + }); + }); +}); diff --git a/src/platform/__tests__/text-decoder.test.ts b/src/platform/__tests__/text-decoder.test.ts new file mode 100644 index 0000000..6fa23dd --- /dev/null +++ b/src/platform/__tests__/text-decoder.test.ts @@ -0,0 +1,52 @@ +import { describe, expect, jest, test } from '@jest/globals'; +import { installTextDecoder } from '../text-decoder'; + +const nativeDecoder = globalThis.TextDecoder; + +function withoutNativeDecoder(run: () => void): void { + Reflect.deleteProperty(globalThis, 'TextDecoder'); + try { + run(); + } finally { + Object.defineProperty(globalThis, 'TextDecoder', { + value: nativeDecoder, + configurable: true, + writable: true, + }); + } +} + +describe('installTextDecoder', () => { + test('adds a UTF-8 decoder when there is none', () => { + withoutNativeDecoder(() => { + installTextDecoder(); + const decoder = new TextDecoder('utf-8'); + const bytes = new Uint8Array([ + 0x63, 0x61, 0x66, 0xc3, 0xa9, 0x20, 0xe2, 0x82, 0xac, 0x20, 0xf0, 0x9f, + 0x98, 0x80, + ]); + expect(decoder.decode(bytes)).toBe('café € 😀'); + expect(decoder.decode(bytes.buffer)).toBe('café € 😀'); + expect(decoder.decode(new Uint8Array([0x61, 0x80, 0x62]))).toBe('a�b'); + expect(decoder.decode()).toBe(''); + expect(() => new TextDecoder('utf-16le')).toThrow(RangeError); + }); + }); + + test('keeps the native decoder', () => { + installTextDecoder(); + expect(globalThis.TextDecoder).toBe(nativeDecoder); + }); + + test('lets tinode-sdk decode a UTF-8 vCard without a native decoder', () => { + withoutNativeDecoder(() => { + jest.isolateModules(() => { + require('..'); + const { TheCard } = require('tinode-sdk'); + const vcard = + 'BEGIN:VCARD\r\nFN;ENCODING=QUOTED-PRINTABLE:=D8=B9=D9=84=DB=8C =E2=82=AC =F0=9F=98=80 caf=C3=A9\r\nEND:VCARD'; + expect(TheCard.importVCard(vcard)?.fn).toBe('علی € \u{1F600} café'); + }); + }); + }); +}); diff --git a/src/platform/graphemes.ts b/src/platform/graphemes.ts new file mode 100644 index 0000000..ab3cecf --- /dev/null +++ b/src/platform/graphemes.ts @@ -0,0 +1,147 @@ +export interface GraphemeSegment { + readonly segment: string; + readonly index: number; +} + +type CodePointRange = readonly [number, number]; +type CodePointTest = (codePoint: number) => boolean; + +const CARRIAGE_RETURN = 0x0d; +const LINE_FEED = 0x0a; +const ZERO_WIDTH_JOINER = 0x200d; + +const COMBINING_MARK_RANGES: readonly CodePointRange[] = [ + [0x0300, 0x036f], + [0x0483, 0x0489], + [0x0591, 0x05bd], + [0x0610, 0x061a], + [0x064b, 0x065f], + [0x0900, 0x0903], + [0x093a, 0x094f], + [0x1ab0, 0x1aff], + [0x1dc0, 0x1dff], + [0x20d0, 0x20ff], + [0xfe00, 0xfe0f], + [0xfe20, 0xfe2f], + [0xe0100, 0xe01ef], +]; + +const PICTOGRAPHIC_RANGES: readonly CodePointRange[] = [ + [0x00a9, 0x00a9], + [0x00ae, 0x00ae], + [0x203c, 0x203c], + [0x2049, 0x2049], + [0x2122, 0x2122], + [0x2139, 0x2139], + [0x2194, 0x21aa], + [0x231a, 0x23ff], + [0x24c2, 0x24c2], + [0x25aa, 0x25fe], + [0x2600, 0x27bf], + [0x2934, 0x2935], + [0x2b05, 0x2b55], + [0x3030, 0x3030], + [0x303d, 0x303d], + [0x3297, 0x3297], + [0x3299, 0x3299], + [0x1f000, 0x1faff], + [0x1fc00, 0x1fffd], +]; + +const REGIONAL_INDICATOR: CodePointRange = [0x1f1e6, 0x1f1ff]; +const EMOJI_MODIFIER: CodePointRange = [0x1f3fb, 0x1f3ff]; +const TAG_CHARACTER: CodePointRange = [0xe0020, 0xe007f]; + +function inRange(codePoint: number, [low, high]: CodePointRange): boolean { + return codePoint >= low && codePoint <= high; +} + +function unicodePropertyTest( + property: string, + fallback: readonly CodePointRange[] +): CodePointTest { + try { + const pattern = new RegExp(`^\\p{${property}}$`, 'u'); + return (codePoint) => pattern.test(String.fromCodePoint(codePoint)); + } catch { + return (codePoint) => fallback.some((range) => inRange(codePoint, range)); + } +} + +const isCombiningMark = unicodePropertyTest('M', COMBINING_MARK_RANGES); +const isPictographic = unicodePropertyTest( + 'Extended_Pictographic', + PICTOGRAPHIC_RANGES +); + +function isControl(codePoint: number): boolean { + return codePoint < 0x20 || (codePoint >= 0x7f && codePoint <= 0x9f); +} + +function isRegionalIndicator(codePoint: number): boolean { + return inRange(codePoint, REGIONAL_INDICATOR); +} + +function isClusterExtender(codePoint: number): boolean { + return ( + codePoint === ZERO_WIDTH_JOINER || + isCombiningMark(codePoint) || + inRange(codePoint, EMOJI_MODIFIER) || + inRange(codePoint, TAG_CHARACTER) + ); +} + +function continuesCluster( + previous: number, + current: number, + regionalIndicatorRun: number +): boolean { + if (previous === CARRIAGE_RETURN) { + return current === LINE_FEED; + } + if (isControl(previous) || isControl(current)) { + return false; + } + if (isClusterExtender(current)) { + return true; + } + if (previous === ZERO_WIDTH_JOINER) { + return isPictographic(current); + } + return isRegionalIndicator(current) && regionalIndicatorRun % 2 === 1; +} + +export function splitGraphemesFallback(str: string): GraphemeSegment[] { + const segments: GraphemeSegment[] = []; + let segment = ''; + let segmentStart = 0; + let offset = 0; + let previous = -1; + let regionalIndicatorRun = 0; + + for (const char of str) { + const codePoint = char.codePointAt(0) ?? 0; + if ( + segment && + continuesCluster(previous, codePoint, regionalIndicatorRun) + ) { + segment += char; + } else { + if (segment) { + segments.push({ segment, index: segmentStart }); + } + segment = char; + segmentStart = offset; + } + regionalIndicatorRun = isRegionalIndicator(codePoint) + ? regionalIndicatorRun + 1 + : 0; + previous = codePoint; + offset += char.length; + } + + if (segment) { + segments.push({ segment, index: segmentStart }); + } + return segments; +} diff --git a/src/platform/index.ts b/src/platform/index.ts new file mode 100644 index 0000000..7962d9e --- /dev/null +++ b/src/platform/index.ts @@ -0,0 +1,5 @@ +import { installIntlSegmenter } from './intl-segmenter'; +import { installTextDecoder } from './text-decoder'; + +installIntlSegmenter(); +installTextDecoder(); diff --git a/src/platform/intl-segmenter.ts b/src/platform/intl-segmenter.ts new file mode 100644 index 0000000..7438d02 --- /dev/null +++ b/src/platform/intl-segmenter.ts @@ -0,0 +1,32 @@ +import { splitGraphemesFallback } from './graphemes'; + +interface GraphemeSegmentData { + segment: string; + index: number; + input: string; +} + +class GraphemeSegmenter { + segment(input: string): GraphemeSegmentData[] { + return splitGraphemesFallback(input).map(({ segment, index }) => ({ + segment, + index, + input, + })); + } + + resolvedOptions(): { locale: string; granularity: 'grapheme' } { + return { locale: 'en', granularity: 'grapheme' }; + } +} + +export function installIntlSegmenter(): void { + if (typeof Intl === 'undefined' || typeof Intl.Segmenter === 'function') { + return; + } + Object.defineProperty(Intl, 'Segmenter', { + value: GraphemeSegmenter, + configurable: true, + writable: true, + }); +} diff --git a/src/platform/text-decoder.ts b/src/platform/text-decoder.ts new file mode 100644 index 0000000..f37d003 --- /dev/null +++ b/src/platform/text-decoder.ts @@ -0,0 +1,36 @@ +import { decodeUtf8 } from './utf8'; + +const UTF8_LABELS = ['utf-8', 'utf8', 'unicode-1-1-utf-8']; + +class Utf8TextDecoder { + readonly encoding = 'utf-8'; + + constructor(label: string = 'utf-8') { + if (!UTF8_LABELS.includes(label.trim().toLowerCase())) { + throw new RangeError(`Unsupported encoding: ${label}`); + } + } + + decode(input?: ArrayBuffer | ArrayBufferView): string { + if (!input) { + return ''; + } + if (ArrayBuffer.isView(input)) { + return decodeUtf8( + new Uint8Array(input.buffer, input.byteOffset, input.byteLength) + ); + } + return decodeUtf8(new Uint8Array(input)); + } +} + +export function installTextDecoder(): void { + if (Reflect.has(globalThis, 'TextDecoder')) { + return; + } + Object.defineProperty(globalThis, 'TextDecoder', { + value: Utf8TextDecoder, + configurable: true, + writable: true, + }); +} diff --git a/src/platform/utf8.ts b/src/platform/utf8.ts new file mode 100644 index 0000000..4557e55 --- /dev/null +++ b/src/platform/utf8.ts @@ -0,0 +1,45 @@ +const REPLACEMENT_CHAR = '\uFFFD'; + +function continuationCount(lead: number): number { + if (lead < 0x80) return 0; + if (lead >= 0xc2 && lead <= 0xdf) return 1; + if (lead >= 0xe0 && lead <= 0xef) return 2; + if (lead >= 0xf0 && lead <= 0xf4) return 3; + return -1; +} + +export function decodeUtf8(bytes: Uint8Array): string { + let result = ''; + let i = 0; + while (i < bytes.length) { + const lead = bytes[i] ?? 0; + const extra = continuationCount(lead); + if (extra < 0) { + result += REPLACEMENT_CHAR; + i++; + continue; + } + let codePoint = extra === 0 ? lead : lead % 2 ** (6 - extra); + let consumed = 1; + let valid = true; + for (let k = 1; k <= extra; k++) { + const next = bytes[i + k]; + if (next === undefined || next < 0x80 || next > 0xbf) { + valid = false; + break; + } + codePoint = codePoint * 64 + (next - 0x80); + consumed++; + } + const minimum = [0, 0x80, 0x800, 0x10000][extra] ?? 0; + const isSurrogate = codePoint >= 0xd800 && codePoint <= 0xdfff; + if (!valid || codePoint < minimum || codePoint > 0x10ffff || isSurrogate) { + result += REPLACEMENT_CHAR; + i += valid ? consumed : Math.max(consumed, 1); + continue; + } + result += String.fromCodePoint(codePoint); + i += consumed; + } + return result; +} From 0159e048202b3a159fa8396ef59febb25162e345 Mon Sep 17 00:00:00 2001 From: amerllica Date: Sun, 25 Oct 2026 17:56:10 +0330 Subject: [PATCH 04/14] refactor: build the React layer on tinode-sdk --- src/index.tsx | 86 +-------------------- src/react/TinodeProvider.tsx | 2 +- src/react/TinodeStoresProvider.tsx | 14 +--- src/react/__fixtures__/fake-client.ts | 2 +- src/react/__fixtures__/render-hook.tsx | 6 +- src/react/__tests__/TinodeProvider.test.tsx | 71 ++++++++--------- src/react/__tests__/useMessages.test.tsx | 2 +- src/react/constants.ts | 3 + src/react/context.ts | 2 +- src/react/createTinode.ts | 14 +++- src/react/index.ts | 1 - src/react/messages-store.ts | 4 +- src/react/netinfo.ts | 23 ------ src/react/ports.ts | 4 +- src/react/session-store.ts | 2 +- src/react/topic-registry.ts | 4 +- src/react/useLogin.ts | 2 +- src/react/useMeTopic.ts | 2 +- src/react/useMessages.ts | 4 +- src/react/useTinode.ts | 2 +- 20 files changed, 67 insertions(+), 183 deletions(-) create mode 100644 src/react/constants.ts delete mode 100644 src/react/netinfo.ts diff --git a/src/index.tsx b/src/index.tsx index 5bee3b8..4498123 100644 --- a/src/index.tsx +++ b/src/index.tsx @@ -1,88 +1,6 @@ -export { Tinode, type TinodeConfig } from './core/tinode'; -export { - default as Topic, - type MessageCallback, - type SubscriberCallback, - type TopicCallbacks, -} from './core/topic'; -export { - default as TopicMe, - type ContactCallback, - type TopicMeCallbacks, -} from './core/me-topic'; -export { - default as TopicFnd, - type FoundContactCallback, -} from './core/fnd-topic'; -export { - default as AccessMode, - type AccessModeInput, - type AccessModeJson, -} from './core/access-mode'; -export { default as CommError } from './core/comm-error'; -export { - default as MetaGetBuilder, - type GetDataType, - type GetOptsType, - type GetQuery, -} from './core/meta-builder'; -export { - default as Drafty, - type DraftyDoc, - type DraftyEnt, - type DraftyEntData, - type DraftyFmt, - type DraftyFormatter, - type DraftyNode, - type DraftySource, -} from './core/drafty'; -export { - default as TheCard, - type CardComm, - type CardData, - type CardName, - type CardOrg, - type CardPhoto, -} from './core/the-card'; -export { - default as LargeFileHelper, - type ReactNativeFileDescriptor, - type UploadData, -} from './core/large-file'; -export { - MESSAGE_STATUS_FAILED, - MESSAGE_STATUS_FATAL, - MESSAGE_STATUS_NONE, - MESSAGE_STATUS_QUEUED, - MESSAGE_STATUS_READ, - MESSAGE_STATUS_RECEIVED, - MESSAGE_STATUS_SENDING, - MESSAGE_STATUS_SENT, - MESSAGE_STATUS_TO_ME, - DEL_CHAR, -} from './core/config'; -export type * from './core/types'; - -export type { - DelLogRange, - DelLogRecord, - MessageRecord, - SeqWindow, - StorageAdapter, - SubscriptionRecord, - TopicRecord, - UserRecord, -} from './core/storage/storage-adapter'; -export { default as MemoryAdapter } from './core/storage/memory-adapter'; -export { default as IndexedDBAdapter } from './core/storage/indexeddb-adapter'; -export { - default as KeyValueAdapter, - fromMMKV, - type KeyValueAdapterOptions, - type KeyValueStore, - type MMKVLike, -} from './core/storage/key-value-adapter'; +import './platform'; +export * from './sdk'; export * from './react'; export { registerDeviceToken, diff --git a/src/react/TinodeProvider.tsx b/src/react/TinodeProvider.tsx index 018a66f..4812549 100644 --- a/src/react/TinodeProvider.tsx +++ b/src/react/TinodeProvider.tsx @@ -1,5 +1,5 @@ import { useState, type ReactNode } from 'react'; -import type { Tinode } from '../core/tinode'; +import type { Tinode } from '../sdk'; import { TinodeClientContext } from './context'; import { createTinode, type CreateTinodeOptions } from './createTinode'; import { diff --git a/src/react/TinodeStoresProvider.tsx b/src/react/TinodeStoresProvider.tsx index 466a36f..29e9cf3 100644 --- a/src/react/TinodeStoresProvider.tsx +++ b/src/react/TinodeStoresProvider.tsx @@ -1,14 +1,12 @@ import { useEffect, useMemo, type ReactNode } from 'react'; import { AppState } from 'react-native'; import { TinodeStoresContext, type TinodeStores } from './context'; -import { subscribeToNetwork, type NetInfoLike } from './netinfo'; import type { ClientPort } from './ports'; import { SessionStore } from './session-store'; import { TopicRegistry } from './topic-registry'; export interface TinodeLifecycleOptions { reconnectOnForeground?: boolean; - netInfo?: NetInfoLike | null; pageSize?: number; } @@ -21,7 +19,6 @@ export function TinodeStoresProvider({ client, children, reconnectOnForeground = true, - netInfo, pageSize, }: TinodeStoresProviderProps) { const stores = useMemo(() => { @@ -35,18 +32,13 @@ export function TinodeStoresProvider({ if (!reconnectOnForeground) { return undefined; } - const reconnect = () => stores.session.reconnect(); const appState = AppState.addEventListener('change', (state) => { if (state === 'active') { - reconnect(); + stores.session.reconnect(); } }); - const stopNetwork = subscribeToNetwork(reconnect, netInfo); - return () => { - appState.remove(); - stopNetwork(); - }; - }, [stores, reconnectOnForeground, netInfo]); + return () => appState.remove(); + }, [stores, reconnectOnForeground]); return ( diff --git a/src/react/__fixtures__/fake-client.ts b/src/react/__fixtures__/fake-client.ts index 01085da..6cf0012 100644 --- a/src/react/__fixtures__/fake-client.ts +++ b/src/react/__fixtures__/fake-client.ts @@ -5,7 +5,7 @@ import type { Message, PubMessage, SeqRange, -} from '../../core/types'; +} from '../../sdk'; import type { ClientPort, ContactPort, diff --git a/src/react/__fixtures__/render-hook.tsx b/src/react/__fixtures__/render-hook.tsx index d4bd889..04267bd 100644 --- a/src/react/__fixtures__/render-hook.tsx +++ b/src/react/__fixtures__/render-hook.tsx @@ -14,11 +14,7 @@ export interface RenderedHook { export function withClient(client: ClientPort, children: ReactElement) { return ( - + {children} ); diff --git a/src/react/__tests__/TinodeProvider.test.tsx b/src/react/__tests__/TinodeProvider.test.tsx index 4e93dec..5cf5bb1 100644 --- a/src/react/__tests__/TinodeProvider.test.tsx +++ b/src/react/__tests__/TinodeProvider.test.tsx @@ -1,14 +1,28 @@ -import { describe, expect, test } from '@jest/globals'; +import { describe, expect, jest, test } from '@jest/globals'; import { act } from 'react'; +import type { NetInfoLike, NetInfoStateLike } from '../../sdk'; import { mount } from '../__fixtures__/render-hook'; import { createTinode, detectPlatform } from '../createTinode'; -import type { NetInfoLike, NetInfoStateLike } from '../netinfo'; import { TinodeProvider } from '../TinodeProvider'; import { useConnection, type ConnectionInfo } from '../useConnection'; import { useTinode } from '../useTinode'; -import { FakeClient } from '../__fixtures__/fake-client'; -import { TinodeStoresProvider } from '../TinodeStoresProvider'; -import { useLogin } from '../useLogin'; + +class FakeWebSocket { + readyState = 0; + onopen = null; + onclose = null; + onerror = null; + onmessage = null; + close(): void {} + send(): void {} +} + +const config = { + appName: 'Test/1.0', + host: 'localhost:6060', + apiKey: 'key', + network: { WebSocket: FakeWebSocket }, +}; class FakeNetInfo implements NetInfoLike { listener: ((state: NetInfoStateLike) => void) | null = null; @@ -38,10 +52,7 @@ describe('TinodeProvider', () => { } const renderer = await mount( - + ); @@ -52,11 +63,7 @@ describe('TinodeProvider', () => { }); test('accepts a client built with createTinode', async () => { - const client = createTinode({ - appName: 'Test/1.0', - host: 'localhost:6060', - apiKey: 'key', - }); + const client = createTinode(config); const seen: { client?: unknown } = {}; function Probe() { @@ -74,34 +81,18 @@ describe('TinodeProvider', () => { await act(async () => renderer.unmount()); }); - test('reconnects when the network comes back after a login', async () => { - const client = new FakeClient(); + test('passes netInfo to the client, which retries when the network is back', () => { const netInfo = new FakeNetInfo(); - const session: { login?: ReturnType } = {}; - - function Probe() { - session.login = useLogin(); - return null; - } - - await mount( - - - - ); - - await act(async () => netInfo.listener?.({ isConnected: false })); - await act(async () => netInfo.listener?.({ isConnected: true })); - expect(client.reconnectCalls).toBe(0); + const client = createTinode({ ...config, netInfo }); + const retryNow = jest + .spyOn(client._connection, 'retryNow') + .mockImplementation(() => {}); - await act(async () => session.login?.loginBasic('alice', 'alice123')); - await act(async () => { - client.disconnect(); - client.onDisconnect?.(); - }); - await act(async () => netInfo.listener?.({ isConnected: false })); - await act(async () => netInfo.listener?.({ isConnected: true })); + netInfo.listener?.({ isConnected: true }); + expect(retryNow).not.toHaveBeenCalled(); - expect(client.reconnectCalls).toBe(1); + netInfo.listener?.({ isConnected: false }); + netInfo.listener?.({ isConnected: true }); + expect(retryNow).toHaveBeenCalledTimes(1); }); }); diff --git a/src/react/__tests__/useMessages.test.tsx b/src/react/__tests__/useMessages.test.tsx index bda8130..c7cc9b1 100644 --- a/src/react/__tests__/useMessages.test.tsx +++ b/src/react/__tests__/useMessages.test.tsx @@ -1,6 +1,6 @@ import { describe, expect, test } from '@jest/globals'; import { act } from 'react'; -import { LOCAL_SEQID } from '../../core/config'; +import { LOCAL_SEQID } from '../constants'; import { FakeClient, makeHistory } from '../__fixtures__/fake-client'; import { renderHook } from '../__fixtures__/render-hook'; import { useMessages } from '../useMessages'; diff --git a/src/react/constants.ts b/src/react/constants.ts new file mode 100644 index 0000000..2f20c37 --- /dev/null +++ b/src/react/constants.ts @@ -0,0 +1,3 @@ +export const TOPIC_ME = 'me'; +export const LOCAL_SEQID = 0xfffffff; +export const DEFAULT_MESSAGES_PAGE = 24; diff --git a/src/react/context.ts b/src/react/context.ts index 8cb4c89..1b3c8f4 100644 --- a/src/react/context.ts +++ b/src/react/context.ts @@ -1,5 +1,5 @@ import { createContext, useContext } from 'react'; -import type { Tinode } from '../core/tinode'; +import type { Tinode } from '../sdk'; import type { ClientPort } from './ports'; import type { SessionStore } from './session-store'; import type { TopicRegistry } from './topic-registry'; diff --git a/src/react/createTinode.ts b/src/react/createTinode.ts index 112d1ba..1206ee1 100644 --- a/src/react/createTinode.ts +++ b/src/react/createTinode.ts @@ -1,6 +1,10 @@ import { Platform } from 'react-native'; -import type { StorageAdapter } from '../core/storage/storage-adapter'; -import { Tinode } from '../core/tinode'; +import { + Tinode, + type NetInfoLike, + type StorageAdapter, + type TinodeNetwork, +} from '../sdk'; export type TinodePlatform = 'ios' | 'android' | 'web'; @@ -11,7 +15,9 @@ export interface CreateTinodeOptions { secure?: boolean; transport?: 'ws' | 'lp'; persist?: boolean; - storage?: StorageAdapter; + storage?: StorageAdapter | null; + netInfo?: NetInfoLike | null; + network?: TinodeNetwork; language?: string; logging?: boolean; onStorageReady?: (error?: unknown) => void; @@ -32,6 +38,8 @@ export function createTinode(options: CreateTinodeOptions): Tinode { platform: detectPlatform(), persist: options.persist ?? false, storage: options.storage, + netInfo: options.netInfo, + network: options.network, }, options.onStorageReady ); diff --git a/src/react/index.ts b/src/react/index.ts index 8d051cf..b7e7ace 100644 --- a/src/react/index.ts +++ b/src/react/index.ts @@ -11,7 +11,6 @@ export { type TinodeLifecycleOptions, type TinodeStoresProviderProps, } from './TinodeStoresProvider'; -export { type NetInfoLike, type NetInfoStateLike } from './netinfo'; export { useTinode } from './useTinode'; export { useConnection, type ConnectionInfo } from './useConnection'; export { useLogin, type LoginApi } from './useLogin'; diff --git a/src/react/messages-store.ts b/src/react/messages-store.ts index 512c976..720a897 100644 --- a/src/react/messages-store.ts +++ b/src/react/messages-store.ts @@ -1,5 +1,5 @@ -import { LOCAL_SEQID } from '../core/config'; -import type { Message } from '../core/types'; +import type { Message } from '../sdk'; +import { LOCAL_SEQID } from './constants'; import { ExternalStore, detachAll } from './external-store'; import { attach } from './multiplex'; import type { MessageContent, TopicPort } from './ports'; diff --git a/src/react/netinfo.ts b/src/react/netinfo.ts deleted file mode 100644 index ef637e2..0000000 --- a/src/react/netinfo.ts +++ /dev/null @@ -1,23 +0,0 @@ -export interface NetInfoStateLike { - isConnected: boolean | null; -} - -export interface NetInfoLike { - addEventListener(listener: (state: NetInfoStateLike) => void): () => void; -} - -export function subscribeToNetwork( - onOnline: () => void, - netInfo: NetInfoLike | null | undefined -): () => void { - if (!netInfo) { - return () => {}; - } - let wasConnected: boolean | null = null; - return netInfo.addEventListener(({ isConnected }) => { - if (isConnected && wasConnected === false) { - onOnline(); - } - wasConnected = isConnected; - }); -} diff --git a/src/react/ports.ts b/src/react/ports.ts index a4b1178..1e3bdd8 100644 --- a/src/react/ports.ts +++ b/src/react/ports.ts @@ -1,12 +1,12 @@ -import type { DraftyDoc } from '../core/drafty'; import type { AuthToken, + DraftyDoc, GetQuery, InfoMessage, Message, PubMessage, SeqRange, -} from '../core/types'; +} from '../sdk'; export type MessageContent = string | DraftyDoc; diff --git a/src/react/session-store.ts b/src/react/session-store.ts index a809afa..e234bcd 100644 --- a/src/react/session-store.ts +++ b/src/react/session-store.ts @@ -1,4 +1,4 @@ -import type { AuthToken } from '../core/types'; +import type { AuthToken } from '../sdk'; import { ExternalStore, detachAll, ignore } from './external-store'; import { attach } from './multiplex'; import type { ClientPort } from './ports'; diff --git a/src/react/topic-registry.ts b/src/react/topic-registry.ts index fe5fc5f..2e6b600 100644 --- a/src/react/topic-registry.ts +++ b/src/react/topic-registry.ts @@ -1,5 +1,5 @@ -import { DEFAULT_MESSAGES_PAGE, TOPIC_ME } from '../core/config'; -import type { GetQuery } from '../core/types'; +import type { GetQuery } from '../sdk'; +import { DEFAULT_MESSAGES_PAGE, TOPIC_ME } from './constants'; import { ExternalStore, detachAll, ignore } from './external-store'; import { attach } from './multiplex'; import type { TopicPort } from './ports'; diff --git a/src/react/useLogin.ts b/src/react/useLogin.ts index 3dec80a..42e248d 100644 --- a/src/react/useLogin.ts +++ b/src/react/useLogin.ts @@ -1,5 +1,5 @@ import { useMemo, useSyncExternalStore } from 'react'; -import type { AuthToken } from '../core/types'; +import type { AuthToken } from '../sdk'; import { useTinodeStores } from './context'; export interface LoginApi { diff --git a/src/react/useMeTopic.ts b/src/react/useMeTopic.ts index 43330c2..e3890c9 100644 --- a/src/react/useMeTopic.ts +++ b/src/react/useMeTopic.ts @@ -1,5 +1,5 @@ import { useMemo, useSyncExternalStore } from 'react'; -import { TOPIC_ME } from '../core/config'; +import { TOPIC_ME } from './constants'; import { ContactsStore, type Contact } from './contacts-store'; import { useTinodeStores } from './context'; import { useTopic } from './useTopic'; diff --git a/src/react/useMessages.ts b/src/react/useMessages.ts index 38e8be1..d9a2993 100644 --- a/src/react/useMessages.ts +++ b/src/react/useMessages.ts @@ -1,6 +1,6 @@ import { useMemo, useSyncExternalStore } from 'react'; -import { DEFAULT_MESSAGES_PAGE } from '../core/config'; -import type { Message } from '../core/types'; +import type { Message } from '../sdk'; +import { DEFAULT_MESSAGES_PAGE } from './constants'; import { MessagesStore } from './messages-store'; import type { MessageContent } from './ports'; import { useTopic } from './useTopic'; diff --git a/src/react/useTinode.ts b/src/react/useTinode.ts index 6ef4247..c1ac030 100644 --- a/src/react/useTinode.ts +++ b/src/react/useTinode.ts @@ -1,5 +1,5 @@ import { useContext } from 'react'; -import type { Tinode } from '../core/tinode'; +import type { Tinode } from '../sdk'; import { TinodeClientContext } from './context'; export function useTinode(): Tinode { From 7c47671d2e19de4b1d86dce959a3e8758c938445 Mon Sep 17 00:00:00 2001 From: amerllica Date: Sun, 25 Oct 2026 17:56:21 +0330 Subject: [PATCH 05/14] refactor: remove the in-repo SDK port --- CONTRIBUTING.md | 3 +- eslint.config.mjs | 12 - package.json | 1 - src/core/__fixtures__/key-value-stores.ts | 81 - src/core/__tests__/access-mode.test.ts | 51 - src/core/__tests__/cbuffer.test.ts | 96 - src/core/__tests__/config.test.ts | 8 - src/core/__tests__/connection.test.ts | 434 ---- src/core/__tests__/drafty.test.ts | 2114 ----------------- src/core/__tests__/graphemes.test.ts | 94 - src/core/__tests__/key-value-adapter.test.ts | 242 -- src/core/__tests__/large-file.test.ts | 344 --- src/core/__tests__/persistent-cache.test.ts | 233 -- src/core/__tests__/storage-adapters.test.ts | 183 -- src/core/__tests__/the-card.test.ts | 1087 --------- src/core/__tests__/tinode.test.ts | 476 ---- src/core/__tests__/topic.test.ts | 52 - src/core/__tests__/utils.test.ts | 691 ------ src/core/access-mode.ts | 288 --- src/core/cbuffer.ts | 154 -- src/core/comm-error.ts | 9 - src/core/config.ts | 46 - src/core/connection.ts | 528 ----- src/core/drafty.ts | 2226 ------------------ src/core/fnd-topic.ts | 88 - src/core/graphemes.ts | 166 -- src/core/large-file.ts | 466 ---- src/core/me-topic.ts | 403 ---- src/core/meta-builder.ts | 220 -- src/core/storage/indexeddb-adapter.ts | 557 ----- src/core/storage/key-value-adapter.ts | 246 -- src/core/storage/memory-adapter.ts | 247 -- src/core/storage/persistent-cache.ts | 429 ---- src/core/storage/resolve-adapter.ts | 15 - src/core/storage/storage-adapter.ts | 115 - src/core/the-card.ts | 713 ------ src/core/tinode.ts | 1648 ------------- src/core/topic.ts | 1664 ------------- src/core/types.ts | 374 --- src/core/utils.ts | 301 --- yarn.lock | 8 - 41 files changed, 1 insertion(+), 17112 deletions(-) delete mode 100644 src/core/__fixtures__/key-value-stores.ts delete mode 100644 src/core/__tests__/access-mode.test.ts delete mode 100644 src/core/__tests__/cbuffer.test.ts delete mode 100644 src/core/__tests__/config.test.ts delete mode 100644 src/core/__tests__/connection.test.ts delete mode 100644 src/core/__tests__/drafty.test.ts delete mode 100644 src/core/__tests__/graphemes.test.ts delete mode 100644 src/core/__tests__/key-value-adapter.test.ts delete mode 100644 src/core/__tests__/large-file.test.ts delete mode 100644 src/core/__tests__/persistent-cache.test.ts delete mode 100644 src/core/__tests__/storage-adapters.test.ts delete mode 100644 src/core/__tests__/the-card.test.ts delete mode 100644 src/core/__tests__/tinode.test.ts delete mode 100644 src/core/__tests__/topic.test.ts delete mode 100644 src/core/__tests__/utils.test.ts delete mode 100644 src/core/access-mode.ts delete mode 100644 src/core/cbuffer.ts delete mode 100644 src/core/comm-error.ts delete mode 100644 src/core/config.ts delete mode 100644 src/core/connection.ts delete mode 100644 src/core/drafty.ts delete mode 100644 src/core/fnd-topic.ts delete mode 100644 src/core/graphemes.ts delete mode 100644 src/core/large-file.ts delete mode 100644 src/core/me-topic.ts delete mode 100644 src/core/meta-builder.ts delete mode 100644 src/core/storage/indexeddb-adapter.ts delete mode 100644 src/core/storage/key-value-adapter.ts delete mode 100644 src/core/storage/memory-adapter.ts delete mode 100644 src/core/storage/persistent-cache.ts delete mode 100644 src/core/storage/resolve-adapter.ts delete mode 100644 src/core/storage/storage-adapter.ts delete mode 100644 src/core/the-card.ts delete mode 100644 src/core/tinode.ts delete mode 100644 src/core/topic.ts delete mode 100644 src/core/types.ts delete mode 100644 src/core/utils.ts diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index 582cec7..4398a4a 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -103,8 +103,7 @@ Our pre-commit hooks verify that your commit message matches this format when co Releases are published by the `release` job in `.github/workflows/ci.yml` when a version tag is pushed. Only maintainers can do this. -1. In a pull request to `main`, bump `version` in `package.json` and `PACKAGE_VERSION` in `src/core/config.ts`. - A test fails if the two differ. +1. In a pull request to `main`, bump `version` in `package.json`. 2. After the pull request is merged, tag the merge commit on `main` with a tag named `vX.Y.Z`, where `X.Y.Z` is the version: diff --git a/eslint.config.mjs b/eslint.config.mjs index d549449..16b00bb 100644 --- a/eslint.config.mjs +++ b/eslint.config.mjs @@ -23,18 +23,6 @@ export default defineConfig([ 'prettier/prettier': 'error', }, }, - { - files: ['src/core/**/*.ts'], - rules: { - 'no-bitwise': 'off', - }, - }, - { - files: ['src/core/__tests__/drafty.test.ts'], - rules: { - 'no-script-url': 'off', - }, - }, { ignores: ['node_modules/', 'lib/'], }, diff --git a/package.json b/package.json index 03d3d70..29d2cff 100644 --- a/package.json +++ b/package.json @@ -73,7 +73,6 @@ "eslint-config-prettier": "^10.1.8", "eslint-plugin-ft-flow": "^3.0.11", "eslint-plugin-prettier": "^5.5.6", - "fake-indexeddb": "^6.2.5", "jest": "^29.7.0", "lefthook": "^2.1.10", "prettier": "^3.9.6", diff --git a/src/core/__fixtures__/key-value-stores.ts b/src/core/__fixtures__/key-value-stores.ts deleted file mode 100644 index 5f97d8e..0000000 --- a/src/core/__fixtures__/key-value-stores.ts +++ /dev/null @@ -1,81 +0,0 @@ -import type { KeyValueStore } from '../storage/key-value-adapter'; - -export class SyncStore implements KeyValueStore { - readonly data = new Map(); - - getItem(key: string): string | null { - return this.data.get(key) ?? null; - } - - setItem(key: string, value: string): void { - this.data.set(key, value); - } - - removeItem(key: string): void { - this.data.delete(key); - } - - getAllKeys(): string[] { - return [...this.data.keys()]; - } -} - -export class AsyncStore implements KeyValueStore { - readonly data = new Map(); - getItemCalls = 0; - multiGetCalls = 0; - - async getItem(key: string): Promise { - this.getItemCalls += 1; - return this.data.get(key) ?? null; - } - - async setItem(key: string, value: string): Promise { - this.data.set(key, value); - } - - async removeItem(key: string): Promise { - this.data.delete(key); - } - - async getAllKeys(): Promise { - return [...this.data.keys()]; - } - - async multiGet(keys: string[]): Promise<[string, string | null][]> { - this.multiGetCalls += 1; - return keys.map((key) => [key, this.data.get(key) ?? null]); - } -} - -class FakeMMKVBase { - readonly data = new Map(); - - getString(key: string): string | undefined { - return this.data.get(key); - } - - set(key: string, value: boolean | string | number | ArrayBuffer): void { - this.data.set(key, String(value)); - } - - getAllKeys(): string[] { - return [...this.data.keys()]; - } - - clearAll(): void { - this.data.clear(); - } -} - -export class FakeMMKVv4 extends FakeMMKVBase { - remove(key: string): boolean { - return this.data.delete(key); - } -} - -export class FakeMMKVv3 extends FakeMMKVBase { - delete(key: string): void { - this.data.delete(key); - } -} diff --git a/src/core/__tests__/access-mode.test.ts b/src/core/__tests__/access-mode.test.ts deleted file mode 100644 index fd728ab..0000000 --- a/src/core/__tests__/access-mode.test.ts +++ /dev/null @@ -1,51 +0,0 @@ -import { describe, expect, test } from '@jest/globals'; -import AccessMode from '../access-mode'; -import { mergeObj } from '../utils'; - -describe('AccessMode', () => { - test('constructs from encoded permissions', () => { - const access = new AccessMode({ given: 'JR', want: 'JRW' }); - - expect(access.getGiven()).toBe('JR'); - expect(access.getWant()).toBe('JRW'); - expect(access.getMode()).toBe('JR'); - expect(access.jsonHelper()).toEqual({ - mode: 'JR', - given: 'JR', - want: 'JRW', - }); - }); - - test('updates permissions and checks individual flags', () => { - const access = new AccessMode({ given: 'JR', want: 'JRW' }); - - access.updateMode('+W'); - access.updateGiven('-J'); - access.updateWant('+P'); - - expect(access.getMode()).toBe('JRW'); - expect(access.getGiven()).toBe('R'); - expect(access.getWant()).toBe('JRWP'); - expect(access.isReader()).toBe(true); - expect(access.isWriter()).toBe(true); - expect(access.isJoiner('given')).toBe(false); - expect(access.isPresencer('want')).toBe(true); - expect(access.getMissing()).toBe('JWP'); - expect(access.getExcessive()).toBe('N'); - }); - - test('preserves AccessMode instances when merging nested data', () => { - const source = new AccessMode({ given: 'JR', want: 'JRW' }); - const merged = mergeObj<{ acs?: AccessMode }>({}, { acs: source }); - - expect(merged.acs).toBeInstanceOf(AccessMode); - expect(merged.acs).not.toBe(source); - expect(merged.acs?.jsonHelper()).toEqual({ - mode: 'JR', - given: 'JR', - want: 'JRW', - }); - expect(merged.acs?.isReader()).toBe(true); - expect(merged.acs?.isWriter()).toBe(false); - }); -}); diff --git a/src/core/__tests__/cbuffer.test.ts b/src/core/__tests__/cbuffer.test.ts deleted file mode 100644 index c40fadd..0000000 --- a/src/core/__tests__/cbuffer.test.ts +++ /dev/null @@ -1,96 +0,0 @@ -import { beforeEach, describe, expect, test } from '@jest/globals'; -import CBuffer from '../cbuffer'; - -interface Visit { - elem: number; - prev: number | undefined; - next: number | undefined; - index: number; -} - -describe('CBuffer', () => { - let buffer: CBuffer; - - beforeEach(() => { - buffer = new CBuffer((a, b) => a - b, true); - }); - - test('should insert elements in sorted order', () => { - buffer.put(3, 1, 2); - expect(buffer.buffer).toEqual([1, 2, 3]); - }); - - test('should insert array elements in sorted order', () => { - buffer.put([3, 1, 2]); - expect(buffer.buffer).toEqual([1, 2, 3]); - }); - - test('should get element at given position', () => { - buffer.put(1, 2, 3); - expect(buffer.getAt(1)).toBe(2); - }); - - test('should get the last element', () => { - buffer.put(1, 2, 3); - expect(buffer.getLast()).toBe(3); - }); - - test('should get the last element with filter', () => { - buffer.put(1, 2, 3); - expect(buffer.getLast((x) => x < 3)).toBe(2); - }); - - test('should delete element at given position', () => { - buffer.put(1, 2, 3); - expect(buffer.delAt(1)).toBe(2); - expect(buffer.buffer).toEqual([1, 3]); - }); - - test('should delete elements in range', () => { - buffer.put(1, 2, 3, 4, 5); - expect(buffer.delRange(1, 4)).toEqual([2, 3, 4]); - expect(buffer.buffer).toEqual([1, 5]); - }); - - test('should return the length of the buffer', () => { - buffer.put(1, 2, 3); - expect(buffer.length()).toBe(3); - }); - - test('should reset the buffer', () => { - buffer.put(1, 2, 3); - buffer.reset(); - expect(buffer.buffer).toEqual([]); - }); - - test('should iterate over elements with forEach', () => { - buffer.put(1, 2, 3); - const result: Visit[] = []; - buffer.forEach((elem, prev, next, index) => { - result.push({ elem, prev, next, index }); - }); - expect(result).toEqual([ - { elem: 1, prev: undefined, next: 2, index: 0 }, - { elem: 2, prev: 1, next: 3, index: 1 }, - { elem: 3, prev: 2, next: undefined, index: 2 }, - ]); - }); - - test('should find element in buffer', () => { - buffer.put(1, 2, 3); - expect(buffer.find(2)).toBe(1); - expect(buffer.find(4)).toBe(-1); - }); - - test('should filter elements in buffer', () => { - buffer.put(1, 2, 3, 4, 5); - buffer.filter((x) => x % 2 === 0); - expect(buffer.buffer).toEqual([2, 4]); - }); - - test('should check if buffer is empty', () => { - expect(buffer.isEmpty()).toBe(true); - buffer.put(1); - expect(buffer.isEmpty()).toBe(false); - }); -}); diff --git a/src/core/__tests__/config.test.ts b/src/core/__tests__/config.test.ts deleted file mode 100644 index eb2163a..0000000 --- a/src/core/__tests__/config.test.ts +++ /dev/null @@ -1,8 +0,0 @@ -import { expect, test } from '@jest/globals'; -import pkg from '../../../package.json'; -import { LIBRARY, PACKAGE_VERSION } from '../config'; - -test('PACKAGE_VERSION matches package.json', () => { - expect(PACKAGE_VERSION).toBe(pkg.version); - expect(LIBRARY).toBe(`react-native-tinode/${pkg.version}`); -}); diff --git a/src/core/__tests__/connection.test.ts b/src/core/__tests__/connection.test.ts deleted file mode 100644 index 3653794..0000000 --- a/src/core/__tests__/connection.test.ts +++ /dev/null @@ -1,434 +0,0 @@ -import { - afterEach, - beforeEach, - describe, - expect, - jest, - test, -} from '@jest/globals'; -import Connection from '../connection'; -import type { - LongPollRequestLike, - WebSocketEventLike, - WebSocketEventName, - WebSocketLike, -} from '../connection'; -import { BACKOFF_BASE } from '../config'; - -const SOCKET_CONNECTING = 0; -const SOCKET_OPEN = 1; -const SOCKET_CLOSED = 3; -const REQUEST_OPENED = 1; -const REQUEST_DONE = 4; - -type Listener = (evt: WebSocketEventLike) => void; - -class FakeWebSocket implements WebSocketLike { - static instances: FakeWebSocket[] = []; - - readyState = SOCKET_CONNECTING; - sent: string[] = []; - readonly url: string; - private readonly listeners = new Map(); - - constructor(url: string) { - this.url = url; - FakeWebSocket.instances.push(this); - } - - addEventListener(type: WebSocketEventName, listener: Listener): void { - this.listeners.set(type, [...(this.listeners.get(type) ?? []), listener]); - } - - send(data: string): void { - this.sent.push(data); - } - - close(): void { - this.readyState = SOCKET_CLOSED; - } - - emit(type: WebSocketEventName, evt: WebSocketEventLike = {}): void { - if (type === 'open') { - this.readyState = SOCKET_OPEN; - } - if (type === 'close') { - this.readyState = SOCKET_CLOSED; - } - (this.listeners.get(type) ?? []).forEach((listener) => listener(evt)); - } - - static latest(): FakeWebSocket { - const socket = FakeWebSocket.instances[FakeWebSocket.instances.length - 1]; - if (!socket) { - throw new Error('No socket was created'); - } - return socket; - } -} - -class FakeRequest implements LongPollRequestLike { - static instances: FakeRequest[] = []; - - readyState = 0; - status = 0; - responseText = ''; - onreadystatechange: ((evt: unknown) => void) | null = null; - method = ''; - url = ''; - body: string | null | undefined = undefined; - aborted = false; - - constructor() { - FakeRequest.instances.push(this); - } - - open(method: string, url: string): void { - this.method = method; - this.url = url; - this.readyState = REQUEST_OPENED; - } - - send(body?: string | null): void { - this.body = body; - } - - abort(): void { - this.aborted = true; - } - - respond(status: number, responseText: string): void { - this.readyState = REQUEST_DONE; - this.status = status; - this.responseText = responseText; - this.onreadystatechange?.({}); - } - - static latest(): FakeRequest { - const request = FakeRequest.instances[FakeRequest.instances.length - 1]; - if (!request) { - throw new Error('No request was created'); - } - return request; - } -} - -const baseConfig = { host: 'api.example.com', apiKey: 'KEY', secure: false }; - -function makeWsConnection(autoreconnect = true): Connection { - return new Connection({ ...baseConfig, transport: 'ws' }, '0', autoreconnect); -} - -function makeLpConnection(autoreconnect = true): Connection { - return new Connection({ ...baseConfig, transport: 'lp' }, '0', autoreconnect); -} - -async function openSocket(conn: Connection): Promise { - const connecting = conn.connect(); - const socket = FakeWebSocket.latest(); - socket.emit('open'); - await connecting; - return socket; -} - -function removeBackoffJitter() { - jest.spyOn(Math, 'random').mockReturnValue(0); -} - -describe('Connection', () => { - beforeEach(() => { - FakeWebSocket.instances = []; - FakeRequest.instances = []; - Connection.setNetworkProviders(FakeWebSocket, FakeRequest); - jest.useFakeTimers(); - }); - - afterEach(() => { - jest.useRealTimers(); - jest.restoreAllMocks(); - Connection.setNetworkProviders(undefined, undefined); - }); - - test('rejects an unknown transport', () => { - expect( - () => new Connection({ ...baseConfig, transport: 'smoke' }, '0', true) - ).toThrow('Unknown or invalid network transport'); - }); - - test('reports the initialized transport', () => { - expect(makeWsConnection().transport()).toBe('ws'); - expect(makeLpConnection().transport()).toBe('lp'); - }); - - describe('websocket', () => { - test('connects to the channels endpoint and notifies onOpen', async () => { - const conn = makeWsConnection(); - const onOpen = jest.fn(); - conn.onOpen = onOpen; - - const socket = await openSocket(conn); - - expect(socket.url).toBe('ws://api.example.com/v0/channels?apikey=KEY'); - expect(onOpen).toHaveBeenCalledTimes(1); - expect(conn.isConnected()).toBe(true); - }); - - test('uses wss when secure', async () => { - const conn = new Connection( - { ...baseConfig, secure: true, transport: 'ws' }, - '0', - true - ); - const socket = await openSocket(conn); - expect(socket.url.startsWith('wss://')).toBe(true); - }); - - test('switches host when connect receives a new one', async () => { - const conn = makeWsConnection(); - const connecting = conn.connect('other.example.com'); - FakeWebSocket.latest().emit('open'); - await connecting; - expect(FakeWebSocket.latest().url).toContain('other.example.com'); - }); - - test('rejects connect on socket error', async () => { - const conn = makeWsConnection(); - const connecting = conn.connect(); - FakeWebSocket.latest().emit('error', { data: 'boom' }); - await expect(connecting).rejects.toEqual({ data: 'boom' }); - }); - - test('delivers incoming messages and sends text', async () => { - const conn = makeWsConnection(); - const onMessage = jest.fn(); - conn.onMessage = onMessage; - const socket = await openSocket(conn); - - socket.emit('message', { data: '{"ctrl":{}}' }); - conn.sendText('hello'); - - expect(onMessage).toHaveBeenCalledWith('{"ctrl":{}}'); - expect(socket.sent).toEqual(['hello']); - }); - - test('throws on send when not connected', () => { - expect(() => makeWsConnection().sendText('hi')).toThrow( - 'Websocket is not connected' - ); - }); - - test('probes instead of reconnecting when already open', async () => { - const conn = makeWsConnection(); - const socket = await openSocket(conn); - - await conn.connect(); - - expect(FakeWebSocket.instances).toHaveLength(1); - expect(socket.sent).toEqual(['1']); - }); - - test('force reconnect replaces the socket', async () => { - const conn = makeWsConnection(false); - await openSocket(conn); - - const reconnecting = conn.connect(null, true); - FakeWebSocket.latest().emit('open'); - await reconnecting; - - expect(FakeWebSocket.instances).toHaveLength(2); - }); - - test('manual disconnect reports a user disconnect and does not reconnect', async () => { - const conn = makeWsConnection(); - const onDisconnect = jest.fn(); - conn.onDisconnect = onDisconnect; - const socket = await openSocket(conn); - - conn.disconnect(); - socket.emit('close'); - jest.advanceTimersByTime(BACKOFF_BASE * 100); - - expect(onDisconnect).toHaveBeenCalledWith( - expect.objectContaining({ code: Connection.NETWORK_USER }), - Connection.NETWORK_USER - ); - expect(FakeWebSocket.instances).toHaveLength(1); - expect(conn.isConnected()).toBe(false); - }); - - test('reconnects with exponential backoff after an unexpected close', async () => { - removeBackoffJitter(); - const conn = makeWsConnection(); - const onDisconnect = jest.fn(); - const iterations: number[] = []; - conn.onDisconnect = onDisconnect; - conn.onAutoreconnectIteration = (timeout) => { - iterations.push(timeout); - }; - const socket = await openSocket(conn); - - socket.emit('close'); - expect(onDisconnect).toHaveBeenCalledWith( - expect.objectContaining({ code: Connection.NETWORK_ERROR }), - Connection.NETWORK_ERROR - ); - expect(iterations).toEqual([BACKOFF_BASE]); - - jest.advanceTimersByTime(BACKOFF_BASE); - expect(FakeWebSocket.instances).toHaveLength(2); - expect(iterations).toEqual([BACKOFF_BASE, 0]); - - FakeWebSocket.latest().emit('close'); - expect(iterations).toEqual([BACKOFF_BASE, 0, BACKOFF_BASE * 2]); - - jest.advanceTimersByTime(BACKOFF_BASE * 2); - expect(FakeWebSocket.instances).toHaveLength(3); - }); - - test('backoffReset restarts the delay sequence', async () => { - removeBackoffJitter(); - const conn = makeWsConnection(); - const iterations: number[] = []; - conn.onAutoreconnectIteration = (timeout) => { - iterations.push(timeout); - }; - const socket = await openSocket(conn); - - socket.emit('close'); - jest.advanceTimersByTime(BACKOFF_BASE); - conn.backoffReset(); - FakeWebSocket.latest().emit('close'); - - expect(iterations.filter((value) => value > 0)).toEqual([ - BACKOFF_BASE, - BACKOFF_BASE, - ]); - }); - - test('does not reconnect when autoreconnect is off', async () => { - const conn = makeWsConnection(false); - const socket = await openSocket(conn); - - socket.emit('close'); - jest.advanceTimersByTime(BACKOFF_BASE * 100); - - expect(FakeWebSocket.instances).toHaveLength(1); - }); - - test('reports a skipped attempt when closed during the wait', async () => { - removeBackoffJitter(); - const conn = makeWsConnection(); - const iterations: number[] = []; - conn.onAutoreconnectIteration = (timeout) => { - iterations.push(timeout); - }; - const socket = await openSocket(conn); - - socket.emit('close'); - conn.disconnect(); - jest.advanceTimersByTime(BACKOFF_BASE); - - expect(iterations).toEqual([BACKOFF_BASE]); - expect(FakeWebSocket.instances).toHaveLength(1); - }); - }); - - describe('long polling', () => { - const handshake = JSON.stringify({ ctrl: { params: { sid: 'abc' } } }); - - async function openPoller(conn: Connection): Promise { - const connecting = conn.connect(); - FakeRequest.latest().respond(201, handshake); - await connecting; - } - - test('connects to the lp endpoint and follows with a sid poll', async () => { - const conn = makeLpConnection(); - const onOpen = jest.fn(); - conn.onOpen = onOpen; - - const connecting = conn.connect(); - const first = FakeRequest.latest(); - expect(first.url).toBe( - 'http://api.example.com/v0/channels/lp?apikey=KEY' - ); - first.respond(201, handshake); - await connecting; - - expect(onOpen).toHaveBeenCalledTimes(1); - expect(FakeRequest.latest().url).toBe( - 'http://api.example.com/v0/channels/lp?apikey=KEY&sid=abc' - ); - expect(conn.isConnected()).toBe(true); - }); - - test('delivers polled messages and keeps polling', async () => { - const conn = makeLpConnection(); - const onMessage = jest.fn(); - conn.onMessage = onMessage; - await openPoller(conn); - - const poll = FakeRequest.latest(); - const before = FakeRequest.instances.length; - poll.respond(200, '{"data":{}}'); - - expect(onMessage).toHaveBeenCalledWith('{"data":{}}'); - expect(FakeRequest.instances).toHaveLength(before + 1); - }); - - test('sends text with POST once a sid is known', async () => { - const conn = makeLpConnection(); - await openPoller(conn); - - conn.sendText('payload'); - - const sender = FakeRequest.latest(); - expect(sender.method).toBe('POST'); - expect(sender.url).toContain('&sid=abc'); - expect(sender.body).toBe('payload'); - }); - - test('throws on send before connecting', () => { - expect(() => makeLpConnection().sendText('x')).toThrow( - 'Long poller failed to connect' - ); - }); - - test('server error disconnects and schedules a reconnect', async () => { - removeBackoffJitter(); - const conn = makeLpConnection(); - const onDisconnect = jest.fn(); - conn.onDisconnect = onDisconnect; - await openPoller(conn); - - FakeRequest.latest().respond(0, ''); - - expect(onDisconnect).toHaveBeenCalledWith( - expect.objectContaining({ code: Connection.NETWORK_ERROR }), - Connection.NETWORK_ERROR - ); - expect(conn.isConnected()).toBe(false); - - const before = FakeRequest.instances.length; - jest.advanceTimersByTime(BACKOFF_BASE); - expect(FakeRequest.instances).toHaveLength(before + 1); - }); - - test('disconnect aborts the active poller', async () => { - const conn = makeLpConnection(); - const onDisconnect = jest.fn(); - conn.onDisconnect = onDisconnect; - await openPoller(conn); - const poller = FakeRequest.latest(); - - conn.disconnect(); - - expect(poller.aborted).toBe(true); - expect(conn.isConnected()).toBe(false); - expect(onDisconnect).toHaveBeenCalledWith( - expect.objectContaining({ code: Connection.NETWORK_USER }), - Connection.NETWORK_USER - ); - }); - }); -}); diff --git a/src/core/__tests__/drafty.test.ts b/src/core/__tests__/drafty.test.ts deleted file mode 100644 index f98753d..0000000 --- a/src/core/__tests__/drafty.test.ts +++ /dev/null @@ -1,2114 +0,0 @@ -import { expect, test } from '@jest/globals'; - -import Drafty from '../drafty'; -import type { DraftyDoc } from '../drafty'; - -const fromWire = (doc: unknown): DraftyDoc => JSON.parse(JSON.stringify(doc)); - -const parse_this: [string, DraftyDoc][] = [ - [ - 'This is *bold*, `code` and _italic_, ~strike~', - { - fmt: [ - { - at: 8, - len: 4, - tp: 'ST', - }, - { - at: 14, - len: 4, - tp: 'CO', - }, - { - at: 23, - len: 6, - tp: 'EM', - }, - { - at: 31, - len: 6, - tp: 'DL', - }, - ], - txt: 'This is bold, code and italic, strike', - }, - ], - [ - 'Это *жЫрный*, `код` и _наклонный_, ~зачеркнутый~', - { - fmt: [ - { - at: 4, - len: 6, - tp: 'ST', - }, - { - at: 12, - len: 3, - tp: 'CO', - }, - { - at: 18, - len: 9, - tp: 'EM', - }, - { - at: 29, - len: 11, - tp: 'DL', - }, - ], - txt: 'Это жЫрный, код и наклонный, зачеркнутый', - }, - ], - [ - 'combined *bold and _italic_*', - { - fmt: [ - { - at: 18, - len: 6, - tp: 'EM', - }, - { - at: 9, - len: 15, - tp: 'ST', - }, - ], - txt: 'combined bold and italic', - }, - ], - [ - 'This *text _has* staggered_ formats', - { - fmt: [ - { - at: 5, - len: 9, - tp: 'ST', - }, - ], - txt: 'This text _has staggered_ formats', - }, - ], - [ - 'an url: https://www.example.com/abc#fragment and another _www.tinode.co_', - { - ent: [ - { - data: { - url: 'https://www.example.com/abc#fragment', - }, - tp: 'LN', - }, - { - data: { - url: 'http://www.tinode.co', - }, - tp: 'LN', - }, - ], - fmt: [ - { - at: 57, - len: 13, - tp: 'EM', - }, - { - at: 8, - len: 36, - key: 0, - }, - { - at: 57, - len: 13, - key: 1, - }, - ], - txt: 'an url: https://www.example.com/abc#fragment and another www.tinode.co', - }, - ], - [ - 'this is a @mention and a #hashtag in a string', - { - ent: [ - { - data: { - val: 'mention', - }, - tp: 'MN', - }, - { - data: { - val: 'hashtag', - }, - tp: 'HT', - }, - ], - fmt: [ - { - at: 10, - key: 0, - len: 8, - }, - { - at: 25, - key: 1, - len: 8, - }, - ], - txt: 'this is a @mention and a #hashtag in a string', - }, - ], - [ - 'second #юникод', - { - ent: [ - { - data: { - val: 'юникод', - }, - tp: 'HT', - }, - ], - fmt: [ - { - at: 7, - key: 0, - len: 7, - }, - ], - txt: 'second #юникод', - }, - ], - [ - '😀 *b1👩🏽‍✈️b2* smile', - { - txt: '😀 b1👩🏽‍✈️b2 smile', - fmt: [ - { - tp: 'ST', - at: 2, - len: 5, - }, - ], - }, - ], - [ - 'first 😀 line\nsecond *line*', - { - txt: 'first 😀 line second line', - fmt: [ - { - tp: 'BR', - at: 12, - len: 1, - }, - { - tp: 'ST', - at: 20, - len: 4, - }, - ], - }, - ], - [ - '🕯️ *bold* https://google.com', - { - txt: '🕯️ bold https://google.com', - fmt: [ - { - at: 2, - len: 4, - tp: 'ST', - }, - { - at: 7, - key: 0, - len: 18, - }, - ], - ent: [ - { - tp: 'LN', - data: { - url: 'https://google.com', - }, - }, - ], - }, - ], - [ - 'Hi 👋🏼 Visit http://localhost:6060\n*New* *line*🫡 Visit http://localhost:8080', - { - txt: 'Hi 👋🏼 Visit http://localhost:6060 New line🫡 Visit http://localhost:8080', - fmt: [ - { - at: 11, - len: 21, - key: 0, - }, - { - at: 32, - len: 1, - tp: 'BR', - }, - { - at: 33, - len: 3, - tp: 'ST', - }, - { - at: 37, - len: 4, - tp: 'ST', - }, - { - at: 49, - len: 21, - key: 1, - }, - ], - ent: [ - { - tp: 'LN', - data: { - url: 'http://localhost:6060', - }, - }, - { - tp: 'LN', - data: { - url: 'http://localhost:8080', - }, - }, - ], - }, - ], - [ - '🔴Hello🔴\n🟠Hello🟠\n🟡Hello🟡', - { - txt: '🔴Hello🔴 🟠Hello🟠 🟡Hello🟡', - fmt: [ - { - tp: 'BR', - at: 7, - len: 1, - }, - { - tp: 'BR', - at: 15, - len: 1, - }, - ], - }, - ], -]; - -test.each(parse_this)('Drafty.parse %s', (src, exp) => { - expect(Drafty.parse(src)).toEqual(exp); -}); - -const shorten_this: [DraftyDoc | string, DraftyDoc][] = [ - [ - 'This is a plain text string.', - { - txt: 'This is a plai…', - }, - ], - [ - { - txt: 'This is a string.', - fmt: [ - { - at: 9, - tp: 'BR', - }, - ], - }, - { - txt: 'This is a stri…', - fmt: [ - { - at: 9, - len: 0, - tp: 'BR', - }, - ], - }, - ], - [ - fromWire({ - txt: 'This is a string.', - fmt: [ - { - at: true, - tp: 'XX', - len: {}, - }, - ], - }), - { - txt: 'This is a stri…', - }, - ], - [ - fromWire({ - txt: 'This is a string.', - fmt: [ - { - at: {}, - tp: 123, - len: null, - }, - ], - }), - { - txt: 'This is a stri…', - }, - ], - [ - fromWire({ - txt: 'This is a string.', - fmt: [ - { - test: 123, - }, - { - at: NaN, - tp: 123, - len: -12, - }, - ], - }), - { - txt: 'This is a stri…', - }, - ], - [ - { - fmt: [ - { - at: -1, - }, - ], - ent: [ - { - data: { - mime: 'image/jpeg', - name: 'hello.jpg', - val: '<38992, bytes: 123456789012345678901234567890123456789012345678901234567890>', - width: 100, - height: 80, - }, - tp: 'EX', - }, - ], - }, - { - txt: '', - fmt: [ - { - at: -1, - key: 0, - len: 0, - }, - ], - ent: [ - { - tp: 'EX', - data: { - height: 80, - mime: 'image/jpeg', - name: 'hello.jpg', - width: 100, - }, - }, - ], - }, - ], - [ - { - fmt: [ - { - at: -100, - len: 99, - }, - ], - ent: [ - { - data: { - mime: 'image/jpeg', - name: 'hello.jpg', - val: '<38992, bytes: 123456789012345678901234567890123456789012345678901234567890>', - width: 100, - height: 80, - }, - tp: 'EX', - }, - ], - }, - { - txt: '', - fmt: [ - { - at: -1, - key: 0, - len: 0, - }, - ], - ent: [ - { - tp: 'EX', - data: { - height: 80, - mime: 'image/jpeg', - name: 'hello.jpg', - width: 100, - }, - }, - ], - }, - ], - [ - fromWire({ - fmt: [ - { - at: -1, - key: 'fake', - }, - ], - ent: [ - { - data: { - width: 100, - }, - tp: 'EX', - }, - ], - }), - { - txt: '', - }, - ], - [ - { - txt: 'Message with attachment', - fmt: [ - { - at: -1, - len: 0, - key: 0, - }, - { - at: 8, - len: 4, - tp: 'ST', - }, - ], - ent: [ - { - data: { - mime: 'image/jpeg', - name: 'hello.jpg', - val: '<38992, bytes: 123456789012345678901234567890123456789012345678901234567890>', - width: 100, - height: 80, - }, - tp: 'EX', - }, - ], - }, - { - txt: 'Message with a…', - fmt: [ - { - at: 8, - len: 4, - tp: 'ST', - }, - { - at: -1, - len: 0, - key: 0, - }, - ], - ent: [ - { - tp: 'EX', - data: { - height: 80, - mime: 'image/jpeg', - name: 'hello.jpg', - width: 100, - }, - }, - ], - }, - ], - [ - { - txt: 'https://api.tinode.co/', - fmt: [ - { - len: 22, - }, - ], - ent: [ - { - data: { - url: 'https://www.youtube.com/watch?v=dQw4w9WgXcQ', - }, - tp: 'LN', - }, - ], - }, - { - txt: 'https://api.ti…', - fmt: [ - { - at: 0, - len: 15, - key: 0, - }, - ], - ent: [ - { - tp: 'LN', - data: { - url: 'https://www.youtube.com/watch?v=dQw4w9WgXcQ', - }, - }, - ], - }, - ], - [ - { - txt: 'https://api.tinode.co/', - fmt: [ - { - len: 22, - }, - ], - ent: [ - { - data: { - url: 'https://api.tinode.co/', - }, - tp: 'LN', - }, - ], - }, - { - txt: 'https://api.ti…', - fmt: [ - { - at: 0, - len: 15, - key: 0, - }, - ], - ent: [ - { - tp: 'LN', - data: { - url: 'https://api.tinode.co/', - }, - }, - ], - }, - ], - [ - { - txt: 'Url one, two', - fmt: [ - { - at: 9, - len: 3, - }, - { - at: 4, - len: 3, - }, - ], - ent: [ - { - data: { - url: 'http://tinode.co', - }, - tp: 'LN', - }, - ], - }, - { - txt: 'Url one, two', - fmt: [ - { - at: 4, - len: 3, - key: 0, - }, - { - at: 9, - len: 3, - key: 0, - }, - ], - ent: [ - { - tp: 'LN', - data: { - url: 'http://tinode.co', - }, - }, - ], - }, - ], - [ - { - txt: 'Url one, two', - fmt: [ - { - at: 9, - len: 3, - key: 0, - }, - { - at: 4, - len: 3, - key: 1, - }, - ], - ent: [ - { - data: { - url: 'http://tinode.co', - }, - tp: 'LN', - }, - { - data: { - url: 'http://example.com', - }, - tp: 'LN', - }, - ], - }, - { - txt: 'Url one, two', - fmt: [ - { - at: 4, - len: 3, - key: 0, - }, - { - at: 9, - len: 3, - key: 1, - }, - ], - ent: [ - { - data: { - url: 'http://example.com', - }, - tp: 'LN', - }, - { - data: { - url: 'http://tinode.co', - }, - tp: 'LN', - }, - ], - }, - ], - [ - { - txt: ' ', - fmt: [ - { - len: 1, - }, - ], - ent: [ - { - data: { - height: 213, - mime: 'image/jpeg', - name: 'roses.jpg', - val: '<38992, bytes: 123456789012345678901234567890123456789012345678901234567890>', - width: 638, - }, - tp: 'IM', - }, - ], - }, - { - txt: ' ', - fmt: [ - { - at: 0, - len: 1, - key: 0, - }, - ], - ent: [ - { - tp: 'IM', - data: { - height: 213, - mime: 'image/jpeg', - name: 'roses.jpg', - width: 638, - }, - }, - ], - }, - ], - [ - { - txt: 'This text has staggered formats', - fmt: [ - { - at: 5, - len: 8, - tp: 'EM', - }, - { - at: 10, - len: 13, - tp: 'ST', - }, - ], - }, - { - txt: 'This text has …', - fmt: [ - { - tp: 'EM', - at: 5, - len: 8, - }, - ], - }, - ], - [ - { - txt: 'This text is formatted and deleted too', - fmt: [ - { - at: 5, - len: 4, - tp: 'ST', - }, - { - at: 13, - len: 9, - tp: 'EM', - }, - { - at: 35, - len: 3, - tp: 'ST', - }, - { - at: 27, - len: 11, - tp: 'DL', - }, - ], - }, - { - txt: 'This text is f…', - fmt: [ - { - tp: 'ST', - at: 5, - len: 4, - }, - { - tp: 'EM', - at: 13, - len: 2, - }, - ], - }, - ], - [ - { - txt: 'мультибайтовый юникод', - fmt: [ - { - len: 14, - tp: 'ST', - }, - { - at: 15, - len: 6, - tp: 'EM', - }, - ], - }, - { - txt: 'мультибайтовый…', - fmt: [ - { - at: 0, - tp: 'ST', - len: 14, - }, - ], - }, - ], - [ - { - txt: 'Alice Johnson This is a test', - fmt: [ - { - at: 13, - len: 1, - tp: 'BR', - }, - { - at: 15, - len: 1, - }, - { - len: 13, - key: 1, - }, - { - len: 16, - tp: 'QQ', - }, - { - at: 16, - len: 1, - tp: 'BR', - }, - ], - ent: [ - { - tp: 'IM', - data: { - mime: 'image/jpeg', - val: '<1292, bytes: /9j/4AAQSkZJ123456789012345678901234567890123456789012345678901234567890rehH5o6D/9k=>', - width: 25, - height: 14, - size: 968, - }, - }, - { - tp: 'MN', - data: { - val: 'usr123abcDE', - }, - }, - ], - }, - { - txt: 'Alice Johnson …', - fmt: [ - { - at: 0, - len: 13, - key: 0, - }, - { - at: 13, - len: 1, - tp: 'BR', - }, - { - at: 0, - len: 15, - tp: 'QQ', - }, - ], - ent: [ - { - tp: 'MN', - data: { - val: 'usr123abcDE', - }, - }, - ], - }, - ], - [ - { - txt: 'a😀c😀d😀e😀f😀g😀h😀i😀j😀k😀l😀m', - }, - { - txt: 'a😀c😀d😀e😀f😀g😀h😀…', - }, - ], - [ - { - txt: '😀 b1👩🏽‍✈️b2 smile 123 123 123 123', - fmt: [ - { - tp: 'ST', - at: 2, - len: 8, - }, - { - tp: 'EM', - at: 0, - len: 20, - }, - ], - }, - { - txt: '😀 b1👩🏽‍✈️b2 smile …', - fmt: [ - { - tp: 'ST', - at: 2, - len: 8, - }, - { - tp: 'EM', - at: 0, - len: 15, - }, - ], - }, - ], -]; - -test.each(shorten_this)('Drafty.shorten %j', (src, exp) => { - expect(Drafty.shorten(src, 15, true)).toEqual(exp); -}); - -const forward_this: [DraftyDoc, DraftyDoc][] = [ - [ - { - txt: ' ', - fmt: [ - { - len: 1, - }, - ], - ent: [ - { - data: { - height: 213, - mime: 'image/jpeg', - name: 'roses.jpg', - val: '<38992, bytes: 123456789012345678901234567890123456789012345678901234567890>', - width: 638, - }, - tp: 'IM', - }, - ], - }, - { - txt: ' ', - fmt: [ - { - at: 0, - len: 1, - key: 0, - }, - ], - ent: [ - { - tp: 'IM', - data: { - height: 213, - mime: 'image/jpeg', - name: 'roses.jpg', - val: '<38992, bytes: 123456789012345678901234567890123456789012345678901234567890>', - width: 638, - }, - }, - ], - }, - ], - [ - { - ent: [ - { - data: { - val: 'usrCPvFc6lpAsw', - }, - tp: 'MN', - }, - ], - fmt: [ - { - len: 13, - }, - { - at: 13, - len: 1, - tp: 'BR', - }, - { - len: 38, - tp: 'QQ', - }, - ], - txt: 'Alice Johnson This is a reply to replyThis is a Reply -> Forward -> Reply.', - }, - { - ent: [ - { - data: { - val: 'usrCPvFc6lpAsw', - }, - tp: 'MN', - }, - ], - fmt: [ - { - at: 0, - len: 13, - key: 0, - }, - { - at: 13, - len: 1, - tp: 'BR', - }, - { - at: 0, - len: 38, - tp: 'QQ', - }, - ], - txt: 'Alice Johnson This is a reply to replyThis is a Reply -> Forward -> Reply.', - }, - ], - [ - { - ent: [ - { - data: { - val: 'usrCPvFc6lpAsw', - }, - tp: 'MN', - }, - { - data: { - val: 'usrCPvFc6lpAsw', - }, - tp: 'MN', - }, - ], - fmt: [ - { - len: 15, - }, - { - at: 15, - len: 1, - tp: 'BR', - }, - { - at: 16, - key: 1, - len: 13, - }, - { - at: 29, - len: 1, - tp: 'BR', - }, - { - at: 16, - len: 36, - tp: 'QQ', - }, - ], - txt: '➦ Alice Johnson Alice Johnson This is a simple replyThis is a reply to reply', - }, - { - ent: [ - { - data: { - val: 'usrCPvFc6lpAsw', - }, - tp: 'MN', - }, - ], - fmt: [ - { - at: 0, - key: 0, - len: 13, - }, - { - at: 13, - len: 1, - tp: 'BR', - }, - { - at: 0, - len: 36, - tp: 'QQ', - }, - ], - txt: 'Alice Johnson This is a simple replyThis is a reply to reply', - }, - ], - [ - { - txt: '➦ tinodeu 🔴Hello🔴 🟠Hello🟠 🟡Hello🟡 🟢Hello🟢', - fmt: [ - { - len: 9, - }, - { - at: 9, - len: 1, - tp: 'BR', - }, - { - at: 19, - len: 1, - tp: 'BR', - }, - { - at: 29, - len: 1, - tp: 'BR', - }, - { - at: 39, - len: 1, - tp: 'BR', - }, - ], - ent: [ - { - tp: 'MN', - data: { - val: 'usrfv76ZZoJQJc', - }, - }, - ], - }, - { - txt: '🔴Hello🔴 🟠Hello🟠 🟡Hello🟡 🟢Hello🟢', - fmt: [ - { - tp: 'BR', - at: 9, - len: 1, - }, - { - tp: 'BR', - at: 19, - len: 1, - }, - { - tp: 'BR', - at: 29, - len: 1, - }, - ], - }, - ], -]; - -test.each(forward_this)('Drafty.forwardedContent %j', (src, exp) => { - expect(Drafty.forwardedContent(src)).toEqual(exp); -}); - -const preview_this: [DraftyDoc, DraftyDoc][] = [ - [ - { - ent: [ - { - data: { - val: 'usrCPvFc6lpAsw', - }, - tp: 'MN', - }, - ], - fmt: [ - { - len: 13, - }, - { - at: 13, - len: 1, - tp: 'BR', - }, - { - len: 38, - tp: 'QQ', - }, - ], - txt: 'Alice Johnson This is a reply to replyThis is a Reply -> Forward -> Reply.', - }, - { - fmt: [ - { - at: 0, - len: 1, - tp: 'QQ', - }, - ], - txt: ' This is a Reply -> Forw…', - }, - ], - [ - { - ent: [ - { - data: { - val: 'usrCPvFc6lpAsw', - }, - tp: 'MN', - }, - { - data: { - val: 'usrCPvFc6lpAsw', - }, - tp: 'MN', - }, - ], - fmt: [ - { - len: 15, - }, - { - at: 15, - len: 1, - tp: 'BR', - }, - { - at: 16, - key: 1, - len: 13, - }, - { - at: 29, - len: 1, - tp: 'BR', - }, - { - at: 16, - len: 36, - tp: 'QQ', - }, - ], - txt: '➦ Alice Johnson Alice Johnson This is a simple replyThis is a reply to reply', - }, - { - ent: [ - { - data: { - val: 'usrCPvFc6lpAsw', - }, - tp: 'MN', - }, - ], - fmt: [ - { - at: 0, - key: 0, - len: 1, - }, - { - at: 2, - len: 1, - tp: 'QQ', - }, - ], - txt: '➦ This is a reply to re…', - }, - ], - [ - { - txt: 'Hi 👋🏼 Visit http://localhost:6060 New line🫡 Visit http://localhost:8080', - fmt: [ - { - at: 11, - len: 21, - key: 0, - }, - { - at: 32, - len: 1, - tp: 'BR', - }, - { - at: 33, - len: 3, - tp: 'ST', - }, - { - at: 37, - len: 4, - tp: 'ST', - }, - { - at: 49, - len: 21, - key: 1, - }, - ], - ent: [ - { - tp: 'LN', - data: { - url: 'http://localhost:6060', - }, - }, - { - tp: 'LN', - data: { - url: 'http://localhost:8080', - }, - }, - ], - }, - { - txt: 'Hi 👋🏼 Visit http://localh…', - fmt: [ - { - at: 11, - len: 14, - key: 0, - }, - ], - ent: [ - { - tp: 'LN', - data: { - url: 'http://localhost:6060', - }, - }, - ], - }, - ], -]; - -test.each(preview_this)('Drafty.preview %j', (src, exp) => { - expect(Drafty.preview(src, 25)).toEqual(exp); -}); - -const reply_this: [DraftyDoc, DraftyDoc][] = [ - [ - { - ent: [ - { - data: { - val: 'usrCPvFc6lpAsw', - }, - tp: 'MN', - }, - ], - fmt: [ - { - len: 13, - }, - { - at: 13, - len: 1, - tp: 'BR', - }, - { - len: 38, - tp: 'QQ', - }, - ], - txt: 'Alice Johnson This is a reply to replyThis is a Reply -> Forward -> Reply.', - }, - { - txt: 'This is a Reply -> Forwa…', - }, - ], - [ - { - ent: [ - { - data: { - val: 'usrCPvFc6lpAsw', - }, - tp: 'MN', - }, - { - data: { - val: 'usrCPvFc6lpAsw', - }, - tp: 'MN', - }, - ], - fmt: [ - { - len: 15, - }, - { - at: 15, - len: 1, - tp: 'BR', - }, - { - at: 16, - key: 1, - len: 13, - }, - { - at: 29, - len: 1, - tp: 'BR', - }, - { - at: 16, - len: 36, - tp: 'QQ', - }, - ], - txt: '➦ Alice Johnson Alice Johnson This is a simple replyThis is a reply to reply', - }, - { - fmt: [ - { - at: 0, - tp: 'MN', - len: 1, - }, - ], - txt: '➦ This is a reply to rep…', - }, - ], - [ - { - txt: 'Message with attachment', - fmt: [ - { - at: -1, - len: 0, - key: 0, - }, - { - at: 8, - len: 4, - tp: 'ST', - }, - ], - ent: [ - { - data: { - mime: 'image/jpeg', - name: 'hello.jpg', - val: '<38992, bytes: 123456789012345678901234567890123456789012345678901234567890>', - width: 100, - height: 80, - }, - tp: 'EX', - }, - ], - }, - { - txt: 'Message with attachment ', - fmt: [ - { - at: 8, - len: 4, - tp: 'ST', - }, - { - at: 23, - len: 1, - key: 0, - }, - ], - ent: [ - { - data: { - mime: 'image/jpeg', - name: 'hello.jpg', - width: 100, - height: 80, - }, - tp: 'EX', - }, - ], - }, - ], - [ - { - fmt: [ - { - at: -1, - }, - ], - ent: [ - { - data: { - mime: 'image/jpeg', - name: 'hello.jpg', - val: '<38992, bytes: 123456789012345678901234567890123456789012345678901234567890>', - width: 100, - height: 80, - }, - tp: 'EX', - }, - ], - }, - { - txt: ' ', - fmt: [ - { - at: 0, - key: 0, - len: 1, - }, - ], - ent: [ - { - tp: 'EX', - data: { - height: 80, - mime: 'image/jpeg', - name: 'hello.jpg', - width: 100, - }, - }, - ], - }, - ], - [ - { - txt: ' ', - fmt: [ - { - len: 1, - }, - ], - ent: [ - { - data: { - height: 213, - mime: 'image/jpeg', - name: 'roses.jpg', - val: '<38992, bytes: 123456789012345678901234567890123456789012345678901234567890>', - width: 638, - }, - tp: 'IM', - }, - ], - }, - { - txt: ' ', - fmt: [ - { - at: 0, - len: 1, - key: 0, - }, - ], - ent: [ - { - tp: 'IM', - data: { - height: 213, - mime: 'image/jpeg', - name: 'roses.jpg', - val: '<38992, bytes: 123456789012345678901234567890123456789012345678901234567890>', - width: 638, - }, - }, - ], - }, - ], -]; - -test.each(reply_this)('Drafty.replyContent %j', (src, exp) => { - expect(Drafty.replyContent(src, 25)).toEqual(exp); -}); - -const html_this: [DraftyDoc, string][] = [ - [ - { - ent: [ - { - data: { - val: 'usrCPvFc6lpAsw', - }, - tp: 'MN', - }, - ], - fmt: [ - { - len: 13, - }, - { - at: 13, - len: 1, - tp: 'BR', - }, - { - len: 38, - tp: 'QQ', - }, - ], - txt: 'Alice Johnson This is a reply to replyThis is a Reply -> Forward -> Reply.', - }, - '
Alice Johnson
This is a reply to reply
This is a Reply -> Forward -> Reply.', - ], - [ - { - ent: [ - { - data: { - val: 'usrCPvFc6lpAsw', - }, - tp: 'MN', - }, - { - data: { - val: 'usrCPvFc6lpAsw', - }, - tp: 'MN', - }, - ], - fmt: [ - { - len: 15, - }, - { - at: 15, - len: 1, - tp: 'BR', - }, - { - at: 16, - key: 1, - len: 13, - }, - { - at: 29, - len: 1, - tp: 'BR', - }, - { - at: 16, - len: 36, - tp: 'QQ', - }, - ], - txt: '➦ Alice Johnson Alice Johnson This is a simple replyThis is a reply to reply', - }, - '➦ Alice Johnson
Alice Johnson
This is a simple reply
This is a reply to reply', - ], - [ - { - txt: 'Hello bold world', - fmt: [ - { - at: 6, - len: 4, - tp: 'ST', - }, - ], - }, - 'Hello bold world', - ], - [ - { - txt: 'Click me for a surprise!', - fmt: [ - { - at: 0, - len: 23, - key: 0, - }, - ], - ent: [ - { - tp: 'LN', - data: { - url: "javascript:alert('XSS')", - }, - }, - ], - }, - 'Click me for a surprise!', - ], - [ - { - txt: "Here is an image ", - }, - "Here is an image ", - ], -]; - -test.each(html_this)('Drafty.UNSAFE_toHTML %j', (src, exp) => { - expect(Drafty.UNSAFE_toHTML(src)).toEqual(exp); -}); - -const md_this: [DraftyDoc, string][] = [ - [ - { - fmt: [ - { - at: 8, - len: 4, - tp: 'ST', - }, - { - at: 14, - len: 4, - tp: 'CO', - }, - { - at: 23, - len: 6, - tp: 'EM', - }, - { - at: 31, - len: 6, - tp: 'DL', - }, - ], - txt: 'This is bold, code and italic, strike', - }, - 'This is *bold*, `code` and _italic_, ~strike~', - ], - [ - { - fmt: [ - { - at: 14, - len: 0, - tp: 'BR', - }, - { - at: 23, - len: 15, - tp: 'ST', - }, - { - at: 32, - len: 6, - tp: 'EM', - }, - ], - txt: 'two lines withcombined bold and italic', - }, - 'two lines with\ncombined *bold and _italic_*', - ], - [ - { - ent: [ - { - data: { - val: 'mention', - }, - tp: 'MN', - }, - { - data: { - val: 'hashtag', - }, - tp: 'HT', - }, - ], - fmt: [ - { - at: 10, - key: 0, - len: 8, - }, - { - at: 25, - key: 1, - len: 8, - }, - ], - txt: 'this is a @mention and a #hashtag in a string', - }, - 'this is a @mention and a #hashtag in a string', - ], -]; - -test.each(md_this)('Drafty.toMarkdown %j', (src, exp) => { - expect(Drafty.toMarkdown(src)).toEqual(exp); -}); - -const invalid_this: [unknown, string][] = [ - [ - { - fmt: [ - null, - { - at: 5, - len: 5, - tp: 'EM', - }, - ], - txt: 'Null style in the middle', - }, - 'Null style in the middle', - ], - [ - { - ent: [ - null, - { - data: { - val: 'usrCPvFc6lpAsw', - }, - tp: 'MN', - }, - ], - fmt: [ - { - len: 4, - }, - { - at: 5, - key: 1, - len: 6, - }, - ], - txt: 'Null entity with reference', - }, - 'Null entity with reference', - ], -]; - -test.each(invalid_this)('Invalid Drafty %j', (src, exp) => { - expect(Drafty.UNSAFE_toHTML(fromWire(src))).toEqual(exp); -}); - -const quote_this: [DraftyDoc, DraftyDoc][] = [ - [ - { - txt: '😀 b1👩🏽‍✈️b2 smile 123 123 123 123', - fmt: [ - { - tp: 'ST', - at: 8, - len: 5, - }, - { - tp: 'EM', - at: 22, - len: 3, - }, - ], - }, - { - ent: [ - { - data: { - val: 'usrbzV_721mIW0', - }, - tp: 'MN', - }, - ], - fmt: [ - { - at: 0, - key: 0, - len: 11, - }, - { - at: 11, - len: 1, - tp: 'BR', - }, - { - at: 20, - len: 5, - tp: 'ST', - }, - { - at: 34, - len: 3, - tp: 'EM', - }, - { - at: 0, - len: 41, - tp: 'QQ', - }, - ], - txt: 'tinode-user 😀 b1👩🏽‍✈️b2 smile 123 123 123 123', - }, - ], -]; - -test.each(quote_this)('Drafty.quote %j', (src, exp) => { - expect(Drafty.quote('tinode-user', 'usrbzV_721mIW0', src)).toEqual(exp); -}); - -test('Drafty.attrValue LN sanitizeUrl', () => { - expect( - Drafty.attrValue('LN', { - url: 'https://example.com/path', - }) - ).toEqual({ - href: 'https://example.com/path', - target: '_blank', - rel: 'noopener noreferrer', - }); - expect( - Drafty.attrValue('LN', { - url: 'http://example.com', - }) - ).toEqual({ - href: 'http://example.com', - target: '_blank', - rel: 'noopener noreferrer', - }); - expect( - Drafty.attrValue('LN', { - url: 'ftp://files.example.com', - }) - ).toEqual({ - href: 'ftp://files.example.com', - target: '_blank', - rel: 'noopener noreferrer', - }); - expect( - Drafty.attrValue('LN', { - url: '/v0/file/s/abc.jpg', - }) - ).toEqual({ - href: '/v0/file/s/abc.jpg', - target: '_blank', - rel: 'noopener noreferrer', - }); - expect( - Drafty.attrValue('LN', { - url: 'relative/path.html', - }) - ).toEqual({ - href: 'relative/path.html', - target: '_blank', - rel: 'noopener noreferrer', - }); - expect( - Drafty.attrValue('LN', { - url: "javascript:alert('XSS')", - }) - ).toEqual({ - href: null, - target: '_blank', - rel: 'noopener noreferrer', - }); - expect( - Drafty.attrValue('LN', { - url: 'data:text/html,', - }) - ).toEqual({ - href: null, - target: '_blank', - rel: 'noopener noreferrer', - }); - expect( - Drafty.attrValue('LN', { - url: 'vbscript:msgbox(1)', - }) - ).toEqual({ - href: null, - target: '_blank', - rel: 'noopener noreferrer', - }); - expect( - Drafty.attrValue('LN', { - url: '//evil.com/path', - }) - ).toEqual({ - href: null, - target: '_blank', - rel: 'noopener noreferrer', - }); -}); - -test('Drafty.attrValue BN sanitizeUrl', () => { - expect( - Drafty.attrValue('BN', { - act: 'url', - ref: 'https://example.com', - name: 'btn', - val: 'v', - }) - ).toEqual({ - 'data-act': 'url', - 'data-val': 'v', - 'data-name': 'btn', - 'data-ref': 'https://example.com', - }); - expect( - Drafty.attrValue('BN', { - act: 'url', - ref: 'javascript:alert(1)', - name: 'btn', - val: 'v', - }) - ).toEqual({ - 'data-act': 'url', - 'data-val': 'v', - 'data-name': 'btn', - 'data-ref': null, - }); -}); - -test('Drafty.getDownloadUrl sanitizeUrl', () => { - expect( - Drafty.getDownloadUrl({ - mime: 'image/jpeg', - ref: 'https://example.com/img.jpg', - }) - ).toBe('https://example.com/img.jpg'); - expect( - Drafty.getDownloadUrl({ - mime: 'image/jpeg', - ref: 'javascript:alert(1)', - }) - ).toBeNull(); - expect( - Drafty.getDownloadUrl({ - mime: 'image/jpeg', - ref: '/v0/file/s/abc.jpg', - }) - ).toBe('/v0/file/s/abc.jpg'); -}); - -test('Drafty.getDownloadUrl falls back to data: URI without a DOM', () => { - expect( - Drafty.getDownloadUrl({ - mime: 'image/png', - val: 'iVBORw0KGgo=', - }) - ).toBe('data:image/png;base64,iVBORw0KGgo='); - expect(Drafty.getDownloadUrl({ val: 'AAAA' })).toBe( - 'data:application/octet-stream;base64,AAAA' - ); -}); - -test('Drafty.parse reuses the first entity for repeated mentions', () => { - expect(Drafty.parse('@alice and @alice')).toEqual({ - txt: '@alice and @alice', - fmt: [ - { at: 0, len: 6, key: 0 }, - { at: 11, len: 6, key: 0 }, - ], - ent: [{ tp: 'MN', data: { val: 'alice' } }], - }); -}); - -test('Drafty.appendLink counts graphemes', () => { - expect( - Drafty.appendLink({ txt: '👋🏼 ' }, { txt: 'link', url: 'https://x.co' }) - ).toEqual({ - txt: '👋🏼 link', - fmt: [{ at: 2, len: 4, key: 0 }], - ent: [{ tp: 'LN', data: { url: 'https://x.co' } }], - }); -}); diff --git a/src/core/__tests__/graphemes.test.ts b/src/core/__tests__/graphemes.test.ts deleted file mode 100644 index 8a76daa..0000000 --- a/src/core/__tests__/graphemes.test.ts +++ /dev/null @@ -1,94 +0,0 @@ -import { describe, expect, test } from '@jest/globals'; - -import { splitGraphemes, splitGraphemesFallback } from '../graphemes'; - -const segmentsOf = (str: string) => - splitGraphemesFallback(str).map(({ segment }) => segment); - -describe('splitGraphemesFallback', () => { - test('plain ASCII and Cyrillic', () => { - expect(segmentsOf('abc')).toEqual(['a', 'b', 'c']); - expect(segmentsOf('жЫр')).toEqual(['ж', 'Ы', 'р']); - expect(segmentsOf('')).toEqual([]); - }); - - test('surrogate pairs', () => { - expect(segmentsOf('a😀b')).toEqual(['a', '😀', 'b']); - expect(segmentsOf('𝒳𝒴')).toEqual(['𝒳', '𝒴']); - }); - - test('combining marks', () => { - expect(segmentsOf('éx')).toEqual(['é', 'x']); - expect(segmentsOf('ạ̈b')).toEqual(['ạ̈', 'b']); - }); - - test('variation selectors', () => { - expect(segmentsOf('❤️!')).toEqual(['❤️', '!']); - expect(segmentsOf('🕯️ x')).toEqual(['🕯️', ' ', 'x']); - }); - - test('skin tone modifiers', () => { - expect(segmentsOf('Hi👋🏼Hi')).toEqual(['H', 'i', '👋🏼', 'H', 'i']); - }); - - test('ZWJ sequences', () => { - expect(segmentsOf('b1👩🏽‍✈️b2')).toEqual(['b', '1', '👩🏽‍✈️', 'b', '2']); - expect(segmentsOf('👨‍👩‍👧‍👦')).toEqual(['👨‍👩‍👧‍👦']); - }); - - test('ZWJ before a letter does not glue the letter', () => { - expect(segmentsOf('a‍b')).toEqual(['a‍', 'b']); - }); - - test('regional indicator flags pair up', () => { - expect(segmentsOf('🇺🇸🇫🇷')).toEqual(['🇺🇸', '🇫🇷']); - expect(segmentsOf('🇺🇸🇫')).toEqual(['🇺🇸', '🇫']); - }); - - test('tag sequence flags', () => { - const england = '🏴\u{E0067}\u{E0062}\u{E0065}\u{E006E}\u{E0067}\u{E007F}'; - expect(segmentsOf(england + 'x')).toEqual([england, 'x']); - }); - - test('keycaps', () => { - expect(segmentsOf('1️⃣#️⃣')).toEqual(['1️⃣', '#️⃣']); - }); - - test('CRLF stays together, other controls split', () => { - expect(segmentsOf('a\r\nb')).toEqual(['a', '\r\n', 'b']); - expect(segmentsOf('\ń')).toEqual(['\n', '́']); - }); - - test('segment index is the UTF-16 offset', () => { - expect(splitGraphemesFallback('a😀👋🏼b')).toEqual([ - { segment: 'a', index: 0 }, - { segment: '😀', index: 1 }, - { segment: '👋🏼', index: 3 }, - { segment: 'b', index: 7 }, - ]); - }); - - test('matches Intl.Segmenter on mixed text', () => { - const samples = [ - 'Это *жЫрный*, `код` и _наклонный_', - '😀 b1👩🏽‍✈️b2 smile 123', - 'Hi 👋🏼 Visit http://localhost:6060', - '🔴Hello🔴 🟠Hello🟠 🇩🇪🇯🇵', - 'café 1️⃣ 👨‍👩‍👧‍👦 ❤️', - ]; - const segmenter = new Intl.Segmenter(); - for (const sample of samples) { - const expected = Array.from(segmenter.segment(sample), (s) => s.segment); - expect(segmentsOf(sample)).toEqual(expected); - } - }); -}); - -describe('splitGraphemes', () => { - test('returns segments with offsets', () => { - expect(splitGraphemes('a👋🏼')).toEqual([ - { segment: 'a', index: 0 }, - { segment: '👋🏼', index: 1 }, - ]); - }); -}); diff --git a/src/core/__tests__/key-value-adapter.test.ts b/src/core/__tests__/key-value-adapter.test.ts deleted file mode 100644 index de853a3..0000000 --- a/src/core/__tests__/key-value-adapter.test.ts +++ /dev/null @@ -1,242 +0,0 @@ -import { describe, expect, test } from '@jest/globals'; -import { - AsyncStore, - FakeMMKVv3, - FakeMMKVv4, - SyncStore, -} from '../__fixtures__/key-value-stores'; -import KeyValueAdapter, { - fromMMKV, - type KeyValueStore, - type MMKVLike, -} from '../storage/key-value-adapter'; -import { MAX_SEQ } from '../storage/storage-adapter'; - -interface ExpoSQLiteKVStore { - getItem(key: string): Promise; - setItem( - key: string, - value: string | ((prevValue: string | null) => string) - ): Promise; - removeItem(key: string): Promise; - getAllKeys(): Promise; - multiGet(keys: string[]): Promise<[string, string | null][]>; -} - -interface AsyncStorageV2 { - getItem: (key: string) => Promise; - setItem: (key: string, value: string) => Promise; - removeItem: (key: string) => Promise; - getAllKeys: () => Promise; - multiGet: ( - keys: readonly string[] - ) => Promise; -} - -interface AsyncStorageV3 { - getItem(key: string): Promise; - setItem(key: string, value: string): Promise; - removeItem(key: string): Promise; - getMany(keys: string[]): Promise>; - getAllKeys(): Promise; -} - -interface MMKVv4 { - set(key: string, value: boolean | string | number | ArrayBuffer): void; - getString(key: string): string | undefined; - remove(key: string): boolean; - getAllKeys(): string[]; -} - -interface MMKVv3 { - set(key: string, value: boolean | string | number | ArrayBuffer): void; - getString(key: string): string | undefined; - delete(key: string): void; - getAllKeys(): string[]; -} - -type PublishedStoresFit = [ - ExpoSQLiteKVStore extends KeyValueStore ? true : never, - AsyncStorageV2 extends KeyValueStore ? true : never, - AsyncStorageV3 extends KeyValueStore ? true : never, - MMKVv4 extends MMKVLike ? true : never, - MMKVv3 extends MMKVLike ? true : never, -]; - -const everything = { since: 0, before: MAX_SEQ, limit: 0 }; - -async function openOn(store: KeyValueStore, prefix?: string) { - const adapter = new KeyValueAdapter(store, { prefix }); - await adapter.open(); - return adapter; -} - -async function seed(adapter: KeyValueAdapter) { - await adapter.putTopic({ - name: 'grpA', - seq: 3, - updated: new Date('2026-10-01T10:00:00.000Z'), - }); - await adapter.putUser({ uid: 'usr1', public: { fn: 'Alice' } }); - await adapter.putSubscription({ - topic: 'grpA', - uid: 'usr1', - lastSeen: { when: new Date('2026-10-02T08:30:00.000Z') }, - }); - for (let seq = 1; seq <= 3; seq++) { - await adapter.putMessage({ - topic: 'grpA', - seq, - ts: new Date(`2026-10-03T0${seq}:00:00.000Z`), - content: `m${seq}`, - }); - } - await adapter.addDelLog([{ topic: 'grpA', clear: 1, low: 10, hi: 12 }]); -} - -describe('KeyValueAdapter', () => { - test('a new adapter on the same store sees everything that was saved', async () => { - const store = new SyncStore(); - await seed(await openOn(store)); - - const reopened = await openOn(store); - - expect(await reopened.getTopic('grpA')).toEqual({ - name: 'grpA', - seq: 3, - updated: new Date('2026-10-01T10:00:00.000Z'), - }); - expect(await reopened.getUser('usr1')).toEqual({ - uid: 'usr1', - public: { fn: 'Alice' }, - }); - const [sub] = await reopened.getSubscriptions('grpA'); - expect(sub?.lastSeen).toEqual({ - when: new Date('2026-10-02T08:30:00.000Z'), - }); - const messages = await reopened.readMessages('grpA', everything); - expect(messages.map((m) => m.seq)).toEqual([3, 2, 1]); - expect(messages[0]?.ts).toEqual(new Date('2026-10-03T03:00:00.000Z')); - expect(await reopened.maxDelId('grpA')).toBe(1); - }); - - test('message status changes are saved', async () => { - const store = new SyncStore(); - const adapter = await openOn(store); - await adapter.putMessage({ topic: 'grpA', seq: 1, _status: 20 }); - - await adapter.updateMessageStatus('grpA', 1, 50); - - const [message] = await ( - await openOn(store) - ).readMessageRanges('grpA', [{ low: 1 }]); - expect(message?._status).toBe(50); - }); - - test('removeMessages deletes stored keys in the half-open range only', async () => { - const store = new SyncStore(); - const adapter = await openOn(store); - for (let seq = 1; seq <= 5; seq++) { - await adapter.putMessage({ topic: 'grpA', seq }); - } - await adapter.putMessage({ topic: 'grpAB', seq: 3 }); - - await adapter.removeMessages('grpA', 2, 4); - - expect([...store.data.keys()].sort()).toEqual([ - 'tinode/msg/grpA/1', - 'tinode/msg/grpA/4', - 'tinode/msg/grpA/5', - 'tinode/msg/grpAB/3', - ]); - }); - - test('removeTopic and destroy leave keys of other topics and other owners alone', async () => { - const store = new SyncStore(); - store.setItem('theme', 'dark'); - const other = await openOn(store, 'other'); - await other.putTopic({ name: 'grpA' }); - const adapter = await openOn(store); - await seed(adapter); - await adapter.putTopic({ name: 'grpAB' }); - - await adapter.removeTopic('grpA'); - expect([...store.data.keys()].sort()).toEqual([ - 'other/topic/grpA', - 'theme', - 'tinode/topic/grpAB', - 'tinode/user/usr1', - ]); - - await adapter.destroy(); - expect([...store.data.keys()].sort()).toEqual([ - 'other/topic/grpA', - 'theme', - ]); - }); - - test('records that cannot be read are skipped on open', async () => { - const store = new SyncStore(); - store.setItem('tinode/topic/grpA', '{not json'); - store.setItem('tinode/msg/grpA/1', JSON.stringify({ topic: 'grpA' })); - store.setItem('tinode/topic/grpB', JSON.stringify({ name: 'grpB' })); - - const adapter = await openOn(store); - - expect(await adapter.getTopics()).toEqual([{ name: 'grpB' }]); - expect(await adapter.readMessages('grpA', everything)).toEqual([]); - }); - - test('loads with one batch read when the store has multiGet', async () => { - const store = new AsyncStore(); - await seed(await openOn(store)); - store.getItemCalls = 0; - - await openOn(store); - - expect(store.multiGetCalls).toBe(2); - expect(store.getItemCalls).toBe(0); - }); - - test('loads with getMany when the store has it', async () => { - const data = new Map(); - const store: KeyValueStore = { - getItem: () => { - throw new Error('getItem should not be used for loading'); - }, - setItem: (key, value) => data.set(key, value), - removeItem: (key) => data.delete(key), - getAllKeys: () => [...data.keys()], - getMany: (keys) => - Object.fromEntries(keys.map((key) => [key, data.get(key) ?? null])), - }; - await seed(await openOn(store)); - - const reopened = await openOn(store); - - expect(await reopened.getTopics()).toHaveLength(1); - }); -}); - -test('the published store typings fit KeyValueStore and MMKVLike', () => { - const fits: PublishedStoresFit = [true, true, true, true, true]; - expect(fits).toHaveLength(5); -}); - -describe('fromMMKV', () => { - test.each([ - ['v4 (remove)', () => new FakeMMKVv4()], - ['v3 (delete)', () => new FakeMMKVv3()], - ])('works with MMKV %s', async (_name, create) => { - const mmkv = create(); - const adapter = await openOn(fromMMKV(mmkv)); - await seed(adapter); - await adapter.removeUser('usr1'); - - const reopened = await openOn(fromMMKV(mmkv)); - - expect(await reopened.getUser('usr1')).toBeUndefined(); - expect(await reopened.readMessages('grpA', everything)).toHaveLength(3); - expect(mmkv.data.has('tinode/user/usr1')).toBe(false); - }); -}); diff --git a/src/core/__tests__/large-file.test.ts b/src/core/__tests__/large-file.test.ts deleted file mode 100644 index 3257491..0000000 --- a/src/core/__tests__/large-file.test.ts +++ /dev/null @@ -1,344 +0,0 @@ -import { - afterEach, - beforeEach, - describe, - expect, - jest, - test, -} from '@jest/globals'; -import LargeFileHelper, { addURLParam } from '../large-file'; -import type { - LargeFileTinode, - ReactNativeFileDescriptor, - UploadProgressEventLike, - XHRLike, -} from '../large-file'; - -const REQUEST_DONE = 4; -const OriginalFormData: unknown = Reflect.get(globalThis, 'FormData'); - -class FakeXHR implements XHRLike { - static instances: FakeXHR[] = []; - - readyState = 0; - status = 0; - statusText = ''; - response: unknown = null; - responseType = ''; - upload: { onprogress: ((evt: UploadProgressEventLike) => void) | null } = { - onprogress: null, - }; - onload: ((evt: unknown) => void) | null = null; - onerror: ((evt: unknown) => void) | null = null; - onabort: ((evt: unknown) => void) | null = null; - onprogress: ((evt: { loaded: number }) => void) | null = null; - method = ''; - url = ''; - headers: Record = {}; - body: FormData | null | undefined = undefined; - aborted = false; - - constructor() { - FakeXHR.instances.push(this); - } - - open(method: string, url: string): void { - this.method = method; - this.url = url; - } - - setRequestHeader(name: string, value: string): void { - this.headers[name] = value; - } - - send(body?: FormData | null): void { - this.body = body; - } - - abort(): void { - this.aborted = true; - this.onabort?.({}); - } - - complete(status: number, response: unknown, statusText = ''): void { - this.readyState = REQUEST_DONE; - this.status = status; - this.statusText = statusText; - this.response = response; - this.onload?.({}); - } - - static latest(): FakeXHR { - const request = FakeXHR.instances[FakeXHR.instances.length - 1]; - if (!request) { - throw new Error('No request was created'); - } - return request; - } -} - -class RecordingFormData { - static instances: RecordingFormData[] = []; - - readonly entries: [string, unknown][] = []; - - constructor() { - RecordingFormData.instances.push(this); - } - - append(name: string, value: unknown): void { - this.entries.push([name, value]); - } -} - -function recordedEntries(): Map { - const form = RecordingFormData.instances[0]; - if (!form) { - throw new Error('No form was built'); - } - return new Map(form.entries); -} - -function makeTinode(overrides: Partial = {}): LargeFileTinode { - return { - _apiKey: 'KEY', - _secure: true, - _host: 'api.example.com', - getAuthToken: () => ({ token: 'TOKEN', expires: new Date(0) }), - getNextUniqueId: () => '101', - logger: jest.fn(), - ...overrides, - }; -} - -describe('addURLParam', () => { - test('appends to a relative url without query', () => { - expect(addURLParam('/v0/file/s/abc.jpg', 'asatt', '1')).toBe( - '/v0/file/s/abc.jpg?asatt=1' - ); - }); - - test('appends to a relative url with a query', () => { - expect(addURLParam('/v0/file/s/abc.jpg?x=y', 'asatt', '1')).toBe( - '/v0/file/s/abc.jpg?x=y&asatt=1' - ); - }); - - test('keeps the hash at the end', () => { - expect(addURLParam('/file#frag', 'asatt', '1')).toBe('/file?asatt=1#frag'); - }); - - test('handles absolute urls', () => { - expect(addURLParam('https://host.example/a/b?c=d', 'k', 'v w')).toBe( - 'https://host.example/a/b?c=d&k=v%20w' - ); - }); -}); - -describe('LargeFileHelper', () => { - beforeEach(() => { - FakeXHR.instances = []; - LargeFileHelper.setNetworkProvider(FakeXHR); - RecordingFormData.instances = []; - Object.defineProperty(globalThis, 'FormData', { - value: RecordingFormData, - configurable: true, - writable: true, - }); - }); - - afterEach(() => { - Object.defineProperty(globalThis, 'FormData', { - value: OriginalFormData, - configurable: true, - writable: true, - }); - LargeFileHelper.setNetworkProvider(undefined); - jest.restoreAllMocks(); - }); - - describe('upload', () => { - const descriptor: ReactNativeFileDescriptor = { - uri: 'file:///tmp/photo.jpg', - name: 'photo.jpg', - type: 'image/jpeg', - }; - - test('posts a react native file descriptor as is, with id and topic', async () => { - const helper = new LargeFileHelper(makeTinode(), '0'); - - const uploading = helper.upload(descriptor, 'usrABC'); - const xhr = FakeXHR.latest(); - xhr.complete( - 200, - JSON.stringify({ - ctrl: { code: 200, text: 'ok', params: { url: '/v0/file/s/x.jpg' } }, - }) - ); - - await expect(uploading).resolves.toBe('/v0/file/s/x.jpg'); - expect(xhr.method).toBe('POST'); - expect(xhr.url).toBe('https://api.example.com/v0/file/u/'); - expect(xhr.headers).toEqual({ - 'X-Tinode-APIKey': 'KEY', - 'X-Tinode-Auth': 'Token TOKEN', - }); - - const entries = recordedEntries(); - expect(xhr.body).toBeInstanceOf(RecordingFormData); - expect(entries.get('file')).toBe(descriptor); - expect(entries.get('id')).toBe('101'); - expect(entries.get('topic')).toBe('usrABC'); - }); - - test('rejects with CommError and calls onFailure on server error', async () => { - const helper = new LargeFileHelper(makeTinode(), '0'); - const onFailure = jest.fn(); - const onSuccess = jest.fn(); - - const uploading = helper.upload( - descriptor, - null, - null, - onSuccess, - onFailure - ); - FakeXHR.latest().complete( - 413, - JSON.stringify({ ctrl: { code: 413, text: 'too large' } }) - ); - - await expect(uploading).rejects.toMatchObject({ code: 413 }); - expect(onFailure).toHaveBeenCalledWith( - expect.objectContaining({ code: 413, text: 'too large' }) - ); - expect(onSuccess).not.toHaveBeenCalled(); - }); - - test('falls back to status when the response is not json', async () => { - const logger = jest.fn(); - const helper = new LargeFileHelper(makeTinode({ logger }), '0'); - - const uploading = helper.upload(descriptor); - FakeXHR.latest().complete(500, '', 'Server Error'); - - await expect(uploading).rejects.toMatchObject({ code: 500 }); - expect(logger).toHaveBeenCalled(); - }); - - test('reports progress to both callbacks', () => { - const helper = new LargeFileHelper(makeTinode(), '0'); - const onProgress = jest.fn(); - const helperProgress = jest.fn(); - helper.onProgress = helperProgress; - - helper.upload(descriptor, null, onProgress).catch(() => {}); - FakeXHR.latest().upload.onprogress?.({ - lengthComputable: true, - loaded: 1, - total: 4, - }); - - expect(onProgress).toHaveBeenCalledWith(0.25); - expect(helperProgress).toHaveBeenCalledWith(0.25); - }); - - test('rejects a base url that is not http(s)', () => { - const helper = new LargeFileHelper(makeTinode(), '0'); - expect(() => helper.uploadWithBaseUrl('ftp://x', descriptor)).toThrow( - "Invalid base URL 'ftp://x'" - ); - }); - - test('cancel aborts pending requests', async () => { - const helper = new LargeFileHelper(makeTinode(), '0'); - const uploading = helper.upload(descriptor); - - helper.cancel(); - - await expect(uploading).rejects.toThrow('upload cancelled by user'); - expect(FakeXHR.latest().aborted).toBe(true); - }); - }); - - describe('download', () => { - test('refuses absolute urls', () => { - const helper = new LargeFileHelper(makeTinode(), '0'); - const onError = jest.fn(); - - const result = helper.download( - 'https://evil.example/f', - 'f', - 'x/y', - null, - onError - ); - - expect(result).toBeUndefined(); - expect(onError).toHaveBeenCalled(); - expect(FakeXHR.instances).toHaveLength(0); - }); - - test('refuses when not authenticated', () => { - const helper = new LargeFileHelper( - makeTinode({ getAuthToken: () => null }), - '0' - ); - const onError = jest.fn(); - - expect( - helper.download('/v0/file/s/a', 'a', 'x/y', null, onError) - ).toBeUndefined(); - expect(onError).toHaveBeenCalledWith('Must authenticate first'); - }); - - test('resolves with the downloaded Blob when there is no document', async () => { - const helper = new LargeFileHelper(makeTinode(), '0'); - const blob = new Blob(['content'], { - type: 'text/plain', - lastModified: 0, - }); - - const downloading = helper.download( - '/v0/file/s/a.txt', - 'a.txt', - 'text/plain' - ); - const xhr = FakeXHR.latest(); - xhr.complete(200, blob); - - await expect(downloading).resolves.toBe(blob); - expect(xhr.method).toBe('GET'); - expect(xhr.url).toBe('/v0/file/s/a.txt?asatt=1'); - expect(xhr.responseType).toBe('blob'); - expect(xhr.headers['X-Tinode-Auth']).toBe('Token TOKEN'); - }); - - test('reports progress as loaded bytes', () => { - const helper = new LargeFileHelper(makeTinode(), '0'); - const onProgress = jest.fn(); - - helper.download('/v0/file/s/a', 'a', 'x/y', onProgress)?.catch(() => {}); - FakeXHR.latest().onprogress?.({ loaded: 512 }); - - expect(onProgress).toHaveBeenCalledWith(512); - }); - - test('rejects on network error', async () => { - const helper = new LargeFileHelper(makeTinode(), '0'); - const onError = jest.fn(); - - const downloading = helper.download( - '/v0/file/s/a', - 'a', - 'x/y', - null, - onError - ); - FakeXHR.latest().onerror?.({}); - - await expect(downloading).rejects.toThrow('failed'); - expect(onError).toHaveBeenCalled(); - }); - }); -}); diff --git a/src/core/__tests__/persistent-cache.test.ts b/src/core/__tests__/persistent-cache.test.ts deleted file mode 100644 index aff597a..0000000 --- a/src/core/__tests__/persistent-cache.test.ts +++ /dev/null @@ -1,233 +0,0 @@ -import { beforeEach, describe, expect, jest, test } from '@jest/globals'; -import PersistentCache, { - type CacheableTopic, -} from '../storage/persistent-cache'; -import MemoryAdapter from '../storage/memory-adapter'; - -class FakeAccessMode { - constructor(readonly mode: string) {} - - jsonHelper() { - return { mode: this.mode }; - } -} - -class FakeTopic implements CacheableTopic { - created = new Date(1000); - updated = new Date(2000); - seq = 0; - read = 0; - recv = 0; - unread = 0; - public: unknown = { fn: 'Group' }; - _tags: string[] = []; - _deleted = false; - acs: FakeAccessMode | undefined; - - constructor(readonly name: string) {} - - getAccessMode() { - return this.acs ?? new FakeAccessMode(''); - } - - setAccessMode(acs: unknown) { - this.acs = new FakeAccessMode(String(Reflect.get(Object(acs), 'mode'))); - } -} - -function newCache() { - const onError = jest.fn(); - const logger = jest.fn(); - const cache = new PersistentCache(onError, logger, new MemoryAdapter()); - return { cache, onError, logger }; -} - -describe('PersistentCache disabled', () => { - const cache = new PersistentCache(null, null, null); - - test('is not ready and resolves empty', async () => { - expect(cache.isReady()).toBe(false); - expect(cache.disabled).toBe(true); - expect(await cache.initDatabase()).toBeUndefined(); - expect(await cache.mapTopics()).toEqual([]); - expect(await cache.mapUsers()).toEqual([]); - expect(await cache.mapSubscriptions('grpA')).toEqual([]); - expect(await cache.readMessages('grpA')).toEqual([]); - expect(await cache.readDelLog('grpA')).toEqual([]); - expect(await cache.maxDelId('grpA')).toBe(0); - expect(await cache.getUser('usr1')).toBeUndefined(); - expect(await cache.updTopic(new FakeTopic('grpA'))).toBeUndefined(); - expect(await cache.deleteDatabase()).toBe(true); - }); -}); - -describe('PersistentCache', () => { - let cache: PersistentCache; - - beforeEach(async () => { - cache = newCache().cache; - await cache.initDatabase(); - }); - - test('ready after init, disabled after delete', async () => { - expect(cache.isReady()).toBe(true); - expect(await cache.deleteDatabase()).toBe(true); - expect(cache.isReady()).toBe(false); - }); - - test('topic serialization round trip', async () => { - const topic = new FakeTopic('grpA'); - topic.seq = 9; - topic.read = 4; - topic._tags = ['a', 'b']; - topic.setAccessMode({ mode: 'JRWP' }); - await cache.updTopic(topic); - - const records = await cache.mapTopics(); - expect(records).toHaveLength(1); - expect(records[0]).toMatchObject({ - name: 'grpA', - seq: 9, - read: 4, - tags: ['a', 'b'], - acs: { mode: 'JRWP' }, - public: { fn: 'Group' }, - }); - - const restored = new FakeTopic('grpA'); - restored.seq = 0; - cache.deserializeTopic(restored, records[0]!); - expect(restored.seq).toBe(9); - expect(restored.read).toBe(4); - expect(restored.unread).toBe(5); - expect(restored._tags).toEqual(['a', 'b']); - expect(restored.acs?.mode).toBe('JRWP'); - }); - - test('mapTopics invokes callback with context', async () => { - await cache.updTopic(new FakeTopic('grpA')); - const seen: string[] = []; - const context = { tag: 'ctx' }; - await cache.mapTopics(function (this: unknown, record) { - expect(this).toBe(context); - seen.push(record.name); - }, context); - expect(seen).toEqual(['grpA']); - }); - - test('markTopicAsDeleted and remTopic', async () => { - await cache.updTopic(new FakeTopic('grpA')); - await cache.markTopicAsDeleted('grpA', true); - expect((await cache.mapTopics())[0]?._deleted).toBe(true); - await cache.markTopicAsDeleted('missing', true); - await cache.remTopic('grpA'); - expect(await cache.mapTopics()).toEqual([]); - }); - - test('users', async () => { - await cache.updUser('usr1'); - expect(await cache.mapUsers()).toEqual([]); - await cache.updUser('usr1', { fn: 'Alice' }); - expect(await cache.getUser('usr1')).toEqual({ - user: 'usr1', - public: { fn: 'Alice' }, - }); - expect(await cache.getUser('usr2')).toBeUndefined(); - expect(await cache.mapUsers()).toEqual([ - { uid: 'usr1', public: { fn: 'Alice' } }, - ]); - await cache.remUser('usr1'); - expect(await cache.mapUsers()).toEqual([]); - }); - - test('subscriptions are merged and expose user', async () => { - await cache.updSubscription('grpA', 'usr1', { - mode: 'JRWP', - user: 'usr1', - online: true, - }); - await cache.updSubscription('grpA', 'usr1', { read: 3 }); - const subs = await cache.mapSubscriptions('grpA'); - expect(subs).toEqual([ - { topic: 'grpA', uid: 'usr1', user: 'usr1', mode: 'JRWP', read: 3 }, - ]); - await cache.remSubscription('grpA', 'usr1'); - expect(await cache.mapSubscriptions('grpA')).toEqual([]); - }); - - test('messages: add, read desc with limit, ranges, status', async () => { - for (let seq = 1; seq <= 5; seq++) { - const pub = { topic: 'grpA', seq, content: `m${seq}` }; - await cache.addMessage(pub); - } - const recent = await cache.readMessages('grpA', { limit: 2 }); - expect(recent.map((m) => m.seq)).toEqual([5, 4]); - const windowed = await cache.readMessages('grpA', { since: 2, before: 4 }); - expect(windowed.map((m) => m.seq)).toEqual([3, 2]); - const ranges = await cache.readMessages('grpA', { - ranges: [{ low: 1, hi: 3 }, { low: 5 }], - }); - expect(ranges.map((m) => m.seq)).toEqual([1, 2, 5]); - - await cache.updMessageStatus('grpA', 3, 4); - const [third] = await cache.readMessages('grpA', { ranges: [{ low: 3 }] }); - expect(third?._status).toBe(4); - expect(third?.content).toBe('m3'); - }); - - test('remMessages single, range and all', async () => { - for (let seq = 1; seq <= 8; seq++) { - await cache.addMessage({ topic: 'grpA', seq }); - } - await cache.remMessages('grpA', 8); - await cache.remMessages('grpA', 2, 4); - await cache.remMessages('grpA', 5, 5); - expect( - (await cache.readMessages('grpA')).map((message) => message.seq) - ).toEqual([7, 6, 5, 4, 1]); - await cache.remMessages('grpA'); - expect(await cache.readMessages('grpA')).toEqual([]); - }); - - test('del log and maxDelId', async () => { - expect(await cache.maxDelId('grpA')).toBe(0); - await cache.addDelLog('grpA', 3, [{ low: 2, hi: 4 }, { low: 9 }]); - await cache.addDelLog('grpA', 5, [{ low: 20, hi: 22 }]); - expect(await cache.maxDelId('grpA')).toBe(5); - expect(await cache.readDelLog('grpA')).toEqual([ - { low: 20, hi: 22 }, - { low: 9, hi: 10 }, - { low: 2, hi: 4 }, - ]); - expect(await cache.readDelLog('grpA', { limit: 2 })).toEqual([ - { low: 20, hi: 22 }, - ]); - expect(await cache.readDelLog('grpA', { ranges: [{ low: 9 }] })).toEqual([ - { low: 9, hi: 10 }, - ]); - }); - - test('adapter failures are logged and rethrown', async () => { - const adapter = new MemoryAdapter(); - const logger = jest.fn(); - const failing = new PersistentCache(null, logger, adapter); - await failing.initDatabase(); - jest.spyOn(adapter, 'getUsers').mockRejectedValue(new Error('boom')); - await expect(failing.mapUsers()).rejects.toThrow('boom'); - expect(logger).toHaveBeenCalledWith( - 'PCache', - 'mapUsers', - expect.any(Error) - ); - }); - - test('open failure reports to onError', async () => { - const adapter = new MemoryAdapter(); - const onError = jest.fn(); - jest.spyOn(adapter, 'open').mockRejectedValue(new Error('denied')); - const failing = new PersistentCache(onError, null, adapter); - await expect(failing.initDatabase()).rejects.toThrow('denied'); - expect(onError).toHaveBeenCalledTimes(1); - expect(failing.isReady()).toBe(false); - }); -}); diff --git a/src/core/__tests__/storage-adapters.test.ts b/src/core/__tests__/storage-adapters.test.ts deleted file mode 100644 index 8baaa3a..0000000 --- a/src/core/__tests__/storage-adapters.test.ts +++ /dev/null @@ -1,183 +0,0 @@ -import 'fake-indexeddb/auto'; -import { beforeEach, describe, expect, test } from '@jest/globals'; -import { AsyncStore, SyncStore } from '../__fixtures__/key-value-stores'; -import IndexedDBAdapter from '../storage/indexeddb-adapter'; -import KeyValueAdapter from '../storage/key-value-adapter'; -import MemoryAdapter from '../storage/memory-adapter'; -import { resolveStorageAdapter } from '../storage/resolve-adapter'; -import { MAX_SEQ, type StorageAdapter } from '../storage/storage-adapter'; - -const everything = { since: 0, before: MAX_SEQ, limit: 0 }; - -function message(topic: string, seq: number) { - return { topic, seq, content: `m${seq}` }; -} - -test('persist picks IndexedDB when the browser has it', () => { - expect(resolveStorageAdapter(true)).toBeInstanceOf(IndexedDBAdapter); - expect(resolveStorageAdapter(false)).toBeNull(); -}); - -describe.each([ - ['MemoryAdapter', () => new MemoryAdapter()], - ['IndexedDBAdapter', () => new IndexedDBAdapter()], - [ - 'KeyValueAdapter over a sync store', - () => new KeyValueAdapter(new SyncStore()), - ], - [ - 'KeyValueAdapter over an async store', - () => new KeyValueAdapter(new AsyncStore()), - ], -])('%s', (_name, create: () => StorageAdapter) => { - let adapter: StorageAdapter; - - beforeEach(async () => { - adapter = create(); - await adapter.open(); - await adapter.destroy(); - await adapter.open(); - }); - - test('open state', async () => { - expect(adapter.isOpen()).toBe(true); - await adapter.close(); - expect(adapter.isOpen()).toBe(false); - }); - - test('destroy drops data', async () => { - await adapter.putTopic({ name: 'grpA' }); - await adapter.destroy(); - await adapter.open(); - expect(await adapter.getTopics()).toEqual([]); - }); - - test('topics round trip and copy', async () => { - const record = { name: 'grpA', seq: 3 }; - await adapter.putTopic(record); - record.seq = 10; - expect(await adapter.getTopic('grpA')).toEqual({ name: 'grpA', seq: 3 }); - expect(await adapter.getTopic('nope')).toBeUndefined(); - expect(await adapter.getTopics()).toHaveLength(1); - }); - - test('users', async () => { - await adapter.putUser({ uid: 'usr1', public: { fn: 'A' } }); - expect(await adapter.getUser('usr1')).toEqual({ - uid: 'usr1', - public: { fn: 'A' }, - }); - expect(await adapter.getUsers()).toHaveLength(1); - await adapter.removeUser('usr1'); - expect(await adapter.getUser('usr1')).toBeUndefined(); - }); - - test('subscriptions per topic', async () => { - await adapter.putSubscription({ topic: 'grpA', uid: 'usr1', mode: 'JRWP' }); - await adapter.putSubscription({ topic: 'grpA', uid: 'usr2' }); - await adapter.putSubscription({ topic: 'grpB', uid: 'usr1' }); - expect(await adapter.getSubscriptions('grpA')).toHaveLength(2); - expect(await adapter.getSubscription('grpA', 'usr1')).toEqual({ - topic: 'grpA', - uid: 'usr1', - mode: 'JRWP', - }); - await adapter.removeSubscription('grpA', 'usr1'); - expect(await adapter.getSubscriptions('grpA')).toHaveLength(1); - expect(await adapter.getSubscriptions('none')).toEqual([]); - }); - - test('single range reads descending with limit', async () => { - for (let seq = 1; seq <= 6; seq++) { - await adapter.putMessage(message('grpA', seq)); - } - await adapter.putMessage(message('grpB', 2)); - const all = await adapter.readMessages('grpA', everything); - expect(all.map((m) => m.seq)).toEqual([6, 5, 4, 3, 2, 1]); - const limited = await adapter.readMessages('grpA', { - since: 0, - before: MAX_SEQ, - limit: 2, - }); - expect(limited.map((m) => m.seq)).toEqual([6, 5]); - const window = await adapter.readMessages('grpA', { - since: 2, - before: 5, - limit: 0, - }); - expect(window.map((m) => m.seq)).toEqual([4, 3, 2]); - expect( - await adapter.readMessages('grpA', { since: 5, before: 5, limit: 0 }) - ).toEqual([]); - }); - - test('range reads are half open', async () => { - for (let seq = 1; seq <= 6; seq++) { - await adapter.putMessage(message('grpA', seq)); - } - const result = await adapter.readMessageRanges('grpA', [ - { low: 2, hi: 4 }, - { low: 6 }, - { low: 5, hi: 5 }, - ]); - expect(result.map((m) => m.seq)).toEqual([2, 3, 6]); - }); - - test('status update and removal', async () => { - for (let seq = 1; seq <= 5; seq++) { - await adapter.putMessage(message('grpA', seq)); - } - await adapter.updateMessageStatus('grpA', 2, 7); - await adapter.updateMessageStatus('grpA', 99, 7); - const [second] = await adapter.readMessageRanges('grpA', [{ low: 2 }]); - expect(second?._status).toBe(7); - await adapter.removeMessages('grpA', 2, 4); - const left = await adapter.readMessages('grpA', everything); - expect(left.map((m) => m.seq)).toEqual([5, 4, 1]); - }); - - test('del log', async () => { - await adapter.addDelLog([ - { topic: 'grpA', clear: 1, low: 2, hi: 4 }, - { topic: 'grpA', clear: 2, low: 10, hi: 11 }, - { topic: 'grpA', clear: 2, low: 20, hi: 25 }, - ]); - expect(await adapter.maxDelId('grpA')).toBe(2); - expect(await adapter.maxDelId('grpB')).toBe(0); - expect(await adapter.readDelLog('grpA', everything)).toEqual([ - { low: 20, hi: 25 }, - { low: 10, hi: 11 }, - { low: 2, hi: 4 }, - ]); - expect( - await adapter.readDelLog('grpA', { since: 0, before: MAX_SEQ, limit: 5 }) - ).toEqual([{ low: 20, hi: 25 }]); - expect( - await adapter.readDelLog('grpA', { since: 3, before: 12, limit: 0 }) - ).toEqual([ - { low: 10, hi: 11 }, - { low: 2, hi: 4 }, - ]); - expect( - await adapter.readDelLogRanges('grpA', [{ low: 10 }, { low: 3, hi: 6 }]) - ).toEqual([ - { low: 10, hi: 11 }, - { low: 2, hi: 4 }, - ]); - }); - - test('removeTopic cascades', async () => { - await adapter.putTopic({ name: 'grpA' }); - await adapter.putSubscription({ topic: 'grpA', uid: 'usr1' }); - await adapter.putMessage(message('grpA', 1)); - await adapter.addDelLog([{ topic: 'grpA', clear: 3, low: 1, hi: 2 }]); - await adapter.putTopic({ name: 'grpB' }); - await adapter.putMessage(message('grpB', 1)); - await adapter.removeTopic('grpA'); - expect(await adapter.getTopic('grpA')).toBeUndefined(); - expect(await adapter.getSubscriptions('grpA')).toEqual([]); - expect(await adapter.readMessages('grpA', everything)).toEqual([]); - expect(await adapter.maxDelId('grpA')).toBe(0); - expect(await adapter.readMessages('grpB', everything)).toHaveLength(1); - }); -}); diff --git a/src/core/__tests__/the-card.test.ts b/src/core/__tests__/the-card.test.ts deleted file mode 100644 index 97e5c65..0000000 --- a/src/core/__tests__/the-card.test.ts +++ /dev/null @@ -1,1087 +0,0 @@ -import { describe, expect, test } from '@jest/globals'; -import TheCard, { type CardData } from '../the-card'; - -import { DEL_CHAR } from '../config'; - -describe('TheCard', () => { - describe('constructor', () => { - test('should create empty card', () => { - const card = new TheCard(); - expect(card || {}).toEqual({}); - }); - - test('should create card with fn', () => { - const card = new TheCard('Alice'); - expect(card).toEqual({ - fn: 'Alice', - }); - }); - - test('should create card with all fields', () => { - const card = new TheCard( - 'Alice', - 'http://example.com/img.jpg', - 'image/jpeg', - 'Note' - ); - expect(card).toEqual({ - fn: 'Alice', - note: 'Note', - photo: { - ref: 'http://example.com/img.jpg', - type: 'jpeg', - data: '␡', - }, - }); - }); - }); - - describe('setFn', () => { - test('should set fn', () => { - const card = TheCard.setFn({}, 'Bob'); - expect(card?.fn).toBe('Bob'); - }); - - test('should trim fn', () => { - const card = TheCard.setFn({}, ' Bob '); - expect(card?.fn).toBe('Bob'); - }); - - test('should remove fn if empty', () => { - const card = TheCard.setFn( - { - fn: 'Bob', - }, - '' - ); - expect(card?.fn).toBeUndefined(); - }); - }); - - describe('getFn', () => { - test('should get fn from card', () => { - const card: CardData = { - fn: 'Charlie', - }; - expect(TheCard.getFn(card)).toBe('Charlie'); - }); - - test('should return null if fn is missing', () => { - const card: CardData = { - note: 'Some note', - }; - expect(TheCard.getFn(card)).toBeNull(); - }); - - test('should return null if card is null', () => { - expect(TheCard.getFn(null)).toBeNull(); - }); - - test('should return null if card is undefined', () => { - expect(TheCard.getFn(undefined)).toBeNull(); - }); - }); - - describe('setNote', () => { - test('should set note', () => { - const card = TheCard.setNote({}, 'My Note'); - expect(card?.note).toBe('My Note'); - }); - - test('should set DEL_CHAR if empty', () => { - const card = TheCard.setNote( - { - note: 'Old', - }, - '' - ); - expect(card?.note).toBe(DEL_CHAR); - }); - }); - - describe('setPhoto', () => { - test('should set photo from ref', () => { - const card = TheCard.setPhoto( - {}, - 'http://example.com/a.png', - 'image/png' - ); - expect(card?.photo).toEqual({ - ref: 'http://example.com/a.png', - type: 'png', - data: '␡', - }); - }); - - test('should set photo from data URI', () => { - const dataUri = 'data:image/png;base64,AQID'; - const card = TheCard.setPhoto({}, dataUri, 'image/png'); - expect(card?.photo).toEqual({ - data: 'AQID', - type: 'png', - ref: DEL_CHAR, - }); - }); - - test('should set DEL_CHAR if null', () => { - const card = TheCard.setPhoto( - { - photo: {}, - }, - null - ); - expect(card?.photo).toBe(DEL_CHAR); - }); - - test('should infer mime type from extension', () => { - const card = TheCard.setPhoto({}, 'http://example.com/a.jpg'); - expect(card?.photo).toEqual({ - ref: 'http://example.com/a.jpg', - type: 'jpeg', - data: DEL_CHAR, - }); - }); - - test('should infer mime type from data URI', () => { - const dataUri = 'data:image/gif;base64,AQID'; - const card = TheCard.setPhoto({}, dataUri); - expect(card?.photo).toEqual({ - data: 'AQID', - type: 'gif', - ref: DEL_CHAR, - }); - }); - - test('should use default mime type if unknown', () => { - const card = TheCard.setPhoto({}, 'http://example.com/a.unknown'); - expect(card?.photo).toEqual({ - ref: 'http://example.com/a.unknown', - type: 'jpeg', - data: DEL_CHAR, - }); - }); - }); - - describe('getPhotoUrl', () => { - test('should return null if no photo', () => { - expect(TheCard.getPhotoUrl({})).toBeNull(); - }); - - test('should return ref url', () => { - const card: CardData = { - photo: { - ref: 'http://example.com/a.png', - type: 'png', - }, - }; - expect(TheCard.getPhotoUrl(card)).toBe('http://example.com/a.png'); - }); - - test('should return data uri', () => { - const card: CardData = { - photo: { - data: 'AQID', - type: 'png', - }, - }; - expect(TheCard.getPhotoUrl(card)).toBe('data:image/png;base64,AQID'); - }); - - test('should handle missing type in data uri', () => { - const card: CardData = { - photo: { - data: 'AQID', - }, - }; - expect(TheCard.getPhotoUrl(card)).toBe('data:image/jpeg;base64,AQID'); - }); - }); - - describe('Communication channels', () => { - test('addPhone', () => { - let card: CardData = {}; - card = TheCard.addPhone(card, '1234567890', 'mobile'); - expect(card?.comm).toHaveLength(1); - expect(card?.comm?.[0]).toEqual({ - value: '1234567890', - des: ['mobile'], - proto: 'tel', - }); - }); - - test('setPhone (replace)', () => { - let card: CardData = { - comm: [ - { - value: '000', - des: ['work'], - proto: 'tel', - }, - ], - }; - card = TheCard.setPhone(card, '1234567890', 'work'); - expect(card?.comm).toHaveLength(1); - expect(card?.comm?.[0]).toEqual({ - value: '1234567890', - des: ['work'], - proto: 'tel', - }); - }); - - test('addEmail', () => { - let card: CardData = {}; - card = TheCard.addEmail(card, 'bob@example.com', 'work'); - expect(card?.comm).toHaveLength(1); - expect(card?.comm?.[0]).toEqual({ - value: 'bob@example.com', - des: ['work'], - proto: 'email', - }); - }); - - test('addTinodeID', () => { - let card: CardData = {}; - card = TheCard.addTinodeID(card, 'usr123', 'home'); - expect(card?.comm).toHaveLength(1); - expect(card?.comm?.[0]).toEqual({ - value: 'usr123', - des: ['home'], - proto: 'tinode', - }); - }); - - test('clearPhone', () => { - let card: CardData = { - comm: [ - { - value: '123', - des: ['mobile'], - proto: 'tel', - }, - { - value: '456', - des: ['work'], - proto: 'tel', - }, - ], - }; - card = TheCard.clearPhone(card, '123', 'mobile'); - expect(card?.comm).toHaveLength(1); - expect(card?.comm?.[0]?.value).toBe('456'); - }); - - test('setEmail', () => { - let card: CardData = { - comm: [ - { - value: 'old@example.com', - des: ['work'], - proto: 'email', - }, - ], - }; - card = TheCard.setEmail(card, 'new@example.com', 'work'); - expect(card?.comm).toHaveLength(1); - expect(card?.comm?.[0]).toEqual({ - value: 'new@example.com', - des: ['work'], - proto: 'email', - }); - }); - - test('setTinodeID', () => { - let card: CardData = { - comm: [ - { - value: 'usr111', - des: ['home'], - proto: 'tinode', - }, - ], - }; - card = TheCard.setTinodeID(card, 'usr222', 'home'); - expect(card?.comm).toHaveLength(1); - expect(card?.comm?.[0]).toEqual({ - value: 'usr222', - des: ['home'], - proto: 'tinode', - }); - }); - - test('clearEmail', () => { - let card: CardData = { - comm: [ - { - value: 'a@example.com', - des: ['home'], - proto: 'email', - }, - { - value: 'b@example.com', - des: ['work'], - proto: 'email', - }, - ], - }; - card = TheCard.clearEmail(card, 'a@example.com', 'home'); - expect(card?.comm).toHaveLength(1); - expect(card?.comm?.[0]?.value).toBe('b@example.com'); - }); - - test('clearTinodeID', () => { - let card: CardData = { - comm: [ - { - value: 'usr1', - des: ['home'], - proto: 'tinode', - }, - { - value: 'usr2', - des: ['work'], - proto: 'tinode', - }, - ], - }; - card = TheCard.clearTinodeID(card, 'usr1', 'home'); - expect(card?.comm).toHaveLength(1); - expect(card?.comm?.[0]?.value).toBe('usr2'); - }); - }); - - describe('exportVCard', () => { - test('should return null for empty card', () => { - expect(TheCard.exportVCard(null)).toBeNull(); - }); - - test('should export minimal card', () => { - const card: CardData = { - fn: 'Alice', - }; - const vcard = TheCard.exportVCard(card); - expect(vcard).toContain('BEGIN:VCARD'); - expect(vcard).toContain('VERSION:3.0'); - expect(vcard).toContain('FN:Alice'); - expect(vcard).toContain('END:VCARD'); - }); - - test('should export full card', () => { - const card: CardData = { - fn: 'Alice', - note: 'My Note', - photo: { - type: 'jpeg', - data: 'base64data', - ref: DEL_CHAR, - }, - comm: [ - { - proto: 'tel', - des: ['cell'], - value: '123456', - }, - { - proto: 'email', - des: ['home'], - value: 'alice@example.com', - }, - { - proto: 'tinode', - des: ['home'], - value: 'tinode:id/usr123', - }, - { - proto: 'http', - des: ['work'], - value: 'https://example.com', - }, - ], - }; - const vcard = TheCard.exportVCard(card); - expect(vcard).toContain('FN:Alice'); - expect(vcard).toContain('NOTE:My Note'); - expect(vcard).toContain('PHOTO;TYPE=JPEG;ENCODING=b:base64data'); - expect(vcard).toContain('TEL;TYPE=CELL:123456'); - expect(vcard).toContain('EMAIL;TYPE=HOME:alice@example.com'); - expect(vcard).toContain('IMPP;TYPE=HOME:tinode:id/usr123'); - expect(vcard).toContain('URL;TYPE=WORK:https://example.com'); - }); - - test('should export card with N, ORG and TITLE', () => { - const card: CardData = { - fn: 'Alice', - n: { - surname: 'Wonderland', - given: 'Alice', - }, - org: { - fn: 'Organization', - title: 'Boss', - }, - }; - const vcard = TheCard.exportVCard(card); - expect(vcard).toContain('FN:Alice'); - expect(vcard).toContain('N:Wonderland;Alice;;;\r\n'); - expect(vcard).toContain('ORG:Organization\r\n'); - expect(vcard).toContain('TITLE:Boss\r\n'); - }); - - test('should export card with birthday (full date)', () => { - const card: CardData = { - fn: 'Alice', - bday: { - y: 1985, - m: 6, - d: 15, - }, - }; - const vcard = TheCard.exportVCard(card); - expect(vcard).toContain('BDAY:1985-06-15'); - }); - - test('should export card with birthday (no year)', () => { - const card: CardData = { - fn: 'Alice', - bday: { - m: 6, - d: 15, - }, - }; - const vcard = TheCard.exportVCard(card); - expect(vcard).toContain('BDAY:---06-15'); - }); - }); - - describe('importVCard', () => { - test('should return null for invalid input', () => { - expect(TheCard.importVCard(null)).toBeNull(); - expect(TheCard.importVCard(123)).toBeNull(); - }); - - test('should import minimal card', () => { - const vcard = 'BEGIN:VCARD\r\nVERSION:3.0\r\nFN:Alice\r\nEND:VCARD'; - const card = TheCard.importVCard(vcard); - expect(card).toEqual({ - fn: 'Alice', - }); - }); - - test('should import full card', () => { - const vcard = - 'BEGIN:VCARD\r\n' + - 'VERSION:3.0\r\n' + - 'FN:Alice\r\n' + - 'NOTE:My Note\r\n' + - 'PHOTO;TYPE=JPEG;ENCODING=b:base64data\r\n' + - 'TEL;TYPE=CELL:123456\r\n' + - 'EMAIL;TYPE=HOME:alice@example.com\r\n' + - 'IMPP;TYPE=HOME:tinode:id/usr123\r\n' + - 'END:VCARD'; - const card = TheCard.importVCard(vcard); - expect(card?.fn).toBe('Alice'); - expect(card?.note).toBe('My Note'); - expect(card?.photo).toEqual({ - type: 'jpeg', - data: 'base64data', - ref: DEL_CHAR, - }); - expect(card?.comm).toContainEqual({ - proto: 'tel', - des: ['cell'], - value: '123456', - }); - expect(card?.comm).toContainEqual({ - proto: 'email', - des: ['home'], - value: 'alice@example.com', - }); - expect(card?.comm).toContainEqual({ - proto: 'tinode', - des: ['home'], - value: 'tinode:id/usr123', - }); - }); - - test('should import card with ref photo', () => { - const vcard = - 'BEGIN:VCARD\r\n' + - 'FN:Bob\r\n' + - 'PHOTO;VALUE=URI:http://example.com/photo.jpg\r\n' + - 'END:VCARD'; - - const card = TheCard.importVCard(vcard); - expect(card?.fn).toBe('Bob'); - expect(card?.photo).toEqual({ - type: 'jpeg', - data: DEL_CHAR, - ref: 'http://example.com/photo.jpg', - }); - }); - - test('should import card with params in FN', () => { - const vcard = `BEGIN:VCARD -VERSION:3.0 -N:Doe;John;Q.,Public -FN;CHARSET=UTF-8:John Doe -TEL;TYPE=WORK,VOICE:(111) 555-1212 -TEL;TYPE=HOME,VOICE:(404) 555-1212 -TEL;TYPE=HOME,TYPE=VOICE:(404) 555-1212 -EMAIL;TYPE=PREF,INTERNET:forrestgump@example.com -EMAIL;TYPE=INTERNET:example@example.com -ADR;TYPE=HOME:;;42 Plantation St.;Baytown;LA;30314;United States of America -URL:https://www.google.com/ -PHOTO;VALUE=URL;TYPE=PNG:http://upload.wikimedia.org/wikipedia/commons/thumb/a/a5/Example_svg.svg/200px-Example_svg.svg.png -AGENT:BEGIN:VCARD - VERSION:3.0 - N:Doe;John;Q.,Public - FN:John Doe - TEL;TYPE=WORK,VOICE:(111) 555-3333 - TEL;TYPE=HOME,VOICE:(404) 555-4444 - TEL;TYPE=HOME,TYPE=VOICE:(404) 555-5555 - EMAIL;TYPE=PREF,INTERNET:forrest-gump-agent@example.com - EMAIL;TYPE=INTERNET:example-agent@example.com - PHOTO;VALUE=URL;TYPE=PNG:http://upload.wikimedia.org/wikipedia/commons/thumb/a/a5/Example_svg.svg/200px-Example_svg.svg.png - END:VCARD -END:VCARD`; - - const card = TheCard.importVCard(vcard); - expect(card?.fn).toBe('John Doe'); - expect(card?.photo).toBeDefined(); - expect(card?.photo).toMatchObject({ - ref: 'http://upload.wikimedia.org/wikipedia/commons/thumb/a/a5/Example_svg.svg/200px-Example_svg.svg.png', - }); - - const phones = card?.comm?.filter((c) => c.proto === 'tel'); - expect(phones).toHaveLength(2); - - expect(card?.comm).toEqual( - expect.arrayContaining([ - expect.objectContaining({ - proto: 'tel', - value: '(111) 555-1212', - des: expect.arrayContaining(['work', 'voice']), - }), - expect.objectContaining({ - proto: 'tel', - value: '(404) 555-1212', - des: expect.arrayContaining(['home', 'voice']), - }), - expect.objectContaining({ - proto: 'email', - value: 'forrestgump@example.com', - des: expect.arrayContaining(['pref']), - }), - expect.objectContaining({ - proto: 'email', - value: 'example@example.com', - des: [], - }), - expect.objectContaining({ - proto: 'http', - value: 'https://www.google.com/', - des: [], - }), - ]) - ); - expect(card?.n).toEqual({ - surname: 'Doe', - given: 'John', - additional: 'Q.,Public', - }); - }); - - test('should import card with N, ORG and TITLE', () => { - const vcard = `BEGIN:VCARD -VERSION:3.0 -N:Miner;Coal;Diamond;Dr.;Jr. -FN:Dr. Coal D. Miner -ORG:Most Evil Corp;North American Division -TITLE:CEO -END:VCARD`; - - const card = TheCard.importVCard(vcard); - expect(card?.n).toEqual({ - surname: 'Miner', - given: 'Coal', - additional: 'Diamond', - prefix: 'Dr.', - suffix: 'Jr.', - }); - expect(card?.org).toEqual({ - fn: 'Most Evil Corp', - title: 'CEO', - }); - }); - - test('should unescape commas and other special characters in vCard fields', () => { - const vcard = `BEGIN:VCARD -VERSION:3.0 -FN:John\\, Doe -N:Doe;John\\, Jr.;;; -NOTE:John Doe has a long and varied history\\, being documented on more police files that anyone -ORG:Company\\, Inc. -TITLE:CEO\\; Founder -END:VCARD`; - - const card = TheCard.importVCard(vcard); - expect(card?.fn).toBe('John, Doe'); - expect(card?.n?.surname).toBe('Doe'); - expect(card?.n?.given).toBe('John, Jr.'); - expect(card?.note).toBe( - 'John Doe has a long and varied history, being documented on more police files that anyone' - ); - expect(card?.org?.fn).toBe('Company, Inc.'); - expect(card?.org?.title).toBe('CEO; Founder'); - }); - - test('should decode Quoted-Printable encoded fields', () => { - const vcard = `BEGIN:VCARD -VERSION:2.1 -FN;CHARSET=UTF-8;QUOTED-PRINTABLE:=E5=8D=81=E5=9F=8E=E7=9B=AE=E7=AE=A1=E7=90=86=E5=A4=A7=E5=9E=8B=E7=9F=A5=E5= -=BA=A7 -N;CHARSET=UTF-8;QUOTED-PRINTABLE:=E5=8D=81=E5=9F=8E;=E7=9B=AE=E7=AE=A1;;; -ORG;ENCODING=QUOTED-PRINTABLE:=E4=BC=9A=E7=A4=BE -TITLE;QUOTED-PRINTABLE:=E7=A4=BE=E9=95=B7 -NOTE;QUOTED-PRINTABLE:This is a note with=20special characters -END:VCARD`; - - const card = TheCard.importVCard(vcard); - expect(card?.fn).toBe('十城目管理大型知座'); - expect(card?.n?.surname).toBe('十城'); - expect(card?.n?.given).toBe('目管'); - expect(card?.org?.fn).toBe('会社'); - expect(card?.org?.title).toBe('社長'); - expect(card?.note).toBe('This is a note with special characters'); - }); - - test('should parse BDAY in YYYY-MM-DD format', () => { - const vcard = `BEGIN:VCARD -VERSION:3.0 -FN:John Doe -BDAY:1985-06-15 -END:VCARD`; - - const card = TheCard.importVCard(vcard); - expect(card?.bday).toEqual({ - y: 1985, - m: 6, - d: 15, - }); - }); - - test('should parse BDAY in YYYYMMDD format', () => { - const vcard = `BEGIN:VCARD -VERSION:3.0 -FN:John Doe -BDAY:19850615 -END:VCARD`; - - const card = TheCard.importVCard(vcard); - expect(card?.bday).toEqual({ - y: 1985, - m: 6, - d: 15, - }); - }); - - test('should parse BDAY in YYMMDD format with YY >= 35 as 19XX', () => { - const vcard = `BEGIN:VCARD -VERSION:3.0 -FN:John Doe -BDAY:850615 -END:VCARD`; - - const card = TheCard.importVCard(vcard); - expect(card?.bday).toEqual({ - y: 1985, - m: 6, - d: 15, - }); - }); - - test('should parse BDAY in YYMMDD format with YY < 35 as 20XX', () => { - const vcard = `BEGIN:VCARD -VERSION:3.0 -FN:John Doe -BDAY:240315 -END:VCARD`; - - const card = TheCard.importVCard(vcard); - expect(card?.bday).toEqual({ - y: 2024, - m: 3, - d: 15, - }); - }); - - test('should parse BDAY in --MMDD format without year', () => { - const vcard = `BEGIN:VCARD -VERSION:3.0 -FN:John Doe -BDAY:--0615 -END:VCARD`; - - const card = TheCard.importVCard(vcard); - expect(card?.bday).toEqual({ - m: 6, - d: 15, - }); - expect(card?.bday?.y).toBeUndefined(); - }); - - test('should parse BDAY in ----MMDD format without year', () => { - const vcard = `BEGIN:VCARD -VERSION:3.0 -FN:John Doe -BDAY:----0615 -END:VCARD`; - - const card = TheCard.importVCard(vcard); - expect(card?.bday).toEqual({ - m: 6, - d: 15, - }); - expect(card?.bday?.y).toBeUndefined(); - }); - - test('should parse BDAY in --MM-DD format without year', () => { - const vcard = `BEGIN:VCARD -VERSION:3.0 -FN:John Doe -BDAY:--06-15 -END:VCARD`; - - const card = TheCard.importVCard(vcard); - expect(card?.bday).toEqual({ - m: 6, - d: 15, - }); - expect(card?.bday?.y).toBeUndefined(); - }); - - test('should ignore time in BDAY field', () => { - const vcard = `BEGIN:VCARD -VERSION:3.0 -FN:John Doe -BDAY:1985-06-15T12:30:00Z -END:VCARD`; - - const card = TheCard.importVCard(vcard); - expect(card?.bday).toEqual({ - y: 1985, - m: 6, - d: 15, - }); - }); - - test('should discard invalid BDAY with invalid month', () => { - const vcard = `BEGIN:VCARD -VERSION:3.0 -FN:John Doe -BDAY:19851315 -END:VCARD`; - - const card = TheCard.importVCard(vcard); - expect(card?.bday).toBeUndefined(); - }); - - test('should discard invalid BDAY with invalid day', () => { - const vcard = `BEGIN:VCARD -VERSION:3.0 -FN:John Doe -BDAY:19850632 -END:VCARD`; - - const card = TheCard.importVCard(vcard); - expect(card?.bday).toBeUndefined(); - }); - - test('should discard obviously invalid BDAY', () => { - const vcard = `BEGIN:VCARD -VERSION:3.0 -FN:John Doe -BDAY:10007059 -END:VCARD`; - - const card = TheCard.importVCard(vcard); - expect(card?.bday).toBeUndefined(); - }); - }); - - describe('getComm', () => { - test('should return array of matching comm entries', () => { - const card: CardData = { - comm: [ - { - proto: 'tel', - des: ['mobile'], - value: '123', - }, - { - proto: 'email', - des: ['home'], - value: 'a@test.com', - }, - { - proto: 'tel', - des: ['work'], - value: '456', - }, - ], - }; - - const phones = TheCard.getComm(card, 'tel'); - expect(phones).toHaveLength(2); - expect(phones[0]?.value).toBe('123'); - expect(phones[1]?.value).toBe('456'); - - const emails = TheCard.getComm(card, 'email'); - expect(emails).toHaveLength(1); - expect(emails[0]?.value).toBe('a@test.com'); - }); - - test('should return empty array for non-existent proto', () => { - const card: CardData = { - comm: [ - { - proto: 'tel', - des: ['mobile'], - value: '123', - }, - ], - }; - expect(TheCard.getComm(card, 'email')).toEqual([]); - }); - - test('should return empty array for card without comm', () => { - const card: CardData = { - fn: 'Test', - }; - expect(TheCard.getComm(card, 'tel')).toEqual([]); - }); - }); - - describe('importVCard - duplication check', () => { - test('should not create duplicate entries when importing vCard with single phone', () => { - const vcard = - 'BEGIN:VCARD\r\nVERSION:3.0\r\nFN:Test\r\nTEL;TYPE=CELL:123456\r\nEND:VCARD'; - const card = TheCard.importVCard(vcard); - - expect(card?.comm).toHaveLength(1); - expect(TheCard.getComm(card, 'tel')).toHaveLength(1); - }); - - test('should not create duplicate entries when importing vCard with multiple phones', () => { - const vcard = - 'BEGIN:VCARD\r\nVERSION:3.0\r\nFN:Test\r\nTEL;TYPE=CELL:111\r\nTEL;TYPE=HOME:222\r\nEND:VCARD'; - const card = TheCard.importVCard(vcard); - - expect(card?.comm).toHaveLength(2); - expect(TheCard.getComm(card, 'tel')).toHaveLength(2); - }); - - test('should not create duplicates with mixed contact types', () => { - const vcard = - 'BEGIN:VCARD\r\nVERSION:3.0\r\nFN:Test\r\nTEL:111\r\nEMAIL:a@test.com\r\nTEL:222\r\nEND:VCARD'; - const card = TheCard.importVCard(vcard); - - expect(card?.comm).toHaveLength(3); - expect(TheCard.getComm(card, 'tel')).toHaveLength(2); - expect(TheCard.getComm(card, 'email')).toHaveLength(1); - }); - - test('should handle folded lines correctly', () => { - const vcard = - 'BEGIN:VCARD\r\nVERSION:3.0\r\nFN:Test\r\nTEL;TYPE=CELL:\r\n 123456\r\nEND:VCARD'; - const card = TheCard.importVCard(vcard); - - expect(card?.comm).toHaveLength(1); - expect(TheCard.getComm(card, 'tel')).toHaveLength(1); - }); - - test('should deduplicate same phone with multiple TYPE values', () => { - const vcard = - 'BEGIN:VCARD\r\nVERSION:3.0\r\nFN:Test\r\n' + - 'TEL;TYPE=WORK,VOICE:(111) 555-1212\r\n' + - 'TEL;TYPE=HOME,VOICE:(111) 555-1212\r\n' + - 'END:VCARD'; - const card = TheCard.importVCard(vcard); - - expect(card?.comm).toHaveLength(1); - expect(card?.comm?.[0]).toEqual({ - proto: 'tel', - des: expect.arrayContaining(['work', 'voice', 'home']), - value: '(111) 555-1212', - }); - expect(card?.comm?.[0]?.des).toHaveLength(3); - }); - - test('should handle comma-separated TYPE values', () => { - const vcard = - 'BEGIN:VCARD\r\nVERSION:3.0\r\nFN:Test\r\n' + - 'TEL;TYPE=WORK,VOICE,FAX:123-456-7890\r\n' + - 'END:VCARD'; - const card = TheCard.importVCard(vcard); - - expect(card?.comm).toHaveLength(1); - expect(card?.comm?.[0]?.des).toEqual( - expect.arrayContaining(['work', 'voice', 'fax']) - ); - expect(card?.comm?.[0]?.des).toHaveLength(3); - }); - }); - - describe('Export/Import cycle', () => { - test('should not duplicate contacts after export/import cycle', () => { - let card: CardData = {}; - card = TheCard.setFn(card, 'Alice Johnson'); - card = TheCard.addPhone(card, '+15551234567', 'mobile'); - card = TheCard.addPhone(card, '+15559876543', 'work'); - card = TheCard.addEmail(card, 'alice@example.com', 'home'); - card = TheCard.addEmail(card, 'alice.johnson@work.com', 'work'); - card = TheCard.addTinodeID(card, 'tinode:id/usrAlice123', 'home'); - - expect(card?.comm).toHaveLength(5); - expect(TheCard.getComm(card, 'tel')).toHaveLength(2); - expect(TheCard.getComm(card, 'email')).toHaveLength(2); - expect(TheCard.getComm(card, 'tinode')).toHaveLength(1); - - const vcardStr = TheCard.exportVCard(card); - expect(vcardStr).toBeTruthy(); - - const importedCard = TheCard.importVCard(vcardStr); - - expect(importedCard?.comm).toHaveLength(5); - - const phones = TheCard.getComm(importedCard, 'tel'); - const emails = TheCard.getComm(importedCard, 'email'); - const tinodeIds = TheCard.getComm(importedCard, 'tinode'); - - expect(phones).toHaveLength(2); - expect(emails).toHaveLength(2); - expect(tinodeIds).toHaveLength(1); - - expect(phones.map((p) => p.value)).toContain('+15551234567'); - expect(phones.map((p) => p.value)).toContain('+15559876543'); - expect(emails.map((e) => e.value)).toContain('alice@example.com'); - expect(emails.map((e) => e.value)).toContain('alice.johnson@work.com'); - expect(tinodeIds[0]?.value).toBe('tinode:id/usrAlice123'); - }); - - test('should handle multiple export/import cycles without duplication', () => { - let card = TheCard.setFn({}, 'Bob Smith'); - card = TheCard.addPhone(card, '+15551111111', 'mobile'); - card = TheCard.addEmail(card, 'bob@test.com', 'home'); - - let vcardStr = TheCard.exportVCard(card); - let imported1 = TheCard.importVCard(vcardStr); - expect(TheCard.getComm(imported1, 'tel')).toHaveLength(1); - expect(TheCard.getComm(imported1, 'email')).toHaveLength(1); - - vcardStr = TheCard.exportVCard(imported1); - let imported2 = TheCard.importVCard(vcardStr); - expect(TheCard.getComm(imported2, 'tel')).toHaveLength(1); - expect(TheCard.getComm(imported2, 'email')).toHaveLength(1); - - vcardStr = TheCard.exportVCard(imported2); - let imported3 = TheCard.importVCard(vcardStr); - expect(TheCard.getComm(imported3, 'tel')).toHaveLength(1); - expect(TheCard.getComm(imported3, 'email')).toHaveLength(1); - }); - - test('should correctly export and import IMPP/Tinode entries', () => { - let card: CardData = {}; - card = TheCard.addTinodeID(card, 'tinode:id/usrTest123', 'home'); - card = TheCard.addTinodeID(card, 'tinode:id/usrTest456', 'work'); - - const vcardStr = TheCard.exportVCard(card); - - expect(vcardStr).toContain('IMPP'); - expect(vcardStr).toContain('tinode:id/usrTest123'); - expect(vcardStr).toContain('tinode:id/usrTest456'); - - const imported = TheCard.importVCard(vcardStr); - const tinodeIds = TheCard.getComm(imported, 'tinode'); - - expect(tinodeIds).toHaveLength(2); - expect(tinodeIds.map((t) => t.value)).toContain('tinode:id/usrTest123'); - expect(tinodeIds.map((t) => t.value)).toContain('tinode:id/usrTest456'); - }); - - test('should correctly export and import URL entries', () => { - let card: CardData = {}; - card = TheCard.setFn(card, 'Test User'); - card.comm = [ - { - proto: 'http', - des: ['work'], - value: 'https://example.com', - }, - { - proto: 'http', - des: ['personal'], - value: 'https://mysite.org', - }, - ]; - - const vcardStr = TheCard.exportVCard(card); - - expect(vcardStr).toContain('URL'); - expect(vcardStr).toContain('https://example.com'); - expect(vcardStr).toContain('https://mysite.org'); - - const imported = TheCard.importVCard(vcardStr); - const urls = TheCard.getComm(imported, 'http'); - - expect(urls).toHaveLength(2); - expect(urls.map((u) => u.value)).toContain('https://example.com'); - expect(urls.map((u) => u.value)).toContain('https://mysite.org'); - }); - - test('should handle contacts without TYPE parameter', () => { - const vcard = `BEGIN:VCARD -VERSION:3.0 -FN:Test User -TEL:(555) 123-4567 -EMAIL:test@example.com -IMPP:tinode:id/usrNoType -END:VCARD`; - - const card = TheCard.importVCard(vcard); - - expect(card?.fn).toBe('Test User'); - expect(card?.comm).toHaveLength(3); - - const phone = card?.comm?.find((c) => c.proto === 'tel'); - expect(phone).toBeDefined(); - expect(phone?.value).toBe('(555) 123-4567'); - expect(phone?.des).toEqual([]); - - const email = card?.comm?.find((c) => c.proto === 'email'); - expect(email).toBeDefined(); - expect(email?.value).toBe('test@example.com'); - expect(email?.des).toEqual([]); - - const tinode = card?.comm?.find((c) => c.proto === 'tinode'); - expect(tinode).toBeDefined(); - expect(tinode?.value).toBe('tinode:id/usrNoType'); - expect(tinode?.des).toEqual([]); - }); - }); -}); - -describe('TheCard without TextDecoder', () => { - test('should decode multi-byte Quoted-Printable UTF-8', () => { - const original = globalThis.TextDecoder; - Reflect.deleteProperty(globalThis, 'TextDecoder'); - try { - const vcard = - 'BEGIN:VCARD\r\nFN;ENCODING=QUOTED-PRINTABLE:=D8=B9=D9=84=DB=8C =E2=82=AC =F0=9F=98=80 caf=C3=A9\r\nEND:VCARD'; - expect(TheCard.importVCard(vcard)?.fn).toBe( - '\u0639\u0644\u06cc \u20ac \u{1F600} caf\u00e9' - ); - } finally { - globalThis.TextDecoder = original; - } - }); -}); diff --git a/src/core/__tests__/tinode.test.ts b/src/core/__tests__/tinode.test.ts deleted file mode 100644 index 03b3d3e..0000000 --- a/src/core/__tests__/tinode.test.ts +++ /dev/null @@ -1,476 +0,0 @@ -import { afterAll, describe, expect, jest, test } from '@jest/globals'; -import * as Const from '../config'; -import { Tinode } from '../tinode'; - -describe('Tinode static methods', () => { - describe('credential', () => { - test('builds a credential from separate arguments', () => { - const cred = Tinode.credential( - 'email', - 'user@example.com', - { key: 'value' }, - 'response' - ); - expect(cred).toHaveLength(1); - expect(cred?.[0]?.meth).toBe('email'); - expect(cred?.[0]?.val).toBe('user@example.com'); - expect(cred?.[0]?.params).toEqual({ key: 'value' }); - expect(cred?.[0]?.resp).toBe('response'); - }); - - test('builds a credential from an object', () => { - const cred = Tinode.credential({ - meth: 'phone', - val: '+1234567890', - params: { code: '123' }, - resp: 'verified', - }); - expect(cred).toHaveLength(1); - expect(cred?.[0]?.meth).toBe('phone'); - expect(cred?.[0]?.val).toBe('+1234567890'); - }); - - test('needs a value or a response besides the method', () => { - expect(Tinode.credential('email')).toBeNull(); - }); - - test('needs a method', () => { - expect(Tinode.credential(undefined, 'value')).toBeNull(); - }); - - test('accepts a method with a value', () => { - expect(Tinode.credential('email', 'test@example.com')).toHaveLength(1); - }); - - test('accepts a method with only a response', () => { - const cred = Tinode.credential('email', null, null, 'response_value'); - expect(cred).toHaveLength(1); - expect(cred?.[0]?.resp).toBe('response_value'); - }); - }); - - describe('topicType', () => { - test.each([ - ['me', 'me'], - ['fnd', 'fnd'], - ['sys', 'sys'], - ['grptest', 'grp'], - ['usr123', 'p2p'], - ['slf', 'slf'], - ])('%s is %s', (name, type) => { - expect(Tinode.topicType(name)).toBe(type); - }); - - test('unknown prefix gives undefined', () => { - expect(Tinode.topicType('invalid-topic')).toBeUndefined(); - }); - }); - - describe('isMeTopicName', () => { - test('matches me', () => { - expect(Tinode.isMeTopicName('me')).toBe(true); - }); - - test('rejects other topics', () => { - expect(Tinode.isMeTopicName('grptest')).toBe(false); - expect(Tinode.isMeTopicName('usr123')).toBe(false); - expect(Tinode.isMeTopicName('fnd')).toBe(false); - }); - - test('rejects null and undefined', () => { - expect(Tinode.isMeTopicName(null)).toBe(false); - expect(Tinode.isMeTopicName(undefined)).toBe(false); - }); - }); - - describe('isSelfTopicName', () => { - test('matches slf', () => { - expect(Tinode.isSelfTopicName('slf')).toBe(true); - }); - - test('rejects other topics', () => { - expect(Tinode.isSelfTopicName('grptest')).toBe(false); - expect(Tinode.isSelfTopicName('usr123')).toBe(false); - }); - }); - - describe('isGroupTopicName', () => { - test('matches grp names', () => { - expect(Tinode.isGroupTopicName('grptest')).toBe(true); - expect(Tinode.isGroupTopicName('grpabcdef')).toBe(true); - }); - - test('rejects other topics', () => { - expect(Tinode.isGroupTopicName('me')).toBe(false); - expect(Tinode.isGroupTopicName('usr123')).toBe(false); - expect(Tinode.isGroupTopicName('fnd')).toBe(false); - }); - }); - - describe('isP2PTopicName', () => { - test('matches usr names', () => { - expect(Tinode.isP2PTopicName('usr123')).toBe(true); - expect(Tinode.isP2PTopicName('usrABC')).toBe(true); - }); - - test('rejects other topics', () => { - expect(Tinode.isP2PTopicName('me')).toBe(false); - expect(Tinode.isP2PTopicName('grptest')).toBe(false); - expect(Tinode.isP2PTopicName('fnd')).toBe(false); - }); - }); - - describe('isCommTopicName', () => { - test('matches p2p, slf and group topics', () => { - expect(Tinode.isCommTopicName('usr123')).toBe(true); - expect(Tinode.isCommTopicName('grptest')).toBe(true); - expect(Tinode.isCommTopicName('slf')).toBe(true); - }); - - test('rejects me, fnd and sys', () => { - expect(Tinode.isCommTopicName('me')).toBe(false); - expect(Tinode.isCommTopicName('fnd')).toBe(false); - expect(Tinode.isCommTopicName('sys')).toBe(false); - }); - }); - - describe('isNewGroupTopicName', () => { - test('matches new and nch prefixes', () => { - expect(Tinode.isNewGroupTopicName('new123')).toBe(true); - expect(Tinode.isNewGroupTopicName('nch123')).toBe(true); - }); - - test('rejects existing topics', () => { - expect(Tinode.isNewGroupTopicName('grptest')).toBe(false); - expect(Tinode.isNewGroupTopicName('usr123')).toBe(false); - expect(Tinode.isNewGroupTopicName('chn123')).toBe(false); - }); - }); - - describe('isChannelTopicName', () => { - test('matches chn and nch prefixes', () => { - expect(Tinode.isChannelTopicName('chn123')).toBe(true); - expect(Tinode.isChannelTopicName('nch123')).toBe(true); - }); - - test('rejects non-channels', () => { - expect(Tinode.isChannelTopicName('grptest')).toBe(false); - expect(Tinode.isChannelTopicName('usr123')).toBe(false); - }); - }); - - describe('getVersion', () => { - test('returns a non-empty string', () => { - const version = Tinode.getVersion(); - expect(typeof version).toBe('string'); - expect(version.length).toBeGreaterThan(0); - }); - }); - - describe('setNetworkProviders', () => { - afterAll(() => { - Tinode.setNetworkProviders( - globalThis.WebSocket, - globalThis.XMLHttpRequest - ); - }); - - test('accepts the platform WebSocket and XMLHttpRequest', () => { - expect(() => { - Tinode.setNetworkProviders( - globalThis.WebSocket, - globalThis.XMLHttpRequest - ); - }).not.toThrow(); - }); - - test('accepts null providers', () => { - expect(() => { - Tinode.setNetworkProviders(null, null); - }).not.toThrow(); - }); - }); - - describe('getLibrary', () => { - test('returns a non-empty string', () => { - const lib = Tinode.getLibrary(); - expect(typeof lib).toBe('string'); - expect(lib.length).toBeGreaterThan(0); - }); - }); - - describe('isNullValue', () => { - test('is true only for DEL_CHAR', () => { - expect(Tinode.isNullValue(Const.DEL_CHAR)).toBe(true); - expect(Tinode.isNullValue('test')).toBe(false); - expect(Tinode.isNullValue('value')).toBe(false); - expect(Tinode.isNullValue('')).toBe(false); - expect(Tinode.isNullValue(null)).toBe(false); - expect(Tinode.isNullValue(undefined)).toBe(false); - }); - }); - - describe('isServerAssignedSeq', () => { - test('accepts ids below LOCAL_SEQID', () => { - expect(Tinode.isServerAssignedSeq(1)).toBe(true); - expect(Tinode.isServerAssignedSeq(100)).toBe(true); - expect(Tinode.isServerAssignedSeq(Const.LOCAL_SEQID - 1)).toBe(true); - }); - - test('rejects local ids', () => { - expect(Tinode.isServerAssignedSeq(Const.LOCAL_SEQID)).toBe(false); - expect(Tinode.isServerAssignedSeq(Const.LOCAL_SEQID + 1)).toBe(false); - }); - - test('rejects zero and negative ids', () => { - expect(Tinode.isServerAssignedSeq(0)).toBe(false); - expect(Tinode.isServerAssignedSeq(-1)).toBe(false); - }); - }); - - describe('parseTinodeUrl', () => { - test('extracts the id from tinode:///id/ URLs', () => { - expect(Tinode.parseTinodeUrl('tinode:///id/usr123')).toBe('usr123'); - expect(Tinode.parseTinodeUrl('tinode:///id/usrABCDEF')).toBe('usrABCDEF'); - }); - - test('returns other strings unchanged', () => { - expect(Tinode.parseTinodeUrl('user@example.com')).toBe( - 'user@example.com' - ); - expect(Tinode.parseTinodeUrl('tinode:///invalid')).toBe( - 'tinode:///invalid' - ); - }); - - test('returns null for non-strings', () => { - expect(Tinode.parseTinodeUrl(null)).toBeNull(); - expect(Tinode.parseTinodeUrl(undefined)).toBeNull(); - expect(Tinode.parseTinodeUrl(123)).toBeNull(); - expect(Tinode.parseTinodeUrl({})).toBeNull(); - }); - }); - - describe('isValidTagValue', () => { - test('accepts 4 to 23 letters, digits, hyphens and underscores', () => { - expect(Tinode.isValidTagValue('test')).toBe(true); - expect(Tinode.isValidTagValue('tag123')).toBe(true); - expect(Tinode.isValidTagValue('a_tag')).toBe(true); - expect(Tinode.isValidTagValue('tag-name')).toBe(true); - }); - - test('rejects tags under 4 characters', () => { - expect(Tinode.isValidTagValue('tag')).toBe(false); - expect(Tinode.isValidTagValue('ab')).toBe(false); - }); - - test('rejects tags over 24 characters', () => { - expect(Tinode.isValidTagValue('a'.repeat(25))).toBe(false); - }); - - test('rejects a leading underscore or hyphen', () => { - expect(Tinode.isValidTagValue('_tag')).toBe(false); - expect(Tinode.isValidTagValue('-tag')).toBe(false); - }); - - test('rejects empty and non-string values', () => { - expect(Tinode.isValidTagValue('')).toBe(false); - expect(Tinode.isValidTagValue(null)).toBe(false); - expect(Tinode.isValidTagValue(undefined)).toBe(false); - expect(Tinode.isValidTagValue(123)).toBe(false); - expect(Tinode.isValidTagValue({})).toBe(false); - }); - }); - - describe('tagSplit', () => { - test('splits prefix and value at the first colon', () => { - expect(Tinode.tagSplit('email:user@example.com')).toEqual({ - prefix: 'email', - value: 'user@example.com', - }); - expect(Tinode.tagSplit('type:value:extra')).toEqual({ - prefix: 'type', - value: 'value:extra', - }); - }); - - test('trims whitespace', () => { - expect(Tinode.tagSplit(' email:test@example.com ')).toEqual({ - prefix: 'email', - value: 'test@example.com', - }); - }); - - test('returns null for malformed tags', () => { - expect(Tinode.tagSplit('notag')).toBeNull(); - expect(Tinode.tagSplit(':')).toBeNull(); - expect(Tinode.tagSplit(':value')).toBeNull(); - expect(Tinode.tagSplit('')).toBeNull(); - expect(Tinode.tagSplit(' ')).toBeNull(); - expect(Tinode.tagSplit(null)).toBeNull(); - expect(Tinode.tagSplit(undefined)).toBeNull(); - }); - }); - - describe('setUniqueTag', () => { - test('adds the tag to an empty or missing list', () => { - expect(Tinode.setUniqueTag([], 'email:test@example.com')).toContain( - 'email:test@example.com' - ); - expect(Tinode.setUniqueTag(null, 'email:test@example.com')).toContain( - 'email:test@example.com' - ); - }); - - test('replaces a tag with the same prefix', () => { - const tags = ['email:old@example.com', 'phone:123456']; - const result = Tinode.setUniqueTag(tags, 'email:new@example.com'); - expect(result).toContain('email:new@example.com'); - expect(result).toContain('phone:123456'); - expect(result).not.toContain('email:old@example.com'); - expect(result).toHaveLength(2); - }); - - test('keeps tags with other prefixes', () => { - const result = Tinode.setUniqueTag( - ['phone:123456'], - 'email:test@example.com' - ); - expect(result).toEqual(['phone:123456', 'email:test@example.com']); - }); - - test('ignores a tag without a prefix', () => { - const tags = ['phone:123456']; - expect(Tinode.setUniqueTag(tags, 'invalid-tag')).toEqual(tags); - }); - }); - - describe('clearTagPrefix', () => { - test('removes every tag with the prefix', () => { - const tags = [ - 'email:test@example.com', - 'phone:123456', - 'email:another@example.com', - ]; - expect(Tinode.clearTagPrefix(tags, 'email')).toEqual(['phone:123456']); - }); - - test('can remove everything', () => { - const tags = ['email:test@example.com', 'email:another@example.com']; - expect(Tinode.clearTagPrefix(tags, 'email')).toHaveLength(0); - }); - - test('keeps the list when nothing matches', () => { - const tags = ['phone:123456', 'alias:username']; - expect(Tinode.clearTagPrefix(tags, 'email')).toEqual(tags); - }); - - test('returns an empty list for null or empty input', () => { - expect(Tinode.clearTagPrefix(null, 'email')).toEqual([]); - expect(Tinode.clearTagPrefix([], 'email')).toEqual([]); - }); - - test('drops null and empty entries', () => { - const tags = ['email:test@example.com', null, '', 'phone:123456']; - expect(Tinode.clearTagPrefix(tags, 'email')).toEqual(['phone:123456']); - }); - }); - - describe('tagByPrefix', () => { - test('returns the first tag with the prefix', () => { - const tags = [ - 'email:test@example.com', - 'phone:123456', - 'email:another@example.com', - ]; - expect(Tinode.tagByPrefix(tags, 'email')).toBe('email:test@example.com'); - }); - - test('returns undefined when nothing matches', () => { - expect( - Tinode.tagByPrefix(['phone:123456', 'alias:username'], 'email') - ).toBeUndefined(); - expect(Tinode.tagByPrefix(null, 'email')).toBeUndefined(); - expect(Tinode.tagByPrefix([], 'email')).toBeUndefined(); - }); - - test('skips null and empty entries', () => { - expect( - Tinode.tagByPrefix( - [null, '', 'email:test@example.com', 'phone:123456'], - 'email' - ) - ).toBe('email:test@example.com'); - expect( - Tinode.tagByPrefix([null, null, 'email:test@example.com'], 'email') - ).toBe('email:test@example.com'); - }); - }); -}); - -describe('Tinode requests', () => { - function connectedTinode() { - const tinode = new Tinode({ host: 'localhost:6060', apiKey: 'test-key' }); - const sent: string[] = []; - tinode._connection.sendText = (msg) => { - sent.push(msg); - }; - const reply = (pkt: object) => { - tinode._connection.onMessage?.(JSON.stringify(pkt)); - }; - const lastPacket = (): Record> => - JSON.parse(sent[sent.length - 1] ?? 'null'); - return { tinode, reply, lastPacket }; - } - - test('loginBasic sends unicode credentials as base64', async () => { - const { tinode, reply, lastPacket } = connectedTinode(); - const done = tinode.loginBasic('alice', 'пароль'); - const login = lastPacket().login; - expect(login?.secret).toBe( - Buffer.from('alice:пароль', 'utf8').toString('base64') - ); - - reply({ - ctrl: { - id: login?.id, - code: 200, - text: 'ok', - ts: '2026-01-01T00:00:00.000Z', - params: { user: 'usrAlice' }, - }, - }); - await done; - expect(tinode.getCurrentUserID()).toBe('usrAlice'); - expect(tinode.getCurrentLogin()).toBe('alice'); - }); - - test('getMeta resolves with the {meta} reply', async () => { - const { tinode, reply, lastPacket } = connectedTinode(); - const done = tinode.getMeta('grpTest', { what: 'tags' }); - const get = lastPacket().get; - expect(get?.topic).toBe('grpTest'); - - reply({ meta: { id: get?.id, topic: 'grpTest', tags: ['alias:test'] } }); - await expect(done).resolves.toEqual({ - id: get?.id, - topic: 'grpTest', - tags: ['alias:test'], - }); - }); - - test('a failed {ctrl} rejects the request with its code', async () => { - jest.spyOn(console, 'log').mockImplementation(() => {}); - const { tinode, reply, lastPacket } = connectedTinode(); - const done = tinode.leave('grpTest'); - reply({ - ctrl: { - id: lastPacket().leave?.id, - code: 404, - text: 'not found', - ts: '2026-01-01T00:00:00.000Z', - }, - }); - await expect(done).rejects.toMatchObject({ code: 404 }); - }); -}); diff --git a/src/core/__tests__/topic.test.ts b/src/core/__tests__/topic.test.ts deleted file mode 100644 index ab2adf0..0000000 --- a/src/core/__tests__/topic.test.ts +++ /dev/null @@ -1,52 +0,0 @@ -import { beforeEach, describe, expect, jest, test } from '@jest/globals'; -import { Tinode } from '../tinode'; -import type Topic from '../topic'; - -describe('Topic subscription persistence', () => { - let tinode: Tinode; - let topic: Topic; - - beforeEach(() => { - tinode = new Tinode({ host: 'localhost:6060', apiKey: 'test-key' }); - const found = tinode.getTopic('grpTest'); - if (!found) { - throw new Error('Topic was not created'); - } - topic = found; - jest.spyOn(tinode._db, 'updSubscription'); - jest.spyOn(tinode._db, 'remSubscription'); - }); - - test('persists a received subscriber update', () => { - const sub = { - user: 'usrAlice', - updated: new Date('2026-01-01T00:00:00Z'), - read: 7, - }; - - topic._processMetaSubs([sub]); - - expect(tinode._db.updSubscription).toHaveBeenCalledWith( - 'grpTest', - 'usrAlice', - sub - ); - expect(tinode._db.remSubscription).not.toHaveBeenCalled(); - }); - - test('removes a deleted subscriber from persistent cache', () => { - topic._processMetaSubs([ - { - user: 'usrAlice', - updated: new Date('2026-01-01T00:00:00Z'), - deleted: new Date('2026-01-02T00:00:00Z'), - }, - ]); - - expect(tinode._db.remSubscription).toHaveBeenCalledWith( - 'grpTest', - 'usrAlice' - ); - expect(tinode._db.updSubscription).not.toHaveBeenCalled(); - }); -}); diff --git a/src/core/__tests__/utils.test.ts b/src/core/__tests__/utils.test.ts deleted file mode 100644 index 9913d52..0000000 --- a/src/core/__tests__/utils.test.ts +++ /dev/null @@ -1,691 +0,0 @@ -import { expect, test } from '@jest/globals'; -import { - isUrlRelative, - rfc3339DateString, - mergeObj, - simplify, - normalizeArray, - normalizeRanges, - listToRanges, - clipInRange, - clipOutRange, -} from '../utils'; -import { DEL_CHAR } from '../config'; - -test('isUrlRelative', () => { - expect(isUrlRelative('example.html')).toBe(true); - expect(isUrlRelative('https:example.com')).toBe(false); - expect(isUrlRelative('http:/example.com')).toBe(false); - expect(isUrlRelative(' \n https://example.com')).toBe(false); -}); - -test('rfc3339DateString', () => { - expect(rfc3339DateString(new Date(Date.UTC(2020, 1, 2, 3, 4, 5, 6)))).toBe( - '2020-02-02T03:04:05.006Z' - ); - expect(rfc3339DateString(new Date(Date.UTC(2020, 1, 2, 3, 4, 5)))).toBe( - '2020-02-02T03:04:05Z' - ); - expect(rfc3339DateString(new Date(0))).toBe(undefined); - expect(rfc3339DateString(new Date(''))).toBe(undefined); -}); -test('mergeObj', () => { - expect( - mergeObj( - { - a: 1, - b: 2, - }, - { - b: 3, - c: 4, - } - ) - ).toEqual({ - a: 1, - b: 3, - c: 4, - }); - expect( - mergeObj(undefined, { - b: 3, - c: 4, - }) - ).toEqual({ - b: 3, - c: 4, - }); - expect( - mergeObj( - { - a: 1, - b: 2, - }, - undefined - ) - ).toEqual({ - a: 1, - b: 2, - }); - expect( - mergeObj( - { - a: 1, - b: 2, - }, - null - ) - ).toEqual({ - a: 1, - b: 2, - }); - expect( - mergeObj( - { - a: 1, - b: 2, - }, - { - b: DEL_CHAR, - c: 4, - } - ) - ).toEqual({ - a: 1, - c: 4, - }); - expect( - mergeObj( - { - a: 1, - b: 2, - d: { - e: 5, - f: 6, - }, - }, - { - b: 3, - d: { - f: 7, - g: 'hello', - }, - } - ) - ).toEqual({ - a: 1, - b: 3, - d: { - e: 5, - f: 7, - g: 'hello', - }, - }); - expect( - mergeObj( - { - a: 1, - b: 2, - }, - DEL_CHAR - ) - ).toEqual(undefined); - expect( - mergeObj( - { - a: 1, - b: 2, - }, - undefined - ) - ).toEqual({ - a: 1, - b: 2, - }); - expect( - mergeObj( - { - a: 1, - b: 2, - }, - 1 - ) - ).toEqual(1); - const polluted = mergeObj({}, JSON.parse('{"__proto__":{"injected":true}}')); - expect(Reflect.get({}, 'injected')).toBeUndefined(); - expect(Reflect.get(polluted, 'injected')).toBeUndefined(); - const withCtor = mergeObj( - {}, - JSON.parse('{"constructor":{"prototype":{"injected2":true}}}') - ); - expect(Reflect.get({}, 'injected2')).toBeUndefined(); - expect(typeof Reflect.get(withCtor, 'constructor')).toBe('function'); -}); -test('simplify', () => { - const obj = { - a: 1, - b: 0, - c: '', - d: null, - e: undefined, - f: false, - g: true, - h: {}, - i: { - j: 1, - }, - k: [], - l: [1], - m: new Date(0), - n: new Date(), - o: new Date(''), - p: new Date('2020-02-02T03:04:05.006Z'), - _q: 1, - _r: 0, - _s: '', - _t: null, - _u: undefined, - _v: false, - _w: true, - _x: {}, - _y: { - j: 1, - }, - _z: [], - _1: [1], - _2: new Date(0), - _3: new Date(), - _4: new Date(''), - _5: new Date('2020-02-02T03:04:05.006Z'), - }; - expect(simplify(obj)).toEqual({ - a: 1, - g: true, - i: { - j: 1, - }, - l: [1], - n: obj.n, - p: obj.p, - }); -}); -test('normalizeArray', () => { - expect(normalizeArray(null)).toEqual([DEL_CHAR]); - expect(normalizeArray([])).toEqual([DEL_CHAR]); - expect(normalizeArray([''])).toEqual([DEL_CHAR]); - expect(normalizeArray(['', ''])).toEqual([DEL_CHAR]); - expect(normalizeArray(['', ' ', ''])).toEqual([DEL_CHAR]); - expect(normalizeArray(['a', 'aa'])).toEqual(['aa']); - expect(normalizeArray(['aA'])).toEqual(['aa']); - expect(normalizeArray(['aa', 'bb'])).toEqual(['aa', 'bb']); - expect(normalizeArray(['aa', 'bb', 'aa'])).toEqual(['aa', 'bb']); - expect(normalizeArray(['aa', 'bb', 'aa', 'bb'])).toEqual(['aa', 'bb']); - expect(normalizeArray(['aa ', 'bb', 'Aa', 'bb', 'Cc'])).toEqual([ - 'aa', - 'bb', - 'cc', - ]); -}); - -test('normalizeRanges', () => { - expect(normalizeRanges('hello', 100)).toEqual([]); - expect(normalizeRanges(null, 100)).toEqual([]); - expect( - normalizeRanges( - { - a: 1, - }, - 100 - ) - ).toEqual([]); - expect( - normalizeRanges( - [ - { - a: 1, - }, - { - b: 2, - }, - ], - 100 - ) - ).toEqual([]); - expect(normalizeRanges([], 100)).toEqual([]); - expect(normalizeRanges([{}], 100)).toEqual([]); - expect( - normalizeRanges( - [ - { - low: 1, - }, - ], - 100 - ) - ).toEqual([ - { - low: 1, - }, - ]); - expect( - normalizeRanges( - [ - { - low: 1, - hi: 2, - }, - ], - 100 - ) - ).toEqual([ - { - low: 1, - hi: 2, - }, - ]); - expect( - normalizeRanges( - [ - { - low: 1, - hi: 101, - }, - ], - 90 - ) - ).toEqual([ - { - low: 1, - hi: 101, - }, - ]); - expect( - normalizeRanges( - [ - { - low: 1, - hi: 101, - }, - { - low: 2, - hi: 102, - }, - ], - 100 - ) - ).toEqual([ - { - low: 1, - hi: 102, - }, - ]); - expect( - normalizeRanges( - [ - { - low: 2, - hi: 102, - }, - { - low: 1, - hi: 101, - }, - ], - 100 - ) - ).toEqual([ - { - low: 1, - hi: 102, - }, - ]); - expect( - normalizeRanges( - [ - { - low: 1, - hi: 101, - }, - { - low: 2, - hi: 102, - }, - { - low: 102, - hi: 110, - }, - ], - 100 - ) - ).toEqual([ - { - low: 1, - hi: 110, - }, - ]); - expect( - normalizeRanges( - [ - { - low: 102, - hi: 110, - }, - { - low: 2, - hi: 102, - }, - { - low: 1, - hi: 101, - }, - ], - 100 - ) - ).toEqual([ - { - low: 1, - hi: 110, - }, - ]); - expect( - normalizeRanges( - [ - { - low: 1, - hi: 101, - }, - { - low: 22, - hi: 120, - }, - { - low: 122, - hi: 125, - }, - ], - 100 - ) - ).toEqual([ - { - low: 1, - hi: 120, - }, - { - low: 122, - hi: 125, - }, - ]); -}); -test('listToRanges', () => { - expect(listToRanges([])).toEqual([]); - expect(listToRanges([1])).toEqual([ - { - low: 1, - }, - ]); - expect(listToRanges([1, 2])).toEqual([ - { - low: 1, - hi: 3, - }, - ]); - expect(listToRanges([1, 2, 3])).toEqual([ - { - low: 1, - hi: 4, - }, - ]); - expect(listToRanges([1, 2, 3, 5])).toEqual([ - { - low: 1, - hi: 4, - }, - { - low: 5, - }, - ]); - expect(listToRanges([5, 3, 2, 1])).toEqual([ - { - low: 1, - hi: 4, - }, - { - low: 5, - }, - ]); - expect(listToRanges([1, 2, 3, 5, 6, 7])).toEqual([ - { - low: 1, - hi: 4, - }, - { - low: 5, - hi: 8, - }, - ]); -}); -test('clipOutRange', () => { - expect( - clipOutRange( - { - low: 10, - hi: 20, - }, - { - low: 10, - hi: 20, - } - ) - ).toEqual([]); - expect( - clipOutRange( - { - low: 10, - hi: 20, - }, - { - low: 5, - hi: 30, - } - ) - ).toEqual([]); - expect( - clipOutRange( - { - low: 10, - hi: 20, - }, - { - low: 30, - hi: 40, - } - ) - ).toEqual([ - { - low: 10, - hi: 20, - }, - ]); - expect( - clipOutRange( - { - low: 10, - hi: 20, - }, - { - low: 1, - hi: 5, - } - ) - ).toEqual([ - { - low: 10, - hi: 20, - }, - ]); - expect( - clipOutRange( - { - low: 10, - hi: 20, - }, - { - low: 1, - hi: 15, - } - ) - ).toEqual([ - { - low: 15, - hi: 20, - }, - ]); - expect( - clipOutRange( - { - low: 10, - hi: 20, - }, - { - low: 15, - hi: 30, - } - ) - ).toEqual([ - { - low: 10, - hi: 15, - }, - ]); - expect( - clipOutRange( - { - low: 10, - hi: 20, - }, - { - low: 12, - hi: 17, - } - ) - ).toEqual([ - { - low: 10, - hi: 12, - }, - { - low: 17, - hi: 20, - }, - ]); -}); -test('clipInRange', () => { - expect( - clipInRange( - { - low: 10, - hi: 20, - }, - { - low: 21, - hi: 30, - } - ) - ).toBeNull(); - expect( - clipInRange( - { - low: 10, - hi: 20, - }, - { - low: 10, - hi: 20, - } - ) - ).toEqual({ - low: 10, - hi: 20, - }); - expect( - clipInRange( - { - low: 10, - hi: 20, - }, - { - low: 5, - hi: 30, - } - ) - ).toEqual({ - low: 10, - hi: 20, - }); - expect( - clipInRange( - { - low: 10, - hi: 20, - }, - { - low: 1, - hi: 15, - } - ) - ).toEqual({ - low: 10, - hi: 15, - }); - expect( - clipInRange( - { - low: 10, - hi: 20, - }, - { - low: 1, - hi: 5, - } - ) - ).toBeNull(); - expect( - clipInRange( - { - low: 10, - hi: 20, - }, - { - low: 1, - hi: 10, - } - ) - ).toBeNull(); - expect( - clipInRange( - { - low: 10, - hi: 20, - }, - { - low: 20, - hi: 30, - } - ) - ).toBeNull(); - expect( - clipInRange( - { - low: 10, - hi: 20, - }, - { - low: 15, - hi: 30, - } - ) - ).toEqual({ - low: 15, - hi: 20, - }); -}); diff --git a/src/core/access-mode.ts b/src/core/access-mode.ts deleted file mode 100644 index c440fc9..0000000 --- a/src/core/access-mode.ts +++ /dev/null @@ -1,288 +0,0 @@ -export type AccessSide = 'given' | 'want' | 'mode'; - -export type AccessValue = number | string | null | undefined; - -export interface AccessModeInput { - given?: AccessValue; - want?: AccessValue; - mode?: AccessValue; -} - -export interface AccessModeJson { - mode: string | null; - given: string | null; - want: string | null; -} - -const FLAG_LETTERS = ['J', 'R', 'W', 'P', 'A', 'S', 'D', 'O'] as const; - -function isAccessSide(side: string): side is AccessSide { - return side === 'given' || side === 'want' || side === 'mode'; -} - -export default class AccessMode { - static readonly _NONE = 0x00; - static readonly _JOIN = 0x01; - static readonly _READ = 0x02; - static readonly _WRITE = 0x04; - static readonly _PRES = 0x08; - static readonly _APPROVE = 0x10; - static readonly _SHARE = 0x20; - static readonly _DELETE = 0x40; - static readonly _OWNER = 0x80; - static readonly _BITMASK = - AccessMode._JOIN | - AccessMode._READ | - AccessMode._WRITE | - AccessMode._PRES | - AccessMode._APPROVE | - AccessMode._SHARE | - AccessMode._DELETE | - AccessMode._OWNER; - static readonly _INVALID = 0x100000; - - given?: number | null; - want?: number | null; - mode?: number | null; - - constructor(acs?: AccessModeInput | null) { - if (acs) { - this.given = - typeof acs.given === 'number' - ? acs.given - : AccessMode.decode(acs.given); - this.want = - typeof acs.want === 'number' ? acs.want : AccessMode.decode(acs.want); - this.mode = acs.mode - ? typeof acs.mode === 'number' - ? acs.mode - : AccessMode.decode(acs.mode) - : (this.given ?? 0) & (this.want ?? 0); - } - } - - static #checkFlag( - val: AccessMode, - side: string | undefined, - flag: number - ): boolean { - const component = side || 'mode'; - if (isAccessSide(component)) { - return ((val[component] ?? 0) & flag) !== 0; - } - throw new Error(`Invalid AccessMode component '${component}'`); - } - - static decode(str: AccessValue): number | null { - if (!str) { - return null; - } else if (typeof str === 'number') { - return str & AccessMode._BITMASK; - } else if (str === 'N' || str === 'n') { - return AccessMode._NONE; - } - - const bitmask: Record = { - J: AccessMode._JOIN, - R: AccessMode._READ, - W: AccessMode._WRITE, - P: AccessMode._PRES, - A: AccessMode._APPROVE, - S: AccessMode._SHARE, - D: AccessMode._DELETE, - O: AccessMode._OWNER, - }; - - let m0 = AccessMode._NONE; - - for (let i = 0; i < str.length; i++) { - const bit = bitmask[str.charAt(i).toUpperCase()]; - if (!bit) { - continue; - } - m0 |= bit; - } - return m0; - } - - static encode(val: number | null | undefined): string | null { - if (val === null || val === AccessMode._INVALID) { - return null; - } else if (val === AccessMode._NONE) { - return 'N'; - } - - let res = ''; - for (let i = 0; i < FLAG_LETTERS.length; i++) { - if (((val ?? 0) & (1 << i)) !== 0) { - res = res + FLAG_LETTERS[i]; - } - } - return res; - } - - static update( - val: number | null | undefined, - upd: AccessValue - ): number | null | undefined { - if (!upd || typeof upd !== 'string') { - return val; - } - - let action = upd.charAt(0); - if (action === '+' || action === '-') { - let val0 = val; - const parts = upd.split(/([-+])/); - for (let i = 1; i < parts.length - 1; i += 2) { - action = parts[i] ?? ''; - const m0 = AccessMode.decode(parts[i + 1]); - if (m0 === AccessMode._INVALID) { - return val; - } - if (m0 === null) { - continue; - } - if (action === '+') { - val0 = (val0 ?? 0) | m0; - } else if (action === '-') { - val0 = (val0 ?? 0) & ~m0; - } - } - return val0; - } - - const val0 = AccessMode.decode(upd); - return val0 !== AccessMode._INVALID ? val0 : val; - } - - static diff(a1: AccessValue, a2: AccessValue): number { - const m1 = AccessMode.decode(a1); - const m2 = AccessMode.decode(a2); - - if (m1 === AccessMode._INVALID || m2 === AccessMode._INVALID) { - return AccessMode._INVALID; - } - return (m1 ?? 0) & ~(m2 ?? 0); - } - - toString(): string { - return ( - '{"mode": "' + - AccessMode.encode(this.mode) + - '", "given": "' + - AccessMode.encode(this.given) + - '", "want": "' + - AccessMode.encode(this.want) + - '"}' - ); - } - - jsonHelper(): AccessModeJson { - return { - mode: AccessMode.encode(this.mode), - given: AccessMode.encode(this.given), - want: AccessMode.encode(this.want), - }; - } - - setMode(m: AccessValue): this { - this.mode = AccessMode.decode(m); - return this; - } - - updateMode(u: AccessValue): this { - this.mode = AccessMode.update(this.mode, u); - return this; - } - - getMode(): string | null { - return AccessMode.encode(this.mode); - } - - setGiven(g: AccessValue): this { - this.given = AccessMode.decode(g); - return this; - } - - updateGiven(u: AccessValue): this { - this.given = AccessMode.update(this.given, u); - return this; - } - - getGiven(): string | null { - return AccessMode.encode(this.given); - } - - setWant(w: AccessValue): this { - this.want = AccessMode.decode(w); - return this; - } - - updateWant(u: AccessValue): this { - this.want = AccessMode.update(this.want, u); - return this; - } - - getWant(): string | null { - return AccessMode.encode(this.want); - } - - getMissing(): string | null { - return AccessMode.encode((this.want ?? 0) & ~(this.given ?? 0)); - } - - getExcessive(): string | null { - return AccessMode.encode((this.given ?? 0) & ~(this.want ?? 0)); - } - - updateAll(val?: AccessModeInput | null): this { - if (val) { - this.updateGiven(val.given); - this.updateWant(val.want); - this.mode = (this.given ?? 0) & (this.want ?? 0); - } - return this; - } - - isOwner(side?: string): boolean { - return AccessMode.#checkFlag(this, side, AccessMode._OWNER); - } - - isPresencer(side?: string): boolean { - return AccessMode.#checkFlag(this, side, AccessMode._PRES); - } - - isMuted(side?: string): boolean { - return !this.isPresencer(side); - } - - isJoiner(side?: string): boolean { - return AccessMode.#checkFlag(this, side, AccessMode._JOIN); - } - - isReader(side?: string): boolean { - return AccessMode.#checkFlag(this, side, AccessMode._READ); - } - - isWriter(side?: string): boolean { - return AccessMode.#checkFlag(this, side, AccessMode._WRITE); - } - - isApprover(side?: string): boolean { - return AccessMode.#checkFlag(this, side, AccessMode._APPROVE); - } - - isAdmin(side?: string): boolean { - return this.isOwner(side) || this.isApprover(side); - } - - isSharer(side?: string): boolean { - return ( - this.isAdmin(side) || AccessMode.#checkFlag(this, side, AccessMode._SHARE) - ); - } - - isDeleter(side?: string): boolean { - return AccessMode.#checkFlag(this, side, AccessMode._DELETE); - } -} diff --git a/src/core/cbuffer.ts b/src/core/cbuffer.ts deleted file mode 100644 index 40b07cf..0000000 --- a/src/core/cbuffer.ts +++ /dev/null @@ -1,154 +0,0 @@ -export type Comparator = (a: T, b: T) => number; - -export type ForEachCallback = ( - elem: T, - prev: T | undefined, - next: T | undefined, - index: number -) => void; - -export type FilterCallback = (elem: T, index: number) => boolean; - -interface NearestResult { - idx: number; - exact?: boolean; -} - -function defaultComparator(a: T, b: T): number { - return a === b ? 0 : a < b ? -1 : 1; -} - -export default class CBuffer { - #comparator: Comparator; - #unique: boolean; - buffer: T[] = []; - - constructor(compare?: Comparator | null, unique?: boolean) { - this.#comparator = compare || defaultComparator; - this.#unique = !!unique; - } - - #findNearest(elem: T, arr: T[], exact: boolean): NearestResult { - let start = 0; - let end = arr.length - 1; - let pivot = 0; - let diff = 0; - let found = false; - - while (start <= end) { - pivot = ((start + end) / 2) | 0; - diff = this.#comparator(arr[pivot] as T, elem); - if (diff < 0) { - start = pivot + 1; - } else if (diff > 0) { - end = pivot - 1; - } else { - found = true; - break; - } - } - if (found) { - return { idx: pivot, exact: true }; - } - if (exact) { - return { idx: -1 }; - } - return { idx: diff < 0 ? pivot + 1 : pivot }; - } - - #insertSorted(elem: T, arr: T[]): T[] { - const found = this.#findNearest(elem, arr, false); - const count = found.exact && this.#unique ? 1 : 0; - arr.splice(found.idx, count, elem); - return arr; - } - - getAt(at: number): T | undefined { - return this.buffer[at]; - } - - getLast(filter?: FilterCallback | null): T | undefined { - if (!filter) { - return this.buffer[this.buffer.length - 1]; - } - for (let i = this.buffer.length - 1; i >= 0; i--) { - if (filter(this.buffer[i] as T, i)) { - return this.buffer[i]; - } - } - return undefined; - } - - put(items: T[]): void; - put(...items: T[]): void; - put(...args: T[] | [T[]]): void { - const first = args[0]; - const insert: T[] = - args.length === 1 && Array.isArray(first) ? first : (args as T[]); - for (const item of insert) { - this.#insertSorted(item, this.buffer); - } - } - - delAt(at: number): T | undefined { - const removed = this.buffer.splice(at | 0, 1); - return removed[0]; - } - - delRange(since: number, before: number): T[] { - return this.buffer.splice(since, before - since); - } - - length(): number { - return this.buffer.length; - } - - reset(): void { - this.buffer = []; - } - - forEach( - callback: ForEachCallback, - startIdx?: number, - beforeIdx?: number, - context?: unknown - ): void { - const start = Math.max(0, (startIdx ?? 0) | 0); - const before = Math.min( - beforeIdx || this.buffer.length, - this.buffer.length - ); - - for (let i = start; i < before; i++) { - callback.call( - context, - this.buffer[i] as T, - i > start ? this.buffer[i - 1] : undefined, - i < before - 1 ? this.buffer[i + 1] : undefined, - i - ); - } - } - - find(elem: T, nearest?: boolean): number { - const { idx } = this.#findNearest(elem, this.buffer, !nearest); - return idx; - } - - filter(callback: FilterCallback, context?: unknown): void { - let count = 0; - for (let i = 0; i < this.buffer.length; i++) { - const elem = this.buffer[i] as T; - if (callback.call(context, elem, i)) { - this.buffer[count] = elem; - count++; - } - } - - this.buffer.splice(count); - } - - isEmpty(): boolean { - return this.buffer.length === 0; - } -} diff --git a/src/core/comm-error.ts b/src/core/comm-error.ts deleted file mode 100644 index a7bc321..0000000 --- a/src/core/comm-error.ts +++ /dev/null @@ -1,9 +0,0 @@ -export default class CommError extends Error { - code: number; - - constructor(message: string, code: number) { - super(`${message} (${code})`); - this.name = 'CommError'; - this.code = code; - } -} diff --git a/src/core/config.ts b/src/core/config.ts deleted file mode 100644 index 28bca59..0000000 --- a/src/core/config.ts +++ /dev/null @@ -1,46 +0,0 @@ -export const PACKAGE_VERSION = '0.1.1'; -export const PROTOCOL_VERSION = '0'; -export const VERSION = '0.25.4'; -export const LIBRARY = 'react-native-tinode/' + PACKAGE_VERSION; - -export const TOPIC_NEW = 'new'; -export const TOPIC_NEW_CHAN = 'nch'; -export const TOPIC_ME = 'me'; -export const TOPIC_FND = 'fnd'; -export const TOPIC_SYS = 'sys'; -export const TOPIC_SLF = 'slf'; -export const TOPIC_CHAN = 'chn'; -export const TOPIC_GRP = 'grp'; -export const TOPIC_P2P = 'p2p'; -export const USER_NEW = 'new'; - -export const LOCAL_SEQID = 0xfffffff; - -export const MESSAGE_STATUS_NONE = 0; -export const MESSAGE_STATUS_QUEUED = 10; -export const MESSAGE_STATUS_SENDING = 20; -export const MESSAGE_STATUS_FAILED = 30; -export const MESSAGE_STATUS_FATAL = 40; -export const MESSAGE_STATUS_SENT = 50; -export const MESSAGE_STATUS_RECEIVED = 60; -export const MESSAGE_STATUS_READ = 70; -export const MESSAGE_STATUS_TO_ME = 80; - -export const EXPIRE_PROMISES_TIMEOUT = 5_000; -export const EXPIRE_PROMISES_PERIOD = 1_000; - -export const RECV_TIMEOUT = 100; - -export const DEFAULT_MESSAGES_PAGE = 24; - -export const DEL_CHAR = '␡'; - -export const MAX_PINNED_COUNT = 5; - -export const TAG_ALIAS = 'alias:'; -export const TAG_EMAIL = 'email:'; -export const TAG_PHONE = 'tel:'; - -export const BACKOFF_BASE = 2_000; -export const BACKOFF_MAX_ITER = 10; -export const BACKOFF_JITTER = 0.3; diff --git a/src/core/connection.ts b/src/core/connection.ts deleted file mode 100644 index 921613d..0000000 --- a/src/core/connection.ts +++ /dev/null @@ -1,528 +0,0 @@ -import CommError from './comm-error'; -import { BACKOFF_BASE, BACKOFF_MAX_ITER, BACKOFF_JITTER } from './config'; -import { jsonParseHelper } from './utils'; - -type Handler = { bivarianceHack(evt: E): void }['bivarianceHack']; - -export type WebSocketEventName = 'open' | 'close' | 'error' | 'message'; - -export interface WebSocketEventLike { - data?: unknown; -} - -export interface WebSocketLike { - readyState: number; - addEventListener( - type: WebSocketEventName, - listener: (evt: WebSocketEventLike) => void - ): void; - send(data: string): void; - close(): void; -} - -export interface LongPollRequestLike { - readyState: number; - status: number; - responseText: string; - onreadystatechange: Handler | null; - open(method: string, url: string, async: boolean): void; - send(body?: string | null): void; - abort(): void; -} - -export type WebSocketProviderType = new (url: string) => WebSocketLike; -export type XHRProviderType = new () => LongPollRequestLike; - -export type ConnectionTransport = 'ws' | 'lp'; - -export type ConnectionLogger = (...args: unknown[]) => void; - -export interface ConnectionConfig { - host: string; - apiKey: string; - transport: string; - secure?: boolean; -} - -export type AutoreconnectIterationCallback = ( - timeout: number, - promise?: Promise -) => void; - -let WebSocketProvider: WebSocketProviderType | undefined; -let XHRProvider: XHRProviderType | undefined; - -const NETWORK_ERROR = 503; -const NETWORK_ERROR_TEXT = 'Connection failed'; - -const NETWORK_USER = 418; -const NETWORK_USER_TEXT = 'Disconnected by client'; - -const XDR_OPENED = 1; -const XDR_DONE = 4; -const WS_OPEN = 1; -const HTTP_CREATED = 201; -const HTTP_BAD_REQUEST = 400; - -const UNKNOWN_TRANSPORT_MESSAGE = - "Unknown or invalid network transport. Running under Node? Call 'Tinode.setNetworkProviders()'."; - -function resolveWebSocketProvider(): WebSocketProviderType | undefined { - return WebSocketProvider ?? globalThis.WebSocket; -} - -function resolveXHRProvider(): XHRProviderType | undefined { - return XHRProvider ?? globalThis.XMLHttpRequest; -} - -function makeBaseUrl( - host: string, - protocol: string, - version: string, - apiKey: string -): string | null { - if (!['http', 'https', 'ws', 'wss'].includes(protocol)) { - return null; - } - let url = `${protocol}://${host}`; - if (url.charAt(url.length - 1) !== '/') { - url += '/'; - } - url += 'v' + version + '/channels'; - if (['http', 'https'].includes(protocol)) { - url += '/lp'; - } - url += '?apikey=' + apiKey; - return url; -} - -function extractSid(packet: unknown): string { - if (typeof packet === 'object' && packet !== null && 'ctrl' in packet) { - const ctrl = packet.ctrl; - if (typeof ctrl === 'object' && ctrl !== null && 'params' in ctrl) { - const params = ctrl.params; - if (typeof params === 'object' && params !== null && 'sid' in params) { - return String(params.sid); - } - } - } - throw new Error('Long poller received a malformed handshake'); -} - -export default class Connection { - static readonly NETWORK_ERROR = NETWORK_ERROR; - static readonly NETWORK_ERROR_TEXT = NETWORK_ERROR_TEXT; - static readonly NETWORK_USER = NETWORK_USER; - static readonly NETWORK_USER_TEXT = NETWORK_USER_TEXT; - - static #log: ConnectionLogger = () => {}; - - #boffTimer: ReturnType | null = null; - #boffIteration = 0; - #boffClosed = false; - - #socket: WebSocketLike | null = null; - - host: string; - secure: boolean | undefined; - apiKey: string; - - version: string; - autoreconnect: boolean; - - initialized: ConnectionTransport | undefined; - - onMessage: ((message: string) => void) | undefined = undefined; - onDisconnect: ((err: CommError, code: number) => void) | undefined = - undefined; - onOpen: (() => void) | undefined = undefined; - onAutoreconnectIteration: AutoreconnectIterationCallback | undefined = - undefined; - - connect: (host_?: string | null, force?: boolean) => Promise = () => - Promise.reject(null); - reconnect: (force?: boolean) => void = () => {}; - disconnect: () => void = () => {}; - sendText: (msg: string) => void = () => {}; - isConnected: () => boolean = () => false; - - constructor( - config: ConnectionConfig, - version_: string, - autoreconnect_: boolean - ) { - this.host = config.host; - this.secure = config.secure; - this.apiKey = config.apiKey; - - this.version = version_; - this.autoreconnect = autoreconnect_; - - if (config.transport === 'lp' && resolveXHRProvider()) { - this.#init_lp(); - this.initialized = 'lp'; - } else if (config.transport === 'ws' && resolveWebSocketProvider()) { - this.#init_ws(); - this.initialized = 'ws'; - } - - if (!this.initialized) { - Connection.#log(UNKNOWN_TRANSPORT_MESSAGE); - throw new Error(UNKNOWN_TRANSPORT_MESSAGE); - } - } - - static setNetworkProviders( - wsProvider?: WebSocketProviderType, - xhrProvider?: XHRProviderType - ): void { - WebSocketProvider = wsProvider; - XHRProvider = xhrProvider; - } - - static set logger(l: ConnectionLogger) { - Connection.#log = l; - } - - transport(): ConnectionTransport | undefined { - return this.initialized; - } - - probe(): void { - this.sendText('1'); - } - - backoffReset(): void { - this.#boffReset(); - } - - #boffReconnect(): void { - if (this.#boffTimer !== null) { - clearTimeout(this.#boffTimer); - } - const timeout = - BACKOFF_BASE * - (Math.pow(2, this.#boffIteration) * - (1.0 + BACKOFF_JITTER * Math.random())); - this.#boffIteration = - this.#boffIteration >= BACKOFF_MAX_ITER - ? this.#boffIteration - : this.#boffIteration + 1; - if (this.onAutoreconnectIteration) { - this.onAutoreconnectIteration(timeout); - } - - this.#boffTimer = setTimeout(() => { - Connection.#log( - `Reconnecting, iter=${this.#boffIteration}, timeout=${timeout}` - ); - if (!this.#boffClosed) { - const prom = this.connect(); - if (this.onAutoreconnectIteration) { - this.onAutoreconnectIteration(0, prom); - } else { - prom.catch(() => {}); - } - } else if (this.onAutoreconnectIteration) { - this.onAutoreconnectIteration(-1); - } - }, timeout); - } - - #boffStop(): void { - if (this.#boffTimer !== null) { - clearTimeout(this.#boffTimer); - } - this.#boffTimer = null; - } - - #boffReset(): void { - this.#boffIteration = 0; - } - - #init_lp(): void { - const Provider = resolveXHRProvider(); - if (!Provider) { - throw new Error(UNKNOWN_TRANSPORT_MESSAGE); - } - - let _lpURL: string | null = null; - let _poller: LongPollRequestLike | null = null; - let _sender: LongPollRequestLike | null = null; - - const lp_sender = (url_: string): LongPollRequestLike => { - const sender = new Provider(); - sender.onreadystatechange = () => { - if (sender.readyState === XDR_DONE && sender.status >= 400) { - throw new CommError('LP sender failed', sender.status); - } - }; - - sender.open('POST', url_, true); - return sender; - }; - - const lp_poller = ( - url_: string, - resolve?: () => void, - reject?: (reason: unknown) => void - ): LongPollRequestLike => { - const poller = new Provider(); - let promiseCompleted = false; - - const startNext = () => { - if (_lpURL === null) { - return; - } - const next = lp_poller(_lpURL); - _poller = next; - next.send(null); - }; - - poller.onreadystatechange = () => { - if (poller.readyState !== XDR_DONE) { - return; - } - if (poller.status === HTTP_CREATED) { - const pkt: unknown = JSON.parse(poller.responseText, jsonParseHelper); - _lpURL = url_ + '&sid=' + extractSid(pkt); - startNext(); - if (this.onOpen) { - this.onOpen(); - } - - if (resolve) { - promiseCompleted = true; - resolve(); - } - - if (this.autoreconnect) { - this.#boffStop(); - } - } else if (poller.status > 0 && poller.status < HTTP_BAD_REQUEST) { - if (this.onMessage) { - this.onMessage(poller.responseText); - } - startNext(); - } else { - if (reject && !promiseCompleted) { - promiseCompleted = true; - reject(poller.responseText); - } - if (this.onMessage && poller.responseText) { - this.onMessage(poller.responseText); - } - if (this.onDisconnect) { - const code = - poller.status || - (this.#boffClosed ? NETWORK_USER : NETWORK_ERROR); - const text = - poller.responseText || - (this.#boffClosed ? NETWORK_USER_TEXT : NETWORK_ERROR_TEXT); - this.onDisconnect(new CommError(text, code), code); - } - - _poller = null; - if (!this.#boffClosed && this.autoreconnect) { - this.#boffReconnect(); - } - } - }; - poller.open('POST', url_, true); - return poller; - }; - - const abortRequest = (request: LongPollRequestLike | null): void => { - if (request) { - request.onreadystatechange = null; - request.abort(); - } - }; - - this.connect = (host_, force) => { - this.#boffClosed = false; - - if (_poller) { - if (!force) { - return Promise.resolve(); - } - abortRequest(_poller); - _poller = null; - } - - if (host_) { - this.host = host_; - } - - return new Promise((resolve, reject) => { - const url = makeBaseUrl( - this.host, - this.secure ? 'https' : 'http', - this.version, - this.apiKey - ); - if (url === null) { - reject(new Error('Invalid long polling URL')); - return; - } - Connection.#log('LP connecting to:', url); - const first = lp_poller(url, resolve, reject); - _poller = first; - first.send(null); - }).catch((err: unknown) => { - Connection.#log('LP connection failed:', err); - }); - }; - - this.reconnect = (force) => { - this.#boffStop(); - this.connect(null, force); - }; - - this.disconnect = () => { - this.#boffClosed = true; - this.#boffStop(); - - abortRequest(_sender); - _sender = null; - abortRequest(_poller); - _poller = null; - - if (this.onDisconnect) { - this.onDisconnect( - new CommError(NETWORK_USER_TEXT, NETWORK_USER), - NETWORK_USER - ); - } - _lpURL = null; - }; - - this.sendText = (msg) => { - if (_lpURL === null) { - throw new Error('Long poller failed to connect'); - } - const sender = lp_sender(_lpURL); - _sender = sender; - if (sender.readyState === XDR_OPENED) { - sender.send(msg); - } else { - throw new Error('Long poller failed to connect'); - } - }; - - this.isConnected = () => _poller !== null; - } - - #init_ws(): void { - const Provider = resolveWebSocketProvider(); - if (!Provider) { - throw new Error(UNKNOWN_TRANSPORT_MESSAGE); - } - - const isSocketOpen = (): boolean => - this.#socket !== null && this.#socket.readyState === WS_OPEN; - - this.connect = (host_, force) => { - this.#boffClosed = false; - - if (this.#socket) { - if (!force && isSocketOpen()) { - this.probe(); - return Promise.resolve(); - } - this.#socket.close(); - this.#socket = null; - } - - if (host_) { - this.host = host_; - } - - return new Promise((resolve, reject) => { - const url = makeBaseUrl( - this.host, - this.secure ? 'wss' : 'ws', - this.version, - this.apiKey - ); - if (url === null) { - reject(new Error('Invalid websocket URL')); - return; - } - - Connection.#log('WS connecting to: ', url); - - const conn = new Provider(url); - - conn.addEventListener('error', (err) => { - reject(err); - }); - - conn.addEventListener('open', () => { - if (this.autoreconnect) { - this.#boffStop(); - } - - if (this.onOpen) { - this.onOpen(); - } - - resolve(); - }); - - conn.addEventListener('close', () => { - this.#socket = null; - - if (this.onDisconnect) { - const code = this.#boffClosed ? NETWORK_USER : NETWORK_ERROR; - this.onDisconnect( - new CommError( - this.#boffClosed ? NETWORK_USER_TEXT : NETWORK_ERROR_TEXT, - code - ), - code - ); - } - - if (!this.#boffClosed && this.autoreconnect) { - this.#boffReconnect(); - } - }); - - conn.addEventListener('message', (evt) => { - if (this.onMessage) { - this.onMessage(String(evt.data)); - } - }); - - this.#socket = conn; - }); - }; - - this.reconnect = (force) => { - this.#boffStop(); - this.connect(null, force); - }; - - this.disconnect = () => { - this.#boffClosed = true; - this.#boffStop(); - - if (!this.#socket) { - return; - } - this.#socket.close(); - this.#socket = null; - }; - - this.sendText = (msg) => { - if (this.#socket && isSocketOpen()) { - this.#socket.send(msg); - } else { - throw new Error('Websocket is not connected'); - } - }; - - this.isConnected = isSocketOpen; - } -} diff --git a/src/core/drafty.ts b/src/core/drafty.ts deleted file mode 100644 index 4c4d35c..0000000 --- a/src/core/drafty.ts +++ /dev/null @@ -1,2226 +0,0 @@ -import type { CardData } from './the-card'; -import { splitGraphemes } from './graphemes'; -import type { GraphemeSegment } from './graphemes'; - -export type DraftyEntityType = - 'AU' | 'BN' | 'EX' | 'HT' | 'IM' | 'LN' | 'MN' | 'TC' | 'VC' | 'VD'; - -export type DraftyStyleType = - | DraftyEntityType - | 'BR' - | 'CO' - | 'DL' - | 'EM' - | 'FM' - | 'HD' - | 'HL' - | 'QQ' - | 'RW' - | 'ST'; - -export type DraftyJsonObject = { readonly [key: string]: unknown }; - -export interface DraftyEntData extends CardData { - act?: string; - aonly?: boolean; - duration?: number; - height?: number; - incoming?: boolean; - mime?: string; - name?: string; - premime?: string; - preref?: string; - preview?: string; - ref?: string; - size?: number; - state?: string; - title?: string; - url?: string; - val?: string | DraftyJsonObject; - vc?: boolean; - width?: number; - _tempPreview?: string; - _processing?: boolean; -} - -export interface DraftyFmt { - at?: number; - len?: number; - tp?: DraftyStyleType; - key?: number; -} - -export interface DraftyEnt { - tp: DraftyStyleType; - data?: DraftyEntData; -} - -export interface DraftyDoc { - txt?: string; - fmt?: DraftyFmt[]; - ent?: DraftyEnt[]; -} - -export type DraftySource = DraftyDoc | string | null | undefined; - -export interface DraftyNode { - type?: DraftyStyleType; - text?: string; - data?: DraftyEntData; - key?: number; - att?: boolean; - children?: DraftyNode[] | null; - parent?: DraftyNode; -} - -export type DraftyFormatter = ( - style: DraftyStyleType | undefined, - data: DraftyEntData | undefined, - values: (R | string)[] | null, - index: number, - stack: DraftyStyleType[] | undefined -) => R | null | undefined; - -export type DraftyEntityCallback = ( - data: DraftyEntData | undefined, - index: number, - tp: DraftyStyleType -) => unknown; - -export type DraftyStyleCallback = ( - tp: DraftyStyleType | undefined, - at: number | undefined, - len: number | undefined, - key: number | undefined, - index: number -) => unknown; - -export type DraftyLogger = (message: string, ...args: unknown[]) => void; - -export type DraftyAttributes = Record< - string, - string | number | boolean | null | undefined ->; - -export interface ImageDesc { - mime?: string; - refurl?: string; - bits?: string; - preview?: string; - width?: number; - height?: number; - filename?: string; - size?: number; - _tempPreview?: string; - urlPromise?: Promise; -} - -export interface VideoDesc { - mime?: string; - refurl?: string; - bits?: string; - preview?: string; - preref?: string; - width?: number; - height?: number; - duration?: number; - filename?: string; - size?: number; - _tempPreview?: string; - urlPromise?: Promise<[string | undefined, string | undefined]>; -} - -export interface AudioDesc { - mime?: string; - refurl?: string; - bits?: string; - duration?: number; - preview?: string; - filename?: string; - size?: number; - urlPromise?: Promise; -} - -export interface AttachmentDesc { - mime?: string; - data?: string; - filename?: string; - size?: number; - refurl?: string; - urlPromise?: Promise; -} - -export interface LinkData { - txt: string; - url: string; -} - -export interface VideoCallUpdate { - state?: string; - duration?: number; - incoming?: boolean; - vc?: boolean; -} - -export type ButtonActionType = 'url' | 'pub'; - -interface FormatTag { - html_tag: string; - md_tag: string | undefined; - isVoid: boolean; -} - -interface Decorator { - open: (data: DraftyEntData) => string; - close: (data: DraftyEntData) => string; - props?: (data: DraftyEntData) => DraftyAttributes | null; -} - -interface InlineStyle { - name: DraftyStyleType; - start: RegExp; - end: RegExp; -} - -interface EntityType { - name: DraftyEntityType; - dataName: 'url' | 'val'; - pack: (val: string) => DraftyEntData; - re: RegExp; -} - -interface Span { - txt: string; - children: Span[]; - at: number; - end: number; - tp: DraftyStyleType; -} - -interface Chunk { - txt?: string; - tp?: DraftyStyleType; - children?: Chunk[]; -} - -interface ExtractedEntity { - offset: number; - len: number; - unique: string; - data: DraftyEntData; - type: DraftyEntityType; -} - -interface TreeSpan { - type?: DraftyStyleType; - start: number; - end: number; - key?: number; - data?: DraftyEntData; -} - -type AllowedEntField = - | 'act' - | 'height' - | 'duration' - | 'fn' - | 'incoming' - | 'mime' - | 'name' - | 'premime' - | 'preref' - | 'preview' - | 'ref' - | 'size' - | 'state' - | 'url' - | 'val' - | 'width'; - -const MAX_PREVIEW_ATTACHMENTS = 3; -const MAX_PREVIEW_DATA_SIZE = 64; -const DRAFTY_MIME_TYPE = 'text/x-drafty'; -const DRAFTY_FR_MIME_TYPE = 'text/x-drafty-fr'; -const DRAFTY_FR_MIME_TYPE_LEGACY = 'application/json'; -const ALLOWED_ENT_FIELDS: readonly AllowedEntField[] = [ - 'act', - 'height', - 'duration', - 'fn', - 'incoming', - 'mime', - 'name', - 'premime', - 'preref', - 'preview', - 'ref', - 'size', - 'state', - 'url', - 'val', - 'width', -]; - -const INLINE_STYLES: readonly InlineStyle[] = [ - { - name: 'ST', - start: /(?:^|[\W_])(\*)[^\s*]/, - end: /[^\s*](\*)(?=$|[\W_])/, - }, - { - name: 'EM', - start: /(?:^|\W)(_)[^\s_]/, - end: /[^\s_](_)(?=$|\W)/, - }, - { - name: 'DL', - start: /(?:^|[\W_])(~)[^\s~]/, - end: /[^\s~](~)(?=$|[\W_])/, - }, - { - name: 'CO', - start: /(?:^|\W)(`)[^`]/, - end: /[^`](`)(?=$|\W)/, - }, -]; - -const FMT_WEIGHT: readonly (DraftyStyleType | undefined)[] = ['QQ']; - -const ENTITY_TYPES: readonly EntityType[] = [ - { - name: 'LN', - dataName: 'url', - pack: (val) => { - if (!/^[a-z]+:\/\//i.test(val)) { - val = 'http://' + val; - } - return { url: val }; - }, - re: /(?:(?:https?|ftp):\/\/|www\.|ftp\.)[-A-Z0-9+&@#/%=~_|$?!:,.]*[A-Z0-9+&@#/%=~_|$]/gi, - }, - { - name: 'MN', - dataName: 'val', - pack: (val) => ({ val: val.slice(1) }), - re: /\B@([\p{L}\p{N}][._\p{L}\p{N}]*[\p{L}\p{N}])/gu, - }, - { - name: 'HT', - dataName: 'val', - pack: (val) => ({ val: val.slice(1) }), - re: /\B#([\p{L}\p{N}][._\p{L}\p{N}]*[\p{L}\p{N}])/gu, - }, -]; - -const FORMAT_TAGS: Record = { - AU: { html_tag: 'audio', md_tag: undefined, isVoid: false }, - BN: { html_tag: 'button', md_tag: undefined, isVoid: false }, - BR: { html_tag: 'br', md_tag: '\n', isVoid: true }, - CO: { html_tag: 'tt', md_tag: '`', isVoid: false }, - DL: { html_tag: 'del', md_tag: '~', isVoid: false }, - EM: { html_tag: 'i', md_tag: '_', isVoid: false }, - EX: { html_tag: '', md_tag: undefined, isVoid: true }, - FM: { html_tag: 'div', md_tag: undefined, isVoid: false }, - HD: { html_tag: '', md_tag: undefined, isVoid: false }, - HL: { html_tag: 'span', md_tag: undefined, isVoid: false }, - HT: { html_tag: 'a', md_tag: undefined, isVoid: false }, - IM: { html_tag: 'img', md_tag: undefined, isVoid: false }, - LN: { html_tag: 'a', md_tag: undefined, isVoid: false }, - MN: { html_tag: 'a', md_tag: undefined, isVoid: false }, - RW: { html_tag: 'div', md_tag: undefined, isVoid: false }, - QQ: { html_tag: 'div', md_tag: undefined, isVoid: false }, - ST: { html_tag: 'b', md_tag: '*', isVoid: false }, - TC: { html_tag: 'div', md_tag: undefined, isVoid: false }, - VC: { html_tag: 'div', md_tag: undefined, isVoid: false }, - VD: { html_tag: 'video', md_tag: undefined, isVoid: false }, -}; - -function toInt(value: unknown): number { - return typeof value === 'number' && Number.isFinite(value) - ? Math.trunc(value) - : 0; -} - -function base64Size(val: unknown): number { - return typeof val === 'string' ? Math.floor(val.length * 0.75) : 0; -} - -function base64toDataUrl(b64: unknown, contentType?: string): string | null { - if (!b64 || typeof b64 !== 'string') { - return null; - } - contentType = contentType || 'image/jpeg'; - return 'data:' + contentType + ';base64,' + b64; -} - -function hasDom(): boolean { - return Reflect.has(globalThis, 'document'); -} - -function base64toBlob(b64: string, contentType?: string): Blob { - const bin = atob(b64); - const arr = new Uint8Array(bin.length); - for (let i = 0; i < bin.length; i++) { - arr[i] = bin.charCodeAt(i); - } - const blob: Blob = Reflect.construct(Blob, [ - [arr.buffer], - { type: contentType }, - ]); - return blob; -} - -function base64toObjectUrl( - b64: unknown, - contentType?: string, - logger?: DraftyLogger | null -): string | null { - if (!b64 || typeof b64 !== 'string') { - return null; - } - - if (hasDom()) { - try { - return URL.createObjectURL(base64toBlob(b64, contentType)); - } catch (err) { - if (logger) { - logger( - 'Drafty: failed to convert object.', - err instanceof Error ? err.message : err - ); - } - } - } - - return base64toDataUrl(b64, contentType || 'application/octet-stream'); -} - -function sanitizeUrl(url: string | undefined): string | null | undefined { - if (!url || typeof url !== 'string') { - return url; - } - if (!/^\s*([a-z][a-z0-9+.-]*:|\/\/)/im.test(url)) { - return url; - } - if (/^(https?|ftp):\/\//i.test(url)) { - return url; - } - return null; -} - -const DECORATORS: Partial> = { - ST: { - open: () => '', - close: () => '', - }, - EM: { - open: () => '', - close: () => '', - }, - DL: { - open: () => '', - close: () => '', - }, - CO: { - open: () => '', - close: () => '', - }, - BR: { - open: () => '
', - close: () => '', - }, - HD: { - open: () => '', - close: () => '', - }, - HL: { - open: () => '', - close: () => '', - }, - LN: { - open: (data) => '', - close: () => '', - props: (data) => ({ - href: sanitizeUrl(data.url), - target: '_blank', - rel: 'noopener noreferrer', - }), - }, - MN: { - open: (data) => '', - close: () => '', - props: (data) => ({ - id: typeof data.val === 'string' ? data.val : undefined, - }), - }, - HT: { - open: (data) => '', - close: () => '', - props: (data) => ({ - id: typeof data.val === 'string' ? data.val : undefined, - }), - }, - BN: { - open: () => '', - props: (data) => ({ - 'data-act': data.act, - 'data-val': typeof data.val === 'string' ? data.val : undefined, - 'data-name': data.name, - 'data-ref': sanitizeUrl(data.ref), - }), - }, - AU: { - open: (data) => { - const url = - data.ref || base64toObjectUrl(data.val, data.mime, Drafty.logger); - return '', - props: (data) => { - const safeRef = sanitizeUrl(data.ref); - return { - 'src': safeRef || base64toObjectUrl(data.val, data.mime, Drafty.logger), - 'data-preload': safeRef ? 'metadata' : 'auto', - 'data-duration': data.duration, - 'data-name': data.name, - 'data-size': data.val ? base64Size(data.val) : toInt(data.size), - 'data-mime': data.mime, - }; - }, - }, - IM: { - open: (data) => { - const tmpPreviewUrl = base64toDataUrl(data._tempPreview, data.mime); - const previewUrl = base64toObjectUrl(data.val, data.mime, Drafty.logger); - const downloadUrl = data.ref || previewUrl; - return ( - (data.name - ? '' - : '') + - '' - ); - }, - close: (data) => (data.name ? '' : ''), - props: (data) => ({ - 'src': - base64toDataUrl(data._tempPreview, data.mime) || - sanitizeUrl(data.ref) || - base64toObjectUrl(data.val, data.mime, Drafty.logger), - 'title': data.name, - 'alt': data.name, - 'data-width': data.width, - 'data-height': data.height, - 'data-name': data.name, - 'data-size': data.ref - ? toInt(data.size) - : data.val - ? base64Size(data.val) - : toInt(data.size), - 'data-mime': data.mime, - }), - }, - FM: { - open: () => '
', - close: () => '
', - }, - RW: { - open: () => '
', - close: () => '
', - }, - QQ: { - open: () => '
', - close: () => '
', - props: () => ({}), - }, - TC: { - open: () => '
', - close: () => '
', - props: (data) => ({ - 'data-fn': data.fn, - 'data-title': data.title, - }), - }, - VC: { - open: () => '
', - close: () => '
', - props: (data) => ({ - 'data-duration': data.duration, - 'data-state': data.state, - }), - }, - VD: { - open: (data) => { - const tmpPreviewUrl = base64toDataUrl(data._tempPreview, data.mime); - const previewUrl = - data.ref || - base64toObjectUrl( - data.preview, - data.premime || 'image/jpeg', - Drafty.logger - ); - return ( - '' - ); - }, - close: () => '', - props: (data) => { - const safePreref = sanitizeUrl(data.preref); - const safeRef = sanitizeUrl(data.ref); - const poster = - safePreref || - base64toObjectUrl( - data.preview, - data.premime || 'image/jpeg', - Drafty.logger - ); - return { - 'src': poster, - 'data-src': - safeRef || base64toObjectUrl(data.val, data.mime, Drafty.logger), - 'data-width': data.width, - 'data-height': data.height, - 'data-preload': safeRef ? 'metadata' : 'auto', - 'data-preview': poster, - 'data-duration': toInt(data.duration), - 'data-name': data.name, - 'data-size': data.ref - ? toInt(data.size) - : data.val - ? base64Size(data.val) - : toInt(data.size), - 'data-mime': data.mime, - }; - }, - }, -}; - -export default class Drafty implements DraftyDoc { - txt = ''; - fmt: DraftyFmt[] = []; - ent: DraftyEnt[] = []; - - static logger?: DraftyLogger | null; - - static readonly contentType = DRAFTY_MIME_TYPE; - - static init(plainText?: unknown): DraftyDoc | null { - if (typeof plainText === 'undefined') { - return { txt: '' }; - } - if (typeof plainText !== 'string') { - return null; - } - return { txt: plainText }; - } - - static parse(content: string): DraftyDoc; - static parse(content: unknown): DraftyDoc | null; - static parse(content: unknown): DraftyDoc | null { - if (typeof content !== 'string') { - return null; - } - - const lines = content.split(/\r?\n/); - - const entityMap: DraftyEnt[] = []; - const entityIndex = new Map(); - - const blx: { txt: string; fmt?: DraftyFmt[]; ent?: DraftyFmt[] }[] = []; - lines.forEach((line) => { - let spans: Span[] = []; - - INLINE_STYLES.forEach((tag) => { - spans = spans.concat(spannify(line, tag.start, tag.end, tag.name)); - }); - - let block: { txt: string; fmt?: DraftyFmt[]; ent?: DraftyFmt[] }; - if (spans.length === 0) { - block = { txt: line }; - } else { - spans.sort((a, b) => { - const diff = a.at - b.at; - return diff !== 0 ? diff : b.end - a.end; - }); - - spans = toSpanTree(spans); - - const chunks = chunkify(line, 0, line.length, spans); - const drafty = draftify(chunks, 0); - - block = { txt: drafty.txt, fmt: drafty.fmt }; - } - - const entities = extractEntities(block.txt); - if (entities.length > 0) { - const ranges: DraftyFmt[] = []; - for (const entity of entities) { - let index = entityIndex.get(entity.unique); - if (index === undefined) { - index = entityMap.length; - entityIndex.set(entity.unique, index); - entityMap.push({ tp: entity.type, data: entity.data }); - } - ranges.push({ at: entity.offset, len: entity.len, key: index }); - } - block.ent = ranges; - } - - blx.push(block); - }); - - const result: DraftyDoc = { txt: '' }; - - const first = blx[0]; - if (first) { - let txt = first.txt; - let fmt = (first.fmt || []).concat(first.ent || []); - - if (fmt.length) { - const segments = splitGraphemes(txt); - for (const ele of fmt) { - ({ at: ele.at, len: ele.len } = toGraphemeValues(ele, segments, txt)); - } - } - - for (const block of blx.slice(1)) { - const offset = splitGraphemes(txt).length + 1; - - fmt.push({ tp: 'BR', len: 1, at: offset - 1 }); - - txt += ' ' + block.txt; - - const ranges = (block.fmt || []).concat(block.ent || []); - if (ranges.length) { - const segments = splitGraphemes(block.txt); - fmt = fmt.concat( - ranges.map((s) => { - const { at, len } = toGraphemeValues(s, segments, block.txt); - s.at = at + offset; - s.len = len; - return s; - }) - ); - } - } - - result.txt = txt; - if (fmt.length > 0) { - result.fmt = fmt; - } - if (entityMap.length > 0) { - result.ent = entityMap; - } - } - return result; - } - - static append(first: DraftyDoc, second: DraftySource): DraftyDoc; - static append( - first: DraftyDoc | null | undefined, - second: DraftySource - ): DraftySource; - static append( - first: DraftyDoc | null | undefined, - second: DraftySource - ): DraftySource { - if (!first) { - return second; - } - if (!second) { - return first; - } - - first.txt = first.txt || ''; - const len = stringToGraphemes(first.txt).length; - - if (typeof second === 'string') { - first.txt += second; - return first; - } - if (second.txt) { - first.txt += second.txt; - } - - if (Array.isArray(second.fmt)) { - const fmts = (first.fmt = first.fmt || []); - const ents = Array.isArray(second.ent) - ? (first.ent = first.ent || []) - : undefined; - second.fmt.forEach((src) => { - const fmt: DraftyFmt = { - at: toInt(src.at) + len, - len: toInt(src.len), - }; - if (src.at === -1) { - fmt.at = -1; - fmt.len = 0; - } - if (src.tp) { - fmt.tp = src.tp; - } else { - const ent = second.ent?.[src.key || 0]; - if (!ent || !ents) { - return; - } - fmt.key = ents.length; - ents.push(ent); - } - fmts.push(fmt); - }); - } - - return first; - } - - static insertImage( - content: DraftyDoc | null | undefined, - at: number, - imageDesc: ImageDesc - ): DraftyDoc { - content = content || { txt: ' ' }; - content.ent = content.ent || []; - content.fmt = content.fmt || []; - - content.fmt.push({ at: toInt(at), len: 1, key: content.ent.length }); - - const data: DraftyEntData = { - mime: imageDesc.mime, - ref: imageDesc.refurl, - val: imageDesc.bits || imageDesc.preview, - width: imageDesc.width, - height: imageDesc.height, - name: imageDesc.filename, - size: toInt(imageDesc.size), - }; - - if (imageDesc.urlPromise) { - data._tempPreview = imageDesc._tempPreview; - data._processing = true; - imageDesc.urlPromise.then( - (url) => { - data.ref = url; - data._tempPreview = undefined; - data._processing = undefined; - }, - () => { - data._processing = undefined; - } - ); - } - - content.ent.push({ tp: 'IM', data }); - - return content; - } - - static insertVideo( - content: DraftyDoc | null | undefined, - at: number, - videoDesc: VideoDesc - ): DraftyDoc { - content = content || { txt: ' ' }; - content.ent = content.ent || []; - content.fmt = content.fmt || []; - - content.fmt.push({ at: toInt(at), len: 1, key: content.ent.length }); - - const data: DraftyEntData = { - mime: videoDesc.mime, - ref: videoDesc.refurl, - val: videoDesc.bits, - preref: videoDesc.preref, - preview: videoDesc.preview, - width: videoDesc.width, - height: videoDesc.height, - duration: toInt(videoDesc.duration), - name: videoDesc.filename, - size: toInt(videoDesc.size), - }; - - if (videoDesc.urlPromise) { - data._tempPreview = videoDesc._tempPreview; - data._processing = true; - videoDesc.urlPromise.then( - (urls) => { - data.ref = urls[0]; - data.preref = urls[1]; - data._tempPreview = undefined; - data._processing = undefined; - }, - () => { - data._processing = undefined; - } - ); - } - - content.ent.push({ tp: 'VD', data }); - - return content; - } - - static insertAudio( - content: DraftyDoc | null | undefined, - at: number, - audioDesc: AudioDesc - ): DraftyDoc { - content = content || { txt: ' ' }; - content.ent = content.ent || []; - content.fmt = content.fmt || []; - - content.fmt.push({ at: toInt(at), len: 1, key: content.ent.length }); - - const data: DraftyEntData = { - mime: audioDesc.mime, - val: audioDesc.bits, - duration: toInt(audioDesc.duration), - preview: audioDesc.preview, - name: audioDesc.filename, - size: toInt(audioDesc.size), - ref: audioDesc.refurl, - }; - - if (audioDesc.urlPromise) { - data._processing = true; - audioDesc.urlPromise.then( - (url) => { - data.ref = url; - data._processing = undefined; - }, - () => { - data._processing = undefined; - } - ); - } - - content.ent.push({ tp: 'AU', data }); - - return content; - } - - static videoCall(audioOnly?: boolean): DraftyDoc { - return { - txt: ' ', - fmt: [{ at: 0, len: 1, key: 0 }], - ent: [{ tp: 'VC', data: { aonly: audioOnly } }], - }; - } - - static updateVideoCall( - content: T, - params: VideoCallUpdate - ): T { - const fmt = content?.fmt?.[0]; - if (!content || !fmt) { - return content; - } - - let ent: DraftyEnt | undefined; - if (fmt.tp === 'VC') { - delete fmt.tp; - fmt.key = 0; - ent = { tp: 'VC' }; - content.ent = [ent]; - } else { - ent = content.ent?.[toInt(fmt.key)]; - if (!ent || ent.tp !== 'VC') { - return content; - } - } - ent.data = ent.data || {}; - Object.assign(ent.data, params); - return content; - } - - static quote(header: string, uid: string, body: DraftySource): DraftyDoc { - const quote = Drafty.append( - Drafty.appendLineBreak(Drafty.mention(header, uid)), - body - ); - - quote.fmt = quote.fmt || []; - quote.fmt.push({ - at: 0, - len: stringToGraphemes(quote.txt || '').length, - tp: 'QQ', - }); - - return quote; - } - - static mention(name: string | null | undefined, uid: string): DraftyDoc { - return { - txt: name || '', - fmt: [{ at: 0, len: stringToGraphemes(name || '').length, key: 0 }], - ent: [{ tp: 'MN', data: { val: uid } }], - }; - } - - static appendLink( - content: DraftyDoc | null | undefined, - linkData: LinkData - ): DraftyDoc { - content = content || { txt: '' }; - content.txt = content.txt || ''; - - content.ent = content.ent || []; - content.fmt = content.fmt || []; - - content.fmt.push({ - at: stringToGraphemes(content.txt).length, - len: stringToGraphemes(linkData.txt).length, - key: content.ent.length, - }); - content.txt += linkData.txt; - - content.ent.push({ tp: 'LN', data: { url: linkData.url } }); - - return content; - } - - static appendImage( - content: DraftyDoc | null | undefined, - imageDesc: ImageDesc - ): DraftyDoc { - content = content || { txt: '' }; - content.txt = (content.txt || '') + ' '; - return Drafty.insertImage( - content, - stringToGraphemes(content.txt).length - 1, - imageDesc - ); - } - - static appendAudio( - content: DraftyDoc | null | undefined, - audioDesc: AudioDesc - ): DraftyDoc { - content = content || { txt: '' }; - content.txt = (content.txt || '') + ' '; - return Drafty.insertAudio( - content, - stringToGraphemes(content.txt).length - 1, - audioDesc - ); - } - - static attachFile( - content: DraftyDoc | null | undefined, - attachmentDesc: AttachmentDesc - ): DraftyDoc { - content = content || { txt: '' }; - - content.ent = content.ent || []; - content.fmt = content.fmt || []; - - content.fmt.push({ at: -1, len: 0, key: content.ent.length }); - - const data: DraftyEntData = { - mime: attachmentDesc.mime, - val: attachmentDesc.data, - name: attachmentDesc.filename, - ref: attachmentDesc.refurl, - size: toInt(attachmentDesc.size), - }; - if (attachmentDesc.urlPromise) { - data._processing = true; - attachmentDesc.urlPromise.then( - (url) => { - data.ref = url; - data._processing = undefined; - }, - () => { - data._processing = undefined; - } - ); - } - content.ent.push({ tp: 'EX', data }); - - return content; - } - - static wrapInto( - content: DraftyDoc | string, - style: DraftyStyleType, - at?: number, - len?: number - ): DraftyDoc { - if (typeof content === 'string') { - content = { txt: content }; - } - content.fmt = content.fmt || []; - - content.fmt.push({ - at: at || 0, - len: len || stringToGraphemes(content.txt || '').length, - tp: style, - }); - - return content; - } - - static wrapAsForm( - content: DraftyDoc | string, - at?: number, - len?: number - ): DraftyDoc { - return Drafty.wrapInto(content, 'FM', at, len); - } - - static insertButton( - content: DraftySource, - at: number, - len: number, - name: string | undefined, - actionType: ButtonActionType, - actionValue?: string, - refUrl?: string - ): DraftyDoc | null { - if (typeof content === 'string') { - content = { txt: content }; - } - - if ( - !content || - !content.txt || - stringToGraphemes(content.txt).length < at + len - ) { - return null; - } - - if (len <= 0 || ['url', 'pub'].indexOf(actionType) === -1) { - return null; - } - if (actionType === 'url' && !refUrl) { - return null; - } - - content.ent = content.ent || []; - content.fmt = content.fmt || []; - - content.fmt.push({ at: toInt(at), len, key: content.ent.length }); - content.ent.push({ - tp: 'BN', - data: { - act: actionType, - val: actionValue, - ref: refUrl === undefined || refUrl === null ? undefined : '' + refUrl, - name, - }, - }); - - return content; - } - - static appendButton( - content: DraftyDoc | null | undefined, - title: string, - name: string | undefined, - actionType: ButtonActionType, - actionValue?: string, - refUrl?: string - ): DraftyDoc | null { - content = content || { txt: '' }; - content.txt = content.txt || ''; - const at = stringToGraphemes(content.txt).length; - content.txt += title; - return Drafty.insertButton( - content, - at, - stringToGraphemes(title).length, - name, - actionType, - actionValue, - refUrl - ); - } - - static attachJSON( - content: DraftyDoc | null | undefined, - data: DraftyJsonObject - ): DraftyDoc { - content = content || { txt: '' }; - content.ent = content.ent || []; - content.fmt = content.fmt || []; - - content.fmt.push({ at: -1, len: 0, key: content.ent.length }); - - content.ent.push({ - tp: 'EX', - data: { mime: DRAFTY_FR_MIME_TYPE, val: data }, - }); - - return content; - } - - static appendLineBreak(content: DraftyDoc | null | undefined): DraftyDoc { - content = content || { txt: '' }; - content.txt = content.txt || ''; - content.fmt = content.fmt || []; - content.fmt.push({ - at: stringToGraphemes(content.txt).length, - len: 1, - tp: 'BR', - }); - content.txt += ' '; - - return content; - } - - static appendTheCard( - content: DraftyDoc | null | undefined, - theCardData: CardData - ): DraftyDoc { - content = content || { txt: '' }; - content.txt = content.txt || ''; - content.ent = content.ent || []; - content.fmt = content.fmt || []; - - content.fmt.push({ - at: stringToGraphemes(content.txt).length, - len: 1, - key: content.ent.length, - }); - content.txt += ' '; - - content.ent.push({ tp: 'TC', data: theCardData }); - - return content; - } - - static UNSAFE_toHTML(doc: DraftySource): string | null { - const tree = draftyToTree(doc); - const htmlFormatter: DraftyFormatter = (type, data, values) => { - const tag = type ? DECORATORS[type] : undefined; - let result = values ? values.join('') : ''; - if (tag) { - result = tag.open(data || {}) + result + tag.close(data || {}); - } - return result; - }; - return treeBottomUp(tree, htmlFormatter, 0) ?? null; - } - - static format( - original: DraftySource, - formatter: DraftyFormatter, - context?: unknown - ): R | null | undefined { - return treeBottomUp(draftyToTree(original), formatter, 0, [], context); - } - - static shorten( - original: DraftySource, - limit: number, - light?: boolean - ): DraftyDoc { - let tree = draftyToTree(original); - tree = shortenTree(tree, limit, '…'); - if (tree && light) { - tree = lightEntity(tree); - } - return treeToDrafty({}, tree, []); - } - - static forwardedContent(original: DraftySource): DraftyDoc { - let tree = draftyToTree(original); - const rmMention = (node: DraftyNode) => { - if (node.type === 'MN') { - if (!node.parent || !node.parent.type) { - return null; - } - } - return node; - }; - tree = treeTopDown(tree, rmMention); - tree = lTrim(tree); - return treeToDrafty({}, tree, []); - } - - static replyContent(original: DraftySource, limit: number): DraftySource { - const convMNnQQnBR = (node: DraftyNode) => { - if (node.type === 'QQ') { - return null; - } else if (node.type === 'MN') { - if ( - (!node.parent || !node.parent.type) && - (node.text || '').startsWith('➦') - ) { - node.text = '➦'; - delete node.children; - delete node.data; - } - } else if (node.type === 'BR') { - node.text = ' '; - delete node.type; - delete node.children; - } - return node; - }; - - let tree = draftyToTree(original); - if (!tree) { - return original; - } - - tree = treeTopDown(tree, convMNnQQnBR); - tree = attachmentsToEnd(tree, MAX_PREVIEW_ATTACHMENTS); - tree = shortenTree(tree, limit, '…'); - const filter = (node: DraftyNode): AllowedEntField[] | null => { - switch (node.type) { - case 'IM': - return ['val']; - case 'VD': - return ['preview']; - } - return null; - }; - tree = lightEntity(tree, filter); - return treeToDrafty({}, tree, []); - } - - static preview( - original: DraftySource, - limit: number, - forwarding?: boolean - ): DraftyDoc { - let tree = draftyToTree(original); - - tree = attachmentsToEnd(tree, MAX_PREVIEW_ATTACHMENTS); - - const convMNnQQnBR = (node: DraftyNode) => { - if (node.type === 'MN') { - if ( - (!node.parent || !node.parent.type) && - (node.text || '').startsWith('➦') - ) { - node.text = '➦'; - delete node.children; - } - } else if (node.type === 'QQ') { - node.text = ' '; - delete node.children; - } else if (node.type === 'BR') { - node.text = ' '; - delete node.children; - delete node.type; - } - return node; - }; - tree = treeTopDown(tree, convMNnQQnBR); - - tree = shortenTree(tree, limit, '…'); - if (forwarding) { - const filter: Partial> = { - IM: ['val'], - VD: ['preview'], - }; - tree = lightEntity(tree, (node) => - node.type ? filter[node.type] : undefined - ); - } else { - tree = lightEntity(tree); - } - - return treeToDrafty({}, tree, []); - } - - static toPlainText(content: DraftyDoc | string): string | undefined { - return typeof content === 'string' ? content : content.txt; - } - - static isPlainText(content: DraftyDoc | string): boolean { - return typeof content === 'string' || !(content.fmt || content.ent); - } - - static toMarkdown(content: DraftySource): string | null { - const tree = draftyToTree(content); - const mdFormatter: DraftyFormatter = (type, _, values) => { - const def = type ? FORMAT_TAGS[type] : undefined; - let result = values ? values.join('') : ''; - if (def) { - if (def.isVoid) { - result = def.md_tag || ''; - } else if (def.md_tag) { - result = def.md_tag + result + def.md_tag; - } - } - return result; - }; - return treeBottomUp(tree, mdFormatter, 0) ?? null; - } - - static isValid(content: unknown): boolean { - if (!isRecord(content)) { - return false; - } - - const { txt, fmt, ent } = content; - - if (!txt && txt !== '' && !fmt && !ent) { - return false; - } - - const txtType = typeof txt; - if (txtType !== 'string' && txtType !== 'undefined' && txt !== null) { - return false; - } - - if (typeof fmt !== 'undefined' && !Array.isArray(fmt) && fmt !== null) { - return false; - } - - if (typeof ent !== 'undefined' && !Array.isArray(ent) && ent !== null) { - return false; - } - return true; - } - - static hasAttachments(content: DraftyDoc): boolean { - if (!Array.isArray(content.fmt)) { - return false; - } - for (const fmt of content.fmt) { - if (fmt && toInt(fmt.at) < 0) { - const ent = content.ent?.[toInt(fmt.key)]; - return !!ent && ent.tp === 'EX' && !!ent.data; - } - } - return false; - } - - static attachments( - content: DraftyDoc, - callback: DraftyEntityCallback, - context?: unknown - ): void { - if (!Array.isArray(content.fmt)) { - return; - } - let count = 0; - for (const fmt of content.fmt) { - if (fmt && toInt(fmt.at) < 0) { - const ent = content.ent?.[toInt(fmt.key)]; - if (ent && ent.tp === 'EX' && ent.data) { - if (callback.call(context, ent.data, count++, 'EX')) { - break; - } - } - } - } - } - - static hasEntities(content: DraftySource): boolean { - return ( - !!content && - typeof content === 'object' && - !!content.ent && - content.ent.length > 0 - ); - } - - static entities( - content: DraftyDoc, - callback: DraftyEntityCallback, - context?: unknown - ): void { - if (content.ent && content.ent.length > 0) { - for (let i = 0; i < content.ent.length; i++) { - const ent = content.ent[i]; - if (ent) { - if (callback.call(context, ent.data, i, ent.tp)) { - break; - } - } - } - } - } - - static styles( - content: DraftyDoc, - callback: DraftyStyleCallback, - context?: unknown - ): void { - if (content.fmt && content.fmt.length > 0) { - for (let i = 0; i < content.fmt.length; i++) { - const fmt = content.fmt[i]; - if (fmt) { - if (callback.call(context, fmt.tp, fmt.at, fmt.len, fmt.key, i)) { - break; - } - } - } - } - } - - static sanitizeEntities( - content: T - ): T { - if (content && content.ent && content.ent.length > 0) { - for (const ent of content.ent) { - if (ent && ent.data) { - const data = copyEntData(ent.data); - if (data) { - ent.data = data; - } else { - delete ent.data; - } - } - } - } - return content; - } - - static getDownloadUrl(entData: DraftyEntData): string | null { - let url: string | null = null; - if (!Drafty.isFormResponseType(entData.mime) && entData.val) { - url = base64toObjectUrl(entData.val, entData.mime, Drafty.logger); - } else if (typeof entData.ref === 'string') { - url = sanitizeUrl(entData.ref) ?? null; - } - return url; - } - - static isProcessing(entData: DraftyEntData): boolean { - return !!entData._processing; - } - - static getPreviewUrl(entData: DraftyEntData): string | null { - return entData.val - ? base64toObjectUrl(entData.val, entData.mime, Drafty.logger) - : null; - } - - static getEntitySize(entData: DraftyEntData): number { - return entData.size - ? entData.size - : entData.val - ? base64Size(entData.val) - : 0; - } - - static getEntityMimeType(entData: DraftyEntData): string { - return entData.mime || 'text/plain'; - } - - static tagName(style: DraftyStyleType | undefined): string | undefined { - return style ? FORMAT_TAGS[style]?.html_tag : undefined; - } - - static attrValue( - style: DraftyStyleType | undefined, - data: DraftyEntData | null | undefined - ): DraftyAttributes | null | undefined { - const props = style ? DECORATORS[style]?.props : undefined; - if (data && props) { - return props(data); - } - return undefined; - } - - static getContentType(): string { - return DRAFTY_MIME_TYPE; - } - - static isFormResponseType(mimeType: string | null | undefined): boolean { - return ( - mimeType === DRAFTY_FR_MIME_TYPE || - mimeType === DRAFTY_FR_MIME_TYPE_LEGACY - ); - } -} - -function chunkify( - line: string, - start: number, - end: number, - spans: Span[] -): Chunk[] { - const chunks: Chunk[] = []; - - if (spans.length === 0) { - return []; - } - - for (const span of spans) { - if (span.at > start) { - chunks.push({ txt: line.slice(start, span.at) }); - } - - const chunk: Chunk = { tp: span.tp }; - const chld = chunkify(line, span.at + 1, span.end, span.children); - if (chld.length > 0) { - chunk.children = chld; - } else { - chunk.txt = span.txt; - } - chunks.push(chunk); - start = span.end + 1; - } - - if (start < end) { - chunks.push({ txt: line.slice(start, end) }); - } - - return chunks; -} - -function spannify( - original: string, - reStart: RegExp, - reEnd: RegExp, - type: DraftyStyleType -): Span[] { - const result: Span[] = []; - let index = 0; - let line = original; - - while (line.length > 0) { - const start = reStart.exec(line); - if (start == null) { - break; - } - - let startOffset = start.index + start[0].lastIndexOf(start[1] ?? ''); - line = line.slice(startOffset + 1); - startOffset += index; - index = startOffset + 1; - - const end = reEnd.exec(line); - if (end == null) { - break; - } - let endOffset = end.index + end[0].indexOf(end[1] ?? ''); - line = line.slice(endOffset + 1); - endOffset += index; - index = endOffset + 1; - - result.push({ - txt: original.slice(startOffset + 1, endOffset), - children: [], - at: startOffset, - end: endOffset, - tp: type, - }); - } - - return result; -} - -function toSpanTree(spans: Span[]): Span[] { - const [first, ...rest] = spans; - if (!first) { - return []; - } - - const tree = [first]; - let last = first; - for (const span of rest) { - if (span.at > last.end) { - tree.push(span); - last = span; - } else if (span.end <= last.end) { - last.children.push(span); - } - } - - for (const span of tree) { - span.children = toSpanTree(span.children); - } - - return tree; -} - -function isRecord(value: unknown): value is Record { - return !!value && typeof value === 'object'; -} - -function isStyleType(value: unknown): value is DraftyStyleType { - return typeof value === 'string' && value in FORMAT_TAGS; -} - -function draftyToTree(doc: DraftySource): DraftyNode | null { - if (!doc) { - return null; - } - - const source: DraftyDoc = typeof doc === 'string' ? { txt: doc } : doc; - const txt = source.txt || ''; - const ent = Array.isArray(source.ent) ? source.ent : []; - let fmt = Array.isArray(source.fmt) ? source.fmt : []; - - if (fmt.length === 0) { - if (ent.length === 0) { - return { text: txt }; - } - fmt = [{ at: 0, len: 0, key: 0 }]; - } - - const graphemes = stringToGraphemes(txt); - - const spans: TreeSpan[] = []; - const attachments: TreeSpan[] = []; - fmt.forEach((span) => { - if (!span || typeof span !== 'object') { - return; - } - - if (!['undefined', 'number'].includes(typeof span.at)) { - return; - } - if (!['undefined', 'number'].includes(typeof span.len)) { - return; - } - const at = toInt(span.at); - const len = toInt(span.len); - if (len < 0) { - return; - } - - const key = span.key || 0; - if ( - ent.length > 0 && - (typeof key !== 'number' || key < 0 || key >= ent.length) - ) { - return; - } - - if (at <= -1) { - attachments.push({ start: -1, end: 0, key }); - return; - } else if (at + len > graphemes.length) { - return; - } - - if (!span.tp) { - if (ent.length > 0 && typeof ent[key] === 'object') { - spans.push({ start: at, end: at + len, key }); - } - } else if (isStyleType(span.tp)) { - spans.push({ type: span.tp, start: at, end: at + len }); - } - }); - - spans.sort((a, b) => { - let diff = a.start - b.start; - if (diff !== 0) { - return diff; - } - diff = b.end - a.end; - if (diff !== 0) { - return diff; - } - return FMT_WEIGHT.indexOf(b.type) - FMT_WEIGHT.indexOf(a.type); - }); - - spans.push(...attachments); - - spans.forEach((span) => { - const entity = span.type ? undefined : ent[span.key ?? 0]; - if (entity && typeof entity === 'object') { - if (isStyleType(entity.tp)) { - span.type = entity.tp; - } - span.data = entity.data; - } - - if (!span.type) { - span.type = 'HD'; - } - }); - - let tree: DraftyNode | null = spansToTree( - {}, - graphemes, - 0, - graphemes.length, - spans - ); - - const flatten = (node: DraftyNode) => { - if (Array.isArray(node.children) && node.children.length === 1) { - const child = node.children[0]; - if (child && !node.type) { - const parent = node.parent; - node = child; - node.parent = parent; - } else if (child && !child.type && !child.children) { - node.text = child.text; - delete node.children; - } - } - return node; - }; - tree = treeTopDown(tree, flatten); - - return tree; -} - -function addNode(parent: DraftyNode, n: DraftyNode | null): DraftyNode { - if (!n) { - return parent; - } - - if (!parent.children) { - parent.children = []; - } - - if (parent.text) { - parent.children.push({ text: parent.text, parent }); - delete parent.text; - } - - n.parent = parent; - parent.children.push(n); - - return parent; -} - -function joinGraphemes( - graphemes: GraphemeSegment[], - start: number, - end: number -): string { - return graphemes - .slice(start, end) - .map((segment) => segment.segment) - .join(''); -} - -function spansToTree( - parent: DraftyNode, - graphemes: GraphemeSegment[], - start: number, - end: number, - spans: TreeSpan[] -): DraftyNode { - if (!spans || spans.length === 0) { - if (start < end) { - addNode(parent, { text: joinGraphemes(graphemes, start, end) }); - } - return parent; - } - - for (let i = 0; i < spans.length; i++) { - const span = spans[i]; - if (!span) { - continue; - } - if (span.start < 0 && span.type === 'EX') { - addNode(parent, { - type: span.type, - data: span.data, - key: span.key, - att: true, - }); - continue; - } - - if (start < span.start) { - addNode(parent, { text: joinGraphemes(graphemes, start, span.start) }); - start = span.start; - } - - const subspans: TreeSpan[] = []; - while (i < spans.length - 1) { - const inner = spans[i + 1]; - if (!inner || inner.start < 0) { - break; - } else if (inner.start < span.end) { - if (inner.end <= span.end) { - const isVoid = inner.type ? FORMAT_TAGS[inner.type].isVoid : false; - if (inner.start < inner.end || isVoid) { - subspans.push(inner); - } - } - i++; - } else { - break; - } - } - - addNode( - parent, - spansToTree( - { type: span.type, data: span.data, key: span.key }, - graphemes, - start, - span.end, - subspans - ) - ); - start = span.end; - } - - if (start < end) { - addNode(parent, { text: joinGraphemes(graphemes, start, end) }); - } - - return parent; -} - -function treeToDrafty( - doc: DraftyDoc, - tree: DraftyNode | null, - keymap: number[] -): DraftyDoc { - if (!tree) { - return doc; - } - - doc.txt = doc.txt || ''; - - const start = stringToGraphemes(doc.txt).length; - - if (tree.text) { - doc.txt += tree.text; - } else if (Array.isArray(tree.children)) { - tree.children.forEach((c) => { - treeToDrafty(doc, c, keymap); - }); - } - - if (tree.type) { - const len = stringToGraphemes(doc.txt).length - start; - doc.fmt = doc.fmt || []; - if (tree.data && Object.keys(tree.data).length > 0) { - doc.ent = doc.ent || []; - const oldKey = tree.key ?? 0; - const newKey = keymap[oldKey] ?? doc.ent.length; - keymap[oldKey] = newKey; - doc.ent[newKey] = { tp: tree.type, data: tree.data }; - if (tree.att) { - doc.fmt.push({ at: -1, len: 0, key: newKey }); - } else { - doc.fmt.push({ at: start, len, key: newKey }); - } - } else { - doc.fmt.push({ tp: tree.type, at: start, len }); - } - } - return doc; -} - -function treeTopDown( - src: DraftyNode | null, - transformer: (node: DraftyNode) => DraftyNode | null -): DraftyNode | null { - if (!src) { - return null; - } - - const dst = transformer(src); - if (!dst || !dst.children) { - return dst; - } - - const children: DraftyNode[] = []; - for (const child of dst.children) { - if (child) { - const n = treeTopDown(child, transformer); - if (n) { - children.push(n); - } - } - } - - dst.children = children.length === 0 ? null : children; - - return dst; -} - -function treeBottomUp( - src: DraftyNode | null, - formatter: DraftyFormatter, - index: number, - stack?: DraftyStyleType[], - context?: unknown -): R | null | undefined { - if (!src) { - return null; - } - - if (stack && src.type) { - stack.push(src.type); - } - - const childValues: (R | string)[] = []; - (src.children || []).forEach((child, i) => { - const n = treeBottomUp(child, formatter, i, stack, context); - if (n) { - childValues.push(n); - } - }); - const values = - childValues.length > 0 ? childValues : src.text ? [src.text] : null; - - if (stack && src.type) { - stack.pop(); - } - - return formatter.call(context, src.type, src.data, values, index, stack); -} - -function shortenTree( - tree: DraftyNode | null, - limit: number, - tail: string -): DraftyNode | null { - if (!tree) { - return null; - } - - if (tail) { - limit -= tail.length; - } - - const shortener = (node: DraftyNode) => { - if (limit <= -1) { - return null; - } - - if (node.att) { - return node; - } - if (limit === 0) { - node.text = tail; - limit = -1; - } else if (node.text) { - const graphemes = stringToGraphemes(node.text); - if (graphemes.length > limit) { - node.text = joinGraphemes(graphemes, 0, limit) + tail; - limit = -1; - } else { - limit -= graphemes.length; - } - } - return node; - }; - - return treeTopDown(tree, shortener); -} - -function lightEntity( - tree: DraftyNode | null, - allow?: (node: DraftyNode) => AllowedEntField[] | null | undefined -): DraftyNode | null { - const lightCopy = (node: DraftyNode) => { - const data = copyEntData(node.data, true, allow ? allow(node) : null); - if (data) { - node.data = data; - } else { - delete node.data; - } - return node; - }; - return treeTopDown(tree, lightCopy); -} - -function lTrim(tree: DraftyNode | null): DraftyNode | null { - if (!tree) { - return null; - } - if (tree.type === 'BR') { - return null; - } - if (tree.text) { - if (!tree.type) { - tree.text = tree.text.trimStart(); - if (!tree.text) { - return null; - } - } - } else if (!tree.type && tree.children && tree.children.length > 0) { - const c = lTrim(tree.children[0] ?? null); - if (c) { - tree.children[0] = c; - } else { - tree.children.shift(); - if (tree.children.length === 0) { - return null; - } - } - } - return tree; -} - -function attachmentsToEnd( - tree: DraftyNode | null, - limit: number -): DraftyNode | null { - if (!tree) { - return null; - } - - if (tree.att) { - tree.text = ' '; - delete tree.att; - delete tree.children; - } else if (tree.children) { - const attachments: DraftyNode[] = []; - const children: DraftyNode[] = []; - for (const c of tree.children) { - if (c.att) { - if (attachments.length === limit) { - continue; - } - if (Drafty.isFormResponseType(c.data?.mime)) { - continue; - } - - delete c.att; - delete c.children; - c.text = ' '; - attachments.push(c); - } else { - children.push(c); - } - } - tree.children = children.concat(attachments); - } - return tree; -} - -function extractEntities(line: string): ExtractedEntity[] { - let extracted: ExtractedEntity[] = []; - ENTITY_TYPES.forEach((entity) => { - let match: RegExpExecArray | null; - while ((match = entity.re.exec(line)) !== null) { - extracted.push({ - offset: match.index, - len: match[0].length, - unique: match[0], - data: entity.pack(match[0]), - type: entity.name, - }); - } - }); - - if (extracted.length === 0) { - return extracted; - } - - extracted.sort((a, b) => a.offset - b.offset); - - let idx = -1; - extracted = extracted.filter((el) => { - const result = el.offset > idx; - idx = el.offset + el.len; - return result; - }); - - return extracted; -} - -function draftify( - chunks: Chunk[] | undefined, - startAt: number -): { txt: string; fmt: DraftyFmt[] } { - let plain = ''; - let ranges: DraftyFmt[] = []; - for (const chunk of chunks || []) { - if (!chunk.txt) { - const drafty = draftify(chunk.children, plain.length + startAt); - chunk.txt = drafty.txt; - ranges = ranges.concat(drafty.fmt); - } - - if (chunk.tp) { - ranges.push({ - at: plain.length + startAt, - len: chunk.txt.length, - tp: chunk.tp, - }); - } - - plain += chunk.txt; - } - return { txt: plain, fmt: ranges }; -} - -function copyEntField( - src: DraftyEntData, - dst: DraftyEntData, - key: K -): void { - dst[key] = src[key]; -} - -function copyEntData( - data: DraftyEntData | undefined, - light?: boolean, - allow?: AllowedEntField[] | null -): DraftyEntData | null { - if (!data || Object.entries(data).length === 0) { - return null; - } - - const allowed = allow || []; - const dc: DraftyEntData = {}; - ALLOWED_ENT_FIELDS.forEach((key) => { - const value: unknown = data[key]; - if (!value) { - return; - } - if ( - light && - !allowed.includes(key) && - (typeof value === 'string' || Array.isArray(value)) && - value.length > MAX_PREVIEW_DATA_SIZE - ) { - return; - } - if (typeof value === 'object') { - return; - } - copyEntField(data, dc, key); - }); - - return Object.keys(dc).length !== 0 ? dc : null; -} - -function graphemeIndices(graphemes: GraphemeSegment[]): number[] { - const result: number[] = []; - let charIndex = 0; - - graphemes.forEach(({ segment }, graphemeIndex) => { - for (let i = 0; i < segment.length; i++) { - result[charIndex + i] = graphemeIndex; - } - charIndex += segment.length; - }); - - return result; -} - -function toGraphemeValues( - fmt: DraftyFmt, - segments: GraphemeSegment[], - txt: string -): { at: number; len: number } { - const indices = graphemeIndices(segments); - const at = toInt(fmt.at); - const len = toInt(fmt.len); - - const correctAt = indices[at] ?? indices.length; - const correctLen = - at + len <= txt.length - ? (indices[at + len - 1] ?? indices.length) - correctAt - : len; - - return { at: correctAt, len: correctLen + 1 }; -} - -function stringToGraphemes(str: string): GraphemeSegment[] { - return splitGraphemes(str); -} diff --git a/src/core/fnd-topic.ts b/src/core/fnd-topic.ts deleted file mode 100644 index a36ef65..0000000 --- a/src/core/fnd-topic.ts +++ /dev/null @@ -1,88 +0,0 @@ -import * as Const from './config'; -import Topic from './topic'; -import type { TopicCallbacks } from './topic'; -import type { CtrlMessage, SetParams, TopicSubscription } from './types'; -import { mergeToCache } from './utils'; - -export type FoundContactCallback = ( - contact: TopicSubscription, - key: string, - all: Record -) => void; - -export default class TopicFnd extends Topic { - _contacts: Record = {}; - - constructor(callbacks?: TopicCallbacks) { - super(Const.TOPIC_FND, callbacks); - } - - override _processMetaSubs(subs: TopicSubscription[]): void { - let updateCount = Object.getOwnPropertyNames(this._contacts).length; - this._contacts = {}; - for (const item of subs) { - const indexBy = item.topic ? item.topic : item.user; - if (!indexBy) { - continue; - } - - const sub = mergeToCache(this._contacts, indexBy, item); - updateCount++; - - if (this.onMetaSub) { - this.onMetaSub(sub); - } - } - - if (updateCount > 0 && this.onSubsUpdated) { - this.onSubsUpdated(Object.keys(this._contacts)); - } - } - - override publish(): Promise { - return Promise.reject(new Error("Publishing to 'fnd' is not supported")); - } - - override setMeta(params: SetParams): Promise { - return super.setMeta(params).then((ctrl) => { - if (Object.keys(this._contacts).length > 0) { - this._contacts = {}; - if (this.onSubsUpdated) { - this.onSubsUpdated([]); - } - } - return ctrl; - }); - } - - checkTagUniqueness(tag: string, caller: string): Promise { - return this.subscribe() - .then(() => - this.setMeta({ - desc: { - public: tag, - }, - }) - ) - .then(() => this.getMeta(this.startMetaQuery().withTags().build())) - .then((meta) => { - const tags = 'tags' in meta ? meta.tags : undefined; - if (!Array.isArray(tags) || tags.length === 0) { - return true; - } - return tags.filter((t) => t !== caller).length === 0; - }); - } - - contacts(callback?: FoundContactCallback, context?: unknown): void { - const cb = callback || this.onMetaSub; - if (cb) { - for (const idx in this._contacts) { - const contact = this._contacts[idx]; - if (contact) { - cb.call(context, contact, idx, this._contacts); - } - } - } - } -} diff --git a/src/core/graphemes.ts b/src/core/graphemes.ts deleted file mode 100644 index fd755d9..0000000 --- a/src/core/graphemes.ts +++ /dev/null @@ -1,166 +0,0 @@ -export interface GraphemeSegment { - readonly segment: string; - readonly index: number; -} - -type CodePointRange = readonly [number, number]; -type CodePointTest = (codePoint: number) => boolean; - -const CARRIAGE_RETURN = 0x0d; -const LINE_FEED = 0x0a; -const ZERO_WIDTH_JOINER = 0x200d; - -const COMBINING_MARK_RANGES: readonly CodePointRange[] = [ - [0x0300, 0x036f], - [0x0483, 0x0489], - [0x0591, 0x05bd], - [0x0610, 0x061a], - [0x064b, 0x065f], - [0x0900, 0x0903], - [0x093a, 0x094f], - [0x1ab0, 0x1aff], - [0x1dc0, 0x1dff], - [0x20d0, 0x20ff], - [0xfe00, 0xfe0f], - [0xfe20, 0xfe2f], - [0xe0100, 0xe01ef], -]; - -const PICTOGRAPHIC_RANGES: readonly CodePointRange[] = [ - [0x00a9, 0x00a9], - [0x00ae, 0x00ae], - [0x203c, 0x203c], - [0x2049, 0x2049], - [0x2122, 0x2122], - [0x2139, 0x2139], - [0x2194, 0x21aa], - [0x231a, 0x23ff], - [0x24c2, 0x24c2], - [0x25aa, 0x25fe], - [0x2600, 0x27bf], - [0x2934, 0x2935], - [0x2b05, 0x2b55], - [0x3030, 0x3030], - [0x303d, 0x303d], - [0x3297, 0x3297], - [0x3299, 0x3299], - [0x1f000, 0x1faff], - [0x1fc00, 0x1fffd], -]; - -const REGIONAL_INDICATOR: CodePointRange = [0x1f1e6, 0x1f1ff]; -const EMOJI_MODIFIER: CodePointRange = [0x1f3fb, 0x1f3ff]; -const TAG_CHARACTER: CodePointRange = [0xe0020, 0xe007f]; - -function inRange(codePoint: number, [low, high]: CodePointRange): boolean { - return codePoint >= low && codePoint <= high; -} - -function unicodePropertyTest( - property: string, - fallback: readonly CodePointRange[] -): CodePointTest { - try { - const pattern = new RegExp(`^\\p{${property}}$`, 'u'); - return (codePoint) => pattern.test(String.fromCodePoint(codePoint)); - } catch { - return (codePoint) => fallback.some((range) => inRange(codePoint, range)); - } -} - -const isCombiningMark = unicodePropertyTest('M', COMBINING_MARK_RANGES); -const isPictographic = unicodePropertyTest( - 'Extended_Pictographic', - PICTOGRAPHIC_RANGES -); - -function isControl(codePoint: number): boolean { - return codePoint < 0x20 || (codePoint >= 0x7f && codePoint <= 0x9f); -} - -function isRegionalIndicator(codePoint: number): boolean { - return inRange(codePoint, REGIONAL_INDICATOR); -} - -function isClusterExtender(codePoint: number): boolean { - return ( - codePoint === ZERO_WIDTH_JOINER || - isCombiningMark(codePoint) || - inRange(codePoint, EMOJI_MODIFIER) || - inRange(codePoint, TAG_CHARACTER) - ); -} - -function continuesCluster( - previous: number, - current: number, - regionalIndicatorRun: number -): boolean { - if (previous === CARRIAGE_RETURN) { - return current === LINE_FEED; - } - if (isControl(previous) || isControl(current)) { - return false; - } - if (isClusterExtender(current)) { - return true; - } - if (previous === ZERO_WIDTH_JOINER) { - return isPictographic(current); - } - return isRegionalIndicator(current) && regionalIndicatorRun % 2 === 1; -} - -export function splitGraphemesFallback(str: string): GraphemeSegment[] { - const segments: GraphemeSegment[] = []; - let segment = ''; - let segmentStart = 0; - let offset = 0; - let previous = -1; - let regionalIndicatorRun = 0; - - for (const char of str) { - const codePoint = char.codePointAt(0) ?? 0; - if ( - segment && - continuesCluster(previous, codePoint, regionalIndicatorRun) - ) { - segment += char; - } else { - if (segment) { - segments.push({ segment, index: segmentStart }); - } - segment = char; - segmentStart = offset; - } - regionalIndicatorRun = isRegionalIndicator(codePoint) - ? regionalIndicatorRun + 1 - : 0; - previous = codePoint; - offset += char.length; - } - - if (segment) { - segments.push({ segment, index: segmentStart }); - } - return segments; -} - -function createNativeSegmenter(): Intl.Segmenter | null { - if (typeof Intl === 'undefined' || typeof Intl.Segmenter !== 'function') { - return null; - } - return new Intl.Segmenter(); -} - -const nativeSegmenter = createNativeSegmenter(); - -export function splitGraphemes(str: string): GraphemeSegment[] { - if (!nativeSegmenter) { - return splitGraphemesFallback(str); - } - return Array.from(nativeSegmenter.segment(str), ({ segment, index }) => ({ - segment, - index, - })); -} diff --git a/src/core/large-file.ts b/src/core/large-file.ts deleted file mode 100644 index 850b4cc..0000000 --- a/src/core/large-file.ts +++ /dev/null @@ -1,466 +0,0 @@ -import CommError from './comm-error'; -import { isUrlRelative, jsonParseHelper } from './utils'; -import type { Tinode } from './tinode'; - -type Handler = { bivarianceHack(evt: E): void }['bivarianceHack']; - -export interface UploadProgressEventLike { - lengthComputable: boolean; - loaded: number; - total: number; -} - -export interface XHRLike { - readyState: number; - status: number; - statusText: string; - response: unknown; - responseType: string; - upload: { onprogress: Handler | null }; - onload: Handler | null; - onerror: Handler | null; - onabort: Handler | null; - onprogress: Handler<{ loaded: number }> | null; - open(method: string, url: string, async: boolean): void; - setRequestHeader(name: string, value: string): void; - send(body?: FormData | null): void; - abort(): void; -} - -export type XHRProviderType = new () => XHRLike; - -export type LargeFileTinode = Pick< - Tinode, - | '_apiKey' - | '_secure' - | '_host' - | 'getAuthToken' - | 'getNextUniqueId' - | 'logger' ->; - -export interface ReactNativeFileDescriptor { - uri: string; - name: string; - type: string; -} - -export type UploadData = Blob | ReactNativeFileDescriptor; - -export interface ServerCtrl { - code: number; - text: string; - params?: Record; -} - -export type ProgressCallback = (progress: number) => void; -export type SuccessCallback = (ctrl: ServerCtrl) => void; -export type FailureCallback = (ctrl: ServerCtrl | null) => void; -export type DownloadErrorCallback = (err: unknown) => void; - -interface BrowserAnchor { - href: string; - style: { display: string }; - setAttribute(name: string, value: string): void; - click(): void; -} - -interface BrowserDocument { - createElement(tag: 'a'): BrowserAnchor; - body: { - appendChild(node: BrowserAnchor): void; - removeChild(node: BrowserAnchor): void; - }; -} - -interface ObjectUrlFactory { - createObjectURL(blob: Blob): string; - revokeObjectURL(url: string): void; -} - -let XHRProvider: XHRProviderType | undefined; - -function resolveXHRProvider(): XHRProviderType { - const provider = XHRProvider ?? globalThis.XMLHttpRequest; - if (!provider) { - throw new Error( - "XMLHttpRequest is not available. Call 'LargeFileHelper.setNetworkProvider()'." - ); - } - return provider; -} - -function isBlob(value: unknown): value is Blob { - return typeof Blob !== 'undefined' && value instanceof Blob; -} - -function isObject(value: unknown): value is Record { - return typeof value === 'object' && value !== null; -} - -function isBrowserDocument(value: unknown): value is BrowserDocument { - return ( - isObject(value) && - typeof value.createElement === 'function' && - isObject(value.body) - ); -} - -function isObjectUrlFactory(value: unknown): value is ObjectUrlFactory { - return ( - (typeof value === 'function' || isObject(value)) && - typeof Reflect.get(value, 'createObjectURL') === 'function' && - typeof Reflect.get(value, 'revokeObjectURL') === 'function' - ); -} - -function getBrowserDocument(): BrowserDocument | null { - const candidate: unknown = Reflect.get(globalThis, 'document'); - return isBrowserDocument(candidate) ? candidate : null; -} - -function getObjectUrlFactory(): ObjectUrlFactory | null { - const candidate: unknown = Reflect.get(globalThis, 'URL'); - return isObjectUrlFactory(candidate) ? candidate : null; -} - -interface Deferred { - promise: Promise; - resolve: (value: T) => void; - reject: (reason: unknown) => void; -} - -function createDeferred(): Deferred { - let resolve: (value: T) => void = () => {}; - let reject: (reason: unknown) => void = () => {}; - const promise = new Promise((res, rej) => { - resolve = res; - reject = rej; - }); - return { promise, resolve, reject }; -} - -function parseCtrl( - response: unknown, - status: number, - statusText: string, - onInvalid: () => void -): ServerCtrl { - try { - if (typeof response === 'string') { - const packet: unknown = JSON.parse(response, jsonParseHelper); - if (isObject(packet) && isObject(packet.ctrl)) { - const { code, text, params } = packet.ctrl; - return { - code: typeof code === 'number' ? code : status, - text: typeof text === 'string' ? text : statusText, - params: isObject(params) ? params : undefined, - }; - } - } - } catch { - onInvalid(); - } - return { code: status, text: statusText }; -} - -export function addURLParam(url: string, key: string, value: string): string { - const hashIndex = url.indexOf('#'); - const hash = hashIndex >= 0 ? url.substring(hashIndex) : ''; - const withoutHash = hashIndex >= 0 ? url.substring(0, hashIndex) : url; - const separator = withoutHash.includes('?') ? '&' : '?'; - const param = `${encodeURIComponent(key)}=${encodeURIComponent(value)}`; - const joined = - withoutHash.endsWith('?') || withoutHash.endsWith('&') - ? withoutHash + param - : withoutHash + separator + param; - return joined + hash; -} - -export default class LargeFileHelper { - _tinode: LargeFileTinode; - _version: string; - _apiKey: string; - _authToken: ReturnType; - xhr: XHRLike[]; - onProgress: ProgressCallback | undefined = undefined; - - constructor(tinode: LargeFileTinode, version: string) { - this._tinode = tinode; - this._version = version; - - this._apiKey = tinode._apiKey; - this._authToken = tinode.getAuthToken(); - - this.xhr = []; - } - - uploadWithBaseUrl( - baseUrl: string | null | undefined, - data: UploadData, - avatarFor?: string | null, - onProgress?: ProgressCallback | null, - onSuccess?: SuccessCallback | null, - onFailure?: FailureCallback | null - ): Promise { - let url = `/v${this._version}/file/u/`; - if (baseUrl) { - let base = baseUrl; - if (base.endsWith('/')) { - base = base.slice(0, -1); - } - if (base.startsWith('http://') || base.startsWith('https://')) { - url = base + url; - } else { - throw new Error(`Invalid base URL '${baseUrl}'`); - } - } - - const Provider = resolveXHRProvider(); - const xhr = new Provider(); - this.xhr.push(xhr); - - xhr.open('POST', url, true); - xhr.setRequestHeader('X-Tinode-APIKey', this._apiKey); - if (this._authToken) { - xhr.setRequestHeader('X-Tinode-Auth', `Token ${this._authToken.token}`); - } - - const deferred = createDeferred(); - const result = deferred.promise; - const toResolve = deferred.resolve; - const toReject = deferred.reject; - - xhr.upload.onprogress = (e) => { - if (e.lengthComputable) { - if (onProgress) { - onProgress(e.loaded / e.total); - } - if (this.onProgress) { - this.onProgress(e.loaded / e.total); - } - } - }; - - xhr.onload = () => { - const ctrl = parseCtrl(xhr.response, xhr.status, xhr.statusText, () => - this._tinode.logger( - 'ERROR: Invalid server response in LargeFileHelper', - xhr.response - ) - ); - - if (xhr.status >= 200 && xhr.status < 300) { - const uploadedUrl = ctrl.params?.url; - if (typeof uploadedUrl === 'string') { - toResolve(uploadedUrl); - } else toReject(new CommError(ctrl.text, ctrl.code)); - if (onSuccess) { - onSuccess(ctrl); - } - } else if (xhr.status >= 400) { - toReject(new CommError(ctrl.text, ctrl.code)); - if (onFailure) { - onFailure(ctrl); - } - } else { - this._tinode.logger( - 'ERROR: Unexpected server response status', - xhr.status, - xhr.response - ); - } - }; - - xhr.onerror = (e) => { - toReject(e || new Error('failed')); - if (onFailure) { - onFailure(null); - } - }; - - xhr.onabort = () => { - toReject(new Error('upload cancelled by user')); - if (onFailure) { - onFailure(null); - } - }; - - try { - const form = new FormData(); - form.append('file', data); - const id = this._tinode.getNextUniqueId(); - if (id) { - form.append('id', id); - } - if (avatarFor) { - form.append('topic', avatarFor); - } - xhr.send(form); - } catch (err) { - toReject(err); - if (onFailure) { - onFailure(null); - } - } - - return result; - } - - upload( - data: UploadData, - avatarFor?: string | null, - onProgress?: ProgressCallback | null, - onSuccess?: SuccessCallback | null, - onFailure?: FailureCallback | null - ): Promise { - const baseUrl = - (this._tinode._secure ? 'https://' : 'http://') + this._tinode._host; - return this.uploadWithBaseUrl( - baseUrl, - data, - avatarFor, - onProgress, - onSuccess, - onFailure - ); - } - - download( - relativeUrl: string, - filename?: string, - mimetype?: string, - onProgress?: ProgressCallback | null, - onError?: DownloadErrorCallback | null - ): Promise | undefined { - if (!isUrlRelative(relativeUrl)) { - if (onError) { - onError(`The URL '${relativeUrl}' must be relative, not absolute`); - } - return; - } - if (!this._authToken) { - if (onError) { - onError('Must authenticate first'); - } - return; - } - - const Provider = resolveXHRProvider(); - const xhr = new Provider(); - this.xhr.push(xhr); - - const url = addURLParam(relativeUrl, 'asatt', '1'); - - xhr.open('GET', url, true); - xhr.setRequestHeader('X-Tinode-APIKey', this._apiKey); - xhr.setRequestHeader('X-Tinode-Auth', 'Token ' + this._authToken.token); - xhr.responseType = 'blob'; - - xhr.onprogress = (e) => { - if (onProgress) { - onProgress(e.loaded); - } - }; - - const deferred = createDeferred(); - const result = deferred.promise; - const toResolve = deferred.resolve; - const toReject = deferred.reject; - - const saveInBrowser = (doc: BrowserDocument, blob: Blob): void => { - const objectUrls = getObjectUrlFactory(); - if (!objectUrls) { - throw new Error('URL.createObjectURL is not available'); - } - const link = doc.createElement('a'); - link.href = objectUrls.createObjectURL( - new Blob([blob], { type: mimetype ?? '', lastModified: Date.now() }) - ); - link.style.display = 'none'; - link.setAttribute('download', filename ?? ''); - doc.body.appendChild(link); - link.click(); - doc.body.removeChild(link); - objectUrls.revokeObjectURL(link.href); - }; - - xhr.onload = () => { - if (xhr.status === 200) { - const doc = getBrowserDocument(); - try { - if (!isBlob(xhr.response)) { - throw new Error('Server response is not a Blob'); - } - if (doc) { - saveInBrowser(doc, xhr.response); - toResolve(); - } else toResolve(xhr.response); - } catch (err) { - toReject(err); - } - } else if (xhr.status >= 400) { - const reject = toReject; - const reader = new FileReader(); - reader.onload = () => { - try { - const pkt: unknown = JSON.parse( - String(reader.result), - jsonParseHelper - ); - const ctrl = isObject(pkt) ? pkt.ctrl : undefined; - if (!isObject(ctrl)) { - throw new Error('Invalid server response'); - } - reject(new CommError(String(ctrl.text), Number(ctrl.code))); - } catch (err) { - this._tinode.logger( - 'ERROR: Invalid server response in LargeFileHelper', - reader.result - ); - reject(err); - } - }; - if (isBlob(xhr.response)) { - reader.readAsText(xhr.response); - } else { - reject(new CommError('Download failed', xhr.status)); - } - } - }; - - xhr.onerror = (e) => { - toReject(new Error('failed')); - if (onError) { - onError(e); - } - }; - - xhr.onabort = () => { - toReject(null); - }; - - try { - xhr.send(); - } catch (err) { - toReject(err); - if (onError) { - onError(err); - } - } - - return result; - } - - cancel(): void { - this.xhr.forEach((req) => { - if (req.readyState < 4) { - req.abort(); - } - }); - } - - static setNetworkProvider(xhrProvider?: XHRProviderType): void { - XHRProvider = xhrProvider; - } -} diff --git a/src/core/me-topic.ts b/src/core/me-topic.ts deleted file mode 100644 index aef8a97..0000000 --- a/src/core/me-topic.ts +++ /dev/null @@ -1,403 +0,0 @@ -import AccessMode from './access-mode'; -import * as Const from './config'; -import Topic from './topic'; -import type { TopicCallbacks } from './topic'; -import type { - Credential, - CtrlMessage, - PresMessage, - PresWhat, - TopicDesc, - TopicSubscription, -} from './types'; -import { mergeObj } from './utils'; - -export type ContactCallback = (contact: Topic, key: string) => void; - -export interface TopicMeCallbacks extends TopicCallbacks { - onContactUpdate?: (what: PresWhat, cont: Topic) => void; -} - -export default class TopicMe extends Topic { - onContactUpdate: TopicMeCallbacks['onContactUpdate']; - - constructor(callbacks?: TopicMeCallbacks) { - super(Const.TOPIC_ME, callbacks); - this.onContactUpdate = callbacks?.onContactUpdate; - } - - override _processMetaDesc(desc: TopicDesc): void { - const turnOff = - desc.acs && !desc.acs.isPresencer() && this.acs && this.acs.isPresencer(); - - mergeObj(this, desc); - this._tinode._db.updTopic(this); - const myUID = this._tinode._myUID; - if (myUID) { - this._updateCachedUser(myUID, desc); - } - - if (turnOff) { - this._tinode.mapTopics((cont) => { - if (cont.online) { - cont.online = false; - cont.seen = Object.assign(cont.seen || {}, { - when: new Date(), - }); - this._refreshContact('off', cont); - } - }); - } - - if (this.onMetaDesc) { - this.onMetaDesc(this); - } - } - - override _processMetaSubs(subs: TopicSubscription[]): void { - let updateCount = 0; - subs.forEach((sub) => { - const topicName = sub.topic; - if ( - !topicName || - topicName === Const.TOPIC_FND || - topicName === Const.TOPIC_ME - ) { - return; - } - sub.online = !!sub.online; - - let cont: TopicSubscription; - if (sub.deleted) { - cont = sub; - this._tinode.cacheRemTopic(topicName); - this._tinode._db.remTopic(topicName); - } else { - if (typeof sub.seq !== 'undefined') { - sub.seq = sub.seq | 0; - sub.recv = (sub.recv ?? 0) | 0; - sub.read = (sub.read ?? 0) | 0; - sub.unread = sub.seq - sub.read; - } - - const topic = this._tinode.getTopic(topicName); - if (!topic) { - return; - } - if (topic._new) { - delete topic._new; - } - - const merged = mergeObj(topic, sub); - cont = merged; - this._tinode._db.updTopic(merged); - - if (Topic.isP2PTopicName(topicName)) { - this._cachePutUser(topicName, merged); - this._tinode._db.updUser(topicName, merged.public); - } - if (!sub._noForwarding) { - sub._noForwarding = true; - topic._processMetaDesc(sub); - } - } - - updateCount++; - - if (this.onMetaSub) { - this.onMetaSub(cont); - } - }); - - if (this.onSubsUpdated && updateCount > 0) { - const keys: string[] = []; - subs.forEach((s) => { - if (s.topic) { - keys.push(s.topic); - } - }); - this.onSubsUpdated(keys, updateCount); - } - } - - override _processMetaCreds(creds: Credential[], upd?: boolean): void { - const first: unknown = creds[0]; - if (creds.length === 1 && first === Const.DEL_CHAR) { - creds = []; - } - if (upd) { - creds.forEach((cr) => { - if (cr.val) { - let idx = this._credentials.findIndex( - (el) => el.meth === cr.meth && el.val === cr.val - ); - if (idx < 0) { - if (!cr.done) { - idx = this._credentials.findIndex( - (el) => el.meth === cr.meth && !el.done - ); - if (idx >= 0) { - this._credentials.splice(idx, 1); - } - } - this._credentials.push(cr); - } else { - const found = this._credentials[idx]; - if (found) { - found.done = cr.done; - } - } - } else if (cr.resp) { - const found = this._credentials.find( - (el) => el.meth === cr.meth && !el.done - ); - if (found) { - found.done = true; - } - } - }); - } else { - this._credentials = creds; - } - if (this.onCredsUpdated) { - this.onCredsUpdated(this._credentials); - } - } - - override _routePres(pres: PresMessage): void { - if (pres.what === 'term') { - this._resetSub(); - return; - } - - if (pres.what === 'upd' && pres.src === Const.TOPIC_ME) { - this.getMeta(this.startMetaQuery().withDesc().build()); - return; - } - - const cont = this._tinode.cacheGetTopic(pres.src); - if (cont) { - switch (pres.what) { - case 'on': - cont.online = true; - break; - case 'off': - if (cont.online) { - cont.online = false; - cont.seen = Object.assign(cont.seen || {}, { - when: new Date(), - }); - } - break; - case 'msg': - cont._updateReceived(pres.seq, pres.act); - break; - case 'upd': - this.getMeta(this.startMetaQuery().withLaterOneSub(pres.src).build()); - break; - case 'acs': - if (!pres.tgt) { - if (cont.acs) { - cont.acs.updateAll(pres.dacs); - } else { - cont.acs = new AccessMode().updateAll(pres.dacs); - } - cont.touched = new Date(); - } - break; - case 'ua': - cont.seen = { - when: new Date(), - ua: pres.ua, - }; - break; - case 'recv': { - const seq = (pres.seq ?? 0) | 0; - pres.seq = seq; - cont.recv = cont.recv ? Math.max(cont.recv, seq) : seq; - break; - } - case 'read': { - const seq = (pres.seq ?? 0) | 0; - pres.seq = seq; - cont.read = cont.read ? Math.max(cont.read, seq) : seq; - cont.recv = cont.recv ? Math.max(cont.read, cont.recv) : cont.recv; - cont.unread = cont.seq - cont.read; - break; - } - case 'gone': - if (pres.src) { - this._tinode.cacheRemTopic(pres.src); - if (!cont._deleted) { - cont._deleted = true; - cont._attached = false; - this._tinode._db.markTopicAsDeleted(pres.src, true); - } else { - this._tinode._db.remTopic(pres.src); - } - } - break; - case 'del': - break; - default: - this._tinode.logger( - "INFO: Unsupported presence update in 'me'", - pres.what - ); - } - - this._refreshContact(pres.what, cont); - } else if (pres.what === 'acs') { - const acs = new AccessMode(pres.dacs); - if (!acs || acs.mode === AccessMode._INVALID) { - this._tinode.logger( - 'ERROR: Invalid access mode update', - pres.src, - pres.dacs - ); - return; - } else if (acs.mode === AccessMode._NONE) { - this._tinode.logger( - 'WARNING: Removing non-existent subscription', - pres.src, - pres.dacs - ); - return; - } else if (pres.src) { - this.getMeta( - this.startMetaQuery().withOneSub(undefined, pres.src).build() - ); - const dummy = this._tinode.getTopic(pres.src); - if (dummy) { - dummy.topic = pres.src; - dummy.online = false; - dummy.acs = acs; - this._tinode._db.updTopic(dummy); - } - } - } else if (pres.what === 'tags') { - this.getMeta(this.startMetaQuery().withTags().build()); - } else if (pres.what === 'msg' && pres.src) { - this.getMeta( - this.startMetaQuery().withOneSub(undefined, pres.src).build() - ); - const dummy = this._tinode.getTopic(pres.src); - if (dummy) { - dummy._deleted = false; - this._tinode._db.updTopic(dummy); - } - } - - if (this.onPres) { - this.onPres(pres); - } - } - - _refreshContact(what: PresWhat, cont: Topic): void { - if (this.onContactUpdate) { - this.onContactUpdate(what, cont); - } - } - - override publish(): Promise { - return Promise.reject(new Error("Publishing to 'me' is not supported")); - } - - delCredential(method: string, value: string): Promise { - if (!this._attached) { - return Promise.reject( - new Error("Cannot delete credential in inactive 'me' topic") - ); - } - return this._tinode.delCredential(method, value).then((ctrl) => { - const index = this._credentials.findIndex( - (el) => el.meth === method && el.val === value - ); - if (index > -1) { - this._credentials.splice(index, 1); - } - if (this.onCredsUpdated) { - this.onCredsUpdated(this._credentials); - } - return ctrl; - }); - } - - contacts( - callback: ContactCallback, - filter?: ((contact: Topic) => boolean) | null, - context?: unknown - ): void { - this._tinode.mapTopics((c, idx) => { - if (c.isCommType() && (!filter || filter(c))) { - callback.call(context, c, idx); - } - }); - } - - getContact(name: string): Topic | undefined { - return this._tinode.cacheGetTopic(name); - } - - override getAccessMode(): AccessMode; - override getAccessMode(name?: string): AccessMode | null; - override getAccessMode(name?: string): AccessMode | null { - if (name) { - const cont = this._tinode.cacheGetTopic(name); - return cont ? cont.acs : null; - } - return this.acs; - } - - override isArchived(name?: string): boolean { - const cont = this._tinode.cacheGetTopic(name); - return !!cont?.private?.arch; - } - - getCredentials(): Credential[] { - return this._credentials; - } - - override pinTopic( - topic: string, - pin?: boolean - ): Promise { - if (!this._attached) { - return Promise.reject( - new Error("Cannot pin topic in inactive 'me' topic") - ); - } - if (!Topic.isCommTopicName(topic)) { - return Promise.reject(new Error('Invalid topic to pin')); - } - - const tpin = Array.isArray(this.private?.tpin) ? this.private.tpin : []; - const found = tpin.includes(topic); - if ((pin && found) || (!pin && !found)) { - return Promise.resolve(tpin); - } - - if (pin) { - tpin.unshift(topic); - } else { - tpin.splice(tpin.indexOf(topic), 1); - } - - return this.setMeta({ - desc: { - private: { - tpin: tpin.length > 0 ? tpin : Const.DEL_CHAR, - }, - }, - }); - } - - override pinnedTopicRank(topic: string): number { - const tpin = this.private?.tpin; - if (!tpin) { - return 0; - } - const idx = tpin.indexOf(topic); - return idx < 0 ? 0 : tpin.length - idx; - } -} diff --git a/src/core/meta-builder.ts b/src/core/meta-builder.ts deleted file mode 100644 index 892e0f4..0000000 --- a/src/core/meta-builder.ts +++ /dev/null @@ -1,220 +0,0 @@ -import type Topic from './topic'; -import { listToRanges, normalizeRanges } from './utils'; -import type { SeqRange } from './utils'; - -export interface GetOptsType { - ims?: Date; - limit?: number; -} - -export interface GetSubType extends GetOptsType { - user?: string; - topic?: string; -} - -export interface GetDataType { - since?: number; - before?: number; - limit?: number; - ranges?: SeqRange[]; -} - -export interface GetDelType { - since?: number; - limit?: number; -} - -export interface GetQuery { - what?: string; - desc?: GetOptsType; - sub?: GetSubType; - data?: GetDataType; - del?: GetDelType; -} - -export interface MetaWhat { - data?: GetDataType; - sub?: GetSubType; - desc?: GetOptsType; - tags?: true; - cred?: true; - aux?: true; - del?: GetDelType; -} - -export type MetaWhatKey = keyof MetaWhat; - -function hasOwnProperties(value: object): boolean { - return Object.getOwnPropertyNames(value).length > 0; -} - -export default class MetaGetBuilder { - topic: Topic; - what: MetaWhat = {}; - - constructor(parent: Topic) { - this.topic = parent; - } - - #get_desc_ims(): Date | undefined { - return this.topic._deleted ? undefined : this.topic.updated; - } - - #get_subs_ims(): Date | undefined { - if (this.topic.isP2PType()) { - return this.#get_desc_ims(); - } - return this.topic._deleted ? undefined : this.topic._lastSubsUpdate; - } - - withData(since?: number, before?: number, limit?: number): this { - this.what.data = { since, before, limit }; - return this; - } - - withLaterData(limit?: number): this { - return this.withData( - this.topic._maxSeq > 0 ? this.topic._maxSeq + 1 : undefined, - undefined, - limit - ); - } - - withDataRanges(ranges: SeqRange[], limit?: number): this { - this.what.data = { - ranges: normalizeRanges(ranges, this.topic._maxSeq), - limit, - }; - return this; - } - - withDataList(list: number[]): this { - return this.withDataRanges(listToRanges(list)); - } - - withEarlierData(limit?: number): this { - return this.withData( - undefined, - this.topic._minSeq > 0 ? this.topic._minSeq : undefined, - limit - ); - } - - withDesc(ims?: Date): this { - this.what.desc = { ims }; - return this; - } - - withLaterDesc(): this { - return this.withDesc(this.#get_desc_ims()); - } - - withSub(ims?: Date, limit?: number, userOrTopic?: string): this { - const opts: GetSubType = { ims, limit }; - if (this.topic.getType() === 'me') { - opts.topic = userOrTopic; - } else { - opts.user = userOrTopic; - } - this.what.sub = opts; - return this; - } - - withOneSub(ims?: Date, userOrTopic?: string): this { - return this.withSub(ims, undefined, userOrTopic); - } - - withLaterOneSub(userOrTopic?: string): this { - return this.withOneSub(this.topic._lastSubsUpdate, userOrTopic); - } - - withLaterSub(limit?: number): this { - return this.withSub(this.#get_subs_ims(), limit); - } - - withTags(): this { - this.what.tags = true; - return this; - } - - withCred(): this { - if (this.topic.getType() === 'me') { - this.what.cred = true; - } else { - this.topic._tinode.logger( - 'ERROR: Invalid topic type for MetaGetBuilder:withCreds', - this.topic.getType() - ); - } - return this; - } - - withAux(): this { - this.what.aux = true; - return this; - } - - withDel(since?: number, limit?: number): this { - if (since || limit) { - this.what.del = { since, limit }; - } - return this; - } - - withLaterDel(limit?: number): this { - return this.withDel( - this.topic._maxSeq > 0 ? this.topic._maxDel + 1 : undefined, - limit - ); - } - - extract(what: K): MetaWhat[K] { - return this.what[what]; - } - - build(): GetQuery | undefined { - const what: string[] = []; - const params: GetQuery = {}; - const { data, sub, desc, tags, cred, aux, del } = this.what; - - if (data) { - what.push('data'); - if (hasOwnProperties(data)) { - params.data = data; - } - } - if (sub) { - what.push('sub'); - if (hasOwnProperties(sub)) { - params.sub = sub; - } - } - if (desc) { - what.push('desc'); - if (hasOwnProperties(desc)) { - params.desc = desc; - } - } - if (tags) { - what.push('tags'); - } - if (cred) { - what.push('cred'); - } - if (aux) { - what.push('aux'); - } - if (del) { - what.push('del'); - if (hasOwnProperties(del)) { - params.del = del; - } - } - - if (what.length === 0) { - return undefined; - } - params.what = what.join(' '); - return params; - } -} diff --git a/src/core/storage/indexeddb-adapter.ts b/src/core/storage/indexeddb-adapter.ts deleted file mode 100644 index ba16efc..0000000 --- a/src/core/storage/indexeddb-adapter.ts +++ /dev/null @@ -1,557 +0,0 @@ -import { - MAX_SEQ, - type DelLogRange, - type DelLogRecord, - type MessageRecord, - type SeqRange, - type SeqWindow, - type StorageAdapter, - type SubscriptionRecord, - type TopicRecord, - type UserRecord, -} from './storage-adapter'; - -const DB_VERSION = 3; -const DB_NAME = 'tinode-web'; - -const STORE_TOPIC = 'topic'; -const STORE_USER = 'user'; -const STORE_SUBSCRIPTION = 'subscription'; -const STORE_MESSAGE = 'message'; -const STORE_DELLOG = 'dellog'; -const INDEX_TOPIC_CLEAR = 'topic_clear'; - -const KEY_LOW_STRING = '-'; -const KEY_HIGH_STRING = '~'; - -export interface IdbRequest { - result: T; - error: unknown; - onsuccess: (() => void) | null; - onerror: (() => void) | null; -} - -export interface IdbOpenRequest extends IdbRequest { - onupgradeneeded: (() => void) | null; - onblocked: (() => void) | null; -} - -export interface IdbCursor { - value: T; - continue(): void; -} - -export interface IdbIndex { - openCursor( - range: unknown, - direction: 'prev' - ): IdbRequest | null>; -} - -export interface IdbObjectStore { - indexNames: { contains(name: string): boolean }; - get(key: unknown): IdbRequest; - getAll(range?: unknown): IdbRequest; - put(value: object): IdbRequest; - delete(key: unknown): IdbRequest; - openCursor( - range: unknown, - direction: 'prev' - ): IdbRequest | null>; - index(name: string): IdbIndex; - createIndex( - name: string, - keyPath: string[], - options: { unique: boolean } - ): unknown; -} - -export interface IdbTransaction { - error: unknown; - oncomplete: (() => void) | null; - onerror: (() => void) | null; - onabort: (() => void) | null; - objectStore(name: string): IdbObjectStore; -} - -export interface IdbDatabase { - objectStoreNames: { contains(name: string): boolean }; - onversionchange: (() => void) | null; - transaction(stores: string[], mode?: 'readwrite'): IdbTransaction; - createObjectStore( - name: string, - options: { keyPath: string | string[] } - ): IdbObjectStore; - close(): void; -} - -export interface IdbFactory { - open(name: string, version: number): IdbOpenRequest; - deleteDatabase(name: string): IdbRequest & { - onblocked: (() => void) | null; - }; -} - -export interface IdbKeyRangeStatic { - only(value: unknown): unknown; - bound( - lower: unknown, - upper: unknown, - lowerOpen?: boolean, - upperOpen?: boolean - ): unknown; -} - -export interface IndexedDBProvider { - factory: IdbFactory; - keyRange: IdbKeyRangeStatic; -} - -function hasFunctions(value: unknown, names: string[]): boolean { - return ( - (typeof value === 'object' || typeof value === 'function') && - value !== null && - names.every((name) => typeof Reflect.get(value, name) === 'function') - ); -} - -function isIdbFactory(value: unknown): value is IdbFactory { - return hasFunctions(value, ['open', 'deleteDatabase']); -} - -function isIdbKeyRange(value: unknown): value is IdbKeyRangeStatic { - return hasFunctions(value, ['only', 'bound']); -} - -function detectProvider(): IndexedDBProvider | null { - const factory: unknown = Reflect.get(globalThis, 'indexedDB'); - const keyRange: unknown = Reflect.get(globalThis, 'IDBKeyRange'); - return isIdbFactory(factory) && isIdbKeyRange(keyRange) - ? { factory, keyRange } - : null; -} - -function requestResult(request: IdbRequest): Promise { - return new Promise((resolve, reject) => { - request.onsuccess = () => resolve(request.result); - request.onerror = () => reject(request.error); - }); -} - -function transactionDone(transaction: IdbTransaction): Promise { - return new Promise((resolve, reject) => { - transaction.oncomplete = () => resolve(); - transaction.onerror = () => reject(transaction.error); - transaction.onabort = () => reject(transaction.error); - }); -} - -function isNonEmptyRange(range: SeqRange): boolean { - return !range.hi || range.hi > range.low; -} - -function toDelLogRange(entry: DelLogRecord): DelLogRange { - return { low: entry.low, hi: entry.hi }; -} - -function createStores(db: IdbDatabase): void { - if (!db.objectStoreNames.contains(STORE_TOPIC)) { - db.createObjectStore(STORE_TOPIC, { keyPath: 'name' }); - } - if (!db.objectStoreNames.contains(STORE_USER)) { - db.createObjectStore(STORE_USER, { keyPath: 'uid' }); - } - if (!db.objectStoreNames.contains(STORE_SUBSCRIPTION)) { - db.createObjectStore(STORE_SUBSCRIPTION, { keyPath: ['topic', 'uid'] }); - } - if (!db.objectStoreNames.contains(STORE_MESSAGE)) { - db.createObjectStore(STORE_MESSAGE, { keyPath: ['topic', 'seq'] }); - } - if (!db.objectStoreNames.contains(STORE_DELLOG)) { - const delLog = db.createObjectStore(STORE_DELLOG, { - keyPath: ['topic', 'low', 'hi'], - }); - if (!delLog.indexNames.contains(INDEX_TOPIC_CLEAR)) { - delLog.createIndex(INDEX_TOPIC_CLEAR, ['topic', 'clear'], { - unique: false, - }); - } - } -} - -export default class IndexedDBAdapter implements StorageAdapter { - #db: IdbDatabase | null = null; - readonly #provider: IndexedDBProvider | null; - - constructor(provider?: IndexedDBProvider) { - this.#provider = provider ?? detectProvider(); - } - - static isSupported(): boolean { - return detectProvider() !== null; - } - - open(): Promise { - if (this.#db) { - return Promise.resolve(); - } - const { factory } = this.#requireProvider(); - return new Promise((resolve, reject) => { - const request = factory.open(DB_NAME, DB_VERSION); - request.onupgradeneeded = () => createStores(request.result); - request.onerror = () => reject(request.error); - request.onsuccess = () => { - const db = request.result; - db.onversionchange = () => { - db.close(); - this.#db = null; - }; - this.#db = db; - resolve(); - }; - }); - } - - close(): Promise { - this.#db?.close(); - this.#db = null; - return Promise.resolve(); - } - - destroy(): Promise { - const { factory } = this.#requireProvider(); - this.#db?.close(); - this.#db = null; - return new Promise((resolve, reject) => { - const request = factory.deleteDatabase(DB_NAME); - request.onblocked = () => reject(new Error('blocked')); - request.onsuccess = () => resolve(); - request.onerror = () => reject(request.error); - }); - } - - isOpen(): boolean { - return this.#db !== null; - } - - async getTopics(): Promise { - return this.#getAll(STORE_TOPIC, isTopicRecord); - } - - async getTopic(name: string): Promise { - return this.#get(STORE_TOPIC, name, isTopicRecord); - } - - async putTopic(record: TopicRecord): Promise { - return this.#put(STORE_TOPIC, record); - } - - async removeTopic(name: string): Promise { - const { keyRange } = this.#requireProvider(); - const transaction = this.#transaction( - [STORE_TOPIC, STORE_SUBSCRIPTION, STORE_MESSAGE, STORE_DELLOG], - 'readwrite' - ); - transaction.objectStore(STORE_TOPIC).delete(keyRange.only(name)); - transaction - .objectStore(STORE_SUBSCRIPTION) - .delete(keyRange.bound([name, KEY_LOW_STRING], [name, KEY_HIGH_STRING])); - transaction - .objectStore(STORE_MESSAGE) - .delete(keyRange.bound([name, 0], [name, MAX_SEQ])); - transaction - .objectStore(STORE_DELLOG) - .delete(keyRange.bound([name, 0, 0], [name, MAX_SEQ, MAX_SEQ])); - return transactionDone(transaction); - } - - async getUsers(): Promise { - return this.#getAll(STORE_USER, isUserRecord); - } - - async getUser(uid: string): Promise { - return this.#get(STORE_USER, uid, isUserRecord); - } - - async putUser(record: UserRecord): Promise { - return this.#put(STORE_USER, record); - } - - async removeUser(uid: string): Promise { - return this.#delete(STORE_USER, uid); - } - - async getSubscriptions(topic: string): Promise { - const { keyRange } = this.#requireProvider(); - return this.#getAll( - STORE_SUBSCRIPTION, - isSubscriptionRecord, - keyRange.bound([topic, KEY_LOW_STRING], [topic, KEY_HIGH_STRING]) - ); - } - - async getSubscription( - topic: string, - uid: string - ): Promise { - return this.#get(STORE_SUBSCRIPTION, [topic, uid], isSubscriptionRecord); - } - - async putSubscription(record: SubscriptionRecord): Promise { - return this.#put(STORE_SUBSCRIPTION, record); - } - - async removeSubscription(topic: string, uid: string): Promise { - return this.#delete(STORE_SUBSCRIPTION, [topic, uid]); - } - - async putMessage(record: MessageRecord): Promise { - return this.#put(STORE_MESSAGE, record); - } - - updateMessageStatus( - topic: string, - seq: number, - status: number - ): Promise { - const transaction = this.#transaction([STORE_MESSAGE], 'readwrite'); - const store = transaction.objectStore(STORE_MESSAGE); - const request = store.get([topic, seq]); - request.onsuccess = () => { - const record = request.result; - if (isMessageRecord(record) && record._status !== status) { - store.put({ ...record, _status: status }); - } - }; - return transactionDone(transaction); - } - - async removeMessages(topic: string, low: number, hi: number): Promise { - if (hi <= low) { - return; - } - const { keyRange } = this.#requireProvider(); - const transaction = this.#transaction([STORE_MESSAGE], 'readwrite'); - transaction - .objectStore(STORE_MESSAGE) - .delete(keyRange.bound([topic, low], [topic, hi], false, true)); - return transactionDone(transaction); - } - - async readMessages( - topic: string, - window: SeqWindow - ): Promise { - if (window.since >= window.before) { - return []; - } - const { keyRange } = this.#requireProvider(); - const range = keyRange.bound( - [topic, window.since], - [topic, window.before], - false, - true - ); - const store = this.#transaction([STORE_MESSAGE]).objectStore(STORE_MESSAGE); - return this.#collectDescending(store, range, window.limit, () => 1).then( - (values) => values.filter(isMessageRecord) - ); - } - - async readMessageRanges( - topic: string, - ranges: SeqRange[] - ): Promise { - const { keyRange } = this.#requireProvider(); - const store = this.#transaction([STORE_MESSAGE]).objectStore(STORE_MESSAGE); - const batches = await Promise.all( - ranges.filter(isNonEmptyRange).map((range) => { - const key = range.hi - ? keyRange.bound([topic, range.low], [topic, range.hi], false, true) - : keyRange.only([topic, range.low]); - return requestResult(store.getAll(key)); - }) - ); - return batches.flat().filter(isMessageRecord); - } - - async addDelLog(records: DelLogRecord[]): Promise { - if (records.length === 0) { - return; - } - const transaction = this.#transaction([STORE_DELLOG], 'readwrite'); - const store = transaction.objectStore(STORE_DELLOG); - records.forEach((record) => store.put(record)); - return transactionDone(transaction); - } - - async readDelLog(topic: string, window: SeqWindow): Promise { - if (window.since >= window.before) { - return []; - } - const { keyRange } = this.#requireProvider(); - const range = keyRange.bound( - [topic, 0, 0], - [topic, window.before, 0], - false, - true - ); - const store = this.#transaction([STORE_DELLOG]).objectStore(STORE_DELLOG); - const entries = await this.#collectDescending( - store, - range, - window.limit, - (value) => (isDelLogRecord(value) ? value.hi - value.low : 0), - (value) => isDelLogRecord(value) && value.hi > window.since - ); - return entries.filter(isDelLogRecord).map(toDelLogRange); - } - - async readDelLogRanges( - topic: string, - ranges: SeqRange[] - ): Promise { - const { keyRange } = this.#requireProvider(); - const store = this.#transaction([STORE_DELLOG]).objectStore(STORE_DELLOG); - const batches = await Promise.all( - ranges.map(async (range) => { - const hi = range.hi || range.low + 1; - const entries = await requestResult( - store.getAll( - keyRange.bound([topic, 0, 0], [topic, hi, 0], false, true) - ) - ); - return entries - .filter(isDelLogRecord) - .filter((entry) => entry.hi > range.low) - .map(toDelLogRange); - }) - ); - return batches.flat(); - } - - async maxDelId(topic: string): Promise { - const { keyRange } = this.#requireProvider(); - const index = this.#transaction([STORE_DELLOG]) - .objectStore(STORE_DELLOG) - .index(INDEX_TOPIC_CLEAR); - const cursor = await requestResult( - index.openCursor(keyRange.bound([topic, 0], [topic, MAX_SEQ]), 'prev') - ); - return cursor ? cursor.value.clear : 0; - } - - #requireProvider(): IndexedDBProvider { - if (!this.#provider) { - throw new Error('IndexedDB is not available'); - } - return this.#provider; - } - - #transaction(stores: string[], mode?: 'readwrite'): IdbTransaction { - if (!this.#db) { - throw new Error('not initialized'); - } - return this.#db.transaction(stores, mode); - } - - async #getAll( - store: string, - guard: (value: unknown) => value is T, - range?: unknown - ): Promise { - const request = this.#transaction([store]).objectStore(store).getAll(range); - return (await requestResult(request)).filter(guard); - } - - async #get( - store: string, - key: unknown, - guard: (value: unknown) => value is T - ): Promise { - const request = this.#transaction([store]).objectStore(store).get(key); - const result = await requestResult(request); - return guard(result) ? result : undefined; - } - - #put(store: string, record: object): Promise { - const transaction = this.#transaction([store], 'readwrite'); - transaction.objectStore(store).put(record); - return transactionDone(transaction); - } - - #delete(store: string, key: unknown): Promise { - const transaction = this.#transaction([store], 'readwrite'); - transaction.objectStore(store).delete(key); - return transactionDone(transaction); - } - - #collectDescending( - store: IdbObjectStore, - range: unknown, - limit: number, - weigh: (value: unknown) => number, - accept: (value: unknown) => boolean = () => true - ): Promise { - return new Promise((resolve, reject) => { - const values: unknown[] = []; - let total = 0; - const request = store.openCursor(range, 'prev'); - request.onerror = () => reject(request.error); - request.onsuccess = () => { - const cursor = request.result; - if (!cursor) { - resolve(values); - return; - } - if (accept(cursor.value)) { - values.push(cursor.value); - total += weigh(cursor.value); - } - if (limit > 0 && total >= limit) { - resolve(values); - return; - } - cursor.continue(); - }; - }); - } -} - -function isRecord(value: unknown): value is Record { - return typeof value === 'object' && value !== null; -} - -function isMessageRecord(value: unknown): value is MessageRecord { - return ( - isRecord(value) && - typeof value.topic === 'string' && - typeof value.seq === 'number' - ); -} - -function isDelLogRecord(value: unknown): value is DelLogRecord { - return ( - isRecord(value) && - typeof value.topic === 'string' && - typeof value.low === 'number' && - typeof value.hi === 'number' && - typeof value.clear === 'number' - ); -} - -function isTopicRecord(value: unknown): value is TopicRecord { - return isRecord(value) && typeof value.name === 'string'; -} - -function isUserRecord(value: unknown): value is UserRecord { - return isRecord(value) && typeof value.uid === 'string'; -} - -function isSubscriptionRecord(value: unknown): value is SubscriptionRecord { - return ( - isRecord(value) && - typeof value.topic === 'string' && - typeof value.uid === 'string' - ); -} diff --git a/src/core/storage/key-value-adapter.ts b/src/core/storage/key-value-adapter.ts deleted file mode 100644 index a3f909f..0000000 --- a/src/core/storage/key-value-adapter.ts +++ /dev/null @@ -1,246 +0,0 @@ -import { reviveTimestamp } from '../utils'; -import MemoryAdapter from './memory-adapter'; -import type { - DelLogRecord, - MessageRecord, - SubscriptionRecord, - TopicRecord, - UserRecord, -} from './storage-adapter'; - -type Awaitable = T | Promise; - -export interface KeyValueStore { - getItem(key: string): Awaitable; - setItem(key: string, value: string): unknown; - removeItem(key: string): unknown; - getAllKeys(): Awaitable; - getMany?( - keys: string[] - ): Awaitable>; - multiGet?( - keys: string[] - ): Awaitable; -} - -interface MMKVReadWrite { - getString(key: string): string | undefined; - set(key: string, value: string): void; - getAllKeys(): string[]; -} - -export type MMKVLike = MMKVReadWrite & - ({ remove(key: string): unknown } | { delete(key: string): unknown }); - -export interface KeyValueAdapterOptions { - prefix?: string; -} - -const DEFAULT_PREFIX = 'tinode'; - -export function fromMMKV(mmkv: MMKVLike): KeyValueStore { - return { - getItem: (key) => mmkv.getString(key), - setItem: (key, value) => mmkv.set(key, value), - removeItem: (key) => - 'remove' in mmkv ? mmkv.remove(key) : mmkv.delete(key), - getAllKeys: () => mmkv.getAllKeys(), - }; -} - -function isRecord(value: unknown): value is Record { - return typeof value === 'object' && value !== null; -} - -function isTopicRecord(value: unknown): value is TopicRecord { - return isRecord(value) && typeof value.name === 'string'; -} - -function isUserRecord(value: unknown): value is UserRecord { - return isRecord(value) && typeof value.uid === 'string'; -} - -function isSubscriptionRecord(value: unknown): value is SubscriptionRecord { - return ( - isRecord(value) && - typeof value.topic === 'string' && - typeof value.uid === 'string' - ); -} - -function isMessageRecord(value: unknown): value is MessageRecord { - return ( - isRecord(value) && - typeof value.topic === 'string' && - typeof value.seq === 'number' - ); -} - -function isDelLogRecord(value: unknown): value is DelLogRecord { - return ( - isRecord(value) && - typeof value.topic === 'string' && - typeof value.clear === 'number' && - typeof value.low === 'number' && - typeof value.hi === 'number' - ); -} - -function parse(raw: string | null | undefined): unknown { - if (!raw) { - return undefined; - } - try { - return JSON.parse(raw, reviveTimestamp); - } catch { - return undefined; - } -} - -export default class KeyValueAdapter extends MemoryAdapter { - readonly #store: KeyValueStore; - readonly #prefix: string; - - constructor(store: KeyValueStore, options: KeyValueAdapterOptions = {}) { - super(); - this.#store = store; - this.#prefix = `${options.prefix ?? DEFAULT_PREFIX}/`; - } - - async open(): Promise { - const keys = (await this.#store.getAllKeys()).filter((key) => - key.startsWith(this.#prefix) - ); - for (const [key, raw] of await this.#readAll(keys)) { - await this.#restore(key.slice(this.#prefix.length), parse(raw)); - } - await super.open(); - } - - async destroy(): Promise { - await super.destroy(); - await this.#removeWhere(() => true); - } - - async putTopic(record: TopicRecord): Promise { - await super.putTopic(record); - await this.#save(`topic/${record.name}`, record); - } - - async removeTopic(name: string): Promise { - await super.removeTopic(name); - await this.#removeWhere( - (path) => - path === `topic/${name}` || - path.startsWith(`sub/${name}/`) || - path.startsWith(`msg/${name}/`) || - path.startsWith(`del/${name}/`) - ); - } - - async putUser(record: UserRecord): Promise { - await super.putUser(record); - await this.#save(`user/${record.uid}`, record); - } - - async removeUser(uid: string): Promise { - await super.removeUser(uid); - await this.#store.removeItem(this.#prefix + `user/${uid}`); - } - - async putSubscription(record: SubscriptionRecord): Promise { - await super.putSubscription(record); - await this.#save(`sub/${record.topic}/${record.uid}`, record); - } - - async removeSubscription(topic: string, uid: string): Promise { - await super.removeSubscription(topic, uid); - await this.#store.removeItem(this.#prefix + `sub/${topic}/${uid}`); - } - - async putMessage(record: MessageRecord): Promise { - await super.putMessage(record); - await this.#save(`msg/${record.topic}/${record.seq}`, record); - } - - async updateMessageStatus( - topic: string, - seq: number, - status: number - ): Promise { - await super.updateMessageStatus(topic, seq, status); - const [record] = await super.readMessageRanges(topic, [{ low: seq }]); - if (record) { - await this.#save(`msg/${topic}/${seq}`, record); - } - } - - async removeMessages(topic: string, low: number, hi: number): Promise { - await super.removeMessages(topic, low, hi); - const messages = `msg/${topic}/`; - await this.#removeWhere((path) => { - if (!path.startsWith(messages)) { - return false; - } - const seq = Number(path.slice(messages.length)); - return seq >= low && seq < hi; - }); - } - - async addDelLog(records: DelLogRecord[]): Promise { - await super.addDelLog(records); - for (const record of records) { - await this.#save( - `del/${record.topic}/${record.low}/${record.hi}`, - record - ); - } - } - - async #readAll( - keys: string[] - ): Promise { - if (this.#store.getMany) { - const values = await this.#store.getMany(keys); - return keys.map((key) => [key, values[key]] as const); - } - if (this.#store.multiGet) { - return this.#store.multiGet(keys); - } - const pairs: [string, string | null | undefined][] = []; - for (const key of keys) { - pairs.push([key, await this.#store.getItem(key)]); - } - return pairs; - } - - async #restore(path: string, value: unknown): Promise { - const kind = path.slice(0, path.indexOf('/')); - if (kind === 'topic' && isTopicRecord(value)) { - await super.putTopic(value); - } else if (kind === 'user' && isUserRecord(value)) { - await super.putUser(value); - } else if (kind === 'sub' && isSubscriptionRecord(value)) { - await super.putSubscription(value); - } else if (kind === 'msg' && isMessageRecord(value)) { - await super.putMessage(value); - } else if (kind === 'del' && isDelLogRecord(value)) { - await super.addDelLog([value]); - } - } - - async #save(path: string, record: object): Promise { - await this.#store.setItem(this.#prefix + path, JSON.stringify(record)); - } - - async #removeWhere(matches: (path: string) => boolean): Promise { - for (const key of await this.#store.getAllKeys()) { - if ( - key.startsWith(this.#prefix) && - matches(key.slice(this.#prefix.length)) - ) { - await this.#store.removeItem(key); - } - } - } -} diff --git a/src/core/storage/memory-adapter.ts b/src/core/storage/memory-adapter.ts deleted file mode 100644 index 30fc647..0000000 --- a/src/core/storage/memory-adapter.ts +++ /dev/null @@ -1,247 +0,0 @@ -import { - type DelLogRange, - type DelLogRecord, - type MessageRecord, - type SeqRange, - type SeqWindow, - type StorageAdapter, - type SubscriptionRecord, - type TopicRecord, - type UserRecord, -} from './storage-adapter'; - -function messageRangeContains(range: SeqRange, seq: number): boolean { - return range.hi ? seq >= range.low && seq < range.hi : seq === range.low; -} - -function isNonEmptyRange(range: SeqRange): boolean { - return !range.hi || range.hi > range.low; -} - -function delLogOverlaps(record: DelLogRecord, since: number, before: number) { - return record.low < before && record.hi > since; -} - -function delLogRangeOf(record: DelLogRecord): DelLogRange { - return { low: record.low, hi: record.hi }; -} - -function descendingDelLog(a: DelLogRecord, b: DelLogRecord): number { - return b.low - a.low || b.hi - a.hi; -} - -function getOrCreate(map: Map, key: string, create: () => V): V { - const existing = map.get(key); - if (existing) { - return existing; - } - const created = create(); - map.set(key, created); - return created; -} - -export default class MemoryAdapter implements StorageAdapter { - #open = false; - readonly #topics = new Map(); - readonly #users = new Map(); - readonly #subscriptions = new Map>(); - readonly #messages = new Map>(); - readonly #delLog = new Map>(); - - open(): Promise { - this.#open = true; - return Promise.resolve(); - } - - close(): Promise { - this.#open = false; - return Promise.resolve(); - } - - destroy(): Promise { - this.#open = false; - this.#topics.clear(); - this.#users.clear(); - this.#subscriptions.clear(); - this.#messages.clear(); - this.#delLog.clear(); - return Promise.resolve(); - } - - isOpen(): boolean { - return this.#open; - } - - async getTopics(): Promise { - return [...this.#topics.values()].map((record) => ({ ...record })); - } - - async getTopic(name: string): Promise { - const record = this.#topics.get(name); - return record && { ...record }; - } - - async putTopic(record: TopicRecord): Promise { - this.#topics.set(record.name, { ...record }); - } - - async removeTopic(name: string): Promise { - this.#topics.delete(name); - this.#subscriptions.delete(name); - this.#messages.delete(name); - this.#delLog.delete(name); - } - - async getUsers(): Promise { - return [...this.#users.values()].map((record) => ({ ...record })); - } - - async getUser(uid: string): Promise { - const record = this.#users.get(uid); - return record && { ...record }; - } - - async putUser(record: UserRecord): Promise { - this.#users.set(record.uid, { ...record }); - } - - async removeUser(uid: string): Promise { - this.#users.delete(uid); - } - - async getSubscriptions(topic: string): Promise { - const records = this.#subscriptions.get(topic); - return records ? [...records.values()].map((r) => ({ ...r })) : []; - } - - async getSubscription( - topic: string, - uid: string - ): Promise { - const record = this.#subscriptions.get(topic)?.get(uid); - return record && { ...record }; - } - - async putSubscription(record: SubscriptionRecord): Promise { - getOrCreate(this.#subscriptions, record.topic, () => new Map()).set( - record.uid, - { ...record } - ); - } - - async removeSubscription(topic: string, uid: string): Promise { - this.#subscriptions.get(topic)?.delete(uid); - } - - async putMessage(record: MessageRecord): Promise { - getOrCreate(this.#messages, record.topic, () => new Map()).set(record.seq, { - ...record, - }); - } - - async updateMessageStatus( - topic: string, - seq: number, - status: number - ): Promise { - const record = this.#messages.get(topic)?.get(seq); - if (record) { - record._status = status; - } - } - - async removeMessages(topic: string, low: number, hi: number): Promise { - const records = this.#messages.get(topic); - if (!records) { - return; - } - for (const seq of [...records.keys()]) { - if (seq >= low && seq < hi) { - records.delete(seq); - } - } - } - - async readMessages( - topic: string, - window: SeqWindow - ): Promise { - if (window.since >= window.before) { - return []; - } - const found = [...(this.#messages.get(topic)?.values() ?? [])] - .filter((r) => r.seq >= window.since && r.seq < window.before) - .sort((a, b) => b.seq - a.seq); - const limited = window.limit > 0 ? found.slice(0, window.limit) : found; - return limited.map((record) => ({ ...record })); - } - - async readMessageRanges( - topic: string, - ranges: SeqRange[] - ): Promise { - const sorted = [...(this.#messages.get(topic)?.values() ?? [])].sort( - (a, b) => a.seq - b.seq - ); - return ranges - .filter(isNonEmptyRange) - .flatMap((range) => - sorted.filter((record) => messageRangeContains(range, record.seq)) - ) - .map((record) => ({ ...record })); - } - - async addDelLog(records: DelLogRecord[]): Promise { - records.forEach((record) => { - getOrCreate(this.#delLog, record.topic, () => new Map()).set( - `${record.low}:${record.hi}`, - { ...record } - ); - }); - } - - async readDelLog(topic: string, window: SeqWindow): Promise { - if (window.since >= window.before) { - return []; - } - const found = this.#delLogRecords(topic) - .filter((r) => delLogOverlaps(r, window.since, window.before)) - .sort(descendingDelLog); - const result: DelLogRange[] = []; - let count = 0; - for (const record of found) { - result.push(delLogRangeOf(record)); - count += record.hi - record.low; - if (window.limit > 0 && count >= window.limit) { - break; - } - } - return result; - } - - async readDelLogRanges( - topic: string, - ranges: SeqRange[] - ): Promise { - const records = this.#delLogRecords(topic).sort( - (a, b) => -descendingDelLog(a, b) - ); - return ranges.flatMap((range) => { - const hi = range.hi || range.low + 1; - return records - .filter((record) => delLogOverlaps(record, range.low, hi)) - .map(delLogRangeOf); - }); - } - - async maxDelId(topic: string): Promise { - return this.#delLogRecords(topic).reduce( - (max, record) => Math.max(max, record.clear), - 0 - ); - } - - #delLogRecords(topic: string): DelLogRecord[] { - return [...(this.#delLog.get(topic)?.values() ?? [])]; - } -} diff --git a/src/core/storage/persistent-cache.ts b/src/core/storage/persistent-cache.ts deleted file mode 100644 index 08c44a8..0000000 --- a/src/core/storage/persistent-cache.ts +++ /dev/null @@ -1,429 +0,0 @@ -import { - MAX_SEQ, - type DelLogRange, - type MessageRecord, - type SeqRange, - type SeqWindow, - type StorageAdapter, - type SubscriptionRecord, - type TopicRecord, - type UserRecord, -} from './storage-adapter'; - -export type PersistentCacheLogger = (...args: unknown[]) => void; -export type PersistentCacheErrorHandler = (error: unknown) => void; - -export interface CacheableTopic { - name: string; - seq: number; - read: number; - unread: number; - acs?: unknown; - _tags?: unknown; - getAccessMode(): { jsonHelper(): unknown }; - setAccessMode(acs: unknown): unknown; -} - -export interface MessageQuery { - since?: number; - before?: number; - limit?: number; - ranges?: SeqRange[]; -} - -export interface CacheableMessage { - topic: string; - seq: number; -} - -export type CachedSubscription = SubscriptionRecord & { user: string }; - -export interface CachedUser { - user: string; - public: unknown; -} - -type EachCallback = (this: unknown, item: T) => void; - -const TOPIC_FIELDS = [ - 'created', - 'updated', - 'deleted', - 'touched', - 'read', - 'recv', - 'seq', - 'clear', - 'defacs', - 'creds', - 'public', - 'trusted', - 'private', - '_aux', - '_deleted', -] as const; - -const SUBSCRIPTION_FIELDS = [ - 'updated', - 'mode', - 'read', - 'recv', - 'clear', - 'lastSeen', - 'userAgent', -] as const; - -const MESSAGE_FIELDS = [ - 'topic', - 'seq', - 'ts', - '_status', - 'from', - 'head', - 'content', -] as const; - -const noop = () => {}; - -function hasOwn(source: object, field: string): boolean { - return Object.prototype.hasOwnProperty.call(source, field); -} - -function copyOwnFields( - source: object, - target: object, - fields: readonly string[] -): void { - fields.forEach((field) => { - if (hasOwn(source, field)) { - const value: unknown = Reflect.get(source, field); - Reflect.set(target, field, value); - } - }); -} - -function positiveOr(value: number | undefined, fallback: number): number { - return value !== undefined && value > 0 ? value : fallback; -} - -function toInteger(value: number | undefined): number { - return value !== undefined && Number.isFinite(value) ? Math.trunc(value) : 0; -} - -function toWindow(query: MessageQuery): SeqWindow { - return { - since: positiveOr(query.since, 0), - before: positiveOr(query.before, MAX_SEQ), - limit: toInteger(query.limit), - }; -} - -function serializeTopic( - existing: TopicRecord | undefined, - topic: CacheableTopic -): TopicRecord { - const record: TopicRecord = existing ?? { name: topic.name }; - copyOwnFields(topic, record, TOPIC_FIELDS); - if (Array.isArray(topic._tags)) { - record.tags = topic._tags; - } - if (topic.acs) { - record.acs = topic.getAccessMode().jsonHelper(); - } - return record; -} - -function deserializeTopic(topic: CacheableTopic, source: TopicRecord): void { - copyOwnFields(source, topic, TOPIC_FIELDS); - if (Array.isArray(source.tags)) { - topic._tags = source.tags; - } - if (source.acs) { - topic.setAccessMode(source.acs); - } - topic.seq = toInteger(topic.seq); - topic.read = toInteger(topic.read); - topic.unread = Math.max(0, topic.seq - topic.read); -} - -function serializeSubscription( - existing: SubscriptionRecord | undefined, - topicName: string, - uid: string, - sub: object -): SubscriptionRecord { - const record: SubscriptionRecord = existing ?? { topic: topicName, uid }; - copyOwnFields(sub, record, SUBSCRIPTION_FIELDS); - return record; -} - -function serializeMessage( - existing: MessageRecord | undefined, - message: CacheableMessage | MessageRecord -): MessageRecord { - const record: MessageRecord = existing ?? { - topic: message.topic, - seq: message.seq, - }; - copyOwnFields(message, record, MESSAGE_FIELDS); - return record; -} - -function visitEach( - items: T[], - callback: EachCallback | undefined, - context: unknown -): void { - if (callback) { - items.forEach((item) => callback.call(context, item)); - } -} - -export default class PersistentCache { - readonly #onError: PersistentCacheErrorHandler; - readonly #logger: PersistentCacheLogger; - readonly #adapter: StorageAdapter | null; - - constructor( - onError: PersistentCacheErrorHandler | null | undefined, - logger: PersistentCacheLogger | null | undefined, - adapter: StorageAdapter | null - ) { - this.#onError = onError ?? noop; - this.#logger = logger ?? noop; - this.#adapter = adapter; - } - - get disabled(): boolean { - return !this.isReady(); - } - - initDatabase(): Promise { - const adapter = this.#adapter; - if (!adapter) { - return Promise.resolve(); - } - return adapter.open().catch((error: unknown) => { - this.#logger('PCache', 'failed to initialize', error); - this.#onError(error); - throw error; - }); - } - - deleteDatabase(): Promise { - const adapter = this.#adapter; - if (!adapter) { - return Promise.resolve(true); - } - return adapter.destroy().then( - () => true, - (error: unknown) => { - this.#logger('PCache', 'deleteDatabase', error); - throw error; - } - ); - } - - isReady(): boolean { - return !!this.#adapter && this.#adapter.isOpen(); - } - - updTopic(topic: CacheableTopic): Promise { - return this.#run('updTopic', undefined, async (adapter) => { - const existing = await adapter.getTopic(topic.name); - await adapter.putTopic(serializeTopic(existing, topic)); - }); - } - - markTopicAsDeleted(name: string, deleted: boolean): Promise { - return this.#run('markTopicAsDeleted', undefined, async (adapter) => { - const record = await adapter.getTopic(name); - if (record && record._deleted !== deleted) { - await adapter.putTopic({ ...record, _deleted: deleted }); - } - }); - } - - remTopic(name: string): Promise { - return this.#run('remTopic', undefined, (adapter) => - adapter.removeTopic(name) - ); - } - - mapTopics( - callback?: EachCallback, - context?: unknown - ): Promise { - return this.#run('mapTopics', [], async (adapter) => { - const records = await adapter.getTopics(); - visitEach(records, callback, context); - return records; - }); - } - - deserializeTopic(topic: CacheableTopic, src: TopicRecord): void { - deserializeTopic(topic, src); - } - - updUser(uid: string, pub?: unknown): Promise { - if (pub === undefined) { - return Promise.resolve(); - } - return this.#run('updUser', undefined, (adapter) => - adapter.putUser({ uid, public: pub }) - ); - } - - remUser(uid: string): Promise { - return this.#run('remUser', undefined, (adapter) => - adapter.removeUser(uid) - ); - } - - mapUsers( - callback?: EachCallback, - context?: unknown - ): Promise { - return this.#run('mapUsers', [], async (adapter) => { - const records = await adapter.getUsers(); - visitEach(records, callback, context); - return records; - }); - } - - getUser(uid: string): Promise { - return this.#run( - 'getUser', - undefined, - async (adapter) => { - const record = await adapter.getUser(uid); - return record && { user: record.uid, public: record.public }; - } - ); - } - - updSubscription(topicName: string, uid: string, sub: object): Promise { - return this.#run('updSubscription', undefined, async (adapter) => { - const existing = await adapter.getSubscription(topicName, uid); - await adapter.putSubscription( - serializeSubscription(existing, topicName, uid, sub) - ); - }); - } - - remSubscription(topicName: string, uid: string): Promise { - return this.#run('remSubscription', undefined, (adapter) => - adapter.removeSubscription(topicName, uid) - ); - } - - mapSubscriptions( - topicName: string, - callback?: EachCallback, - context?: unknown - ): Promise { - return this.#run('mapSubscriptions', [], async (adapter) => { - const records = (await adapter.getSubscriptions(topicName)).map( - (record) => ({ ...record, user: record.uid }) - ); - visitEach(records, callback, context); - return records; - }); - } - - addMessage(msg: CacheableMessage): Promise { - return this.#run('addMessage', undefined, (adapter) => - adapter.putMessage(serializeMessage(undefined, msg)) - ); - } - - updMessageStatus( - topicName: string, - seq: number, - status: number - ): Promise { - return this.#run('updMessageStatus', undefined, (adapter) => - adapter.updateMessageStatus(topicName, seq, status) - ); - } - - remMessages(topicName: string, from?: number, to?: number): Promise { - return this.#run('remMessages', undefined, (adapter) => { - const low = from ?? 0; - const hi = to ?? 0; - if (!low && !hi) { - return adapter.removeMessages(topicName, 0, MAX_SEQ); - } - if (hi > 0) { - return hi > low - ? adapter.removeMessages(topicName, low, hi) - : Promise.resolve(); - } - return adapter.removeMessages(topicName, low, low + 1); - }); - } - - readMessages( - topicName: string, - query?: MessageQuery | null, - callback?: EachCallback, - context?: unknown - ): Promise { - const params = query ?? {}; - return this.#run('readMessages', [], async (adapter) => { - const records = Array.isArray(params.ranges) - ? await adapter.readMessageRanges(topicName, params.ranges) - : await adapter.readMessages(topicName, toWindow(params)); - visitEach(records, callback, context); - return records; - }); - } - - addDelLog( - topicName: string, - delId: number, - ranges: SeqRange[] - ): Promise { - return this.#run('addDelLog', undefined, (adapter) => - adapter.addDelLog( - ranges.map((range) => ({ - topic: topicName, - clear: delId, - low: range.low, - hi: range.hi || range.low + 1, - })) - ) - ); - } - - readDelLog( - topicName: string, - query?: MessageQuery | null - ): Promise { - const params = query ?? {}; - return this.#run('readDelLog', [], (adapter) => - Array.isArray(params.ranges) - ? adapter.readDelLogRanges(topicName, params.ranges) - : adapter.readDelLog(topicName, toWindow(params)) - ); - } - - maxDelId(topicName: string): Promise { - return this.#run('maxDelId', 0, (adapter) => adapter.maxDelId(topicName)); - } - - #run( - operation: string, - fallback: T, - work: (adapter: StorageAdapter) => Promise - ): Promise { - const adapter = this.#adapter; - if (!adapter || !adapter.isOpen()) { - return Promise.resolve(fallback); - } - return work(adapter).catch((error: unknown) => { - this.#logger('PCache', operation, error); - throw error; - }); - } -} diff --git a/src/core/storage/resolve-adapter.ts b/src/core/storage/resolve-adapter.ts deleted file mode 100644 index ef6e02d..0000000 --- a/src/core/storage/resolve-adapter.ts +++ /dev/null @@ -1,15 +0,0 @@ -import IndexedDBAdapter from './indexeddb-adapter'; -import type { StorageAdapter } from './storage-adapter'; - -export function resolveStorageAdapter( - persist: boolean, - custom?: StorageAdapter | null -): StorageAdapter | null { - if (custom) { - return custom; - } - if (persist && IndexedDBAdapter.isSupported()) { - return new IndexedDBAdapter(); - } - return null; -} diff --git a/src/core/storage/storage-adapter.ts b/src/core/storage/storage-adapter.ts deleted file mode 100644 index 65c1c77..0000000 --- a/src/core/storage/storage-adapter.ts +++ /dev/null @@ -1,115 +0,0 @@ -export interface SeqRange { - low: number; - hi?: number; -} - -export interface TopicRecord { - name: string; - created?: Date; - updated?: Date; - deleted?: Date; - touched?: Date; - read?: number; - recv?: number; - seq?: number; - clear?: number; - defacs?: unknown; - creds?: unknown; - public?: unknown; - trusted?: unknown; - private?: unknown; - _aux?: unknown; - _deleted?: boolean; - tags?: string[]; - acs?: unknown; -} - -export interface UserRecord { - uid: string; - public: unknown; -} - -export interface SubscriptionRecord { - topic: string; - uid: string; - updated?: Date; - mode?: string; - read?: number; - recv?: number; - clear?: number; - lastSeen?: unknown; - userAgent?: string; -} - -export interface MessageRecord { - topic: string; - seq: number; - ts?: Date; - _status?: number; - from?: string; - head?: unknown; - content?: unknown; -} - -export interface DelLogRecord { - topic: string; - clear: number; - low: number; - hi: number; -} - -export interface DelLogRange { - low: number; - hi: number; -} - -export interface SeqWindow { - since: number; - before: number; - limit: number; -} - -export interface StorageAdapter { - open(): Promise; - close(): Promise; - destroy(): Promise; - isOpen(): boolean; - - getTopics(): Promise; - getTopic(name: string): Promise; - putTopic(record: TopicRecord): Promise; - removeTopic(name: string): Promise; - - getUsers(): Promise; - getUser(uid: string): Promise; - putUser(record: UserRecord): Promise; - removeUser(uid: string): Promise; - - getSubscriptions(topic: string): Promise; - getSubscription( - topic: string, - uid: string - ): Promise; - putSubscription(record: SubscriptionRecord): Promise; - removeSubscription(topic: string, uid: string): Promise; - - putMessage(record: MessageRecord): Promise; - updateMessageStatus( - topic: string, - seq: number, - status: number - ): Promise; - removeMessages(topic: string, low: number, hi: number): Promise; - readMessages(topic: string, window: SeqWindow): Promise; - readMessageRanges( - topic: string, - ranges: SeqRange[] - ): Promise; - - addDelLog(records: DelLogRecord[]): Promise; - readDelLog(topic: string, window: SeqWindow): Promise; - readDelLogRanges(topic: string, ranges: SeqRange[]): Promise; - maxDelId(topic: string): Promise; -} - -export const MAX_SEQ = Number.MAX_SAFE_INTEGER; diff --git a/src/core/the-card.ts b/src/core/the-card.ts deleted file mode 100644 index 37b2226..0000000 --- a/src/core/the-card.ts +++ /dev/null @@ -1,713 +0,0 @@ -import { DEL_CHAR } from './config'; - -const THE_CARD_MIME_TYPE = 'text/x-the-card'; -const REPLACEMENT_CHAR = '�'; -const DEFAULT_IMAGE_MIME_TYPE = 'image/jpeg'; -const DATA_URL_PATTERN = /^data:(image\/[-a-z0-9+.]+)?(;base64)?,/i; -const HEX_BYTE_PATTERN = /^[0-9A-F]{2}$/i; - -const IMAGE_MIME_BY_EXTENSION: Record = { - jpg: 'image/jpeg', - jpeg: 'image/jpeg', - png: 'image/png', - gif: 'image/gif', - bmp: 'image/bmp', - webp: 'image/webp', - svg: 'image/svg+xml', -}; - -export type CardCommProto = 'tel' | 'email' | 'tinode' | 'http' | 'impp'; - -export interface CardName { - surname?: string; - given?: string; - additional?: string; - prefix?: string; - suffix?: string; -} - -export interface CardOrg { - fn?: string; - title?: string; -} - -export interface CardPhoto { - type?: string; - data?: string; - ref?: string; -} - -export interface CardBirthday { - y?: number; - m: number; - d: number; -} - -export interface CardComm { - proto: CardCommProto; - des: string[]; - value: string; -} - -export interface CardData { - fn?: string; - n?: CardName; - org?: CardOrg; - note?: string; - bday?: CardBirthday; - photo?: CardPhoto | typeof DEL_CHAR; - comm?: CardComm[]; -} - -type MaybeCard = CardData | null | undefined; - -export default interface TheCard extends CardData {} - -export default class TheCard { - static contentType = THE_CARD_MIME_TYPE; - - constructor( - fn?: string, - imageUrl?: string, - imageMimeType?: string, - note?: string - ) { - Object.assign(this, theCard(fn, imageUrl, imageMimeType, note) ?? {}); - } - - merge(other: CardData) { - Object.assign(this, other); - } - - get contentType(): string { - return THE_CARD_MIME_TYPE; - } - - get size(): number { - return JSON.stringify(this).length; - } - - static setFn(card: MaybeCard, fn?: string | null): CardData { - const result = card ?? {}; - result.fn = fn?.trim() || undefined; - return result; - } - - static getFn(card: MaybeCard): string | null { - return card?.fn ? card.fn : null; - } - - static setNote(card: MaybeCard, note?: string | null): CardData { - const result = card ?? {}; - result.note = note?.trim() || DEL_CHAR; - return result; - } - - static setPhoto( - card: MaybeCard, - imageUrl?: string | null, - imageMimeType?: string | null - ): CardData { - const result = card ?? {}; - if (!imageUrl) { - result.photo = DEL_CHAR; - return result; - } - const dataUrl = DATA_URL_PATTERN.exec(imageUrl); - let mimeType: string | null | undefined = imageMimeType; - let photo: CardPhoto; - if (dataUrl) { - mimeType = dataUrl[1]; - photo = { - data: imageUrl.substring(imageUrl.indexOf(',') + 1), - ref: DEL_CHAR, - }; - } else { - photo = { data: DEL_CHAR, ref: imageUrl }; - mimeType = mimeType || mimeTypeFromExtension(imageUrl); - } - photo.type = imageSubtype(mimeType); - result.photo = photo; - return result; - } - - static getPhotoUrl(card: MaybeCard): string | null { - const photo = card?.photo; - if (!photo || typeof photo === 'string') { - return null; - } - if (photo.ref && photo.ref !== DEL_CHAR) { - return photo.ref; - } - if (photo.data && photo.data !== DEL_CHAR) { - return `data:image/${photo.type || 'jpeg'};base64,${photo.data}`; - } - return null; - } - - static getOrg(card: MaybeCard): string | null { - return card?.org?.fn || null; - } - - static setPhone(card: MaybeCard, phone: string, type = 'voice'): CardData { - return addOrSetComm(card, 'tel', phone, type, true); - } - - static setEmail(card: MaybeCard, email: string, type = 'home'): CardData { - return addOrSetComm(card, 'email', email, type, true); - } - - static setTinodeID( - card: MaybeCard, - tinodeID: string, - type = 'home' - ): CardData { - return addOrSetComm(card, 'tinode', tinodeID, type, true); - } - - static addPhone(card: MaybeCard, phone: string, type = 'voice'): CardData { - return addOrSetComm(card, 'tel', phone, type, false); - } - - static addEmail(card: MaybeCard, email: string, type = 'home'): CardData { - return addOrSetComm(card, 'email', email, type, false); - } - - static addTinodeID( - card: MaybeCard, - tinodeID: string, - type = 'home' - ): CardData { - return addOrSetComm(card, 'tinode', tinodeID, type, false); - } - - static clearPhone( - card: T, - phone?: string, - type?: string - ): T { - return clearComm(card, 'tel', phone, type); - } - - static clearEmail( - card: T, - email?: string, - type?: string - ): T { - return clearComm(card, 'email', email, type); - } - - static clearTinodeID( - card: T, - tinodeID?: string, - type?: string - ): T { - return clearComm(card, 'tinode', tinodeID, type); - } - - static getComm(card: MaybeCard, proto: string): CardComm[] { - if (card && Array.isArray(card.comm)) { - return card.comm.filter((c) => c.proto === proto); - } - return []; - } - - static getEmails(card: MaybeCard): string[] { - return TheCard.getComm(card, 'email').map((c) => c.value); - } - - static getPhones(card: MaybeCard): string[] { - return TheCard.getComm(card, 'tel').map((c) => c.value); - } - - static getFirstTinodeID(card: MaybeCard): string | null { - return TheCard.getComm(card, 'tinode')[0]?.value ?? null; - } - - static exportVCard(card: MaybeCard): string | null { - if (!card) { - return null; - } - - let vcard = 'BEGIN:VCARD\r\nVERSION:3.0\r\n'; - - if (card.fn) { - vcard += `FN:${card.fn}\r\n`; - } - - if (card.n) { - vcard += `N:${card.n.surname || ''};${card.n.given || ''};${card.n.additional || ''};${card.n.prefix || ''};${card.n.suffix || ''}\r\n`; - } - - if (card.org) { - if (card.org.fn) { - vcard += `ORG:${card.org.fn}\r\n`; - } - if (card.org.title) { - vcard += `TITLE:${card.org.title}\r\n`; - } - } - - if (card.note && card.note !== DEL_CHAR) { - vcard += `NOTE:${card.note}\r\n`; - } - - if (card.bday && card.bday.m && card.bday.d) { - const year = card.bday.y ? String(card.bday.y).padStart(4, '0') : '--'; - const month = String(card.bday.m).padStart(2, '0'); - const day = String(card.bday.d).padStart(2, '0'); - vcard += `BDAY:${year}-${month}-${day}\r\n`; - } - - if (card.photo && typeof card.photo !== 'string') { - const { ref, data, type } = card.photo; - if (ref && ref !== DEL_CHAR) { - vcard += `PHOTO;VALUE=URI:${ref}\r\n`; - } else if (data && data !== DEL_CHAR) { - vcard += `PHOTO;TYPE=${(type ?? '').toUpperCase()};ENCODING=b:${data}\r\n`; - } - } - - if (Array.isArray(card.comm)) { - card.comm.forEach((comm) => { - const types = comm.des.join(',').toUpperCase(); - const property = VCARD_PROPERTY_BY_PROTO[comm.proto]; - if (property) { - vcard += `${property};TYPE=${types}:${comm.value}\r\n`; - } - }); - } - - vcard += 'END:VCARD\r\n'; - return vcard; - } - - static importVCard(vcardStr: unknown): CardData | null { - if (!vcardStr || typeof vcardStr !== 'string') { - return null; - } - - const card: CardData = {}; - const commMap = new Map>(); - - unfoldLines(vcardStr).forEach((line) => { - const [keyPart, ...valueParts] = line.split(':'); - if (!keyPart || valueParts.length === 0) { - return; - } - const rawValue = valueParts.join(':'); - const keyParams = keyPart.split(';'); - const key = (keyParams[0] ?? '').trim().toUpperCase(); - const isQuotedPrintable = keyParams.some((param) => { - const normalized = param.trim().toUpperCase(); - return ( - normalized === 'QUOTED-PRINTABLE' || - normalized === 'ENCODING=QUOTED-PRINTABLE' - ); - }); - const textValue = isQuotedPrintable - ? decodeQuotedPrintable(rawValue) - : rawValue; - - switch (key) { - case 'FN': - card.fn = unescapeValue(textValue); - break; - case 'N': - assignName(card, textValue); - break; - case 'ORG': { - const org = card.org ?? {}; - const name = textValue.split(';')[0]; - if (name) { - org.fn = unescapeValue(name); - } else { - delete org.fn; - } - card.org = org; - break; - } - case 'TITLE': { - const org = card.org ?? {}; - if (textValue) { - org.title = unescapeValue(textValue); - } else { - delete org.title; - } - card.org = org; - break; - } - case 'NOTE': - card.note = unescapeValue(textValue); - break; - case 'BDAY': { - const bday = parseBirthday(rawValue); - if (bday) { - card.bday = bday; - } - break; - } - case 'PHOTO': - card.photo = parsePhoto(keyPart, rawValue); - break; - case 'TEL': - collectComm(commMap, `tel|${rawValue}`, keyPart); - break; - case 'EMAIL': - collectComm(commMap, `email|${rawValue}`, keyPart); - break; - case 'IMPP': - collectComm( - commMap, - rawValue.startsWith('tinode:') - ? `tinode|${rawValue}` - : `impp|${rawValue}`, - keyPart - ); - break; - case 'URL': - collectComm(commMap, `http|${rawValue}`, keyPart); - break; - default: - break; - } - }); - - if (commMap.size > 0) { - card.comm = []; - commMap.forEach((types, mapKey) => { - const [proto, value] = mapKey.split('|', 2); - if (isCommProto(proto) && value !== undefined) { - card.comm?.push({ proto, des: Array.from(types), value }); - } - }); - } - - return card; - } - - static isFileSupported(type?: string | null, name?: string | null): boolean { - return ( - type === 'text/vcard' || - (name ?? '').endsWith('.vcf') || - (name ?? '').endsWith('.vcard') - ); - } -} - -const VCARD_PROPERTY_BY_PROTO: Partial> = { - tel: 'TEL', - email: 'EMAIL', - tinode: 'IMPP', - http: 'URL', -}; - -function isCommProto(value: string | undefined): value is CardCommProto { - return ( - value === 'tel' || - value === 'email' || - value === 'tinode' || - value === 'http' || - value === 'impp' - ); -} - -function imageSubtype(mimeType?: string | null): string { - return (mimeType || DEFAULT_IMAGE_MIME_TYPE).substring('image/'.length); -} - -function mimeTypeFromExtension(url: string): string | null { - const ext = /\.([a-z0-9]+)$/i.exec(url); - const extension = ext?.[1]?.toLowerCase(); - return (extension && IMAGE_MIME_BY_EXTENSION[extension]) || null; -} - -function theCard( - fn?: string, - imageUrl?: string, - imageMimeType?: string, - note?: string -): CardData | null { - let card: CardData | null = null; - const name = fn?.trim(); - const trimmedNote = note?.trim(); - - if (name) { - card = { fn: name }; - } - - if (typeof trimmedNote === 'string') { - card = card ?? {}; - card.note = trimmedNote || DEL_CHAR; - } - - if (imageUrl) { - card = TheCard.setPhoto(card, imageUrl, imageMimeType); - } - - return card; -} - -function addOrSetComm( - card: MaybeCard, - proto: CardCommProto, - value: string, - type: string, - setOnly: boolean -): CardData { - const result = card ?? {}; - const trimmed = value?.trim(); - if (trimmed) { - let comm = result.comm ?? []; - if (setOnly) { - comm = comm.filter((c) => c.proto !== proto || !c.des.includes(type)); - } - comm.push({ proto, des: [type], value: trimmed }); - result.comm = comm; - } - return result; -} - -function clearComm( - card: T, - proto: CardCommProto, - value?: string, - type?: string -): T { - if (card && Array.isArray(card.comm)) { - card.comm = card.comm.filter((c) => { - if (c.proto !== proto) return true; - if (value && c.value !== value) return true; - if (type) { - return !c.des.includes(type); - } - return false; - }); - } - return card; -} - -function unfoldLines(vcardStr: string): string[] { - const lines: string[] = []; - let currentLine = ''; - vcardStr.split(/\r\n|\n/).forEach((line) => { - if (line.startsWith(' ') || line.startsWith('\t')) { - currentLine += line.substring(1); - } else if (currentLine.endsWith('=')) { - currentLine = currentLine.substring(0, currentLine.length - 1) + line; - } else { - if (currentLine) { - lines.push(currentLine); - } - currentLine = line; - } - }); - if (currentLine) { - lines.push(currentLine); - } - return lines; -} - -function unescapeValue(value: string): string { - return value.replace(/\\([,;\\n])/g, (_match, char: string) => - char === 'n' ? '\n' : char - ); -} - -function decodeQuotedPrintable(value: string): string { - const bytes: number[] = []; - let i = 0; - while (i < value.length) { - const hex = value.substring(i + 1, i + 3); - if ( - value[i] === '=' && - i + 2 < value.length && - HEX_BYTE_PATTERN.test(hex) - ) { - bytes.push(parseInt(hex, 16)); - i += 3; - } else { - bytes.push(value.charCodeAt(i)); - i++; - } - } - return decodeUtf8(new Uint8Array(bytes)); -} - -function decodeUtf8(bytes: Uint8Array): string { - if (typeof TextDecoder !== 'undefined') { - return new TextDecoder('utf-8').decode(bytes); - } - return decodeUtf8Manually(bytes); -} - -function continuationCount(lead: number): number { - if (lead < 0x80) return 0; - if (lead >= 0xc2 && lead <= 0xdf) return 1; - if (lead >= 0xe0 && lead <= 0xef) return 2; - if (lead >= 0xf0 && lead <= 0xf4) return 3; - return -1; -} - -function decodeUtf8Manually(bytes: Uint8Array): string { - let result = ''; - let i = 0; - while (i < bytes.length) { - const lead = bytes[i] ?? 0; - const extra = continuationCount(lead); - if (extra < 0) { - result += REPLACEMENT_CHAR; - i++; - continue; - } - let codePoint = extra === 0 ? lead : lead % 2 ** (6 - extra); - let consumed = 1; - let valid = true; - for (let k = 1; k <= extra; k++) { - const next = bytes[i + k]; - if (next === undefined || next < 0x80 || next > 0xbf) { - valid = false; - break; - } - codePoint = codePoint * 64 + (next - 0x80); - consumed++; - } - const minimum = [0, 0x80, 0x800, 0x10000][extra] ?? 0; - const isSurrogate = codePoint >= 0xd800 && codePoint <= 0xdfff; - if (!valid || codePoint < minimum || codePoint > 0x10ffff || isSurrogate) { - result += REPLACEMENT_CHAR; - i += valid ? consumed : Math.max(consumed, 1); - continue; - } - result += String.fromCodePoint(codePoint); - i += consumed; - } - return result; -} - -function assignName(card: CardData, textValue: string) { - const parts = textValue.split(';'); - const name: CardName = {}; - const fields: (keyof CardName)[] = [ - 'surname', - 'given', - 'additional', - 'prefix', - 'suffix', - ]; - fields.forEach((field, index) => { - const part = parts[index]; - if (part) { - name[field] = unescapeValue(part); - } - }); - if (Object.keys(name).length > 0) { - card.n = name; - } else { - delete card.n; - } -} - -function parseTypes(keyPart: string): string[] { - return keyPart - .split(';') - .filter((param) => param.trim().toUpperCase().startsWith('TYPE=')) - .flatMap((param) => - param - .substring(param.indexOf('=') + 1) - .split(',') - .map((t) => { - const cleaned = t.trim().toLowerCase(); - return cleaned.startsWith('type=') ? cleaned.substring(5) : cleaned; - }) - ) - .filter((t) => t !== 'internet'); -} - -function collectComm( - commMap: Map>, - mapKey: string, - keyPart: string -) { - const collected = commMap.get(mapKey) ?? new Set(); - parseTypes(keyPart).forEach((t) => collected.add(t)); - commMap.set(mapKey, collected); -} - -function parsePhoto(keyPart: string, value: string): CardPhoto { - let type = 'jpeg'; - let encoding: string | null = null; - keyPart - .split(';') - .slice(1) - .forEach((param) => { - const [pKey, pValue] = param.split('='); - const name = pKey?.trim().toUpperCase(); - if (name === 'TYPE') { - type = pValue ? pValue.trim().toLowerCase() : 'jpeg'; - } else if (name === 'ENCODING') { - encoding = pValue ? pValue.trim().toLowerCase() : null; - } - }); - return encoding === 'b' - ? { type, data: value, ref: DEL_CHAR } - : { type, data: DEL_CHAR, ref: value }; -} - -interface DateParts { - year: number | null; - month: number | null; - day: number | null; -} - -function parseDateParts(dateStr: string): DateParts { - const noHyphens = dateStr.replace(/-/g, ''); - const parts: DateParts = { year: null, month: null, day: null }; - - if (noHyphens.length === 6 && /^\d{6}$/.test(noHyphens)) { - const yy = parseInt(noHyphens.substring(0, 2), 10); - parts.month = parseInt(noHyphens.substring(2, 4), 10); - parts.day = parseInt(noHyphens.substring(4, 6), 10); - parts.year = yy >= 35 ? 1900 + yy : 2000 + yy; - } else if (dateStr.startsWith('--')) { - const cleaned = dateStr.replace(/^-+/, ''); - if (cleaned.length === 4 && /^\d{4}$/.test(cleaned)) { - parts.month = parseInt(cleaned.substring(0, 2), 10); - parts.day = parseInt(cleaned.substring(2, 4), 10); - } else if (cleaned.includes('-')) { - const pieces = cleaned.split('-'); - parts.month = parseInt(pieces[0] ?? '', 10); - parts.day = parseInt(pieces[1] ?? '', 10); - } - } else if (noHyphens.length === 8 && /^\d{8}$/.test(noHyphens)) { - parts.year = parseInt(noHyphens.substring(0, 4), 10); - parts.month = parseInt(noHyphens.substring(4, 6), 10); - parts.day = parseInt(noHyphens.substring(6, 8), 10); - } else if (dateStr.includes('-')) { - const pieces = dateStr.split('-'); - if (pieces[0] && !/^-+$/.test(pieces[0])) { - parts.year = parseInt(pieces[0], 10); - } - if (pieces.length >= 2) { - parts.month = parseInt(pieces[1] ?? '', 10); - } - if (pieces.length >= 3) { - parts.day = parseInt(pieces[2] ?? '', 10); - } - } - return parts; -} - -function parseBirthday(value: string): CardBirthday | null { - const dateStr = (value.split(/[T ]/)[0] ?? '').trim(); - const { year, month, day } = parseDateParts(dateStr); - - const isValidMonth = !!month && month >= 1 && month <= 12; - const isValidDay = !!day && day >= 1 && day <= 31; - const isValidYear = !year || (year >= 1800 && year <= 2200); - - if (!month || !day || !isValidMonth || !isValidDay || !isValidYear) { - return null; - } - return year ? { y: year, m: month, d: day } : { m: month, d: day }; -} diff --git a/src/core/tinode.ts b/src/core/tinode.ts deleted file mode 100644 index 02c13dc..0000000 --- a/src/core/tinode.ts +++ /dev/null @@ -1,1648 +0,0 @@ -import AccessMode from './access-mode'; -import CommError from './comm-error'; -import * as Const from './config'; -import Connection from './connection'; -import type { - AutoreconnectIterationCallback, - WebSocketProviderType, - XHRProviderType as ConnectionXHRProviderType, -} from './connection'; -import Drafty from './drafty'; -import type { DraftyDoc } from './drafty'; -import TopicFnd from './fnd-topic'; -import LargeFileHelper from './large-file'; -import type { XHRProviderType as LargeFileXHRProviderType } from './large-file'; -import TopicMe from './me-topic'; -import MetaGetBuilder from './meta-builder'; -import type { GetQuery } from './meta-builder'; -import PersistentCache from './storage/persistent-cache'; -import { resolveStorageAdapter } from './storage/resolve-adapter'; -import type { StorageAdapter } from './storage/storage-adapter'; -import TheCard from './the-card'; -import Topic from './topic'; -import type { - AccPacket, - AccountParams, - AuthToken, - ClientMessage, - Credential, - CtrlMessage, - DataMessage, - DelPacket, - GetPacket, - InfoMessage, - MetaMessage, - NotePacket, - PresMessage, - PubMessage, - PushPayload, - ServerMessage, - ServerParams, - SetPacket, - SetParams, - SubPacket, -} from './types'; -import { - isUrlRelative, - jsonParseHelper, - mergeObj, - rfc3339DateString, - simplify, -} from './utils'; -import type { SeqRange } from './utils'; - -export { AccessMode, Drafty, TheCard }; - -export type XHRProviderType = ConnectionXHRProviderType & - LargeFileXHRProviderType; - -export interface TinodeConfig { - appName?: string; - host: string; - apiKey: string; - transport?: 'ws' | 'lp' | null; - secure?: boolean; - platform?: 'ios' | 'android' | 'web'; - persist?: boolean; - storage?: StorageAdapter | null; -} - -interface PendingPromise { - resolve(ctrl: CtrlMessage): void; - resolveMeta?(meta: MetaMessage): void; - reject(err: Error): void; - ts: Date; -} - -let WebSocketProvider: WebSocketProviderType | undefined = - typeof WebSocket !== 'undefined' ? WebSocket : undefined; -let XHRProvider: XHRProviderType | undefined = - typeof XMLHttpRequest !== 'undefined' ? XMLHttpRequest : undefined; - -const BASE64_CHARS = - 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/'; - -function detectTransport(): 'ws' | 'lp' | null { - if (WebSocketProvider) { - return 'ws'; - } - if (XHRProvider) { - return 'lp'; - } - return null; -} - -function base64EncodeLatin1(binary: string): string { - let output = ''; - for (let i = 0; i < binary.length; i += 3) { - const a = binary.charCodeAt(i); - const b = i + 1 < binary.length ? binary.charCodeAt(i + 1) : 0; - const c = i + 2 < binary.length ? binary.charCodeAt(i + 2) : 0; - const triple = (a << 16) | (b << 8) | c; - output += BASE64_CHARS.charAt((triple >> 18) & 63); - output += BASE64_CHARS.charAt((triple >> 12) & 63); - output += - i + 1 < binary.length ? BASE64_CHARS.charAt((triple >> 6) & 63) : '='; - output += i + 2 < binary.length ? BASE64_CHARS.charAt(triple & 63) : '='; - } - return output; -} - -function b64EncodeUnicode(str: string): string { - const binary = encodeURIComponent(str).replace( - /%([0-9A-F]{2})/g, - (_match, hex: string) => String.fromCharCode(parseInt(hex, 16)) - ); - return typeof btoa === 'function' ? btoa(binary) : base64EncodeLatin1(binary); -} - -function jsonBuildHelper(_key: string, val: unknown): unknown { - if (val instanceof Date) { - return rfc3339DateString(val); - } - if (val instanceof AccessMode) { - return val.jsonHelper(); - } - if ( - val === undefined || - val === null || - val === false || - (Array.isArray(val) && val.length === 0) || - (typeof val === 'object' && Object.keys(val).length === 0) - ) { - return undefined; - } - return val; -} - -function jsonLoggerHelper(key: string, val: unknown): unknown { - if (typeof val === 'string' && val.length > 128) { - return ( - '<' + - val.length + - ', bytes: ' + - val.substring(0, 12) + - '...' + - val.substring(val.length - 12) + - '>' - ); - } - return jsonBuildHelper(key, val); -} - -function navigatorField(name: string): string | undefined { - const nav: unknown = Reflect.get(globalThis, 'navigator'); - if (typeof nav !== 'object' || nav === null) { - return undefined; - } - const value: unknown = Reflect.get(nav, name); - return typeof value === 'string' ? value : undefined; -} - -function getBrowserInfo(ua: string | undefined, product?: string): string { - ua = ua || ''; - const reactnative = /reactnative/i.test(product || '') ? 'ReactNative; ' : ''; - let result: string; - ua = ua.replace(' (KHTML, like Gecko)', ''); - const webkit = ua.match(/(AppleWebKit\/[.\d]+)/i); - if (webkit) { - const priority = ['edg', 'chrome', 'safari', 'mobile', 'version']; - const parts = ua - .substring((webkit.index ?? 0) + webkit[0].length) - .split(' '); - const tokens: [string, string, number][] = []; - let version: string | undefined; - for (const part of parts) { - const m2 = /([\w.]+)[/]([.\d]+)/.exec(part); - if (m2 && m2[1] && m2[2]) { - const name = m2[1]; - tokens.push([ - name, - m2[2], - priority.findIndex((e) => name.toLowerCase().startsWith(e)), - ]); - if (name === 'Version') { - version = m2[2]; - } - } - } - tokens.sort((a, b) => a[2] - b[2]); - const top = tokens[0]; - if (top) { - if (top[0].toLowerCase().startsWith('edg')) { - top[0] = 'Edge'; - } else if (top[0] === 'OPR') { - top[0] = 'Opera'; - } else if (top[0] === 'Safari' && version) { - top[1] = version; - } - result = top[0] + '/' + top[1]; - } else { - result = webkit[1] ?? ''; - } - } else if (/firefox/i.test(ua)) { - const m = /Firefox\/([.\d]+)/g.exec(ua); - result = m ? 'Firefox/' + m[1] : 'Firefox/?'; - } else { - const m = /([\w.]+)\/([.\d]+)/.exec(ua); - result = m ? m[1] + '/' + m[2] : (ua.split(' ')[0] ?? ''); - } - - const [name, ver] = result.split('/'); - if (ver !== undefined) { - const v = ver.split('.'); - const minor = v[1] ? '.' + v[1].substring(0, 2) : ''; - result = `${name}/${v[0]}${minor}`; - } - return reactnative + result; -} - -export class Tinode { - static readonly MESSAGE_STATUS_NONE = Const.MESSAGE_STATUS_NONE; - static readonly MESSAGE_STATUS_QUEUED = Const.MESSAGE_STATUS_QUEUED; - static readonly MESSAGE_STATUS_SENDING = Const.MESSAGE_STATUS_SENDING; - static readonly MESSAGE_STATUS_FAILED = Const.MESSAGE_STATUS_FAILED; - static readonly MESSAGE_STATUS_FATAL = Const.MESSAGE_STATUS_FATAL; - static readonly MESSAGE_STATUS_SENT = Const.MESSAGE_STATUS_SENT; - static readonly MESSAGE_STATUS_RECEIVED = Const.MESSAGE_STATUS_RECEIVED; - static readonly MESSAGE_STATUS_READ = Const.MESSAGE_STATUS_READ; - static readonly MESSAGE_STATUS_TO_ME = Const.MESSAGE_STATUS_TO_ME; - - static readonly DEL_CHAR = Const.DEL_CHAR; - - static readonly MAX_MESSAGE_SIZE = 'maxMessageSize'; - static readonly MAX_SUBSCRIBER_COUNT = 'maxSubscriberCount'; - static readonly MIN_TAG_LENGTH = 'minTagLength'; - static readonly MAX_TAG_LENGTH = 'maxTagLength'; - static readonly MAX_TAG_COUNT = 'maxTagCount'; - static readonly MAX_FILE_UPLOAD_SIZE = 'maxFileUploadSize'; - static readonly REQ_CRED_VALIDATORS = 'reqCred'; - static readonly MSG_DELETE_AGE = 'msgDelAge'; - - static readonly URI_TOPIC_ID_PREFIX = 'tinode:///id/'; - static readonly URI_TOPIC_ALIAS_PREFIX = 'tinode:///alias/'; - - static readonly TAG_ALIAS = Const.TAG_ALIAS; - static readonly TAG_EMAIL = Const.TAG_EMAIL; - static readonly TAG_PHONE = Const.TAG_PHONE; - - _host: string; - _secure: boolean | undefined; - _appName: string; - _apiKey: string; - _browser = ''; - _platform: string; - _hwos = 'undefined'; - _humanLanguage = 'xx'; - - _loggingEnabled = false; - _trimLongStrings = false; - _myUID: string | null = null; - _authenticated = false; - _login: string | null = null; - _authToken: AuthToken | null = null; - _inPacketCount = 0; - _messageId = Math.floor(Math.random() * 0xffff + 0xffff); - _serverInfo: ServerParams | null = null; - _deviceToken: string | null = null; - - _pendingPromises: Record = {}; - _expirePromises: ReturnType | null = null; - - _connection: Connection; - _persist = false; - _db: PersistentCache; - _cache: Record = {}; - - onWebsocketOpen: (() => void) | undefined = undefined; - onConnect: (() => void) | undefined = undefined; - onDisconnect: ((err?: Error | null) => void) | undefined = undefined; - onLogin: ((code: number, text: string | undefined) => void) | undefined = - undefined; - onCtrlMessage: ((ctrl: CtrlMessage) => void) | undefined = undefined; - onDataMessage: ((data: DataMessage) => void) | undefined = undefined; - onPresMessage: ((pres: PresMessage) => void) | undefined = undefined; - onMetaMessage: ((meta: MetaMessage) => void) | undefined = undefined; - onInfoMessage: ((info: InfoMessage) => void) | undefined = undefined; - onMessage: ((pkt: ServerMessage) => void) | undefined = undefined; - onRawMessage: ((text: string) => void) | undefined = undefined; - onNetworkProbe: (() => void) | undefined = undefined; - onAutoreconnectIteration: AutoreconnectIterationCallback | undefined = - undefined; - - constructor(config: TinodeConfig, onComplete?: (err?: unknown) => void) { - this._host = config.host; - this._secure = config.secure; - this._appName = config.appName || 'Undefined'; - this._apiKey = config.apiKey; - this._platform = config.platform || 'web'; - - const product = navigatorField('product'); - if (product === 'ReactNative') { - this._browser = 'ReactNative'; - this._hwos = this._platform; - } else if (typeof Reflect.get(globalThis, 'navigator') === 'object') { - this._browser = getBrowserInfo(navigatorField('userAgent'), product); - this._hwos = navigatorField('platform') ?? this._hwos; - } - this._humanLanguage = navigatorField('language') || 'en-US'; - - Connection.logger = this.logger; - Drafty.logger = this.logger; - - const transport = - config.transport === 'lp' || config.transport === 'ws' - ? config.transport - : detectTransport(); - this._connection = new Connection( - { - host: config.host, - apiKey: config.apiKey, - transport: transport ?? '', - secure: config.secure, - }, - Const.PROTOCOL_VERSION, - true - ); - this._connection.onMessage = (data) => { - this.#dispatchMessage(data); - }; - this._connection.onOpen = () => this.#connectionOpen(); - this._connection.onDisconnect = (err) => this.#disconnected(err); - this._connection.onAutoreconnectIteration = (timeout, promise) => { - if (this.onAutoreconnectIteration) { - this.onAutoreconnectIteration(timeout, promise); - } - }; - - this._persist = !!(config.persist || config.storage); - this._db = new PersistentCache( - this.logger, - this.logger, - resolveStorageAdapter(this._persist, config.storage) - ); - - if (this._persist) { - this.#loadPersistentCache(onComplete); - } else { - this._db.deleteDatabase().then(() => { - if (onComplete) { - onComplete(); - } - }); - } - } - - #loadPersistentCache(onComplete?: (err?: unknown) => void): void { - const prom: Promise[] = []; - this._db - .initDatabase() - .then(() => - this._db.mapTopics((data) => { - if (this.#cacheGetTopic(data.name)) { - return; - } - let topic: Topic; - if (data.name === Const.TOPIC_ME) { - topic = new TopicMe(); - } else if (data.name === Const.TOPIC_FND) { - topic = new TopicFnd(); - } else { - topic = new Topic(data.name); - } - this._db.deserializeTopic(topic, data); - this.#attachCacheToTopic(topic); - topic._cachePutSelf(); - this._db.maxDelId(topic.name).then((clear) => { - topic._maxDel = Math.max(topic._maxDel, clear || 0); - }); - delete topic._new; - prom.push(topic._loadMessages(this._db)); - prom.push( - this._db.mapSubscriptions(topic.name, (sub) => { - topic._processMetaSubs([sub], true); - }) - ); - }) - ) - .then(() => - this._db.mapUsers((data) => { - this.#cachePut('user', data.uid, mergeObj({}, data.public)); - }) - ) - .then(() => Promise.all(prom)) - .then(() => { - if (onComplete) { - onComplete(); - } - this.logger('Persistent cache initialized.'); - }) - .catch((err: unknown) => { - if (onComplete) { - onComplete(err); - } - this.logger('Failed to initialize persistent cache:', err); - }); - } - - logger = (str: unknown, ...args: unknown[]): void => { - if (this._loggingEnabled) { - const d = new Date(); - const dateString = - ('0' + d.getUTCHours()).slice(-2) + - ':' + - ('0' + d.getUTCMinutes()).slice(-2) + - ':' + - ('0' + d.getUTCSeconds()).slice(-2) + - '.' + - ('00' + d.getUTCMilliseconds()).slice(-3); - - console.log('[' + dateString + ']', str, args.join(' ')); - } - }; - - #execPromise( - id: string, - code: number, - onOK: CtrlMessage | null, - errorText?: string - ): void { - const callbacks = this._pendingPromises[id]; - if (!callbacks) { - return; - } - delete this._pendingPromises[id]; - if (code >= 200 && code < 400) { - if (onOK) { - callbacks.resolve(onOK); - } - } else { - callbacks.reject(new CommError(errorText ?? '', code)); - } - } - - #execMetaPromise(id: string, meta: MetaMessage): void { - const callbacks = this._pendingPromises[id]; - if (callbacks?.resolveMeta) { - delete this._pendingPromises[id]; - callbacks.resolveMeta(meta); - } - } - - #send(pkt: ClientMessage, id?: string): void { - simplify(pkt); - const msg = JSON.stringify(pkt); - this.logger( - 'out: ' + - (this._trimLongStrings ? JSON.stringify(pkt, jsonLoggerHelper) : msg) - ); - try { - this._connection.sendText(msg); - } catch (err) { - if (id) { - this.#execPromise( - id, - Connection.NETWORK_ERROR, - null, - err instanceof Error ? err.message : String(err) - ); - } else { - throw err; - } - } - } - - #request(pkt: ClientMessage, id: string | undefined): Promise { - if (!id) { - return Promise.reject(new Error('Request has no id')); - } - const promise = new Promise((resolve, reject) => { - this._pendingPromises[id] = { resolve, reject, ts: new Date() }; - }); - this.#send(pkt, id); - return promise; - } - - #requestMeta( - pkt: ClientMessage, - id: string | undefined - ): Promise { - if (!id) { - return Promise.reject(new Error('Request has no id')); - } - const promise = new Promise( - (resolve, reject) => { - this._pendingPromises[id] = { - resolve, - resolveMeta: resolve, - reject, - ts: new Date(), - }; - } - ); - this.#send(pkt, id); - return promise; - } - - #dispatchMessage(data: string): void { - if (!data) { - return; - } - - this._inPacketCount++; - - if (this.onRawMessage) { - this.onRawMessage(data); - } - - if (data === '0') { - if (this.onNetworkProbe) { - this.onNetworkProbe(); - } - return; - } - - const pkt: ServerMessage | null = JSON.parse(data, jsonParseHelper); - if (!pkt) { - this.logger('in: ' + data); - this.logger('ERROR: failed to parse data'); - return; - } - - this.logger( - 'in: ' + - (this._trimLongStrings ? JSON.stringify(pkt, jsonLoggerHelper) : data) - ); - - if (this.onMessage) { - this.onMessage(pkt); - } - - const ctrl = pkt.ctrl; - if (ctrl) { - if (this.onCtrlMessage) { - this.onCtrlMessage(ctrl); - } - - if (ctrl.id) { - this.#execPromise(ctrl.id, ctrl.code, ctrl, ctrl.text); - } - setTimeout(() => { - if (ctrl.code === 205 && ctrl.text === 'evicted') { - const topic = this.#cacheGetTopic(ctrl.topic); - if (topic) { - topic._resetSub(); - if (ctrl.params?.unsub) { - topic._gone(); - } - } - } else if (ctrl.code < 300 && ctrl.params) { - if (ctrl.params.what === 'data') { - const topic = this.#cacheGetTopic(ctrl.topic); - if (topic) { - topic._allMessagesReceived(ctrl.params.count ?? 0); - } - } else if (ctrl.params.what === 'sub') { - const topic = this.#cacheGetTopic(ctrl.topic); - if (topic) { - topic._processMetaSubs([]); - } - } - } - }, 0); - return; - } - - setTimeout(() => { - if (pkt.meta) { - const topic = this.#cacheGetTopic(pkt.meta.topic); - if (topic) { - topic._routeMeta(pkt.meta); - } - - if (pkt.meta.id) { - this.#execMetaPromise(pkt.meta.id, pkt.meta); - } - - if (this.onMetaMessage) { - this.onMetaMessage(pkt.meta); - } - } else if (pkt.data) { - const topic = this.#cacheGetTopic(pkt.data.topic); - if (topic) { - topic._routeData(pkt.data); - } - - if (this.onDataMessage) { - this.onDataMessage(pkt.data); - } - } else if (pkt.pres) { - const topic = this.#cacheGetTopic(pkt.pres.topic); - if (topic) { - topic._routePres(pkt.pres); - } - - if (this.onPresMessage) { - this.onPresMessage(pkt.pres); - } - } else if (pkt.info) { - const topic = this.#cacheGetTopic(pkt.info.topic); - if (topic) { - topic._routeInfo(pkt.info); - } - - if (this.onInfoMessage) { - this.onInfoMessage(pkt.info); - } - } else { - this.logger('ERROR: Unknown packet received.'); - } - }, 0); - } - - #connectionOpen(): void { - if (!this._expirePromises) { - this._expirePromises = setInterval(() => { - const err = new CommError('timeout', 504); - const expires = new Date( - new Date().getTime() - Const.EXPIRE_PROMISES_TIMEOUT - ); - for (const id in this._pendingPromises) { - const callbacks = this._pendingPromises[id]; - if (callbacks && callbacks.ts < expires) { - this.logger('Promise expired', id); - delete this._pendingPromises[id]; - callbacks.reject(err); - } - } - }, Const.EXPIRE_PROMISES_PERIOD); - } - this.hello(); - } - - #disconnected(err: CommError): void { - this._inPacketCount = 0; - this._serverInfo = null; - this._authenticated = false; - - if (this._expirePromises) { - clearInterval(this._expirePromises); - this._expirePromises = null; - } - - this.mapTopics((topic) => { - topic._resetSub(); - }); - - for (const key in this._pendingPromises) { - this._pendingPromises[key]?.reject(err); - } - this._pendingPromises = {}; - - if (this.onDisconnect) { - this.onDisconnect(err); - } - } - - #getUserAgent(): string { - return ( - this._appName + - ' (' + - (this._browser ? this._browser + '; ' : '') + - this._hwos + - '); ' + - Const.LIBRARY - ); - } - - #cachePut(type: 'topic' | 'user', name: string, obj: unknown): void { - this._cache[type + ':' + name] = obj; - } - - #cacheGet(type: 'topic' | 'user', name: string | null | undefined): unknown { - return this._cache[type + ':' + name]; - } - - #cacheDel(type: 'topic' | 'user', name: string): void { - delete this._cache[type + ':' + name]; - } - - #cacheGetTopic(name: string | null | undefined): Topic | undefined { - const topic = this.#cacheGet('topic', name); - return topic instanceof Topic ? topic : undefined; - } - - #attachCacheToTopic(topic: Topic): void { - topic._tinode = this; - - topic._cacheGetUser = (uid) => { - const pub = this.#cacheGet('user', uid); - if (pub) { - return { - user: uid, - public: mergeObj({}, pub), - }; - } - return undefined; - }; - topic._cachePutUser = (uid, user) => { - this.#cachePut('user', uid, mergeObj({}, user.public)); - }; - topic._cacheDelUser = (uid) => { - this.#cacheDel('user', uid); - }; - topic._cachePutSelf = () => { - this.#cachePut('topic', topic.name, topic); - }; - topic._cacheDelSelf = () => { - this.#cacheDel('topic', topic.name); - }; - } - - #loginSuccessful(ctrl: CtrlMessage): CtrlMessage { - if (!ctrl.params || !ctrl.params.user) { - return ctrl; - } - this._myUID = ctrl.params.user; - this._authenticated = ctrl.code >= 200 && ctrl.code < 300; - if (ctrl.params.token && ctrl.params.expires) { - this._authToken = { - token: ctrl.params.token, - expires: ctrl.params.expires, - }; - } else { - this._authToken = null; - } - - if (this.onLogin) { - this.onLogin(ctrl.code, ctrl.text); - } - - return ctrl; - } - - static credential( - meth?: string | Credential | null, - val?: string | null, - params?: unknown, - resp?: string | null - ): Credential[] | null { - if (meth && typeof meth === 'object') { - ({ val, params, resp, meth } = meth); - } - if (meth && (val || resp)) { - return [ - { - meth: meth, - val: val ?? undefined, - resp: resp ?? undefined, - params: params, - }, - ]; - } - return null; - } - - static topicType(name: string | null | undefined) { - return Topic.topicType(name); - } - - static isMeTopicName(name: string | null | undefined): boolean { - return Topic.isMeTopicName(name); - } - - static isSelfTopicName(name: string | null | undefined): boolean { - return Topic.isSelfTopicName(name); - } - - static isGroupTopicName(name: string | null | undefined): boolean { - return Topic.isGroupTopicName(name); - } - - static isP2PTopicName(name: string | null | undefined): boolean { - return Topic.isP2PTopicName(name); - } - - static isCommTopicName(name: string | null | undefined): boolean { - return Topic.isCommTopicName(name); - } - - static isNewGroupTopicName(name: string | null | undefined): boolean { - return Topic.isNewGroupTopicName(name); - } - - static isChannelTopicName(name: string | null | undefined): boolean { - return Topic.isChannelTopicName(name); - } - - static getVersion(): string { - return Const.VERSION; - } - - static setNetworkProviders( - wsProvider?: WebSocketProviderType | null, - xhrProvider?: XHRProviderType | null - ): void { - WebSocketProvider = wsProvider ?? undefined; - XHRProvider = xhrProvider ?? undefined; - - Connection.setNetworkProviders(WebSocketProvider, XHRProvider); - LargeFileHelper.setNetworkProvider(XHRProvider); - } - - static getLibrary(): string { - return Const.LIBRARY; - } - - static isNullValue(str: unknown): boolean { - return str === Const.DEL_CHAR; - } - - static isServerAssignedSeq(seq: number): boolean { - return seq > 0 && seq < Const.LOCAL_SEQID; - } - - static parseTinodeUrl(tinodeUrl: unknown): string | null { - if (!tinodeUrl || typeof tinodeUrl !== 'string') { - return null; - } - if (!tinodeUrl.startsWith('tinode:')) { - return tinodeUrl; - } - const parts = tinodeUrl.substring(7).split('/'); - if (parts.length < 2 || parts[parts.length - 2] !== 'id') { - return tinodeUrl; - } - return parts[parts.length - 1] ?? tinodeUrl; - } - - static isValidTagValue(tag: unknown): boolean { - const ALIAS_REGEX = /^[a-z0-9][a-z0-9_-]{3,23}$/i; - return ( - typeof tag === 'string' && - tag.length > 3 && - tag.length < 24 && - ALIAS_REGEX.test(tag) - ); - } - - static tagSplit( - tag: string | null | undefined - ): { prefix: string; value: string } | null { - if (!tag) { - return null; - } - - tag = tag.trim(); - - const splitAt = tag.indexOf(':'); - if (splitAt <= 0) { - return null; - } - - const value = tag.substring(splitAt + 1); - if (!value) { - return null; - } - return { - prefix: tag.substring(0, splitAt), - value: value, - }; - } - - static setUniqueTag( - tags: string[] | null | undefined, - uniqueTag: string - ): string[] { - if (!tags || tags.length === 0) { - return [uniqueTag]; - } - - const parts = Tinode.tagSplit(uniqueTag); - if (!parts) { - return tags; - } - - const result = tags.filter((tag) => tag && !tag.startsWith(parts.prefix)); - result.push(uniqueTag); - return result; - } - - static clearTagPrefix( - tags: (string | null | undefined)[] | null | undefined, - prefix: string - ): string[] { - if (!tags || tags.length === 0) { - return []; - } - return tags.filter( - (tag): tag is string => !!tag && !tag.startsWith(prefix) - ); - } - - static tagByPrefix( - tags: (string | null | undefined)[] | null | undefined, - prefix: string - ): string | undefined { - if (!tags) { - return undefined; - } - return tags.find((tag): tag is string => !!tag && tag.startsWith(prefix)); - } - - getNextUniqueId(): string | undefined { - return this._messageId !== 0 ? '' + this._messageId++ : undefined; - } - - connect(host_?: string | null): Promise { - return this._connection.connect(host_); - } - - reconnect(force?: boolean): void { - this._connection.reconnect(force); - } - - disconnect(): void { - this._connection.disconnect(); - } - - clearStorage(): Promise { - if (this._db.isReady()) { - return this._db.deleteDatabase(); - } - return Promise.resolve(); - } - - initStorage(): Promise { - if (!this._db.isReady()) { - return this._db.initDatabase(); - } - return Promise.resolve(); - } - - networkProbe(): void { - this._connection.probe(); - } - - isConnected(): boolean { - return this._connection.isConnected(); - } - - isAuthenticated(): boolean { - return this._authenticated; - } - - authorizeURL(url: T): T | string { - if (typeof url !== 'string') { - return url; - } - - if (isUrlRelative(url)) { - const base = 'scheme://host/'; - const parsed = new URL(url, base); - if (this._apiKey) { - parsed.searchParams.append('apikey', this._apiKey); - } - if (this._authToken && this._authToken.token) { - parsed.searchParams.append('auth', 'token'); - parsed.searchParams.append('secret', this._authToken.token); - } - return parsed.toString().substring(base.length - 1); - } - return url; - } - - account( - uid: string | null, - scheme: string | null, - secret: string | null, - login?: boolean, - params?: AccountParams - ): Promise { - const acc: AccPacket = { - id: this.getNextUniqueId(), - user: uid, - scheme: scheme, - secret: secret, - login: login, - desc: {}, - }; - const pkt: ClientMessage = { acc }; - - if (params) { - acc.desc.defacs = params.defacs; - acc.desc.public = params.public; - acc.desc.private = params.private; - acc.desc.trusted = params.trusted; - - acc.tags = params.tags; - acc.cred = params.cred; - - acc.tmpscheme = params.scheme; - acc.tmpsecret = params.secret; - - if (Array.isArray(params.attachments) && params.attachments.length > 0) { - pkt.extra = { - attachments: params.attachments.filter((ref) => isUrlRelative(ref)), - }; - } - } - - return this.#request(pkt, acc.id); - } - - createAccount( - scheme: string, - secret: string, - login?: boolean, - params?: AccountParams - ): Promise { - let promise = this.account(Const.USER_NEW, scheme, secret, login, params); - if (login) { - promise = promise.then((ctrl) => this.#loginSuccessful(ctrl)); - } - return promise; - } - - createAccountBasic( - username: string | null | undefined, - password: string | null | undefined, - params?: AccountParams - ): Promise { - username = username || ''; - password = password || ''; - return this.createAccount( - 'basic', - b64EncodeUnicode(username + ':' + password), - true, - params - ); - } - - updateAccountBasic( - uid: string | null, - username: string | null | undefined, - password: string | null | undefined, - params?: AccountParams - ): Promise { - username = username || ''; - password = password || ''; - return this.account( - uid, - 'basic', - b64EncodeUnicode(username + ':' + password), - false, - params - ); - } - - hello(): Promise { - const id = this.getNextUniqueId(); - const pkt: ClientMessage = { - hi: { - id: id, - ver: Const.VERSION, - ua: this.#getUserAgent(), - dev: this._deviceToken, - lang: this._humanLanguage, - platf: this._platform, - }, - }; - - return this.#request(pkt, id) - .then((ctrl) => { - this._connection.backoffReset(); - - if (ctrl.params) { - this._serverInfo = ctrl.params; - } - - if (this.onConnect) { - this.onConnect(); - } - - return ctrl; - }) - .catch((err: unknown) => { - this._connection.reconnect(true); - - if (this.onDisconnect) { - this.onDisconnect( - err instanceof Error ? err : new Error(String(err)) - ); - } - return undefined; - }); - } - - setDeviceToken(dt: string | null | undefined | false): boolean { - let sent = false; - const token = dt || null; - if (token !== this._deviceToken) { - this._deviceToken = token; - if (this.isConnected() && this.isAuthenticated()) { - this.#send({ - hi: { - dev: token || Tinode.DEL_CHAR, - }, - }); - sent = true; - } - } - return sent; - } - - login( - scheme: string, - secret: string, - cred?: Credential[] | null - ): Promise { - const id = this.getNextUniqueId(); - const pkt: ClientMessage = { - login: { - id: id, - scheme: scheme, - secret: secret, - cred: cred, - }, - }; - - return this.#request(pkt, id).then((ctrl) => this.#loginSuccessful(ctrl)); - } - - loginBasic( - uname: string, - password: string, - cred?: Credential[] | null - ): Promise { - return this.login( - 'basic', - b64EncodeUnicode(uname + ':' + password), - cred - ).then((ctrl) => { - this._login = uname; - return ctrl; - }); - } - - loginToken(token: string, cred?: Credential[] | null): Promise { - return this.login('token', token, cred); - } - - requestResetAuthSecret( - scheme: string, - method: string, - value: string - ): Promise { - return this.login( - 'reset', - b64EncodeUnicode(scheme + ':' + method + ':' + value) - ); - } - - getAuthToken(): AuthToken | null { - if (this._authToken && this._authToken.expires.getTime() > Date.now()) { - return this._authToken; - } - this._authToken = null; - return null; - } - - setAuthToken(token: AuthToken | null): void { - this._authToken = token; - } - - subscribe( - topicName: string, - getParams?: GetQuery, - setParams?: SetParams - ): Promise { - const sub: SubPacket = { - id: this.getNextUniqueId(), - topic: topicName, - set: {}, - get: getParams, - }; - const pkt: ClientMessage = { sub }; - const name = topicName || Const.TOPIC_NEW; - - if (setParams) { - if (setParams.sub) { - sub.set.sub = setParams.sub; - } - - const desc = setParams.desc; - if (desc) { - if (Tinode.isNewGroupTopicName(name)) { - sub.set.desc = desc; - } else if (Tinode.isP2PTopicName(name) && desc.defacs) { - sub.set.desc = { - defacs: desc.defacs, - }; - } - } - - if ( - Array.isArray(setParams.attachments) && - setParams.attachments.length > 0 - ) { - pkt.extra = { - attachments: setParams.attachments.filter((ref) => - isUrlRelative(ref) - ), - }; - } - - if (setParams.tags) { - sub.set.tags = setParams.tags; - } - if (setParams.aux) { - sub.set.aux = setParams.aux; - } - } - return this.#request(pkt, sub.id); - } - - leave(topic: string, unsub?: boolean): Promise { - const id = this.getNextUniqueId(); - return this.#request({ leave: { id, topic, unsub } }, id); - } - - createMessage( - topic: string, - content: DraftyDoc | string, - noEcho?: boolean - ): PubMessage { - const dft = typeof content === 'string' ? Drafty.parse(content) : content; - let head: PubMessage['head'] = null; - if (dft && !Drafty.isPlainText(dft)) { - head = { - mime: Drafty.getContentType(), - }; - content = dft; - } - return { - id: this.getNextUniqueId(), - topic: topic, - noecho: noEcho, - head: head, - content: content, - }; - } - - publish( - topicName: string, - content: DraftyDoc | string, - noEcho?: boolean - ): Promise { - return this.publishMessage(this.createMessage(topicName, content, noEcho)); - } - - publishMessage( - pub: PubMessage, - attachments?: string[] | null - ): Promise { - const msg: PubMessage = { - ...pub, - seq: undefined, - from: undefined, - ts: undefined, - }; - const pkt: ClientMessage = { - pub: msg, - }; - if (attachments) { - pkt.extra = { - attachments: attachments.filter((ref) => isUrlRelative(ref)), - }; - } - return this.#request(pkt, msg.id); - } - - oobNotification(data: PushPayload): void { - this.logger( - 'oob: ' + - (this._trimLongStrings ? JSON.stringify(data, jsonLoggerHelper) : data) - ); - - switch (data.what) { - case 'msg': { - if (!data.seq || data.seq < 1 || !data.topic) { - break; - } - - if (!this.isConnected()) { - break; - } - - const topic = this.#cacheGetTopic(data.topic); - if (!topic) { - break; - } - - if (topic.isSubscribed()) { - break; - } - - if (topic.maxMsgSeq() < data.seq) { - if (topic.isChannelType()) { - topic._updateReceived(data.seq, 'fake-uid'); - } - - if (data.xfrom && !this.#cacheGet('user', data.xfrom)) { - this.getMeta( - data.xfrom, - new MetaGetBuilder(topic).withDesc().build() - ).catch((err: unknown) => { - this.logger('Failed to get the name of a new sender', err); - }); - } - - topic - .subscribe() - .then(() => - topic.getMeta( - new MetaGetBuilder(topic) - .withLaterData(24) - .withLaterDel(24) - .build() - ) - ) - .then(() => { - topic.leaveDelayed(false, 1000); - }) - .catch((err: unknown) => { - this.logger('On push data fetch failed', err); - }) - .finally(() => { - this.getMeTopic()._refreshContact('msg', topic); - }); - } - break; - } - - case 'read': - this.getMeTopic()._routePres({ - what: 'read', - seq: data.seq, - }); - break; - - case 'sub': { - if (!this.isMe(data.xfrom)) { - break; - } - - const mode = { - given: data.modeGiven, - want: data.modeWant, - }; - const acs = new AccessMode(mode); - const pres: PresMessage = - !acs.mode || acs.mode === AccessMode._NONE - ? { - what: 'gone', - src: data.topic, - } - : { - what: 'acs', - src: data.topic, - dacs: mode, - }; - this.getMeTopic()._routePres(pres); - break; - } - - default: - this.logger('Unknown push type ignored', data.what); - } - } - - getMeta( - topic: string, - params?: GetQuery - ): Promise { - const id = this.getNextUniqueId(); - const get = mergeObj({ id, topic }, params); - return this.#requestMeta({ get }, id); - } - - setMeta(topic: string, params: SetParams): Promise { - const set: SetPacket = { id: this.getNextUniqueId(), topic }; - const pkt: ClientMessage = { set }; - const what: string[] = []; - - if (params) { - if ('desc' in params) { - what.push('desc'); - set.desc = params.desc; - } - if ('sub' in params) { - what.push('sub'); - set.sub = params.sub; - } - if ('tags' in params) { - what.push('tags'); - set.tags = params.tags; - } - if ('cred' in params) { - what.push('cred'); - set.cred = params.cred; - } - if ('aux' in params) { - what.push('aux'); - set.aux = params.aux; - } - - if (Array.isArray(params.attachments) && params.attachments.length > 0) { - pkt.extra = { - attachments: params.attachments.filter((ref) => isUrlRelative(ref)), - }; - } - } - - if (what.length === 0) { - return Promise.reject(new Error('Invalid {set} parameters')); - } - - return this.#request(pkt, set.id); - } - - delMessages( - topic: string, - ranges: SeqRange[], - hard?: boolean - ): Promise { - const del: DelPacket = { - id: this.getNextUniqueId(), - topic: topic, - what: 'msg', - delseq: ranges, - hard: hard, - }; - return this.#request({ del }, del.id); - } - - delTopic(topicName: string, hard?: boolean): Promise { - const del: DelPacket = { - id: this.getNextUniqueId(), - topic: topicName, - what: 'topic', - hard: hard, - }; - return this.#request({ del }, del.id); - } - - delSubscription(topicName: string, user: string): Promise { - const del: DelPacket = { - id: this.getNextUniqueId(), - topic: topicName, - what: 'sub', - user: user, - }; - return this.#request({ del }, del.id); - } - - delCredential(method: string, value: string): Promise { - const del: DelPacket = { - id: this.getNextUniqueId(), - topic: Const.TOPIC_ME, - what: 'cred', - cred: { - meth: method, - val: value, - }, - }; - return this.#request({ del }, del.id); - } - - delCurrentUser(hard?: boolean): Promise { - const del: DelPacket = { - id: this.getNextUniqueId(), - topic: null, - what: 'user', - hard: hard, - }; - return this.#request({ del }, del.id).then(() => { - this._myUID = null; - }); - } - - note(topicName: string, what: 'recv' | 'read', seq: number): void { - if (seq <= 0 || seq >= Const.LOCAL_SEQID) { - throw new Error(`Invalid message id ${seq}`); - } - - const note: NotePacket = { - topic: topicName, - what: what, - seq: seq, - }; - this.#send({ note }); - } - - noteKeyPress(topicName: string, type?: 'kp' | 'kpa' | 'kpv'): void { - const note: NotePacket = { - topic: topicName, - what: type || 'kp', - }; - this.#send({ note }); - } - - videoCall( - topicName: string, - seq: number, - evt: string, - payload?: unknown - ): void { - const note: NotePacket = { - topic: topicName, - seq: seq, - what: 'call', - event: evt, - payload: payload, - }; - this.#send({ note }, note.id); - } - - getTopic(topicName: typeof Const.TOPIC_ME): TopicMe; - getTopic(topicName: typeof Const.TOPIC_FND): TopicFnd; - getTopic(topicName: string | null | undefined): Topic | undefined; - getTopic(topicName: string | null | undefined): Topic | undefined { - let topic = this.#cacheGetTopic(topicName); - if (!topic && topicName) { - if (topicName === Const.TOPIC_ME) { - topic = new TopicMe(); - } else if (topicName === Const.TOPIC_FND) { - topic = new TopicFnd(); - } else { - topic = new Topic(topicName); - } - this.#attachCacheToTopic(topic); - topic._cachePutSelf(); - } - return topic; - } - - cacheGetTopic(topicName: string | null | undefined): Topic | undefined { - return this.#cacheGetTopic(topicName); - } - - cacheRemTopic(topicName: string): void { - this.#cacheDel('topic', topicName); - } - - mapTopics( - func: (topic: Topic, key: string) => boolean | void, - context?: unknown - ): void { - for (const idx in this._cache) { - const topic = this._cache[idx]; - if (idx.startsWith('topic:') && topic instanceof Topic) { - if (func.call(context, topic, idx)) { - break; - } - } - } - } - - isTopicCached(topicName: string): boolean { - return !!this.#cacheGetTopic(topicName); - } - - newGroupTopicName(isChan?: boolean): string { - return ( - (isChan ? Const.TOPIC_NEW_CHAN : Const.TOPIC_NEW) + this.getNextUniqueId() - ); - } - - getMeTopic(): TopicMe { - return this.getTopic(Const.TOPIC_ME); - } - - getFndTopic(): TopicFnd { - return this.getTopic(Const.TOPIC_FND); - } - - getLargeFileHelper(): LargeFileHelper { - return new LargeFileHelper(this, Const.PROTOCOL_VERSION); - } - - getCurrentUserID(): string | null { - return this._myUID; - } - - isMe(uid: string | null | undefined): boolean { - return this._myUID === uid; - } - - getCurrentLogin(): string | null { - return this._login; - } - - getServerInfo(): ServerParams | null { - return this._serverInfo; - } - - report(action: string, target: string): Promise { - return this.publish( - Const.TOPIC_SYS, - Drafty.attachJSON(null, { - action: action, - target: target, - }) - ); - } - - getServerParam(name: string, defaultValue?: unknown): unknown { - return (this._serverInfo && this._serverInfo[name]) || defaultValue; - } - - enableLogging(enabled: boolean, trimLongStrings?: boolean): void { - this._loggingEnabled = enabled; - this._trimLongStrings = enabled && !!trimLongStrings; - } - - setHumanLanguage(hl: string | null | undefined): void { - if (hl) { - this._humanLanguage = hl; - } - } - - isTopicOnline(name: string): boolean { - return !!this.#cacheGetTopic(name)?.online; - } - - getTopicAccessMode(name: string): AccessMode | null { - const topic = this.#cacheGetTopic(name); - return topic ? topic.acs : null; - } - - wantAkn(status: boolean): void { - if (status) { - this._messageId = Math.floor(Math.random() * 0xffffff + 0xffffff); - } else { - this._messageId = 0; - } - } -} diff --git a/src/core/topic.ts b/src/core/topic.ts deleted file mode 100644 index e89bf6b..0000000 --- a/src/core/topic.ts +++ /dev/null @@ -1,1664 +0,0 @@ -import AccessMode from './access-mode'; -import type { AccessModeInput } from './access-mode'; -import CBuffer from './cbuffer'; -import CommError from './comm-error'; -import * as Const from './config'; -import Drafty from './drafty'; -import type { DraftyDoc } from './drafty'; -import MetaGetBuilder from './meta-builder'; -import type { GetDataType, GetQuery } from './meta-builder'; -import type PersistentCache from './storage/persistent-cache'; -import type { MessageRecord } from './storage/storage-adapter'; -import type { Tinode } from './tinode'; -import type { - Credential, - CtrlMessage, - DefAcs, - InfoMessage, - LastSeen, - Message, - MessageHead, - MetaMessage, - PresMessage, - PubMessage, - SetParams, - TopicDesc, - TopicPrivate, - TopicSubscription, - TopicType, -} from './types'; -import { - listToRanges, - mergeObj, - mergeToCache, - normalizeArray, - normalizeRanges, -} from './utils'; -import type { SeqRange } from './utils'; - -export type MessageCallback = ( - data: Message, - prev: Message | undefined, - next: Message | undefined, - idx: number -) => void; - -export type SubscriberCallback = ( - sub: TopicSubscription, - key: string, - all: Record -) => void; - -export type ReceiptKind = 'recv' | 'read'; - -export interface TopicCallbacks { - onData?: (data?: Message) => void; - onMeta?: (meta: MetaMessage) => void; - onPres?: (pres: PresMessage) => void; - onInfo?: (info: InfoMessage) => void; - onMetaDesc?: (topic: Topic) => void; - onMetaSub?: (sub: TopicSubscription) => void; - onSubsUpdated?: (keys: string[], count?: number) => void; - onTagsUpdated?: (tags: string[]) => void; - onCredsUpdated?: (creds: Credential[]) => void; - onAuxUpdated?: (aux: Record) => void; - onDeleteTopic?: () => void; - onAllMessagesReceived?: (count: number) => void; -} - -const TOPIC_TYPES: Record = { - me: Const.TOPIC_ME, - fnd: Const.TOPIC_FND, - grp: Const.TOPIC_GRP, - new: Const.TOPIC_GRP, - nch: Const.TOPIC_GRP, - chn: Const.TOPIC_GRP, - usr: Const.TOPIC_P2P, - sys: Const.TOPIC_SYS, - slf: Const.TOPIC_SLF, -}; - -function bySeq(a: Message, b: Message): number { - return a.seq - b.seq; -} - -function isMessageHead(head: unknown): head is MessageHead { - return typeof head === 'object' && head !== null && !Array.isArray(head); -} - -function isMessageContent(content: unknown): content is DraftyDoc | string { - return ( - typeof content === 'string' || - (typeof content === 'object' && content !== null) - ); -} - -function messageFromRecord(rec: MessageRecord): Message { - const { head, content, ...rest } = rec; - return { - ...rest, - head: isMessageHead(head) ? head : undefined, - content: isMessageContent(content) ? content : undefined, - }; -} - -export default class Topic { - #tinode: Tinode | null = null; - - name: string; - created: Date | undefined = undefined; - updated: Date | undefined = undefined; - touched: Date = new Date(0); - deleted: Date | undefined = undefined; - acs: AccessMode = new AccessMode(null); - defacs: DefAcs | undefined = undefined; - private: TopicPrivate | null = null; - public: unknown = null; - trusted: unknown = null; - - seq = 0; - read = 0; - recv = 0; - unread = 0; - clear = 0; - subcnt = 0; - online: boolean | undefined = undefined; - seen: LastSeen | undefined = undefined; - topic: string | undefined = undefined; - - _users: Record = {}; - _queuedSeqId: number = Const.LOCAL_SEQID; - _maxSeq = 0; - _minSeq = 0; - _noEarlierMsgs = false; - _maxDel = 0; - _recvNotificationTimer: ReturnType | null = null; - _tags: string[] = []; - _credentials: Credential[] = []; - _aux: Record = {}; - _messageVersions: Record> = {}; - _messages: CBuffer = new CBuffer(bySeq, true); - _attached = false; - _lastSubsUpdate: Date = new Date(0); - _new?: boolean = true; - _deleted = false; - _delayedLeaveTimer: ReturnType | null = null; - - onData: TopicCallbacks['onData']; - onMeta: TopicCallbacks['onMeta']; - onPres: TopicCallbacks['onPres']; - onInfo: TopicCallbacks['onInfo']; - onMetaDesc: TopicCallbacks['onMetaDesc']; - onMetaSub: TopicCallbacks['onMetaSub']; - onSubsUpdated: TopicCallbacks['onSubsUpdated']; - onTagsUpdated: TopicCallbacks['onTagsUpdated']; - onCredsUpdated: TopicCallbacks['onCredsUpdated']; - onAuxUpdated: TopicCallbacks['onAuxUpdated']; - onDeleteTopic: TopicCallbacks['onDeleteTopic']; - onAllMessagesReceived: TopicCallbacks['onAllMessagesReceived']; - - _cacheGetUser: (uid: string) => TopicSubscription | undefined = () => - undefined; - _cachePutUser: (uid: string, user: TopicSubscription) => void = () => {}; - _cacheDelUser: (uid: string) => void = () => {}; - _cachePutSelf: () => void = () => {}; - _cacheDelSelf: () => void = () => {}; - - constructor(name: string, callbacks?: TopicCallbacks) { - this.name = name; - this.onData = callbacks?.onData; - this.onMeta = callbacks?.onMeta; - this.onPres = callbacks?.onPres; - this.onInfo = callbacks?.onInfo; - this.onMetaDesc = callbacks?.onMetaDesc; - this.onMetaSub = callbacks?.onMetaSub; - this.onSubsUpdated = callbacks?.onSubsUpdated; - this.onTagsUpdated = callbacks?.onTagsUpdated; - this.onCredsUpdated = callbacks?.onCredsUpdated; - this.onAuxUpdated = callbacks?.onAuxUpdated; - this.onDeleteTopic = callbacks?.onDeleteTopic; - this.onAllMessagesReceived = callbacks?.onAllMessagesReceived; - } - - get _tinode(): Tinode { - if (!this.#tinode) { - throw new Error(`Topic '${this.name}' is not attached to Tinode`); - } - return this.#tinode; - } - - set _tinode(tinode: Tinode) { - this.#tinode = tinode; - } - - static topicType(name: string | null | undefined): TopicType | undefined { - return TOPIC_TYPES[typeof name === 'string' ? name.substring(0, 3) : 'xxx']; - } - - static isMeTopicName(name: string | null | undefined): boolean { - return Topic.topicType(name) === Const.TOPIC_ME; - } - - static isSelfTopicName(name: string | null | undefined): boolean { - return Topic.topicType(name) === Const.TOPIC_SLF; - } - - static isGroupTopicName(name: string | null | undefined): boolean { - return Topic.topicType(name) === Const.TOPIC_GRP; - } - - static isP2PTopicName(name: string | null | undefined): boolean { - return Topic.topicType(name) === Const.TOPIC_P2P; - } - - static isCommTopicName(name: string | null | undefined): boolean { - return ( - Topic.isP2PTopicName(name) || - Topic.isGroupTopicName(name) || - Topic.isSelfTopicName(name) - ); - } - - static isNewGroupTopicName(name: string | null | undefined): boolean { - if (typeof name !== 'string') { - return false; - } - const prefix = name.substring(0, 3); - return prefix === Const.TOPIC_NEW || prefix === Const.TOPIC_NEW_CHAN; - } - - static isChannelTopicName(name: string | null | undefined): boolean { - if (typeof name !== 'string') { - return false; - } - const prefix = name.substring(0, 3); - return prefix === Const.TOPIC_CHAN || prefix === Const.TOPIC_NEW_CHAN; - } - - static #isReplacementMsg(pub: Message): boolean { - return !!pub.head?.replace; - } - - isSubscribed(): boolean { - return this._attached; - } - - subscribe( - getParams?: GetQuery, - setParams?: SetParams - ): Promise { - if (this._delayedLeaveTimer) { - clearTimeout(this._delayedLeaveTimer); - } - this._delayedLeaveTimer = null; - - if (this._attached) { - return Promise.resolve(this); - } - - return this._tinode - .subscribe(this.name || Const.TOPIC_NEW, getParams, setParams) - .then((ctrl) => { - if (ctrl.code >= 300) { - return ctrl; - } - - this._attached = true; - this._deleted = false; - this.acs = ctrl.params?.acs ?? this.acs; - - if (this._new) { - delete this._new; - - if (ctrl.topic && this.name !== ctrl.topic) { - this._cacheDelSelf(); - this.name = ctrl.topic; - } - this._cachePutSelf(); - - this.created = ctrl.ts; - this.updated = ctrl.ts; - - if (this.name !== Const.TOPIC_ME && this.name !== Const.TOPIC_FND) { - const me = this._tinode.getMeTopic(); - if (me.onMetaSub) { - me.onMetaSub(this); - } - if (me.onSubsUpdated) { - me.onSubsUpdated([this.name], 1); - } - } - - if (setParams?.desc) { - setParams.desc._noForwarding = true; - this._processMetaDesc(setParams.desc); - } - } - return ctrl; - }); - } - - createMessage(data: DraftyDoc | string, noEcho?: boolean): PubMessage { - return this._tinode.createMessage(this.name, data, noEcho); - } - - publish( - data: DraftyDoc | string, - noEcho?: boolean - ): Promise { - return this.publishMessage(this.createMessage(data, noEcho)); - } - - publishMessage(pub: PubMessage): Promise { - if (!this._attached) { - return Promise.reject(new Error('Cannot publish on inactive topic')); - } - if (pub._sending) { - return Promise.reject(new Error('The message is already being sent')); - } - - pub._sending = true; - pub._failed = false; - - let attachments: string[] | null = null; - const content = pub.content; - if (typeof content === 'object' && Drafty.hasEntities(content)) { - const refs: string[] = []; - Drafty.entities(content, (data) => { - if (data) { - if (data.ref) { - refs.push(data.ref); - } - if (data.preref) { - refs.push(data.preref); - } - } - }); - if (refs.length > 0) { - attachments = refs; - } - } - - return this._tinode - .publishMessage(pub, attachments) - .then((ctrl) => { - const newSeq = ctrl.params?.seq ?? 0; - pub._sending = false; - pub.ts = ctrl.ts; - const msg = Object.assign(pub, { seq: pub.seq ?? newSeq }); - this.swapMessageId(msg, newSeq); - this._maybeUpdateMessageVersionsCache(msg); - this._routeData(msg); - return ctrl; - }) - .catch((err: unknown) => { - this._tinode.logger('WARNING: Message rejected by the server', err); - pub._sending = false; - pub._failed = true; - if (this.onData) { - this.onData(); - } - return undefined; - }); - } - - publishDraft( - pub: PubMessage, - prom?: Promise | null - ): Promise { - const seq = pub.seq || this._getQueuedSeqId(); - if (!pub._noForwarding) { - pub._noForwarding = true; - const msg = Object.assign(pub, { - seq, - ts: new Date(), - from: this._tinode.getCurrentUserID() ?? undefined, - noecho: true, - }); - this._messages.put(msg); - this._tinode._db.addMessage(msg); - - if (this.onData) { - this.onData(msg); - } - } - - return (prom || Promise.resolve()) - .then(() => { - if (pub._cancelled) { - return { - code: 300, - text: 'cancelled', - }; - } - return this.publishMessage(pub); - }) - .catch((err: unknown) => { - this._tinode.logger('WARNING: Message draft rejected', err); - pub._sending = false; - pub._failed = true; - pub._fatal = - err instanceof CommError ? err.code >= 400 && err.code < 500 : false; - if (this.onData) { - this.onData(); - } - throw err; - }); - } - - leave(unsub?: boolean): Promise { - if (!this._attached && !unsub) { - return Promise.reject(new Error('Cannot leave inactive topic')); - } - - return this._tinode.leave(this.name, unsub).then((ctrl) => { - this._resetSub(); - if (unsub) { - this._gone(); - } - return ctrl; - }); - } - - leaveDelayed(unsub: boolean, delay: number): void { - if (this._delayedLeaveTimer) { - clearTimeout(this._delayedLeaveTimer); - } - this._delayedLeaveTimer = setTimeout(() => { - this._delayedLeaveTimer = null; - this.leave(unsub).catch((err: unknown) => { - this._tinode.logger('WARNING: Delayed leave failed', err); - }); - }, delay); - } - - getMeta(params?: GetQuery): Promise { - return this._tinode.getMeta(this.name, params); - } - - getMessagesPage( - limit: number, - gaps: SeqRange[] | null | undefined, - min: number, - max: number, - newer: boolean - ): Promise { - let query = gaps - ? this.startMetaQuery().withDataRanges(gaps, limit) - : newer - ? this.startMetaQuery().withData(min, undefined, limit) - : this.startMetaQuery().withData(undefined, max, limit); - - return this._loadMessages(this._tinode._db, query.extract('data')).then( - (count) => { - const missing = this.msgHasMoreMessages(min, max, newer); - if (missing.length === 0) { - return { - topic: this.name, - code: 200, - params: { - count: count, - }, - }; - } - - query = this.startMetaQuery().withDataRanges(missing, limit - count); - return this.getMeta(query.build()); - } - ); - } - - getPinnedMessages(): Promise { - const pins = this.aux('pins'); - if (!Array.isArray(pins)) { - return Promise.resolve(0); - } - const pinned = pins.filter((seq): seq is number => typeof seq === 'number'); - - const loaded: number[] = []; - let remains = pinned; - const db = this._tinode._db; - return db - .readMessages(this.name, { ranges: listToRanges([...remains]) }) - .then((msgs) => { - msgs.forEach((rec) => { - if (rec) { - const data = messageFromRecord(rec); - loaded.push(data.seq); - this._messages.put(data); - this._maybeUpdateMessageVersionsCache(data); - } - }); - if (loaded.length < pinned.length) { - remains = pinned.filter((seq) => !loaded.includes(seq)); - return db.readDelLog(this.name, { - ranges: listToRanges([...remains]), - }); - } - return null; - }) - .then((ranges) => { - if (ranges) { - remains.forEach((seq) => { - if (ranges.find((r) => r.low <= seq && r.hi > seq)) { - loaded.push(seq); - } - }); - } - if (loaded.length === pinned.length) { - return { - topic: this.name, - code: 200, - params: { - count: loaded.length, - }, - }; - } - - remains = pinned.filter((seq) => !loaded.includes(seq)); - return this.getMeta( - this.startMetaQuery().withDataList(remains).build() - ); - }); - } - - setMeta(params: SetParams): Promise { - if (params.tags) { - params.tags = normalizeArray(params.tags); - } - return this._tinode.setMeta(this.name, params).then((ctrl) => { - if (ctrl && ctrl.code >= 300) { - return ctrl; - } - - if (params.sub) { - params.sub.topic = this.name; - if (ctrl.params?.acs) { - params.sub.acs = ctrl.params.acs; - params.sub.updated = ctrl.ts; - } - if (!params.sub.user) { - params.sub.user = this._tinode.getCurrentUserID(); - if (!params.desc) { - params.desc = {}; - } - } - params.sub._noForwarding = true; - const { user, mode, ...rest } = params.sub; - this._processMetaSubs([ - { ...rest, user: user ?? undefined, mode: mode ?? undefined }, - ]); - } - - if (params.desc) { - if (ctrl.params?.acs) { - params.desc.acs = ctrl.params.acs; - params.desc.updated = ctrl.ts; - } - this._processMetaDesc(params.desc); - } - - if (params.tags) { - this._processMetaTags(params.tags); - } - if (params.cred) { - this._processMetaCreds([params.cred], true); - } - if (params.aux) { - this._processMetaAux(params.aux); - } - - return ctrl; - }); - } - - updateMode(uid: string | null, update: string): Promise { - const user = uid ? this.subscriber(uid) : undefined; - const am = user?.acs - ? user.acs.updateGiven(update).getGiven() - : this.getAccessMode().updateWant(update).getWant(); - - return this.setMeta({ - sub: { - user: uid, - mode: am, - }, - }); - } - - invite(uid: string, mode?: string | null): Promise { - return this.setMeta({ - sub: { - user: uid, - mode: mode, - }, - }); - } - - archive(arch: boolean): Promise { - if (this.private && !this.private.arch === !arch) { - return Promise.resolve(arch); - } - return this.setMeta({ - desc: { - private: { - arch: arch ? true : Const.DEL_CHAR, - }, - }, - }); - } - - pinMessage(seq: number, pin: boolean): Promise { - const current = this.aux('pins'); - let pinned: number[] = Array.isArray(current) - ? current.filter((id): id is number => typeof id === 'number') - : []; - let changed = false; - if (pin) { - if (!pinned.includes(seq)) { - changed = true; - if (pinned.length === Const.MAX_PINNED_COUNT) { - pinned.shift(); - } - pinned.push(seq); - } - } else if (pinned.includes(seq)) { - changed = true; - pinned = pinned.filter((id) => id !== seq); - } - if (changed) { - return this.setMeta({ - aux: { - pins: pinned.length > 0 ? pinned : Const.DEL_CHAR, - }, - }); - } - return Promise.resolve(); - } - - pinTopic(_topic: string, _pin?: boolean): Promise { - return Promise.reject(new Error('Pinning topics is not supported here')); - } - - pinnedTopicRank(_topic: string): number { - return 0; - } - - delMessages(ranges: SeqRange[], hard?: boolean): Promise { - if (!this._attached) { - return Promise.reject( - new Error('Cannot delete messages in inactive topic') - ); - } - - const tosend = normalizeRanges(ranges, this._maxSeq); - - const result: Promise = - tosend.length > 0 - ? this._tinode.delMessages(this.name, tosend, hard) - : Promise.resolve({ - code: 200, - params: { - del: 0, - }, - }); - - return result.then((ctrl) => { - const del = ctrl.params?.del ?? 0; - if (del > this._maxDel) { - this._maxDel = Math.max(del, this._maxDel); - this.clear = Math.max(del, this.clear); - } - - ranges.forEach((rec) => { - if (rec.hi) { - this.flushMessageRange(rec.low, rec.hi); - } else { - this.flushMessage(rec.low); - } - this._messages.put({ - topic: this.name, - seq: rec.low, - low: rec.low, - hi: rec.hi, - _deleted: true, - }); - }); - - this._tinode._db.addDelLog(this.name, del, ranges); - - if (this.onData) { - this.onData(); - } - return ctrl; - }); - } - - delMessagesAll(hardDel?: boolean): Promise { - if (!this._maxSeq || this._maxSeq <= 0) { - return Promise.resolve(); - } - return this.delMessages( - [ - { - low: 1, - hi: this._maxSeq + 1, - }, - ], - hardDel - ); - } - - delMessagesList(list: number[], hardDel?: boolean): Promise { - return this.delMessages(listToRanges(list), hardDel); - } - - delMessagesEdits(seq: number, hardDel?: boolean): Promise { - const list = [seq]; - this.messageVersions(seq, (msg) => list.push(msg.seq)); - return this.delMessagesList(list, hardDel); - } - - delTopic(hard?: boolean): Promise { - if (this._deleted) { - this._gone(); - return Promise.resolve(null); - } - - return this._tinode.delTopic(this.name, hard).then((ctrl) => { - this._deleted = true; - this._resetSub(); - this._gone(); - return ctrl; - }); - } - - delSubscription(user: string): Promise { - if (!this._attached) { - return Promise.reject( - new Error('Cannot delete subscription in inactive topic') - ); - } - return this._tinode.delSubscription(this.name, user).then((ctrl) => { - delete this._users[user]; - if (this.onSubsUpdated) { - this.onSubsUpdated(Object.keys(this._users)); - } - return ctrl; - }); - } - - note(what: ReceiptKind, seq: number): void { - if (!this._attached) { - return; - } - - const myUID = this._tinode.getCurrentUserID(); - const user = myUID ? this._users[myUID] : undefined; - let update = false; - if (user) { - const current = user[what]; - if (!current || current < seq) { - user[what] = seq; - update = true; - } - } else { - update = (this[what] | 0) < seq; - } - - if (update) { - this._tinode.note(this.name, what, seq); - this._updateMyReadRecv(what, seq); - - if (this.acs != null && !this.acs.isMuted()) { - this._tinode.getMeTopic()._refreshContact(what, this); - } - } - } - - noteRecv(seq: number): void { - this.note('recv', seq); - } - - noteRead(seq?: number): void { - const target = seq || this._maxSeq; - if (target > 0) { - this.note('read', target); - } - } - - noteKeyPress(): void { - if (this._attached) { - this._tinode.noteKeyPress(this.name); - } else { - this._tinode.logger('INFO: Cannot send notification in inactive topic'); - } - } - - noteRecording(audioOnly?: boolean): void { - if (this._attached) { - this._tinode.noteKeyPress(this.name, audioOnly ? 'kpa' : 'kpv'); - } else { - this._tinode.logger('INFO: Cannot send notification in inactive topic'); - } - } - - videoCall(evt: string, seq: number, payload?: unknown): void { - if (!this._attached && !['ringing', 'hang-up'].includes(evt)) { - return; - } - this._tinode.videoCall(this.name, seq, evt, payload); - } - - _updateMyReadRecv( - what: ReceiptKind | 'msg', - seq?: number, - ts?: Date - ): boolean { - let oldVal: number; - let doUpdate = false; - - const value = (seq ?? 0) | 0; - this.seq = this.seq | 0; - this.read = this.read | 0; - this.recv = this.recv | 0; - switch (what) { - case 'recv': - oldVal = this.recv; - this.recv = Math.max(this.recv, value); - doUpdate = oldVal !== this.recv; - break; - case 'read': - oldVal = this.read; - this.read = Math.max(this.read, value); - doUpdate = oldVal !== this.read; - break; - case 'msg': - oldVal = this.seq; - this.seq = Math.max(this.seq, value); - if (ts && (!this.touched || this.touched < ts)) { - this.touched = ts; - } - doUpdate = oldVal !== this.seq; - break; - } - - if (this.recv < this.read) { - this.recv = this.read; - doUpdate = true; - } - if (this.seq < this.recv) { - this.seq = this.recv; - if (ts && (!this.touched || this.touched < ts)) { - this.touched = ts; - } - doUpdate = true; - } - this.unread = this.seq - this.read; - return doUpdate; - } - - userDesc(uid: string): TopicSubscription | undefined { - return this._cacheGetUser(uid); - } - - p2pPeerDesc(): TopicSubscription | undefined { - if (!this.isP2PType()) { - return undefined; - } - return this._users[this.name]; - } - - subscribers(callback?: SubscriberCallback, context?: unknown): void { - const cb = callback || this.onMetaSub; - if (cb) { - for (const idx in this._users) { - const user = this._users[idx]; - if (user) { - cb.call(context, user, idx, this._users); - } - } - } - } - - tags(): string[] { - return this._tags.slice(0); - } - - aux(key: string): unknown { - return this._aux[key]; - } - - alias(): string | undefined { - const alias = this._tags?.find((t) => t.startsWith(Const.TAG_ALIAS)); - if (!alias) { - return undefined; - } - return alias.substring(Const.TAG_ALIAS.length); - } - - subscriber(uid: string): TopicSubscription | undefined { - return this._users[uid]; - } - - messageVersions( - origSeq: number, - callback?: MessageCallback, - context?: unknown - ): void { - if (!callback) { - return; - } - const versions = this._messageVersions[origSeq]; - if (!versions) { - return; - } - versions.forEach(callback, undefined, undefined, context); - } - - messages( - callback?: MessageCallback, - sinceId?: number, - beforeId?: number, - context?: unknown - ): void { - const cb = callback || this.onData; - if (!cb) { - return; - } - const startIdx = - typeof sinceId === 'number' - ? this._messages.find(this.#seqProbe(sinceId), true) - : undefined; - const beforeIdx = - typeof beforeId === 'number' - ? this._messages.find(this.#seqProbe(beforeId), true) - : undefined; - if (startIdx === -1 || beforeIdx === -1) { - return; - } - - const msgs: { data: Message; idx: number }[] = []; - this._messages.forEach( - (msg, _prev, _next, i) => { - if (Topic.#isReplacementMsg(msg)) { - return; - } - if (msg._deleted) { - return; - } - const latest = this.latestMsgVersion(msg.seq) || msg; - if (!latest._origTs) { - latest._origTs = latest.ts; - latest._origSeq = latest.seq; - latest.ts = msg.ts; - latest.seq = msg.seq; - } - msgs.push({ - data: latest, - idx: i, - }); - }, - startIdx, - beforeIdx, - {} - ); - - msgs.forEach((val, i) => { - cb.call(context, val.data, msgs[i - 1]?.data, msgs[i + 1]?.data, val.idx); - }); - } - - findMessage(seq: number): Message | undefined { - const idx = this._messages.find(this.#seqProbe(seq)); - if (idx >= 0) { - return this._messages.getAt(idx); - } - return undefined; - } - - latestMessage(): Message | undefined { - return this._messages.getLast((msg) => !msg._deleted); - } - - latestMsgVersion(seq: number): Message | null { - const versions = this._messageVersions[seq]; - return versions?.getLast() ?? null; - } - - maxMsgSeq(): number { - return this._maxSeq; - } - - minMsgSeq(): number { - return this._minSeq; - } - - maxClearId(): number { - return this._maxDel; - } - - messageCount(): number { - return this._messages.length(); - } - - queuedMessages(callback: MessageCallback, context?: unknown): void { - if (!callback) { - throw new Error('Callback must be provided'); - } - this.messages(callback, Const.LOCAL_SEQID, undefined, context); - } - - msgReceiptCount(what: ReceiptKind, seq: number): number { - let count = 0; - if (seq > 0) { - const me = this._tinode.getCurrentUserID(); - for (const idx in this._users) { - const user = this._users[idx]; - const value = user?.[what]; - if (user && user.user !== me && value !== undefined && value >= seq) { - count++; - } - } - } - return count; - } - - msgReadCount(seq: number): number { - return this.msgReceiptCount('read', seq); - } - - msgRecvCount(seq: number): number { - return this.msgReceiptCount('recv', seq); - } - - msgHasMoreMessages(min: number, max: number, newer: boolean): SeqRange[] { - const gaps: SeqRange[] = []; - if (min >= max) { - return gaps; - } - let maxSeq = 0; - this._messages.forEach((msg, prev) => { - const expected = prev - ? prev._deleted - ? (prev.hi ?? prev.seq + 1) - : prev.seq + 1 - : 1; - if (msg.seq > expected) { - const gap = { low: expected, hi: msg.seq }; - if (newer ? gap.hi >= min : gap.low < max) { - gaps.push(gap); - } - } - maxSeq = expected; - }); - - if (maxSeq < this.seq) { - const gap = { low: maxSeq + 1, hi: this.seq + 1 }; - if (newer ? gap.hi >= min : gap.low < max) { - gaps.push(gap); - } - } - return gaps; - } - - isNewMessage(seqId: number): boolean { - return this._maxSeq <= seqId; - } - - flushMessage(seqId: number): Message | undefined { - const idx = this._messages.find(this.#seqProbe(seqId)); - delete this._messageVersions[seqId]; - if (idx >= 0) { - this._tinode._db.remMessages(this.name, seqId); - return this._messages.delAt(idx); - } - return undefined; - } - - flushMessageRange(fromId: number, untilId: number): Message[] { - this._tinode._db.remMessages(this.name, fromId, untilId); - - for (let i = fromId; i < untilId; i++) { - delete this._messageVersions[i]; - } - - const since = this._messages.find(this.#seqProbe(fromId), true); - return since >= 0 - ? this._messages.delRange( - since, - this._messages.find(this.#seqProbe(untilId), true) - ) - : []; - } - - swapMessageId(pub: Message, newSeqId: number): void { - const idx = this._messages.find(pub); - const numMessages = this._messages.length(); - if (idx >= 0 && idx < numMessages) { - this._messages.delAt(idx); - this._tinode._db.remMessages(this.name, pub.seq); - pub.seq = newSeqId; - this._messages.put(pub); - this._tinode._db.addMessage(pub); - } - } - - cancelSend(seqId: number): boolean { - const idx = this._messages.find(this.#seqProbe(seqId)); - const msg = idx >= 0 ? this._messages.getAt(idx) : undefined; - if (msg) { - const status = this.msgStatus(msg); - if ( - status === Const.MESSAGE_STATUS_QUEUED || - status === Const.MESSAGE_STATUS_FAILED || - status === Const.MESSAGE_STATUS_FATAL - ) { - this._tinode._db.remMessages(this.name, seqId); - msg._cancelled = true; - this._messages.delAt(idx); - if (this.onData) { - this.onData(); - } - return true; - } - } - return false; - } - - getType(): TopicType | undefined { - return Topic.topicType(this.name); - } - - getAccessMode(): AccessMode { - return this.acs; - } - - setAccessMode(acs?: AccessModeInput | null): AccessMode { - return (this.acs = new AccessMode(acs)); - } - - getDefaultAccess(): DefAcs | undefined { - return this.defacs; - } - - startMetaQuery(): MetaGetBuilder { - return new MetaGetBuilder(this); - } - - isArchived(): boolean { - return !!this.private?.arch; - } - - isMeType(): boolean { - return Topic.isMeTopicName(this.name); - } - - isSelfType(): boolean { - return Topic.isSelfTopicName(this.name); - } - - isChannelType(): boolean { - return Topic.isChannelTopicName(this.name); - } - - isGroupType(): boolean { - return Topic.isGroupTopicName(this.name); - } - - isP2PType(): boolean { - return Topic.isP2PTopicName(this.name); - } - - isCommType(): boolean { - return Topic.isCommTopicName(this.name); - } - - msgStatus(msg: Message, upd?: boolean): number { - let status = Const.MESSAGE_STATUS_NONE; - if (this._tinode.isMe(msg.from)) { - if (msg._sending) { - status = Const.MESSAGE_STATUS_SENDING; - } else if (msg._fatal || msg._cancelled) { - status = Const.MESSAGE_STATUS_FATAL; - } else if (msg._failed) { - status = Const.MESSAGE_STATUS_FAILED; - } else if (msg.seq >= Const.LOCAL_SEQID) { - status = Const.MESSAGE_STATUS_QUEUED; - } else if (this.msgReadCount(msg.seq) > 0) { - status = Const.MESSAGE_STATUS_READ; - } else if (this.msgRecvCount(msg.seq) > 0) { - status = Const.MESSAGE_STATUS_RECEIVED; - } else if (msg.seq > 0) { - status = Const.MESSAGE_STATUS_SENT; - } - } else { - status = Const.MESSAGE_STATUS_TO_ME; - } - - if (upd && msg._status !== status) { - msg._status = status; - this._tinode._db.updMessageStatus(this.name, msg.seq, status); - } - - return status; - } - - #seqProbe(seq: number): Message { - return { topic: this.name, seq }; - } - - _maybeUpdateMessageVersionsCache(msg: Message): void { - const replace = msg.head?.replace; - if (!replace) { - const versions = this._messageVersions[msg.seq]; - if (versions) { - versions.filter((version) => version.from === msg.from); - if (versions.isEmpty()) { - delete this._messageVersions[msg.seq]; - } - } - return; - } - - const targetSeq = parseInt(replace.split(':')[1] ?? '', 10); - if (isNaN(targetSeq) || targetSeq > msg.seq) { - return; - } - const targetMsg = this.findMessage(targetSeq); - if (targetMsg && targetMsg.from !== msg.from) { - return; - } - const versions = - this._messageVersions[targetSeq] || new CBuffer(bySeq, true); - versions.put(msg); - this._messageVersions[targetSeq] = versions; - } - - _routeData(data: Message): void { - if (data.content) { - if (data.ts && (!this.touched || this.touched < data.ts)) { - this.touched = data.ts; - this._tinode._db.updTopic(this); - } - } - - if (data.seq > this._maxSeq) { - this._maxSeq = data.seq; - this.msgStatus(data, true); - if (this._recvNotificationTimer) { - clearTimeout(this._recvNotificationTimer); - } - this._recvNotificationTimer = setTimeout(() => { - this._recvNotificationTimer = null; - this.noteRecv(this._maxSeq); - }, Const.RECV_TIMEOUT); - } - - if (data.seq < this._minSeq || this._minSeq === 0) { - this._minSeq = data.seq; - } - - const outgoing = - (!this.isChannelType() && !data.from) || this._tinode.isMe(data.from); - - if ( - data.head?.webrtc && - data.head.mime === Drafty.getContentType() && - data.content && - typeof data.content === 'object' - ) { - data.content = Drafty.updateVideoCall(data.content, { - state: data.head.webrtc, - duration: data.head['webrtc-duration'], - incoming: !outgoing, - vc: data.head.vc ? true : undefined, - }); - } - - if (!data._noForwarding) { - this._messages.put(data); - this._tinode._db.addMessage(data); - this._maybeUpdateMessageVersionsCache(data); - } - - if (this.onData) { - this.onData(data); - } - - const what = outgoing ? 'read' : 'msg'; - this._updateMyReadRecv(what, data.seq, data.ts); - - if (!outgoing && data.from) { - this._routeInfo({ - what: 'read', - from: data.from, - seq: data.seq, - _noForwarding: true, - }); - } - - this._tinode.getMeTopic()._refreshContact(what, this); - } - - _routeMeta(meta: MetaMessage): void { - if (meta.desc) { - this._processMetaDesc(meta.desc); - } - if (meta.sub && meta.sub.length > 0) { - this._processMetaSubs(meta.sub, true); - } - if (meta.del) { - this._processDelMessages(meta.del.clear, meta.del.delseq); - } - if (meta.tags) { - this._processMetaTags(meta.tags); - } - if (meta.cred) { - this._processMetaCreds(meta.cred); - } - if (meta.aux) { - this._processMetaAux(meta.aux); - } - if (this.onMeta) { - this.onMeta(meta); - } - } - - _routePres(pres: PresMessage): void { - switch (pres.what) { - case 'del': - this._processDelMessages(pres.clear ?? 0, pres.delseq); - break; - case 'on': - case 'off': { - const user = pres.src ? this._users[pres.src] : undefined; - if (user) { - user.online = pres.what === 'on'; - } else { - this._tinode.logger( - 'WARNING: Presence update for an unknown user', - this.name, - pres.src - ); - } - break; - } - case 'term': - this._resetSub(); - break; - case 'upd': - if (pres.src && !this._tinode.isTopicCached(pres.src)) { - this.getMeta( - this.startMetaQuery().withOneSub(undefined, pres.src).build() - ); - } - break; - case 'aux': - this.getMeta(this.startMetaQuery().withAux().build()); - break; - case 'acs': { - const uid = pres.src || this._tinode.getCurrentUserID(); - if (!uid) { - break; - } - const user = this._users[uid]; - if (!user) { - const acs = new AccessMode().updateAll(pres.dacs); - if (acs && acs.mode !== AccessMode._NONE) { - let sub = this._cacheGetUser(uid); - if (!sub) { - sub = { - user: uid, - acs: acs, - }; - this.getMeta( - this.startMetaQuery().withOneSub(undefined, uid).build() - ); - } else { - sub.acs = acs; - } - sub.updated = new Date(); - this._processMetaSubs([sub]); - } - } else { - const acs = (user.acs ?? new AccessMode()).updateAll(pres.dacs); - this._processMetaSubs([ - { - user: uid, - updated: new Date(), - acs: acs, - }, - ]); - } - break; - } - default: - this._tinode.logger('INFO: Ignored presence update', pres.what); - } - - if (this.onPres) { - this.onPres(pres); - } - } - - _routeInfo(info: InfoMessage): void { - switch (info.what) { - case 'recv': - case 'read': { - const user = info.from ? this._users[info.from] : undefined; - if (user) { - user[info.what] = info.seq; - if ((user.recv ?? 0) < (user.read ?? 0)) { - user.recv = user.read; - } - } - const msg = this.latestMessage(); - if (msg) { - this.msgStatus(msg, true); - } - - if (this._tinode.isMe(info.from) && !info._noForwarding) { - this._updateMyReadRecv(info.what, info.seq); - } - - this._tinode.getMeTopic()._refreshContact(info.what, this); - break; - } - case 'kp': - case 'kpa': - case 'kpv': - break; - case 'call': - break; - default: - this._tinode.logger('INFO: Ignored info update', info.what); - } - - if (this.onInfo) { - this.onInfo(info); - } - } - - _processMetaDesc(desc: TopicDesc): void { - if (this.isP2PType()) { - delete desc.defacs; - this._tinode._db.updUser(this.name, desc.public); - } - - mergeObj(this, desc); - this._tinode._db.updTopic(this); - - if (this.name !== Const.TOPIC_ME && !desc._noForwarding) { - const me = this._tinode.getMeTopic(); - if (me.onMetaSub) { - me.onMetaSub(this); - } - if (me.onSubsUpdated) { - me.onSubsUpdated([this.name], 1); - } - } - - if (this.onMetaDesc) { - this.onMetaDesc(this); - } - } - - _processMetaSubs(subs: TopicSubscription[], skipSubcnt?: boolean): void { - for (const sub of subs) { - sub.online = !!sub.online; - this._lastSubsUpdate = new Date( - Math.max( - this._lastSubsUpdate.getTime(), - sub.updated ? sub.updated.getTime() : 0 - ) - ); - - const uid = sub.user; - if (!uid) { - continue; - } - - let user: TopicSubscription; - if (!sub.deleted) { - if (this._tinode.isMe(uid) && sub.acs) { - this._processMetaDesc({ - updated: sub.updated, - touched: sub.touched, - acs: sub.acs, - }); - } - if (!this._users[uid] && !skipSubcnt) { - this.subcnt++; - } - user = this._updateCachedUser(uid, sub); - this._tinode._db.updSubscription(this.name, uid, sub); - } else { - delete this._users[uid]; - this._tinode._db.remSubscription(this.name, uid); - if (!skipSubcnt) { - this.subcnt--; - } - user = sub; - } - - if (this.onMetaSub) { - this.onMetaSub(user); - } - } - - if (this.onSubsUpdated) { - this.onSubsUpdated(Object.keys(this._users)); - } - } - - _processMetaTags(tags: string[] | string): void { - const list = - typeof tags === 'string' || - (tags.length === 1 && tags[0] === Const.DEL_CHAR) - ? [] - : tags; - this._tags = list; - this._tinode._db.updTopic(this); - if (this.onTagsUpdated) { - this.onTagsUpdated(list); - } - } - - _processMetaCreds(_creds: Credential[], _upd?: boolean): void {} - - _processMetaAux(aux: Record | string | null): void { - const update = aux && typeof aux === 'object' ? aux : {}; - this._aux = mergeObj(this._aux, update); - this._tinode._db.updTopic(this); - if (this.onAuxUpdated) { - this.onAuxUpdated(this._aux); - } - } - - _processDelMessages(clear: number, delseq?: SeqRange[]): void { - this._maxDel = Math.max(clear, this._maxDel); - this.clear = Math.max(clear, this.clear); - let count = 0; - if (Array.isArray(delseq)) { - delseq.forEach((rec) => { - if (!rec.hi) { - count++; - this.flushMessage(rec.low); - } else { - count += rec.hi - rec.low; - this.flushMessageRange(rec.low, rec.hi); - } - this._messages.put({ - topic: this.name, - seq: rec.low, - low: rec.low, - hi: rec.hi, - _deleted: true, - }); - }); - - this._tinode._db.addDelLog(this.name, clear, delseq); - } - - if (count > 0 && this.onData) { - this.onData(); - } - } - - _allMessagesReceived(count: number): void { - if (this.onAllMessagesReceived) { - this.onAllMessagesReceived(count); - } - } - - _resetSub(): void { - this._attached = false; - } - - _gone(): void { - this._messages.reset(); - this._tinode._db.remMessages(this.name); - this._users = {}; - this.acs = new AccessMode(null); - this.private = null; - this.public = null; - this.trusted = null; - this._maxSeq = 0; - this._minSeq = 0; - this._attached = false; - - const me = this._tinode.getMeTopic(); - if (me) { - me._routePres({ - _noForwarding: true, - what: 'gone', - topic: Const.TOPIC_ME, - src: this.name, - }); - } - if (this.onDeleteTopic) { - this.onDeleteTopic(); - } - } - - _updateCachedUser(uid: string, obj: TopicSubscription): TopicSubscription { - const cached = mergeObj( - this._cacheGetUser(uid) ?? {}, - obj - ); - this._cachePutUser(uid, cached); - return mergeToCache(this._users, uid, cached); - } - - _getQueuedSeqId(): number { - return this._queuedSeqId++; - } - - _loadMessages(db: PersistentCache, query?: GetDataType): Promise { - const params = query || {}; - params.limit = params.limit || Const.DEFAULT_MESSAGES_PAGE; - - let count = 0; - return db - .readMessages(this.name, params) - .then((msgs) => { - msgs.forEach((rec) => { - const data = messageFromRecord(rec); - if (data.seq > this._maxSeq) { - this._maxSeq = data.seq; - } - if (data.seq < this._minSeq || this._minSeq === 0) { - this._minSeq = data.seq; - } - this._messages.put(data); - this._maybeUpdateMessageVersionsCache(data); - }); - count = msgs.length; - }) - .then(() => db.readDelLog(this.name, params)) - .then((dellog) => { - dellog.forEach((rec) => { - this._messages.put({ - topic: this.name, - seq: rec.low, - low: rec.low, - hi: rec.hi, - _deleted: true, - }); - }); - return count; - }); - } - - _updateReceived(seq: number | undefined, act?: string): void { - this.touched = new Date(); - this.seq = (seq ?? 0) | 0; - if (!act || this._tinode.isMe(act)) { - this.read = this.read ? Math.max(this.read, this.seq) : this.seq; - this.recv = this.recv ? Math.max(this.read, this.recv) : this.read; - } - this.unread = this.seq - (this.read | 0); - this._tinode._db.updTopic(this); - } -} diff --git a/src/core/types.ts b/src/core/types.ts deleted file mode 100644 index 8aeb3b1..0000000 --- a/src/core/types.ts +++ /dev/null @@ -1,374 +0,0 @@ -import type AccessMode from './access-mode'; -import type { AccessModeInput } from './access-mode'; -import type { DraftyDoc } from './drafty'; -import type { GetQuery } from './meta-builder'; -import type { SeqRange } from './utils'; - -export type { GetQuery, SeqRange }; - -export type TopicType = 'me' | 'fnd' | 'grp' | 'p2p' | 'sys' | 'slf'; - -export interface DefAcs { - auth?: string; - anon?: string; -} - -export interface AuthToken { - token: string; - expires: Date; -} - -export interface Credential { - meth: string; - val?: string; - resp?: string; - params?: unknown; - done?: boolean; -} - -export interface LastSeen { - when?: Date; - ua?: string; -} - -export interface TopicPrivate { - arch?: boolean; - tpin?: string[]; - comment?: string; - [key: string]: unknown; -} - -export interface TopicDesc { - created?: Date; - updated?: Date; - touched?: Date; - deleted?: Date; - defacs?: DefAcs; - acs?: AccessMode; - seq?: number; - read?: number; - recv?: number; - clear?: number; - unread?: number; - subcnt?: number; - online?: boolean; - seen?: LastSeen; - public?: unknown; - private?: unknown; - trusted?: unknown; - _noForwarding?: boolean; -} - -export interface TopicSubscription { - user?: string; - topic?: string; - created?: Date; - updated?: Date; - touched?: Date; - deleted?: Date; - acs?: AccessMode; - mode?: string; - seq?: number; - read?: number; - recv?: number; - clear?: number; - unread?: number; - online?: boolean; - seen?: LastSeen; - public?: unknown; - private?: unknown; - trusted?: unknown; - _noForwarding?: boolean; -} - -export interface MessageHead { - 'mime'?: string; - 'replace'?: string; - 'forwarded'?: string; - 'webrtc'?: string; - 'webrtc-duration'?: number; - 'vc'?: boolean; - [key: string]: unknown; -} - -export interface Message { - id?: string; - topic: string; - seq: number; - from?: string; - ts?: Date; - head?: MessageHead | null; - content?: DraftyDoc | string; - noecho?: boolean; - low?: number; - hi?: number; - _deleted?: boolean; - _sending?: boolean; - _failed?: boolean; - _fatal?: boolean; - _cancelled?: boolean; - _status?: number; - _noForwarding?: boolean; - _origTs?: Date; - _origSeq?: number; -} - -export interface PubMessage extends Omit { - seq?: number; -} - -export interface CtrlParams { - what?: string; - count?: number; - seq?: number; - del?: number; - acs?: AccessMode; - user?: string; - token?: string; - expires?: Date; - unsub?: boolean; - ver?: string; - build?: string; - sid?: string; - [key: string]: unknown; -} - -export interface CtrlMessage { - id?: string; - topic?: string; - code: number; - text?: string; - ts?: Date; - params?: CtrlParams; -} - -export interface DataMessage { - topic: string; - from?: string; - ts: Date; - seq: number; - head?: MessageHead; - content?: DraftyDoc | string; -} - -export interface DelValues { - clear: number; - delseq: SeqRange[]; -} - -export interface MetaMessage { - id?: string; - topic: string; - ts?: Date; - desc?: TopicDesc; - sub?: TopicSubscription[]; - tags?: string[]; - cred?: Credential[]; - del?: DelValues; - aux?: Record; -} - -export type PresWhat = - | 'on' - | 'off' - | 'ua' - | 'upd' - | 'gone' - | 'acs' - | 'term' - | 'msg' - | 'read' - | 'recv' - | 'del' - | 'tags' - | 'aux'; - -export interface PresMessage { - topic?: string; - src?: string; - what: PresWhat; - seq?: number; - clear?: number; - delseq?: SeqRange[]; - ua?: string; - act?: string; - tgt?: string; - dacs?: AccessModeInput; - _noForwarding?: boolean; -} - -export type InfoWhat = 'kp' | 'kpa' | 'kpv' | 'recv' | 'read' | 'call'; - -export interface InfoMessage { - topic?: string; - src?: string; - from?: string; - what: InfoWhat; - seq?: number; - event?: string; - payload?: unknown; - _noForwarding?: boolean; -} - -export interface ServerMessage { - ctrl?: CtrlMessage; - data?: DataMessage; - meta?: MetaMessage; - pres?: PresMessage; - info?: InfoMessage; -} - -export interface ServerParams { - ver?: string; - build?: string; - sid?: string; - [key: string]: unknown; -} - -export interface SetDesc { - defacs?: DefAcs; - public?: unknown; - private?: unknown; - trusted?: unknown; - acs?: AccessMode; - updated?: Date; - _noForwarding?: boolean; -} - -export interface SetSub { - user?: string | null; - mode?: string | null; - topic?: string; - acs?: AccessMode; - updated?: Date; - _noForwarding?: boolean; -} - -export interface SetParams { - desc?: SetDesc; - sub?: SetSub; - tags?: string[]; - cred?: Credential; - aux?: Record; - attachments?: string[]; -} - -export interface AccountParams { - defacs?: DefAcs; - public?: unknown; - private?: unknown; - trusted?: unknown; - tags?: string[]; - cred?: Credential[]; - scheme?: string; - secret?: string; - attachments?: string[]; -} - -export interface HiPacket { - id?: string; - ver?: string; - ua?: string; - dev?: string | null; - lang?: string; - platf?: string; -} - -export interface AccPacket { - id?: string; - user: string | null; - scheme: string | null; - secret: string | null; - tmpscheme?: string; - tmpsecret?: string; - login?: boolean; - tags?: string[]; - desc: SetDesc; - cred?: Credential[]; -} - -export interface LoginPacket { - id?: string; - scheme: string; - secret: string; - cred?: Credential[] | null; -} - -export interface SubPacket { - id?: string; - topic: string; - get?: GetQuery; - set: { - desc?: SetDesc; - sub?: SetSub; - tags?: string[]; - aux?: Record; - }; -} - -export interface LeavePacket { - id?: string; - topic: string; - unsub?: boolean; -} - -export interface GetPacket extends GetQuery { - id?: string; - topic: string; -} - -export interface SetPacket { - id?: string; - topic: string; - desc?: SetDesc; - sub?: SetSub; - tags?: string[]; - cred?: Credential; - aux?: Record; -} - -export type DelWhat = 'msg' | 'topic' | 'sub' | 'cred' | 'user'; - -export interface DelPacket { - id?: string; - topic: string | null; - what: DelWhat; - delseq?: SeqRange[]; - user?: string; - cred?: { meth: string; val: string }; - hard?: boolean; -} - -export type NoteWhat = 'recv' | 'read' | 'kp' | 'kpa' | 'kpv' | 'call'; - -export interface NotePacket { - id?: string; - topic: string; - what: NoteWhat; - seq?: number; - event?: string; - payload?: unknown; -} - -export interface ClientMessage { - hi?: HiPacket; - acc?: AccPacket; - login?: LoginPacket; - sub?: SubPacket; - leave?: LeavePacket; - pub?: PubMessage; - get?: GetPacket; - set?: SetPacket; - del?: DelPacket; - note?: NotePacket; - extra?: { attachments: string[] }; -} - -export interface PushPayload { - what: string; - topic?: string; - seq?: number; - xfrom?: string; - modeGiven?: string; - modeWant?: string; -} diff --git a/src/core/utils.ts b/src/core/utils.ts deleted file mode 100644 index bcfd9b6..0000000 --- a/src/core/utils.ts +++ /dev/null @@ -1,301 +0,0 @@ -import AccessMode from './access-mode'; -import { DEL_CHAR, LOCAL_SEQID } from './config'; - -export interface SeqRange { - low: number; - hi?: number; -} - -export interface BoundedSeqRange { - low: number; - hi: number; -} - -const TIMESTAMP_KEYS = [ - 'ts', - 'touched', - 'updated', - 'created', - 'when', - 'deleted', - 'expires', -]; -const MIN_TIMESTAMP_LENGTH = 20; -const MAX_TIMESTAMP_LENGTH = 24; -const UNSAFE_MERGE_KEYS = ['__proto__', 'constructor', '_noForwarding']; -const RELATIVE_URL_BLOCKER = /^\s*([a-z][a-z0-9+.-]*:|\/\/)/im; - -function isObjectLike(value: unknown): value is object { - return typeof value === 'object' && value !== null; -} - -function isValidDate(d: unknown): d is Date { - return d instanceof Date && !isNaN(d.getTime()) && d.getTime() !== 0; -} - -function padNumber(val: number, size = 2): string { - return String(val).padStart(size, '0'); -} - -export function reviveTimestamp(key: string, val: unknown): unknown { - if ( - typeof val === 'string' && - val.length >= MIN_TIMESTAMP_LENGTH && - val.length <= MAX_TIMESTAMP_LENGTH && - TIMESTAMP_KEYS.includes(key) - ) { - const date = new Date(val); - if (!isNaN(date.getTime())) { - return date; - } - } - return val; -} - -export function jsonParseHelper(key: string, val: unknown): unknown { - if (key === 'acs' && typeof val === 'object') { - return new AccessMode(val); - } - return reviveTimestamp(key, val); -} - -export function isUrlRelative(url: string | null | undefined): boolean { - return !!url && !RELATIVE_URL_BLOCKER.test(url); -} - -export function rfc3339DateString(d: unknown): string | undefined { - if (!isValidDate(d)) { - return undefined; - } - - const millis = d.getUTCMilliseconds(); - return ( - d.getUTCFullYear() + - '-' + - padNumber(d.getUTCMonth() + 1) + - '-' + - padNumber(d.getUTCDate()) + - 'T' + - padNumber(d.getUTCHours()) + - ':' + - padNumber(d.getUTCMinutes()) + - ':' + - padNumber(d.getUTCSeconds()) + - (millis ? '.' + padNumber(millis, 3) : '') + - 'Z' - ); -} - -function mergeValue(dst: unknown, src: unknown): unknown { - if (typeof src !== 'object') { - if (src === undefined) { - return dst; - } - if (src === DEL_CHAR) { - return undefined; - } - return src; - } - if (src === null) { - return dst; - } - - if (src instanceof Date && !isNaN(src.getTime())) { - return !dst || - !(dst instanceof Date) || - isNaN(dst.getTime()) || - dst.getTime() < src.getTime() - ? src - : dst; - } - - if (src instanceof AccessMode) { - return new AccessMode(src); - } - - if (src instanceof Array) { - return src; - } - - const target: object = isObjectLike(dst) ? dst : {}; - - for (const prop of Object.keys(src)) { - if (UNSAFE_MERGE_KEYS.includes(prop)) { - continue; - } - try { - Reflect.set( - target, - prop, - mergeValue(Reflect.get(target, prop), Reflect.get(src, prop)) - ); - } catch (err) { - console.warn('Error merging property:', prop, err); - } - } - return target; -} - -export function mergeObj>( - dst: T | undefined, - src: unknown -): T { - return mergeValue(dst, src) as T; -} - -export function mergeToCache( - cache: Record, - key: string, - newval: unknown -): T { - const merged = mergeObj(cache[key], newval); - cache[key] = merged; - return merged; -} - -function shouldStripValue(value: unknown, key: string): boolean { - return ( - key[0] === '_' || - !value || - (Array.isArray(value) && value.length === 0) || - (value instanceof Date && !isValidDate(value)) - ); -} - -export function simplify(obj: T): Partial { - Object.keys(obj).forEach((key) => { - const value: unknown = Reflect.get(obj, key); - if (shouldStripValue(value, key)) { - Reflect.deleteProperty(obj, key); - } else if (isObjectLike(value) && !(value instanceof Date)) { - simplify(value); - if (Object.getOwnPropertyNames(value).length === 0) { - Reflect.deleteProperty(obj, key); - } - } - }); - return obj; -} - -export function normalizeArray(arr: unknown): string[] { - let out: string[] = []; - if (Array.isArray(arr)) { - for (const item of arr) { - if (item && typeof item === 'string') { - const tag = item.trim().toLowerCase(); - if (tag.length > 1) { - out.push(tag); - } - } - } - out = out.sort().filter((item, pos, ary) => !pos || item !== ary[pos - 1]); - } - if (out.length === 0) { - out.push(DEL_CHAR); - } - return out; -} - -function hasNumericLow(range: unknown): range is SeqRange { - return isObjectLike(range) && typeof Reflect.get(range, 'low') === 'number'; -} - -function isUsableRange(range: SeqRange): boolean { - return range.low < LOCAL_SEQID && range.low > 0; -} - -function compareRanges(r1: SeqRange, r2: SeqRange): number { - if (r1.low < r2.low) { - return -1; - } - if (r1.low === r2.low) { - return (r2.hi ?? 0) - (r1.hi ?? 0); - } - return 1; -} - -function clipPendingRange(range: SeqRange, maxSeq: number): SeqRange { - if (!range.hi || range.hi < LOCAL_SEQID) { - return { ...range }; - } - return { low: range.low, hi: maxSeq + 1 }; -} - -export function normalizeRanges(ranges: unknown, maxSeq: number): SeqRange[] { - if (!Array.isArray(ranges)) { - return []; - } - - const candidates: SeqRange[] = ranges.filter(hasNumericLow); - candidates.sort(compareRanges); - - const clipped = candidates - .filter(isUsableRange) - .map((range) => clipPendingRange(range, maxSeq)); - - return clipped.reduce((out, range) => { - const prev = out[out.length - 1]; - if (prev && prev.hi !== undefined && range.low <= prev.hi) { - prev.hi = Math.max(prev.hi, range.hi ?? range.low + 1); - } else { - out.push(range); - } - return out; - }, []); -} - -export function listToRanges(list: number[]): SeqRange[] { - list.sort((a, b) => a - b); - return list.reduce((out, id) => { - const prev = out[out.length - 1]; - if (!prev) { - out.push({ low: id }); - } else if (prev.hi ? id > prev.hi : id !== prev.low + 1) { - out.push({ low: id }); - } else { - prev.hi = prev.hi ? Math.max(prev.hi, id + 1) : id + 1; - } - return out; - }, []); -} - -export function clipOutRange( - src: BoundedSeqRange, - clip: BoundedSeqRange -): BoundedSeqRange[] { - if (clip.hi <= src.low || clip.low >= src.hi) { - return [src]; - } - - if (clip.low <= src.low) { - if (clip.hi >= src.hi) { - return []; - } - return [{ low: clip.hi, hi: src.hi }]; - } - - const result = [{ low: src.low, hi: clip.low }]; - if (clip.hi < src.hi) { - result.push({ low: clip.hi, hi: src.hi }); - } - - return result; -} - -export function clipInRange( - src: BoundedSeqRange, - clip: BoundedSeqRange -): BoundedSeqRange | null { - if (clip.hi <= src.low || clip.low >= src.hi) { - return null; - } - - if (src.low >= clip.low && src.hi <= clip.hi) { - return src; - } - - return { - low: Math.max(src.low, clip.low), - hi: Math.min(src.hi, clip.hi), - }; -} diff --git a/yarn.lock b/yarn.lock index 66c55f0..4d6b64b 100644 --- a/yarn.lock +++ b/yarn.lock @@ -5704,13 +5704,6 @@ __metadata: languageName: node linkType: hard -"fake-indexeddb@npm:^6.2.5": - version: 6.2.6 - resolution: "fake-indexeddb@npm:6.2.6" - checksum: 10c0/d55b3155548f08da1c9d7552314eed30fd1880c1f7643654c8b0c1fdf80591682d9f88e7a5c481113f48b994cb09820d61eee0dd8b966ca4f4497fce0eb748de - languageName: node - linkType: hard - "fast-deep-equal@npm:^3.1.1, fast-deep-equal@npm:^3.1.3": version: 3.1.3 resolution: "fast-deep-equal@npm:3.1.3" @@ -9297,7 +9290,6 @@ __metadata: eslint-config-prettier: "npm:^10.1.8" eslint-plugin-ft-flow: "npm:^3.0.11" eslint-plugin-prettier: "npm:^5.5.6" - fake-indexeddb: "npm:^6.2.5" jest: "npm:^29.7.0" lefthook: "npm:^2.1.10" prettier: "npm:^3.9.6" From df687b4c5ae781865ea3d7a7683ec36831cf86f0 Mon Sep 17 00:00:00 2001 From: amerllica Date: Sun, 25 Oct 2026 17:56:23 +0330 Subject: [PATCH 06/14] docs: describe the package as a React layer over tinode-sdk --- NOTICE | 10 ++- README.md | 43 +++++++---- docs/DECISIONS.md | 129 ++++++++++++++++----------------- docs/persistence/README.md | 2 +- docs/persistence/auth-token.md | 4 +- 5 files changed, 99 insertions(+), 89 deletions(-) diff --git a/NOTICE b/NOTICE index 60ea100..c5a791f 100644 --- a/NOTICE +++ b/NOTICE @@ -1,7 +1,9 @@ react-native-tinode Copyright 2026 amerllica -This product is a TypeScript re-implementation of tinode-js (tinode-sdk), -https://github.com/tinode/tinode-js, Copyright Tinode LLC, licensed under the -Apache License, Version 2.0. The source was ported module by module and modified -to run on React Native (Hermes) as well as in web browsers. +This product depends on tinode-sdk (tinode-js), https://github.com/tinode/tinode-js, +Copyright Tinode LLC, licensed under the Apache License, Version 2.0. + +The TypeScript declarations in src/sdk/types.ts describe the tinode-sdk API and are +derived from its source. The grapheme splitter and UTF-8 decoder in src/platform are +original work of this project. diff --git a/README.md b/README.md index 8db6f6c..f5bf383 100644 --- a/README.md +++ b/README.md @@ -1,13 +1,11 @@ # react-native-tinode -[Tinode](https://github.com/tinode/chat) chat client for React Native and the web, written in TypeScript. - -It is a port of the official JavaScript SDK ([tinode-js](https://github.com/tinode/tinode-js) v0.25.4) that does not -depend on browser APIs, plus a set of React hooks. +React hooks and providers for [Tinode](https://github.com/tinode/chat) chat on React Native and the web, on top of +the official JavaScript SDK, [tinode-sdk](https://github.com/tinode/tinode-js). - iOS, Android and web. Works in Expo Go and in bare React Native. -- No native code and no runtime dependencies. -- Typed protocol messages, topics, Drafty documents and contact cards. +- No native code. +- TypeScript types for the whole SDK: protocol messages, topics, Drafty documents and contact cards. - Offline cache: IndexedDB on the web; `expo-sqlite`, MMKV or AsyncStorage on native, in one line. ## Installation @@ -16,6 +14,10 @@ depend on browser APIs, plus a set of React hooks. yarn add react-native-tinode ``` +`tinode-sdk` comes with it. Until the next `tinode-sdk` release is on npm, it is installed from a pinned commit of +the [tinode-js](https://github.com/tinode/tinode-js) `devel` branch, so installing needs `git` and `npm` on the +machine (both are on CI runners and EAS build images). + ## Quick start ```tsx @@ -60,7 +62,7 @@ On the Android emulator the example rewrites `localhost` to `10.0.2.2`. ## Using the client directly -The core API follows tinode-js, so its [documentation](https://tinode.github.io/js-api/) applies. +`Tinode` is the `tinode-sdk` client, so its [documentation](https://tinode.github.io/js-api/) applies. ```ts import { createTinode } from 'react-native-tinode'; @@ -100,15 +102,18 @@ added through `attach(target, 'onData', fn)`, which you can use too. ## Reconnecting -The provider reconnects when the app comes back to the foreground. To also reconnect when the network comes back, -pass NetInfo: +The provider reconnects when the app comes back to the foreground. When the connection drops, the client retries with +a growing delay. To retry at once when the network comes back, pass NetInfo in the config: ```tsx import NetInfo from '@react-native-community/netinfo'; - + ``` +`netInfo` is anything with `addEventListener(listener)` that returns an unsubscribe function and calls the listener +with `{ isConnected }`, so a small wrapper over the browser `online` and `offline` events works on the web too. + ## Persistence By default nothing is cached (`persist: false`). With a cache, your app can show chats at once on start, and chats @@ -137,7 +142,8 @@ The store is your app's dependency, not this library's. To keep users signed in `tinode.getLargeFileHelper()` uploads and downloads attachments. - `upload()` accepts a web `Blob`/`File` or a React Native file object `{ uri, name, type }`. -- `download()` saves the file in the browser. On native it resolves with the `Blob`, and saving it is up to you. +- `download()` saves the file in the browser. It does not work on native yet: the current `tinode-sdk` needs a DOM + for it. Until the fix is released upstream, download attachments yourself with `fetch` and the auth token. ## Push notifications @@ -151,11 +157,16 @@ registerDeviceToken(tinode, await messaging().getToken()); With Expo, use `(await Notifications.getDevicePushTokenAsync()).data`. The server sends FCM data messages; how to show them is up to the app. -## Differences from tinode-js +## What this package adds to tinode-sdk + +- Providers and hooks with shared topic subscriptions, paging and typing state. +- TypeScript types. `tinode-sdk` is plain JavaScript and ships no types. +- Two small polyfills for Hermes, installed only when missing: `Intl.Segmenter` (grapheme level only, used by Drafty) + and a UTF-8 `TextDecoder` (used by vCard import). Import `react-native-tinode` before `tinode-sdk` so they are in + place when the SDK loads. +- `isCommError(error)`, because `tinode-sdk` does not export its `CommError` class. -- No global polyfills. Nothing touches `window`, `document` or `navigator` without checking first. -- `Tinode.setDatabaseProvider()` is gone. Use the `storage` option. -- A number of upstream bugs are fixed. See [docs/DECISIONS.md](docs/DECISIONS.md) for the reasoning behind the port. +See [docs/DECISIONS.md](docs/DECISIONS.md) for the reasoning. ## Contributing @@ -165,4 +176,4 @@ show them is up to the app. ## License -Apache-2.0. Based on [tinode-js](https://github.com/tinode/tinode-js) by Tinode LLC, see [NOTICE](NOTICE). +Apache-2.0. Uses [tinode-sdk](https://github.com/tinode/tinode-js) by Tinode LLC, see [NOTICE](NOTICE). diff --git a/docs/DECISIONS.md b/docs/DECISIONS.md index 86fc336..6b69318 100644 --- a/docs/DECISIONS.md +++ b/docs/DECISIONS.md @@ -1,73 +1,70 @@ # Decisions -## 1. Re-implement tinode-js in TypeScript instead of wrapping `tinode-sdk` - -The first plan was to wrap the `tinode-sdk` npm package and add types and shims around it. -We chose a full TypeScript port instead. - -Reasons: - -- `tinode-sdk` assumes a browser at many points: `window.location` in `LargeFileHelper`, - `document` for downloads, `indexedDB` for the cache, `Intl.Segmenter` in Drafty, - `navigator.userAgent` in the constructor, and an import-time shim that writes `global.window`. - Shimming these from outside the bundle is fragile and changes global state for the whole app. -- The SDK has no types. Hand-written `.d.ts` files drift from the runtime. -- Storage is hard-wired to IndexedDB. A port lets us put storage behind an adapter now, - without an upstream change. - -Cost: protocol fixes in upstream do not arrive automatically. Track upstream releases and port -relevant changes by hand. The port targets tinode-js **v0.25.4**; `VERSION` in -`src/core/config.ts` is the version sent to the server and must match the ported feature level. - -## 2. Module layout mirrors upstream - -`src/core/*.ts` keeps upstream file names, class names, method names and argument order. -This keeps the port easy to diff against upstream releases and keeps the public API familiar to -existing Tinode users. - -## 3. Storage is an adapter - -`StorageAdapter` (`src/core/storage/storage-adapter.ts`) is a small record-based interface with -no SDK classes in it. `PersistentCache` does all Topic ↔ record mapping and keeps the upstream -`DB` method names. - -- Web: `IndexedDBAdapter` uses the same database name, version and schema as upstream, so an - existing browser cache stays valid. -- Native: `KeyValueAdapter` wraps any key-value store the app already has (`expo-sqlite/kv-store`, - MMKV through `fromMMKV`, AsyncStorage). The library imports none of them, so it keeps zero - dependencies and still runs in Expo Go. The store's shape is a TypeScript interface, and a test - checks it against each store's published typings. -- `KeyValueAdapter` extends `MemoryAdapter`: it loads the whole cache on open and writes every - change through. That is fine for contacts and recent chats. A SQLite adapter for large offline - histories is planned for 0.2.0 (issue #1). -- No eviction: the cache keeps every message it has seen, like the upstream web client. -- `MemoryAdapter` exists for tests and for a session-only cache. - -`Tinode.setDatabaseProvider()` from upstream is removed. Use the `storage` config key. - -## 4. Platform rules - -- No browser globals without a `typeof` guard. No writes to globals. -- `Intl.Segmenter` is missing on Hermes: Drafty uses a fallback grapheme splitter. -- `TextDecoder` may be missing: TheCard has a UTF-8 fallback. -- `new Blob([ArrayBuffer])` and object URLs for such Blobs throw on React Native: code falls - back to `data:` URIs. -- `LargeFileHelper.download()` saves the file through the DOM on web (upstream behaviour). Where - there is no DOM it resolves with the downloaded `Blob`; saving it is the app's job. -- `LargeFileHelper.upload()` accepts a React Native file descriptor `{ uri, name, type }` as - well as a web `Blob`/`File`. +## 1. Wrap `tinode-sdk` instead of porting it + +Until 0.1.x this package carried its own TypeScript port of tinode-js, because `tinode-sdk` assumed a browser and had +IndexedDB hard-wired. [tinode/tinode-js#103](https://github.com/tinode/tinode-js/pull/103) moved the platform +dependencies into the SDK's config: `storage` (any storage adapter), `netInfo` (reconnect when the network is back) +and `network` (`WebSocket` and `XMLHttpRequest`). With that merged, the port has no reason to exist: protocol fixes +now arrive with `tinode-sdk` instead of being ported by hand. + +This package keeps only what the SDK does not do: React providers and hooks, TypeScript types, and two Hermes +polyfills (section 4). + +## 2. `tinode-sdk` is pinned to a GitHub commit until the next release + +The merged work is on the tinode-js `devel` branch and not on npm yet, so `package.json` depends on +`github:tinode/tinode-js#commit=`. Yarn downloads that commit, runs `npm install` and `npm pack` in it once, and +stores the packed checksum in `yarn.lock`, so CI installs are reproducible. When a release with the change is on npm, +replace the pin with a version range. + +## 3. Types live in `src/sdk` + +`tinode-sdk` is plain JavaScript and ships no types. + +- `src/sdk/types.ts` declares the SDK surface: classes as `declare class` (so each name is both the instance type and + the constructor), plus the protocol and storage types. It started as the declarations of the old port, which had + the same API, and is aligned with upstream where they differ (`network` option, `setDatabaseProvider`, the socket + shape upstream uses). +- `src/sdk/tinode-sdk.d.ts` tells TypeScript what the untyped module exports, using only inline imports from + `./types`, so emitted declarations never refer to `tinode-sdk` itself. +- `src/sdk/index.ts` re-exports the values with those types. Constants that upstream only has as `Tinode` statics + (`MESSAGE_STATUS_*`, `DEL_CHAR`) are exported as plain constants. + +Upstream does not export `Topic`, `TopicMe`, `TopicFnd`, `CommError`, `MetaGetBuilder` or `LargeFileHelper`, so they +are types only. Instances come from the client (`getTopic`, `getMeTopic`, `startMetaQuery`, `getLargeFileHelper`). +`isCommError` replaces `instanceof CommError`. `TOPIC_ME`, `LOCAL_SEQID` and `DEFAULT_MESSAGES_PAGE` are not exported +upstream either; the React layer keeps its own copies in `src/react/constants.ts`. + +When `tinode-sdk` changes its API, update `src/sdk/types.ts` by hand. `src/sdk/__tests__/sdk.test.ts` loads the real +SDK, so a missing export fails there. + +## 4. Hermes polyfills + +`tinode-sdk` calls `new Intl.Segmenter()` when it loads (Drafty) and uses `TextDecoder` for vCard import. Hermes +has neither. `src/platform` installs a grapheme-only `Intl.Segmenter` and a UTF-8-only `TextDecoder`, each only when +the global is missing, and `src/index.tsx` imports it before the SDK. `package.json` lists `src/platform` and +`lib/module/platform` in `sideEffects`, so web bundlers keep the import. + +These go away when tinode-js ships its own fallbacks (planned as the next upstream PR, together with downloads without +a DOM). Until then `LargeFileHelper.download()` works on the web only. ## 5. React layer -Hooks live in `src/react`. Tinode callbacks are single-slot properties, so the hooks attach -listeners through a small multiplexer instead of overwriting app callbacks. -NetInfo is not a dependency, not even an optional one. A guarded `require` of an optional package -breaks bare React Native builds, because Metro defaults `allowOptionalDependencies` to `false`. -Apps that want reconnect on network change pass their NetInfo module to the provider -(`netInfo={NetInfo}`). Without it, reconnect still happens on `AppState` change and through the -SDK's own backoff. +Hooks live in `src/react`. Tinode callbacks are single-slot properties, so the hooks attach listeners through a small +multiplexer instead of overwriting app callbacks. + +NetInfo is not a dependency, not even an optional one. A guarded `require` of an optional package breaks bare React +Native builds, because Metro defaults `allowOptionalDependencies` to `false`. Apps that want a fast reconnect pass +their NetInfo module in the config (`netInfo: NetInfo`); the SDK then retries at once when the network comes back. +The provider still reconnects on `AppState` change. + +## 6. Storage + +Storage adapters come from `tinode-sdk`: `IndexedDBAdapter` (the default in browsers when `persist` is on), +`KeyValueAdapter` over any key-value store the app already has (`expo-sqlite/kv-store`, MMKV through `fromMMKV`, +AsyncStorage) and `MemoryAdapter`. This package imports none of the stores, so it still runs in Expo Go. -## 6. License +## 7. License -The port is a derivative work of tinode-js (Apache-2.0). This package is released under -Apache-2.0, with attribution in `NOTICE`. +This package is released under Apache-2.0. It depends on tinode-sdk (Apache-2.0), with attribution in `NOTICE`. diff --git a/docs/persistence/README.md b/docs/persistence/README.md index d13711a..14c3f63 100644 --- a/docs/persistence/README.md +++ b/docs/persistence/README.md @@ -14,7 +14,7 @@ The cache is never the source of truth. The server is. Deleting the cache loses | Bare React Native, or an Expo development build that wants the fastest store | `react-native-mmkv` | [mmkv.md](mmkv.md) | | Already uses AsyncStorage | `@react-native-async-storage/async-storage` | [async-storage.md](async-storage.md) | | Web | nothing to do: `persist: true` uses IndexedDB | below | -| Thousands of messages per chat kept offline | SQLite adapter, planned for 0.2.0 | [issue #1](https://github.com/amerllica/react-native-tinode/issues/1) | +| Thousands of messages per chat kept offline | SQLite adapter, planned | [issue #1](https://github.com/amerllica/react-native-tinode/issues/1) | The login token does not belong in this cache. See [auth-token.md](auth-token.md). diff --git a/docs/persistence/auth-token.md b/docs/persistence/auth-token.md index 3965dfe..30876a1 100644 --- a/docs/persistence/auth-token.md +++ b/docs/persistence/auth-token.md @@ -13,13 +13,13 @@ Use a secure store for the token, not the chat cache: ```tsx import * as SecureStore from 'expo-secure-store'; import { useEffect } from 'react'; -import { CommError, useLogin } from 'react-native-tinode'; +import { isCommError, useLogin } from 'react-native-tinode'; const TOKEN_KEY = 'tinode-token'; const UNAUTHORIZED = 401; function isRejectedToken(error: unknown) { - return error instanceof CommError && error.code === UNAUTHORIZED; + return isCommError(error) && error.code === UNAUTHORIZED; } export function useRememberedLogin() { From ce5e2ebaf7b47f0ac6f9bf41fa35f3e3526a203e Mon Sep 17 00:00:00 2001 From: amerllica Date: Sun, 25 Oct 2026 18:28:29 +0330 Subject: [PATCH 07/14] refactor: split the tinode-sdk declarations into one file per area --- NOTICE | 2 +- docs/DECISIONS.md | 11 +- src/sdk/types.ts | 1956 ---------------------------------- src/sdk/types/access-mode.ts | 60 ++ src/sdk/types/connection.ts | 55 + src/sdk/types/drafty.ts | 289 +++++ src/sdk/types/index.ts | 114 ++ src/sdk/types/large-file.ts | 60 ++ src/sdk/types/network.ts | 64 ++ src/sdk/types/storage.ts | 402 +++++++ src/sdk/types/the-card.ts | 96 ++ src/sdk/types/tinode.ts | 276 +++++ src/sdk/types/topic.ts | 346 ++++++ src/sdk/types/wire.ts | 367 +++++++ 14 files changed, 2137 insertions(+), 1961 deletions(-) delete mode 100644 src/sdk/types.ts create mode 100644 src/sdk/types/access-mode.ts create mode 100644 src/sdk/types/connection.ts create mode 100644 src/sdk/types/drafty.ts create mode 100644 src/sdk/types/index.ts create mode 100644 src/sdk/types/large-file.ts create mode 100644 src/sdk/types/network.ts create mode 100644 src/sdk/types/storage.ts create mode 100644 src/sdk/types/the-card.ts create mode 100644 src/sdk/types/tinode.ts create mode 100644 src/sdk/types/topic.ts create mode 100644 src/sdk/types/wire.ts diff --git a/NOTICE b/NOTICE index c5a791f..5fd3497 100644 --- a/NOTICE +++ b/NOTICE @@ -4,6 +4,6 @@ Copyright 2026 amerllica This product depends on tinode-sdk (tinode-js), https://github.com/tinode/tinode-js, Copyright Tinode LLC, licensed under the Apache License, Version 2.0. -The TypeScript declarations in src/sdk/types.ts describe the tinode-sdk API and are +The TypeScript declarations in src/sdk/types/ describe the tinode-sdk API and are derived from its source. The grapheme splitter and UTF-8 decoder in src/platform are original work of this project. diff --git a/docs/DECISIONS.md b/docs/DECISIONS.md index 6b69318..871f274 100644 --- a/docs/DECISIONS.md +++ b/docs/DECISIONS.md @@ -22,8 +22,10 @@ replace the pin with a version range. `tinode-sdk` is plain JavaScript and ships no types. -- `src/sdk/types.ts` declares the SDK surface: classes as `declare class` (so each name is both the instance type and - the constructor), plus the protocol and storage types. It started as the declarations of the old port, which had +- `src/sdk/types/` declares the SDK surface, one file per area (Drafty, TheCard, storage, topics, wire messages, the + client): classes as `declare class` (so each name is both the instance type and the constructor), plus the + protocol and storage types. `src/sdk/types/index.ts` lists the public names one by one, so internal helper types + stay out of the package API. It started as the declarations of the old port, which had the same API, and is aligned with upstream where they differ (`network` option, `setDatabaseProvider`, the socket shape upstream uses). - `src/sdk/tinode-sdk.d.ts` tells TypeScript what the untyped module exports, using only inline imports from @@ -36,8 +38,9 @@ are types only. Instances come from the client (`getTopic`, `getMeTopic`, `start `isCommError` replaces `instanceof CommError`. `TOPIC_ME`, `LOCAL_SEQID` and `DEFAULT_MESSAGES_PAGE` are not exported upstream either; the React layer keeps its own copies in `src/react/constants.ts`. -When `tinode-sdk` changes its API, update `src/sdk/types.ts` by hand. `src/sdk/__tests__/sdk.test.ts` loads the real -SDK, so a missing export fails there. +When `tinode-sdk` changes its API, update `src/sdk/types/` by hand. `src/sdk/__tests__/sdk.test.ts` loads the real +SDK, so a missing export fails there. The goal is to move these declarations into tinode-js, so that `tinode-sdk` +ships its own types and `src/sdk` shrinks to the re-exports. ## 4. Hermes polyfills diff --git a/src/sdk/types.ts b/src/sdk/types.ts deleted file mode 100644 index a057622..0000000 --- a/src/sdk/types.ts +++ /dev/null @@ -1,1956 +0,0 @@ -type AccessValue = number | string | null | undefined; -export interface AccessModeInput { - given?: AccessValue; - want?: AccessValue; - mode?: AccessValue; -} -export interface AccessModeJson { - mode: string | null; - given: string | null; - want: string | null; -} -export declare class AccessMode { - #private; - static readonly _NONE = 0; - static readonly _JOIN = 1; - static readonly _READ = 2; - static readonly _WRITE = 4; - static readonly _PRES = 8; - static readonly _APPROVE = 16; - static readonly _SHARE = 32; - static readonly _DELETE = 64; - static readonly _OWNER = 128; - static readonly _BITMASK: number; - static readonly _INVALID = 1048576; - given?: number | null; - want?: number | null; - mode?: number | null; - constructor(acs?: AccessModeInput | null); - static decode(str: AccessValue): number | null; - static encode(val: number | null | undefined): string | null; - static update( - val: number | null | undefined, - upd: AccessValue - ): number | null | undefined; - static diff(a1: AccessValue, a2: AccessValue): number; - toString(): string; - jsonHelper(): AccessModeJson; - setMode(m: AccessValue): this; - updateMode(u: AccessValue): this; - getMode(): string | null; - setGiven(g: AccessValue): this; - updateGiven(u: AccessValue): this; - getGiven(): string | null; - setWant(w: AccessValue): this; - updateWant(u: AccessValue): this; - getWant(): string | null; - getMissing(): string | null; - getExcessive(): string | null; - updateAll(val?: AccessModeInput | null): this; - isOwner(side?: string): boolean; - isPresencer(side?: string): boolean; - isMuted(side?: string): boolean; - isJoiner(side?: string): boolean; - isReader(side?: string): boolean; - isWriter(side?: string): boolean; - isApprover(side?: string): boolean; - isAdmin(side?: string): boolean; - isSharer(side?: string): boolean; - isDeleter(side?: string): boolean; -} - -type CardCommProto = 'tel' | 'email' | 'tinode' | 'http' | 'impp'; -export interface CardName { - surname?: string; - given?: string; - additional?: string; - prefix?: string; - suffix?: string; -} -export interface CardOrg { - fn?: string; - title?: string; -} -export interface CardPhoto { - type?: string; - data?: string; - ref?: string; -} -interface CardBirthday { - y?: number; - m: number; - d: number; -} -export interface CardComm { - proto: CardCommProto; - des: string[]; - value: string; -} -export interface CardData { - fn?: string; - n?: CardName; - org?: CardOrg; - note?: string; - bday?: CardBirthday; - photo?: CardPhoto | '\u2421'; - comm?: CardComm[]; -} -type MaybeCard = CardData | null | undefined; -export interface TheCard extends CardData {} -export declare class TheCard { - static contentType: string; - constructor( - fn?: string, - imageUrl?: string, - imageMimeType?: string, - note?: string - ); - merge(other: CardData): void; - get contentType(): string; - get size(): number; - static setFn(card: MaybeCard, fn?: string | null): CardData; - static getFn(card: MaybeCard): string | null; - static setNote(card: MaybeCard, note?: string | null): CardData; - static setPhoto( - card: MaybeCard, - imageUrl?: string | null, - imageMimeType?: string | null - ): CardData; - static getPhotoUrl(card: MaybeCard): string | null; - static getOrg(card: MaybeCard): string | null; - static setPhone(card: MaybeCard, phone: string, type?: string): CardData; - static setEmail(card: MaybeCard, email: string, type?: string): CardData; - static setTinodeID( - card: MaybeCard, - tinodeID: string, - type?: string - ): CardData; - static addPhone(card: MaybeCard, phone: string, type?: string): CardData; - static addEmail(card: MaybeCard, email: string, type?: string): CardData; - static addTinodeID( - card: MaybeCard, - tinodeID: string, - type?: string - ): CardData; - static clearPhone( - card: T, - phone?: string, - type?: string - ): T; - static clearEmail( - card: T, - email?: string, - type?: string - ): T; - static clearTinodeID( - card: T, - tinodeID?: string, - type?: string - ): T; - static getComm(card: MaybeCard, proto: string): CardComm[]; - static getEmails(card: MaybeCard): string[]; - static getPhones(card: MaybeCard): string[]; - static getFirstTinodeID(card: MaybeCard): string | null; - static exportVCard(card: MaybeCard): string | null; - static importVCard(vcardStr: unknown): CardData | null; - static isFileSupported(type?: string | null, name?: string | null): boolean; -} - -type DraftyEntityType = - 'AU' | 'BN' | 'EX' | 'HT' | 'IM' | 'LN' | 'MN' | 'TC' | 'VC' | 'VD'; -type DraftyStyleType = - | DraftyEntityType - | 'BR' - | 'CO' - | 'DL' - | 'EM' - | 'FM' - | 'HD' - | 'HL' - | 'QQ' - | 'RW' - | 'ST'; -type DraftyJsonObject = { - readonly [key: string]: unknown; -}; -export interface DraftyEntData extends CardData { - act?: string; - aonly?: boolean; - duration?: number; - height?: number; - incoming?: boolean; - mime?: string; - name?: string; - premime?: string; - preref?: string; - preview?: string; - ref?: string; - size?: number; - state?: string; - title?: string; - url?: string; - val?: string | DraftyJsonObject; - vc?: boolean; - width?: number; - _tempPreview?: string; - _processing?: boolean; -} -export interface DraftyFmt { - at?: number; - len?: number; - tp?: DraftyStyleType; - key?: number; -} -export interface DraftyEnt { - tp: DraftyStyleType; - data?: DraftyEntData; -} -export interface DraftyDoc { - txt?: string; - fmt?: DraftyFmt[]; - ent?: DraftyEnt[]; -} -export type DraftySource = DraftyDoc | string | null | undefined; -export interface DraftyNode { - type?: DraftyStyleType; - text?: string; - data?: DraftyEntData; - key?: number; - att?: boolean; - children?: DraftyNode[] | null; - parent?: DraftyNode; -} -export type DraftyFormatter = ( - style: DraftyStyleType | undefined, - data: DraftyEntData | undefined, - values: (R | string)[] | null, - index: number, - stack: DraftyStyleType[] | undefined -) => R | null | undefined; -type DraftyEntityCallback = ( - data: DraftyEntData | undefined, - index: number, - tp: DraftyStyleType -) => unknown; -type DraftyStyleCallback = ( - tp: DraftyStyleType | undefined, - at: number | undefined, - len: number | undefined, - key: number | undefined, - index: number -) => unknown; -type DraftyLogger = (message: string, ...args: unknown[]) => void; -type DraftyAttributes = Record< - string, - string | number | boolean | null | undefined ->; -interface ImageDesc { - mime?: string; - refurl?: string; - bits?: string; - preview?: string; - width?: number; - height?: number; - filename?: string; - size?: number; - _tempPreview?: string; - urlPromise?: Promise; -} -interface VideoDesc { - mime?: string; - refurl?: string; - bits?: string; - preview?: string; - preref?: string; - width?: number; - height?: number; - duration?: number; - filename?: string; - size?: number; - _tempPreview?: string; - urlPromise?: Promise<[string | undefined, string | undefined]>; -} -interface AudioDesc { - mime?: string; - refurl?: string; - bits?: string; - duration?: number; - preview?: string; - filename?: string; - size?: number; - urlPromise?: Promise; -} -interface AttachmentDesc { - mime?: string; - data?: string; - filename?: string; - size?: number; - refurl?: string; - urlPromise?: Promise; -} -interface LinkData { - txt: string; - url: string; -} -interface VideoCallUpdate { - state?: string; - duration?: number; - incoming?: boolean; - vc?: boolean; -} -type ButtonActionType = 'url' | 'pub'; -export declare class Drafty implements DraftyDoc { - txt: string; - fmt: DraftyFmt[]; - ent: DraftyEnt[]; - static logger?: DraftyLogger | null; - static readonly contentType = 'text/x-drafty'; - static init(plainText?: unknown): DraftyDoc | null; - static parse(content: string): DraftyDoc; - static parse(content: unknown): DraftyDoc | null; - static append(first: DraftyDoc, second: DraftySource): DraftyDoc; - static append( - first: DraftyDoc | null | undefined, - second: DraftySource - ): DraftySource; - static insertImage( - content: DraftyDoc | null | undefined, - at: number, - imageDesc: ImageDesc - ): DraftyDoc; - static insertVideo( - content: DraftyDoc | null | undefined, - at: number, - videoDesc: VideoDesc - ): DraftyDoc; - static insertAudio( - content: DraftyDoc | null | undefined, - at: number, - audioDesc: AudioDesc - ): DraftyDoc; - static videoCall(audioOnly?: boolean): DraftyDoc; - static updateVideoCall( - content: T, - params: VideoCallUpdate - ): T; - static quote(header: string, uid: string, body: DraftySource): DraftyDoc; - static mention(name: string | null | undefined, uid: string): DraftyDoc; - static appendLink( - content: DraftyDoc | null | undefined, - linkData: LinkData - ): DraftyDoc; - static appendImage( - content: DraftyDoc | null | undefined, - imageDesc: ImageDesc - ): DraftyDoc; - static appendAudio( - content: DraftyDoc | null | undefined, - audioDesc: AudioDesc - ): DraftyDoc; - static attachFile( - content: DraftyDoc | null | undefined, - attachmentDesc: AttachmentDesc - ): DraftyDoc; - static wrapInto( - content: DraftyDoc | string, - style: DraftyStyleType, - at?: number, - len?: number - ): DraftyDoc; - static wrapAsForm( - content: DraftyDoc | string, - at?: number, - len?: number - ): DraftyDoc; - static insertButton( - content: DraftySource, - at: number, - len: number, - name: string | undefined, - actionType: ButtonActionType, - actionValue?: string, - refUrl?: string - ): DraftyDoc | null; - static appendButton( - content: DraftyDoc | null | undefined, - title: string, - name: string | undefined, - actionType: ButtonActionType, - actionValue?: string, - refUrl?: string - ): DraftyDoc | null; - static attachJSON( - content: DraftyDoc | null | undefined, - data: DraftyJsonObject - ): DraftyDoc; - static appendLineBreak(content: DraftyDoc | null | undefined): DraftyDoc; - static appendTheCard( - content: DraftyDoc | null | undefined, - theCardData: CardData - ): DraftyDoc; - static UNSAFE_toHTML(doc: DraftySource): string | null; - static format( - original: DraftySource, - formatter: DraftyFormatter, - context?: unknown - ): R | null | undefined; - static shorten( - original: DraftySource, - limit: number, - light?: boolean - ): DraftyDoc; - static forwardedContent(original: DraftySource): DraftyDoc; - static replyContent(original: DraftySource, limit: number): DraftySource; - static preview( - original: DraftySource, - limit: number, - forwarding?: boolean - ): DraftyDoc; - static toPlainText(content: DraftyDoc | string): string | undefined; - static isPlainText(content: DraftyDoc | string): boolean; - static toMarkdown(content: DraftySource): string | null; - static isValid(content: unknown): boolean; - static hasAttachments(content: DraftyDoc): boolean; - static attachments( - content: DraftyDoc, - callback: DraftyEntityCallback, - context?: unknown - ): void; - static hasEntities(content: DraftySource): boolean; - static entities( - content: DraftyDoc, - callback: DraftyEntityCallback, - context?: unknown - ): void; - static styles( - content: DraftyDoc, - callback: DraftyStyleCallback, - context?: unknown - ): void; - static sanitizeEntities( - content: T - ): T; - static getDownloadUrl(entData: DraftyEntData): string | null; - static isProcessing(entData: DraftyEntData): boolean; - static getPreviewUrl(entData: DraftyEntData): string | null; - static getEntitySize(entData: DraftyEntData): number; - static getEntityMimeType(entData: DraftyEntData): string; - static tagName(style: DraftyStyleType | undefined): string | undefined; - static attrValue( - style: DraftyStyleType | undefined, - data: DraftyEntData | null | undefined - ): DraftyAttributes | null | undefined; - static getContentType(): string; - static isFormResponseType(mimeType: string | null | undefined): boolean; -} - -type Comparator = (a: T, b: T) => number; -type ForEachCallback = ( - elem: T, - prev: T | undefined, - next: T | undefined, - index: number -) => void; -type FilterCallback = (elem: T, index: number) => boolean; -declare class CBuffer { - #private; - buffer: T[]; - constructor(compare?: Comparator | null, unique?: boolean); - getAt(at: number): T | undefined; - getLast(filter?: FilterCallback | null): T | undefined; - put(items: T[]): void; - put(...items: T[]): void; - delAt(at: number): T | undefined; - delRange(since: number, before: number): T[]; - length(): number; - reset(): void; - forEach( - callback: ForEachCallback, - startIdx?: number, - beforeIdx?: number, - context?: unknown - ): void; - find(elem: T, nearest?: boolean): number; - filter(callback: FilterCallback, context?: unknown): void; - isEmpty(): boolean; -} - -export interface SeqRange$1 { - low: number; - hi?: number; -} -export interface TopicRecord { - name: string; - created?: Date; - updated?: Date; - deleted?: Date; - touched?: Date; - read?: number; - recv?: number; - seq?: number; - clear?: number; - defacs?: unknown; - creds?: unknown; - public?: unknown; - trusted?: unknown; - private?: unknown; - _aux?: unknown; - _deleted?: boolean; - tags?: string[]; - acs?: unknown; -} -export interface UserRecord { - uid: string; - public: unknown; -} -export interface SubscriptionRecord { - topic: string; - uid: string; - updated?: Date; - mode?: string; - read?: number; - recv?: number; - clear?: number; - lastSeen?: unknown; - userAgent?: string; -} -export interface MessageRecord { - topic: string; - seq: number; - ts?: Date; - _status?: number; - from?: string; - head?: unknown; - content?: unknown; -} -export interface DelLogRecord { - topic: string; - clear: number; - low: number; - hi: number; -} -export interface DelLogRange { - low: number; - hi: number; -} -export interface SeqWindow { - since: number; - before: number; - limit: number; -} -export interface StorageAdapter { - open(): Promise; - close(): Promise; - destroy(): Promise; - isOpen(): boolean; - getTopics(): Promise; - getTopic(name: string): Promise; - putTopic(record: TopicRecord): Promise; - removeTopic(name: string): Promise; - getUsers(): Promise; - getUser(uid: string): Promise; - putUser(record: UserRecord): Promise; - removeUser(uid: string): Promise; - getSubscriptions(topic: string): Promise; - getSubscription( - topic: string, - uid: string - ): Promise; - putSubscription(record: SubscriptionRecord): Promise; - removeSubscription(topic: string, uid: string): Promise; - putMessage(record: MessageRecord): Promise; - updateMessageStatus( - topic: string, - seq: number, - status: number - ): Promise; - removeMessages(topic: string, low: number, hi: number): Promise; - readMessages(topic: string, window: SeqWindow): Promise; - readMessageRanges( - topic: string, - ranges: SeqRange$1[] - ): Promise; - addDelLog(records: DelLogRecord[]): Promise; - readDelLog(topic: string, window: SeqWindow): Promise; - readDelLogRanges(topic: string, ranges: SeqRange$1[]): Promise; - maxDelId(topic: string): Promise; -} - -type PersistentCacheLogger = (...args: unknown[]) => void; -type PersistentCacheErrorHandler = (error: unknown) => void; -interface CacheableTopic { - name: string; - seq: number; - read: number; - unread: number; - acs?: unknown; - _tags?: unknown; - getAccessMode(): { - jsonHelper(): unknown; - }; - setAccessMode(acs: unknown): unknown; -} -interface MessageQuery { - since?: number; - before?: number; - limit?: number; - ranges?: SeqRange$1[]; -} -interface CacheableMessage { - topic: string; - seq: number; -} -type CachedSubscription = SubscriptionRecord & { - user: string; -}; -interface CachedUser { - user: string; - public: unknown; -} -type EachCallback = (this: unknown, item: T) => void; -declare class PersistentCache { - #private; - constructor( - onError: PersistentCacheErrorHandler | null | undefined, - logger: PersistentCacheLogger | null | undefined, - adapter: StorageAdapter | null - ); - get disabled(): boolean; - initDatabase(): Promise; - deleteDatabase(): Promise; - isReady(): boolean; - updTopic(topic: CacheableTopic): Promise; - markTopicAsDeleted(name: string, deleted: boolean): Promise; - remTopic(name: string): Promise; - mapTopics( - callback?: EachCallback, - context?: unknown - ): Promise; - deserializeTopic(topic: CacheableTopic, src: TopicRecord): void; - updUser(uid: string, pub?: unknown): Promise; - remUser(uid: string): Promise; - mapUsers( - callback?: EachCallback, - context?: unknown - ): Promise; - getUser(uid: string): Promise; - updSubscription(topicName: string, uid: string, sub: object): Promise; - remSubscription(topicName: string, uid: string): Promise; - mapSubscriptions( - topicName: string, - callback?: EachCallback, - context?: unknown - ): Promise; - addMessage(msg: CacheableMessage): Promise; - updMessageStatus( - topicName: string, - seq: number, - status: number - ): Promise; - remMessages(topicName: string, from?: number, to?: number): Promise; - readMessages( - topicName: string, - query?: MessageQuery | null, - callback?: EachCallback, - context?: unknown - ): Promise; - addDelLog( - topicName: string, - delId: number, - ranges: SeqRange$1[] - ): Promise; - readDelLog( - topicName: string, - query?: MessageQuery | null - ): Promise; - maxDelId(topicName: string): Promise; -} - -export interface SeqRange { - low: number; - hi?: number; -} - -export type MessageCallback = ( - data: Message, - prev: Message | undefined, - next: Message | undefined, - idx: number -) => void; -export type SubscriberCallback = ( - sub: TopicSubscription, - key: string, - all: Record -) => void; -type ReceiptKind = 'recv' | 'read'; -export interface TopicCallbacks { - onData?: (data?: Message) => void; - onMeta?: (meta: MetaMessage) => void; - onPres?: (pres: PresMessage) => void; - onInfo?: (info: InfoMessage) => void; - onMetaDesc?: (topic: Topic) => void; - onMetaSub?: (sub: TopicSubscription) => void; - onSubsUpdated?: (keys: string[], count?: number) => void; - onTagsUpdated?: (tags: string[]) => void; - onCredsUpdated?: (creds: Credential[]) => void; - onAuxUpdated?: (aux: Record) => void; - onDeleteTopic?: () => void; - onAllMessagesReceived?: (count: number) => void; -} -export declare class Topic { - #private; - name: string; - created: Date | undefined; - updated: Date | undefined; - touched: Date; - deleted: Date | undefined; - acs: AccessMode; - defacs: DefAcs | undefined; - private: TopicPrivate | null; - public: unknown; - trusted: unknown; - seq: number; - read: number; - recv: number; - unread: number; - clear: number; - subcnt: number; - online: boolean | undefined; - seen: LastSeen | undefined; - topic: string | undefined; - _users: Record; - _queuedSeqId: number; - _maxSeq: number; - _minSeq: number; - _noEarlierMsgs: boolean; - _maxDel: number; - _recvNotificationTimer: ReturnType | null; - _tags: string[]; - _credentials: Credential[]; - _aux: Record; - _messageVersions: Record>; - _messages: CBuffer; - _attached: boolean; - _lastSubsUpdate: Date; - _new?: boolean; - _deleted: boolean; - _delayedLeaveTimer: ReturnType | null; - onData: TopicCallbacks['onData']; - onMeta: TopicCallbacks['onMeta']; - onPres: TopicCallbacks['onPres']; - onInfo: TopicCallbacks['onInfo']; - onMetaDesc: TopicCallbacks['onMetaDesc']; - onMetaSub: TopicCallbacks['onMetaSub']; - onSubsUpdated: TopicCallbacks['onSubsUpdated']; - onTagsUpdated: TopicCallbacks['onTagsUpdated']; - onCredsUpdated: TopicCallbacks['onCredsUpdated']; - onAuxUpdated: TopicCallbacks['onAuxUpdated']; - onDeleteTopic: TopicCallbacks['onDeleteTopic']; - onAllMessagesReceived: TopicCallbacks['onAllMessagesReceived']; - _cacheGetUser: (uid: string) => TopicSubscription | undefined; - _cachePutUser: (uid: string, user: TopicSubscription) => void; - _cacheDelUser: (uid: string) => void; - _cachePutSelf: () => void; - _cacheDelSelf: () => void; - constructor(name: string, callbacks?: TopicCallbacks); - get _tinode(): Tinode; - set _tinode(tinode: Tinode); - static topicType(name: string | null | undefined): TopicType | undefined; - static isMeTopicName(name: string | null | undefined): boolean; - static isSelfTopicName(name: string | null | undefined): boolean; - static isGroupTopicName(name: string | null | undefined): boolean; - static isP2PTopicName(name: string | null | undefined): boolean; - static isCommTopicName(name: string | null | undefined): boolean; - static isNewGroupTopicName(name: string | null | undefined): boolean; - static isChannelTopicName(name: string | null | undefined): boolean; - isSubscribed(): boolean; - subscribe( - getParams?: GetQuery, - setParams?: SetParams - ): Promise; - createMessage(data: DraftyDoc | string, noEcho?: boolean): PubMessage; - publish( - data: DraftyDoc | string, - noEcho?: boolean - ): Promise; - publishMessage(pub: PubMessage): Promise; - publishDraft( - pub: PubMessage, - prom?: Promise | null - ): Promise; - leave(unsub?: boolean): Promise; - leaveDelayed(unsub: boolean, delay: number): void; - getMeta(params?: GetQuery): Promise; - getMessagesPage( - limit: number, - gaps: SeqRange[] | null | undefined, - min: number, - max: number, - newer: boolean - ): Promise; - getPinnedMessages(): Promise; - setMeta(params: SetParams): Promise; - updateMode(uid: string | null, update: string): Promise; - invite(uid: string, mode?: string | null): Promise; - archive(arch: boolean): Promise; - pinMessage(seq: number, pin: boolean): Promise; - pinTopic(_topic: string, _pin?: boolean): Promise; - pinnedTopicRank(_topic: string): number; - delMessages(ranges: SeqRange[], hard?: boolean): Promise; - delMessagesAll(hardDel?: boolean): Promise; - delMessagesList(list: number[], hardDel?: boolean): Promise; - delMessagesEdits(seq: number, hardDel?: boolean): Promise; - delTopic(hard?: boolean): Promise; - delSubscription(user: string): Promise; - note(what: ReceiptKind, seq: number): void; - noteRecv(seq: number): void; - noteRead(seq?: number): void; - noteKeyPress(): void; - noteRecording(audioOnly?: boolean): void; - videoCall(evt: string, seq: number, payload?: unknown): void; - _updateMyReadRecv( - what: ReceiptKind | 'msg', - seq?: number, - ts?: Date - ): boolean; - userDesc(uid: string): TopicSubscription | undefined; - p2pPeerDesc(): TopicSubscription | undefined; - subscribers(callback?: SubscriberCallback, context?: unknown): void; - tags(): string[]; - aux(key: string): unknown; - alias(): string | undefined; - subscriber(uid: string): TopicSubscription | undefined; - messageVersions( - origSeq: number, - callback?: MessageCallback, - context?: unknown - ): void; - messages( - callback?: MessageCallback, - sinceId?: number, - beforeId?: number, - context?: unknown - ): void; - findMessage(seq: number): Message | undefined; - latestMessage(): Message | undefined; - latestMsgVersion(seq: number): Message | null; - maxMsgSeq(): number; - minMsgSeq(): number; - maxClearId(): number; - messageCount(): number; - queuedMessages(callback: MessageCallback, context?: unknown): void; - msgReceiptCount(what: ReceiptKind, seq: number): number; - msgReadCount(seq: number): number; - msgRecvCount(seq: number): number; - msgHasMoreMessages(min: number, max: number, newer: boolean): SeqRange[]; - isNewMessage(seqId: number): boolean; - flushMessage(seqId: number): Message | undefined; - flushMessageRange(fromId: number, untilId: number): Message[]; - swapMessageId(pub: Message, newSeqId: number): void; - cancelSend(seqId: number): boolean; - getType(): TopicType | undefined; - getAccessMode(): AccessMode; - setAccessMode(acs?: AccessModeInput | null): AccessMode; - getDefaultAccess(): DefAcs | undefined; - startMetaQuery(): MetaGetBuilder; - isArchived(): boolean; - isMeType(): boolean; - isSelfType(): boolean; - isChannelType(): boolean; - isGroupType(): boolean; - isP2PType(): boolean; - isCommType(): boolean; - msgStatus(msg: Message, upd?: boolean): number; - _maybeUpdateMessageVersionsCache(msg: Message): void; - _routeData(data: Message): void; - _routeMeta(meta: MetaMessage): void; - _routePres(pres: PresMessage): void; - _routeInfo(info: InfoMessage): void; - _processMetaDesc(desc: TopicDesc): void; - _processMetaSubs(subs: TopicSubscription[], skipSubcnt?: boolean): void; - _processMetaTags(tags: string[] | string): void; - _processMetaCreds(_creds: Credential[], _upd?: boolean): void; - _processMetaAux(aux: Record | string | null): void; - _processDelMessages(clear: number, delseq?: SeqRange[]): void; - _allMessagesReceived(count: number): void; - _resetSub(): void; - _gone(): void; - _updateCachedUser(uid: string, obj: TopicSubscription): TopicSubscription; - _getQueuedSeqId(): number; - _loadMessages(db: PersistentCache, query?: GetDataType): Promise; - _updateReceived(seq: number | undefined, act?: string): void; -} - -export interface GetOptsType { - ims?: Date; - limit?: number; -} -interface GetSubType extends GetOptsType { - user?: string; - topic?: string; -} -export interface GetDataType { - since?: number; - before?: number; - limit?: number; - ranges?: SeqRange[]; -} -interface GetDelType { - since?: number; - limit?: number; -} -export interface GetQuery { - what?: string; - desc?: GetOptsType; - sub?: GetSubType; - data?: GetDataType; - del?: GetDelType; -} -interface MetaWhat { - data?: GetDataType; - sub?: GetSubType; - desc?: GetOptsType; - tags?: true; - cred?: true; - aux?: true; - del?: GetDelType; -} -type MetaWhatKey = keyof MetaWhat; -export declare class MetaGetBuilder { - #private; - topic: Topic; - what: MetaWhat; - constructor(parent: Topic); - withData(since?: number, before?: number, limit?: number): this; - withLaterData(limit?: number): this; - withDataRanges(ranges: SeqRange[], limit?: number): this; - withDataList(list: number[]): this; - withEarlierData(limit?: number): this; - withDesc(ims?: Date): this; - withLaterDesc(): this; - withSub(ims?: Date, limit?: number, userOrTopic?: string): this; - withOneSub(ims?: Date, userOrTopic?: string): this; - withLaterOneSub(userOrTopic?: string): this; - withLaterSub(limit?: number): this; - withTags(): this; - withCred(): this; - withAux(): this; - withDel(since?: number, limit?: number): this; - withLaterDel(limit?: number): this; - extract(what: K): MetaWhat[K]; - build(): GetQuery | undefined; -} - -export type TopicType = 'me' | 'fnd' | 'grp' | 'p2p' | 'sys' | 'slf'; -export interface DefAcs { - auth?: string; - anon?: string; -} -export interface AuthToken { - token: string; - expires: Date; -} -export interface Credential { - meth: string; - val?: string; - resp?: string; - params?: unknown; - done?: boolean; -} -export interface LastSeen { - when?: Date; - ua?: string; -} -export interface TopicPrivate { - arch?: boolean; - tpin?: string[]; - comment?: string; - [key: string]: unknown; -} -export interface TopicDesc { - created?: Date; - updated?: Date; - touched?: Date; - deleted?: Date; - defacs?: DefAcs; - acs?: AccessMode; - seq?: number; - read?: number; - recv?: number; - clear?: number; - unread?: number; - subcnt?: number; - online?: boolean; - seen?: LastSeen; - public?: unknown; - private?: unknown; - trusted?: unknown; - _noForwarding?: boolean; -} -export interface TopicSubscription { - user?: string; - topic?: string; - created?: Date; - updated?: Date; - touched?: Date; - deleted?: Date; - acs?: AccessMode; - mode?: string; - seq?: number; - read?: number; - recv?: number; - clear?: number; - unread?: number; - online?: boolean; - seen?: LastSeen; - public?: unknown; - private?: unknown; - trusted?: unknown; - _noForwarding?: boolean; -} -export interface MessageHead { - 'mime'?: string; - 'replace'?: string; - 'forwarded'?: string; - 'webrtc'?: string; - 'webrtc-duration'?: number; - 'vc'?: boolean; - [key: string]: unknown; -} -export interface Message { - id?: string; - topic: string; - seq: number; - from?: string; - ts?: Date; - head?: MessageHead | null; - content?: DraftyDoc | string; - noecho?: boolean; - low?: number; - hi?: number; - _deleted?: boolean; - _sending?: boolean; - _failed?: boolean; - _fatal?: boolean; - _cancelled?: boolean; - _status?: number; - _noForwarding?: boolean; - _origTs?: Date; - _origSeq?: number; -} -export interface PubMessage extends Omit { - seq?: number; -} -export interface CtrlParams { - what?: string; - count?: number; - seq?: number; - del?: number; - acs?: AccessMode; - user?: string; - token?: string; - expires?: Date; - unsub?: boolean; - ver?: string; - build?: string; - sid?: string; - [key: string]: unknown; -} -export interface CtrlMessage { - id?: string; - topic?: string; - code: number; - text?: string; - ts?: Date; - params?: CtrlParams; -} -export interface DataMessage { - topic: string; - from?: string; - ts: Date; - seq: number; - head?: MessageHead; - content?: DraftyDoc | string; -} -export interface DelValues { - clear: number; - delseq: SeqRange[]; -} -export interface MetaMessage { - id?: string; - topic: string; - ts?: Date; - desc?: TopicDesc; - sub?: TopicSubscription[]; - tags?: string[]; - cred?: Credential[]; - del?: DelValues; - aux?: Record; -} -export type PresWhat = - | 'on' - | 'off' - | 'ua' - | 'upd' - | 'gone' - | 'acs' - | 'term' - | 'msg' - | 'read' - | 'recv' - | 'del' - | 'tags' - | 'aux'; -export interface PresMessage { - topic?: string; - src?: string; - what: PresWhat; - seq?: number; - clear?: number; - delseq?: SeqRange[]; - ua?: string; - act?: string; - tgt?: string; - dacs?: AccessModeInput; - _noForwarding?: boolean; -} -export type InfoWhat = 'kp' | 'kpa' | 'kpv' | 'recv' | 'read' | 'call'; -export interface InfoMessage { - topic?: string; - src?: string; - from?: string; - what: InfoWhat; - seq?: number; - event?: string; - payload?: unknown; - _noForwarding?: boolean; -} -export interface ServerMessage { - ctrl?: CtrlMessage; - data?: DataMessage; - meta?: MetaMessage; - pres?: PresMessage; - info?: InfoMessage; -} -export interface ServerParams { - ver?: string; - build?: string; - sid?: string; - [key: string]: unknown; -} -export interface SetDesc { - defacs?: DefAcs; - public?: unknown; - private?: unknown; - trusted?: unknown; - acs?: AccessMode; - updated?: Date; - _noForwarding?: boolean; -} -export interface SetSub { - user?: string | null; - mode?: string | null; - topic?: string; - acs?: AccessMode; - updated?: Date; - _noForwarding?: boolean; -} -export interface SetParams { - desc?: SetDesc; - sub?: SetSub; - tags?: string[]; - cred?: Credential; - aux?: Record; - attachments?: string[]; -} -export interface AccountParams { - defacs?: DefAcs; - public?: unknown; - private?: unknown; - trusted?: unknown; - tags?: string[]; - cred?: Credential[]; - scheme?: string; - secret?: string; - attachments?: string[]; -} -export interface HiPacket { - id?: string; - ver?: string; - ua?: string; - dev?: string | null; - lang?: string; - platf?: string; -} -export interface AccPacket { - id?: string; - user: string | null; - scheme: string | null; - secret: string | null; - tmpscheme?: string; - tmpsecret?: string; - login?: boolean; - tags?: string[]; - desc: SetDesc; - cred?: Credential[]; -} -export interface LoginPacket { - id?: string; - scheme: string; - secret: string; - cred?: Credential[] | null; -} -export interface SubPacket { - id?: string; - topic: string; - get?: GetQuery; - set: { - desc?: SetDesc; - sub?: SetSub; - tags?: string[]; - aux?: Record; - }; -} -export interface LeavePacket { - id?: string; - topic: string; - unsub?: boolean; -} -export interface GetPacket extends GetQuery { - id?: string; - topic: string; -} -export interface SetPacket { - id?: string; - topic: string; - desc?: SetDesc; - sub?: SetSub; - tags?: string[]; - cred?: Credential; - aux?: Record; -} -export type DelWhat = 'msg' | 'topic' | 'sub' | 'cred' | 'user'; -export interface DelPacket { - id?: string; - topic: string | null; - what: DelWhat; - delseq?: SeqRange[]; - user?: string; - cred?: { - meth: string; - val: string; - }; - hard?: boolean; -} -export type NoteWhat = 'recv' | 'read' | 'kp' | 'kpa' | 'kpv' | 'call'; -export interface NotePacket { - id?: string; - topic: string; - what: NoteWhat; - seq?: number; - event?: string; - payload?: unknown; -} -export interface ClientMessage { - hi?: HiPacket; - acc?: AccPacket; - login?: LoginPacket; - sub?: SubPacket; - leave?: LeavePacket; - pub?: PubMessage; - get?: GetPacket; - set?: SetPacket; - del?: DelPacket; - note?: NotePacket; - extra?: { - attachments: string[]; - }; -} -export interface PushPayload { - what: string; - topic?: string; - seq?: number; - xfrom?: string; - modeGiven?: string; - modeWant?: string; -} - -export declare class CommError extends Error { - code: number; - constructor(message: string, code: number); -} - -type Handler$1 = { - bivarianceHack(evt: E): void; -}['bivarianceHack']; -export interface WebSocketLike { - readonly OPEN?: number; - readyState: number; - onopen: ((evt: unknown) => void) | null; - onclose: ((evt: unknown) => void) | null; - onerror: ((evt: unknown) => void) | null; - onmessage: ((evt: { data: unknown }) => void) | null; - send(data: string): void; - close(): void; -} -export interface LongPollRequestLike { - readyState: number; - status: number; - responseText: string; - onreadystatechange: Handler$1 | null; - open(method: string, url: string, async: boolean): void; - send(body?: string | null): void; - abort(): void; -} -export type WebSocketProviderType = new (url: string) => WebSocketLike; -export type XHRProviderType$2 = new () => LongPollRequestLike; -type ConnectionTransport = 'ws' | 'lp'; -type ConnectionLogger = (...args: unknown[]) => void; -interface ConnectionConfig { - host: string; - apiKey: string; - transport: string; - secure?: boolean; -} -export type AutoreconnectIterationCallback = ( - timeout: number, - promise?: Promise -) => void; -declare class Connection { - #private; - static readonly NETWORK_ERROR = 503; - static readonly NETWORK_ERROR_TEXT = 'Connection failed'; - static readonly NETWORK_USER = 418; - static readonly NETWORK_USER_TEXT = 'Disconnected by client'; - host: string; - secure: boolean | undefined; - apiKey: string; - version: string; - autoreconnect: boolean; - initialized: ConnectionTransport | undefined; - onMessage: ((message: string) => void) | undefined; - onDisconnect: ((err: CommError, code: number) => void) | undefined; - onOpen: (() => void) | undefined; - onAutoreconnectIteration: AutoreconnectIterationCallback | undefined; - connect: (host_?: string | null, force?: boolean) => Promise; - reconnect: (force?: boolean) => void; - disconnect: () => void; - sendText: (msg: string) => void; - isConnected: () => boolean; - constructor( - config: ConnectionConfig, - version_: string, - autoreconnect_: boolean - ); - static setNetworkProviders( - wsProvider?: WebSocketProviderType, - xhrProvider?: XHRProviderType$2 - ): void; - static set logger(l: ConnectionLogger); - transport(): ConnectionTransport | undefined; - probe(): void; - backoffReset(): void; - retryNow(): void; -} - -export type FoundContactCallback = ( - contact: TopicSubscription, - key: string, - all: Record -) => void; -export declare class TopicFnd extends Topic { - _contacts: Record; - constructor(callbacks?: TopicCallbacks); - _processMetaSubs(subs: TopicSubscription[]): void; - publish(): Promise; - setMeta(params: SetParams): Promise; - checkTagUniqueness(tag: string, caller: string): Promise; - contacts(callback?: FoundContactCallback, context?: unknown): void; -} - -type Handler = { - bivarianceHack(evt: E): void; -}['bivarianceHack']; -interface UploadProgressEventLike { - lengthComputable: boolean; - loaded: number; - total: number; -} -interface XHRLike { - readyState: number; - status: number; - statusText: string; - response: unknown; - responseType: string; - upload: { - onprogress: Handler | null; - }; - onload: Handler | null; - onerror: Handler | null; - onabort: Handler | null; - onprogress: Handler<{ - loaded: number; - }> | null; - open(method: string, url: string, async: boolean): void; - setRequestHeader(name: string, value: string): void; - send(body?: FormData | null): void; - abort(): void; -} -export type XHRProviderType$1 = new () => XHRLike; -type LargeFileTinode = Pick< - Tinode, - | '_apiKey' - | '_secure' - | '_host' - | 'getAuthToken' - | 'getNextUniqueId' - | 'logger' ->; -export interface ReactNativeFileDescriptor { - uri: string; - name: string; - type: string; -} -export type UploadData = Blob | ReactNativeFileDescriptor; -interface ServerCtrl { - code: number; - text: string; - params?: Record; -} -type ProgressCallback = (progress: number) => void; -type SuccessCallback = (ctrl: ServerCtrl) => void; -type FailureCallback = (ctrl: ServerCtrl | null) => void; -type DownloadErrorCallback = (err: unknown) => void; -export declare class LargeFileHelper { - _tinode: LargeFileTinode; - _version: string; - _apiKey: string; - _authToken: ReturnType; - xhr: XHRLike[]; - onProgress: ProgressCallback | undefined; - constructor(tinode: LargeFileTinode, version: string); - uploadWithBaseUrl( - baseUrl: string | null | undefined, - data: UploadData, - avatarFor?: string | null, - onProgress?: ProgressCallback | null, - onSuccess?: SuccessCallback | null, - onFailure?: FailureCallback | null - ): Promise; - upload( - data: UploadData, - avatarFor?: string | null, - onProgress?: ProgressCallback | null, - onSuccess?: SuccessCallback | null, - onFailure?: FailureCallback | null - ): Promise; - download( - relativeUrl: string, - filename?: string, - mimetype?: string, - onProgress?: ProgressCallback | null, - onError?: DownloadErrorCallback | null - ): Promise | undefined; - cancel(): void; - static setNetworkProvider(xhrProvider?: XHRProviderType$1): void; -} - -export type ContactCallback = (contact: Topic, key: string) => void; -export interface TopicMeCallbacks extends TopicCallbacks { - onContactUpdate?: (what: PresWhat, cont: Topic) => void; -} -export declare class TopicMe extends Topic { - onContactUpdate: TopicMeCallbacks['onContactUpdate']; - constructor(callbacks?: TopicMeCallbacks); - _processMetaDesc(desc: TopicDesc): void; - _processMetaSubs(subs: TopicSubscription[]): void; - _processMetaCreds(creds: Credential[], upd?: boolean): void; - _routePres(pres: PresMessage): void; - _refreshContact(what: PresWhat, cont: Topic): void; - publish(): Promise; - delCredential(method: string, value: string): Promise; - contacts( - callback: ContactCallback, - filter?: ((contact: Topic) => boolean) | null, - context?: unknown - ): void; - getContact(name: string): Topic | undefined; - getAccessMode(): AccessMode; - getAccessMode(name?: string): AccessMode | null; - isArchived(name?: string): boolean; - getCredentials(): Credential[]; - pinTopic(topic: string, pin?: boolean): Promise; - pinnedTopicRank(topic: string): number; -} - -export interface NetInfoStateLike { - isConnected: boolean | null; -} -export interface NetInfoLike { - addEventListener(listener: (state: NetInfoStateLike) => void): () => void; -} - -export type XHRProviderType = XHRProviderType$2 & XHRProviderType$1; -export interface TinodeNetwork { - WebSocket?: WebSocketProviderType; - XMLHttpRequest?: XHRProviderType; -} -export interface TinodeConfig { - appName?: string; - host: string; - apiKey: string; - transport?: 'ws' | 'lp' | null; - secure?: boolean; - platform?: 'ios' | 'android' | 'web'; - persist?: boolean; - storage?: StorageAdapter | null; - netInfo?: NetInfoLike | null; - network?: TinodeNetwork; -} -interface PendingPromise { - resolve(ctrl: CtrlMessage): void; - resolveMeta?(meta: MetaMessage): void; - reject(err: Error): void; - ts: Date; -} -export declare class Tinode { - #private; - static readonly MESSAGE_STATUS_NONE = 0; - static readonly MESSAGE_STATUS_QUEUED = 10; - static readonly MESSAGE_STATUS_SENDING = 20; - static readonly MESSAGE_STATUS_FAILED = 30; - static readonly MESSAGE_STATUS_FATAL = 40; - static readonly MESSAGE_STATUS_SENT = 50; - static readonly MESSAGE_STATUS_RECEIVED = 60; - static readonly MESSAGE_STATUS_READ = 70; - static readonly MESSAGE_STATUS_TO_ME = 80; - static readonly DEL_CHAR = '\u2421'; - static readonly MAX_MESSAGE_SIZE = 'maxMessageSize'; - static readonly MAX_SUBSCRIBER_COUNT = 'maxSubscriberCount'; - static readonly MIN_TAG_LENGTH = 'minTagLength'; - static readonly MAX_TAG_LENGTH = 'maxTagLength'; - static readonly MAX_TAG_COUNT = 'maxTagCount'; - static readonly MAX_FILE_UPLOAD_SIZE = 'maxFileUploadSize'; - static readonly REQ_CRED_VALIDATORS = 'reqCred'; - static readonly MSG_DELETE_AGE = 'msgDelAge'; - static readonly URI_TOPIC_ID_PREFIX = 'tinode:///id/'; - static readonly URI_TOPIC_ALIAS_PREFIX = 'tinode:///alias/'; - static readonly TAG_ALIAS = 'alias:'; - static readonly TAG_EMAIL = 'email:'; - static readonly TAG_PHONE = 'tel:'; - _host: string; - _secure: boolean | undefined; - _appName: string; - _apiKey: string; - _browser: string; - _platform: string; - _hwos: string; - _humanLanguage: string; - _loggingEnabled: boolean; - _trimLongStrings: boolean; - _myUID: string | null; - _authenticated: boolean; - _login: string | null; - _authToken: AuthToken | null; - _inPacketCount: number; - _messageId: number; - _serverInfo: ServerParams | null; - _deviceToken: string | null; - _pendingPromises: Record; - _expirePromises: ReturnType | null; - _connection: Connection; - _persist: boolean; - _db: PersistentCache; - _cache: Record; - onWebsocketOpen: (() => void) | undefined; - onConnect: (() => void) | undefined; - onDisconnect: ((err?: Error | null) => void) | undefined; - onLogin: ((code: number, text: string | undefined) => void) | undefined; - onCtrlMessage: ((ctrl: CtrlMessage) => void) | undefined; - onDataMessage: ((data: DataMessage) => void) | undefined; - onPresMessage: ((pres: PresMessage) => void) | undefined; - onMetaMessage: ((meta: MetaMessage) => void) | undefined; - onInfoMessage: ((info: InfoMessage) => void) | undefined; - onMessage: ((pkt: ServerMessage) => void) | undefined; - onRawMessage: ((text: string) => void) | undefined; - onNetworkProbe: (() => void) | undefined; - onAutoreconnectIteration: AutoreconnectIterationCallback | undefined; - constructor(config: TinodeConfig, onComplete?: (err?: unknown) => void); - logger: (str: unknown, ...args: unknown[]) => void; - static credential( - meth?: string | Credential | null, - val?: string | null, - params?: unknown, - resp?: string | null - ): Credential[] | null; - static topicType(name: string | null | undefined): TopicType | undefined; - static isMeTopicName(name: string | null | undefined): boolean; - static isSelfTopicName(name: string | null | undefined): boolean; - static isGroupTopicName(name: string | null | undefined): boolean; - static isP2PTopicName(name: string | null | undefined): boolean; - static isCommTopicName(name: string | null | undefined): boolean; - static isNewGroupTopicName(name: string | null | undefined): boolean; - static isChannelTopicName(name: string | null | undefined): boolean; - static getVersion(): string; - /** @deprecated Pass `network: { WebSocket, XMLHttpRequest }` in the config instead. */ - static setNetworkProviders( - wsProvider?: WebSocketProviderType | null, - xhrProvider?: XHRProviderType | null - ): void; - /** @deprecated Pass `storage: new IndexedDBAdapter(provider)` in the config instead. */ - static setDatabaseProvider(idbProvider?: unknown): void; - static getLibrary(): string; - static isNullValue(str: unknown): boolean; - static isServerAssignedSeq(seq: number): boolean; - static parseTinodeUrl(tinodeUrl: unknown): string | null; - static isValidTagValue(tag: unknown): boolean; - static tagSplit(tag: string | null | undefined): { - prefix: string; - value: string; - } | null; - static setUniqueTag( - tags: string[] | null | undefined, - uniqueTag: string - ): string[]; - static clearTagPrefix( - tags: (string | null | undefined)[] | null | undefined, - prefix: string - ): string[]; - static tagByPrefix( - tags: (string | null | undefined)[] | null | undefined, - prefix: string - ): string | undefined; - getNextUniqueId(): string | undefined; - connect(host_?: string | null): Promise; - reconnect(force?: boolean): void; - disconnect(): void; - clearStorage(): Promise; - initStorage(): Promise; - networkProbe(): void; - isConnected(): boolean; - isAuthenticated(): boolean; - authorizeURL(url: T): T | string; - account( - uid: string | null, - scheme: string | null, - secret: string | null, - login?: boolean, - params?: AccountParams - ): Promise; - createAccount( - scheme: string, - secret: string, - login?: boolean, - params?: AccountParams - ): Promise; - createAccountBasic( - username: string | null | undefined, - password: string | null | undefined, - params?: AccountParams - ): Promise; - updateAccountBasic( - uid: string | null, - username: string | null | undefined, - password: string | null | undefined, - params?: AccountParams - ): Promise; - hello(): Promise; - setDeviceToken(dt: string | null | undefined | false): boolean; - login( - scheme: string, - secret: string, - cred?: Credential[] | null - ): Promise; - loginBasic( - uname: string, - password: string, - cred?: Credential[] | null - ): Promise; - loginToken(token: string, cred?: Credential[] | null): Promise; - requestResetAuthSecret( - scheme: string, - method: string, - value: string - ): Promise; - getAuthToken(): AuthToken | null; - setAuthToken(token: AuthToken | null): void; - subscribe( - topicName: string, - getParams?: GetQuery, - setParams?: SetParams - ): Promise; - leave(topic: string, unsub?: boolean): Promise; - createMessage( - topic: string, - content: DraftyDoc | string, - noEcho?: boolean - ): PubMessage; - publish( - topicName: string, - content: DraftyDoc | string, - noEcho?: boolean - ): Promise; - publishMessage( - pub: PubMessage, - attachments?: string[] | null - ): Promise; - oobNotification(data: PushPayload): void; - getMeta(topic: string, params?: GetQuery): Promise; - setMeta(topic: string, params: SetParams): Promise; - delMessages( - topic: string, - ranges: SeqRange[], - hard?: boolean - ): Promise; - delTopic(topicName: string, hard?: boolean): Promise; - delSubscription(topicName: string, user: string): Promise; - delCredential(method: string, value: string): Promise; - delCurrentUser(hard?: boolean): Promise; - note(topicName: string, what: 'recv' | 'read', seq: number): void; - noteKeyPress(topicName: string, type?: 'kp' | 'kpa' | 'kpv'): void; - videoCall( - topicName: string, - seq: number, - evt: string, - payload?: unknown - ): void; - getTopic(topicName: 'me'): TopicMe; - getTopic(topicName: 'fnd'): TopicFnd; - getTopic(topicName: string | null | undefined): Topic | undefined; - cacheGetTopic(topicName: string | null | undefined): Topic | undefined; - cacheRemTopic(topicName: string): void; - mapTopics( - func: (topic: Topic, key: string) => boolean | void, - context?: unknown - ): void; - isTopicCached(topicName: string): boolean; - newGroupTopicName(isChan?: boolean): string; - getMeTopic(): TopicMe; - getFndTopic(): TopicFnd; - getLargeFileHelper(): LargeFileHelper; - getCurrentUserID(): string | null; - isMe(uid: string | null | undefined): boolean; - getCurrentLogin(): string | null; - getServerInfo(): ServerParams | null; - report(action: string, target: string): Promise; - getServerParam(name: string, defaultValue?: unknown): unknown; - enableLogging(enabled: boolean, trimLongStrings?: boolean): void; - setHumanLanguage(hl: string | null | undefined): void; - isTopicOnline(name: string): boolean; - getTopicAccessMode(name: string): AccessMode | null; - wantAkn(status: boolean): void; -} - -export declare class MemoryAdapter implements StorageAdapter { - #private; - open(): Promise; - close(): Promise; - destroy(): Promise; - isOpen(): boolean; - getTopics(): Promise; - getTopic(name: string): Promise; - putTopic(record: TopicRecord): Promise; - removeTopic(name: string): Promise; - getUsers(): Promise; - getUser(uid: string): Promise; - putUser(record: UserRecord): Promise; - removeUser(uid: string): Promise; - getSubscriptions(topic: string): Promise; - getSubscription( - topic: string, - uid: string - ): Promise; - putSubscription(record: SubscriptionRecord): Promise; - removeSubscription(topic: string, uid: string): Promise; - putMessage(record: MessageRecord): Promise; - updateMessageStatus( - topic: string, - seq: number, - status: number - ): Promise; - removeMessages(topic: string, low: number, hi: number): Promise; - readMessages(topic: string, window: SeqWindow): Promise; - readMessageRanges( - topic: string, - ranges: SeqRange$1[] - ): Promise; - addDelLog(records: DelLogRecord[]): Promise; - readDelLog(topic: string, window: SeqWindow): Promise; - readDelLogRanges(topic: string, ranges: SeqRange$1[]): Promise; - maxDelId(topic: string): Promise; -} - -interface IdbRequest { - result: T; - error: unknown; - onsuccess: (() => void) | null; - onerror: (() => void) | null; -} -interface IdbOpenRequest extends IdbRequest { - onupgradeneeded: (() => void) | null; - onblocked: (() => void) | null; -} -interface IdbCursor { - value: T; - continue(): void; -} -interface IdbIndex { - openCursor( - range: unknown, - direction: 'prev' - ): IdbRequest | null>; -} -interface IdbObjectStore { - indexNames: { - contains(name: string): boolean; - }; - get(key: unknown): IdbRequest; - getAll(range?: unknown): IdbRequest; - put(value: object): IdbRequest; - delete(key: unknown): IdbRequest; - openCursor( - range: unknown, - direction: 'prev' - ): IdbRequest | null>; - index(name: string): IdbIndex; - createIndex( - name: string, - keyPath: string[], - options: { - unique: boolean; - } - ): unknown; -} -interface IdbTransaction { - error: unknown; - oncomplete: (() => void) | null; - onerror: (() => void) | null; - onabort: (() => void) | null; - objectStore(name: string): IdbObjectStore; -} -interface IdbDatabase { - objectStoreNames: { - contains(name: string): boolean; - }; - onversionchange: (() => void) | null; - transaction(stores: string[], mode?: 'readwrite'): IdbTransaction; - createObjectStore( - name: string, - options: { - keyPath: string | string[]; - } - ): IdbObjectStore; - close(): void; -} -interface IdbFactory { - open(name: string, version: number): IdbOpenRequest; - deleteDatabase(name: string): IdbRequest & { - onblocked: (() => void) | null; - }; -} -interface IdbKeyRangeStatic { - only(value: unknown): unknown; - bound( - lower: unknown, - upper: unknown, - lowerOpen?: boolean, - upperOpen?: boolean - ): unknown; -} -interface IndexedDBProvider { - factory: IdbFactory; - keyRange: IdbKeyRangeStatic; -} -export declare class IndexedDBAdapter implements StorageAdapter { - #private; - constructor(provider?: IndexedDBProvider); - static isSupported(): boolean; - open(): Promise; - close(): Promise; - destroy(): Promise; - isOpen(): boolean; - getTopics(): Promise; - getTopic(name: string): Promise; - putTopic(record: TopicRecord): Promise; - removeTopic(name: string): Promise; - getUsers(): Promise; - getUser(uid: string): Promise; - putUser(record: UserRecord): Promise; - removeUser(uid: string): Promise; - getSubscriptions(topic: string): Promise; - getSubscription( - topic: string, - uid: string - ): Promise; - putSubscription(record: SubscriptionRecord): Promise; - removeSubscription(topic: string, uid: string): Promise; - putMessage(record: MessageRecord): Promise; - updateMessageStatus( - topic: string, - seq: number, - status: number - ): Promise; - removeMessages(topic: string, low: number, hi: number): Promise; - readMessages(topic: string, window: SeqWindow): Promise; - readMessageRanges( - topic: string, - ranges: SeqRange$1[] - ): Promise; - addDelLog(records: DelLogRecord[]): Promise; - readDelLog(topic: string, window: SeqWindow): Promise; - readDelLogRanges(topic: string, ranges: SeqRange$1[]): Promise; - maxDelId(topic: string): Promise; -} - -type Awaitable = T | Promise; -export interface KeyValueStore { - getItem(key: string): Awaitable; - setItem(key: string, value: string): unknown; - removeItem(key: string): unknown; - getAllKeys(): Awaitable; - getMany?( - keys: string[] - ): Awaitable>; - multiGet?( - keys: string[] - ): Awaitable; -} -interface MMKVReadWrite { - getString(key: string): string | undefined; - set(key: string, value: string): void; - getAllKeys(): string[]; -} -export type MMKVLike = MMKVReadWrite & - ( - | { - remove(key: string): unknown; - } - | { - delete(key: string): unknown; - } - ); -export interface KeyValueAdapterOptions { - prefix?: string; -} -export declare class KeyValueAdapter extends MemoryAdapter { - #private; - constructor(store: KeyValueStore, options?: KeyValueAdapterOptions); - open(): Promise; - destroy(): Promise; - putTopic(record: TopicRecord): Promise; - removeTopic(name: string): Promise; - putUser(record: UserRecord): Promise; - removeUser(uid: string): Promise; - putSubscription(record: SubscriptionRecord): Promise; - removeSubscription(topic: string, uid: string): Promise; - putMessage(record: MessageRecord): Promise; - updateMessageStatus( - topic: string, - seq: number, - status: number - ): Promise; - removeMessages(topic: string, low: number, hi: number): Promise; - addDelLog(records: DelLogRecord[]): Promise; -} diff --git a/src/sdk/types/access-mode.ts b/src/sdk/types/access-mode.ts new file mode 100644 index 0000000..26b629d --- /dev/null +++ b/src/sdk/types/access-mode.ts @@ -0,0 +1,60 @@ +type AccessValue = number | string | null | undefined; +export interface AccessModeInput { + given?: AccessValue; + want?: AccessValue; + mode?: AccessValue; +} +export interface AccessModeJson { + mode: string | null; + given: string | null; + want: string | null; +} +export declare class AccessMode { + #private; + static readonly _NONE = 0; + static readonly _JOIN = 1; + static readonly _READ = 2; + static readonly _WRITE = 4; + static readonly _PRES = 8; + static readonly _APPROVE = 16; + static readonly _SHARE = 32; + static readonly _DELETE = 64; + static readonly _OWNER = 128; + static readonly _BITMASK: number; + static readonly _INVALID = 1048576; + given?: number | null; + want?: number | null; + mode?: number | null; + constructor(acs?: AccessModeInput | null); + static decode(str: AccessValue): number | null; + static encode(val: number | null | undefined): string | null; + static update( + val: number | null | undefined, + upd: AccessValue + ): number | null | undefined; + static diff(a1: AccessValue, a2: AccessValue): number; + toString(): string; + jsonHelper(): AccessModeJson; + setMode(m: AccessValue): this; + updateMode(u: AccessValue): this; + getMode(): string | null; + setGiven(g: AccessValue): this; + updateGiven(u: AccessValue): this; + getGiven(): string | null; + setWant(w: AccessValue): this; + updateWant(u: AccessValue): this; + getWant(): string | null; + getMissing(): string | null; + getExcessive(): string | null; + updateAll(val?: AccessModeInput | null): this; + isOwner(side?: string): boolean; + isPresencer(side?: string): boolean; + isMuted(side?: string): boolean; + isJoiner(side?: string): boolean; + isReader(side?: string): boolean; + isWriter(side?: string): boolean; + isApprover(side?: string): boolean; + isAdmin(side?: string): boolean; + isSharer(side?: string): boolean; + isDeleter(side?: string): boolean; +} diff --git a/src/sdk/types/connection.ts b/src/sdk/types/connection.ts new file mode 100644 index 0000000..0576f66 --- /dev/null +++ b/src/sdk/types/connection.ts @@ -0,0 +1,55 @@ +import type { LongPollXHRProvider, WebSocketProviderType } from './network'; + +export declare class CommError extends Error { + code: number; + constructor(message: string, code: number); +} + +type ConnectionTransport = 'ws' | 'lp'; +type ConnectionLogger = (...args: unknown[]) => void; +interface ConnectionConfig { + host: string; + apiKey: string; + transport: string; + secure?: boolean; +} +export type AutoreconnectIterationCallback = ( + timeout: number, + promise?: Promise +) => void; +export declare class Connection { + #private; + static readonly NETWORK_ERROR = 503; + static readonly NETWORK_ERROR_TEXT = 'Connection failed'; + static readonly NETWORK_USER = 418; + static readonly NETWORK_USER_TEXT = 'Disconnected by client'; + host: string; + secure: boolean | undefined; + apiKey: string; + version: string; + autoreconnect: boolean; + initialized: ConnectionTransport | undefined; + onMessage: ((message: string) => void) | undefined; + onDisconnect: ((err: CommError, code: number) => void) | undefined; + onOpen: (() => void) | undefined; + onAutoreconnectIteration: AutoreconnectIterationCallback | undefined; + connect: (host_?: string | null, force?: boolean) => Promise; + reconnect: (force?: boolean) => void; + disconnect: () => void; + sendText: (msg: string) => void; + isConnected: () => boolean; + constructor( + config: ConnectionConfig, + version_: string, + autoreconnect_: boolean + ); + static setNetworkProviders( + wsProvider?: WebSocketProviderType, + xhrProvider?: LongPollXHRProvider + ): void; + static set logger(l: ConnectionLogger); + transport(): ConnectionTransport | undefined; + probe(): void; + backoffReset(): void; + retryNow(): void; +} diff --git a/src/sdk/types/drafty.ts b/src/sdk/types/drafty.ts new file mode 100644 index 0000000..831a0d0 --- /dev/null +++ b/src/sdk/types/drafty.ts @@ -0,0 +1,289 @@ +import type { CardData } from './the-card'; + +type DraftyEntityType = + 'AU' | 'BN' | 'EX' | 'HT' | 'IM' | 'LN' | 'MN' | 'TC' | 'VC' | 'VD'; +type DraftyStyleType = + | DraftyEntityType + | 'BR' + | 'CO' + | 'DL' + | 'EM' + | 'FM' + | 'HD' + | 'HL' + | 'QQ' + | 'RW' + | 'ST'; +type DraftyJsonObject = { + readonly [key: string]: unknown; +}; +export interface DraftyEntData extends CardData { + act?: string; + aonly?: boolean; + duration?: number; + height?: number; + incoming?: boolean; + mime?: string; + name?: string; + premime?: string; + preref?: string; + preview?: string; + ref?: string; + size?: number; + state?: string; + title?: string; + url?: string; + val?: string | DraftyJsonObject; + vc?: boolean; + width?: number; + _tempPreview?: string; + _processing?: boolean; +} +export interface DraftyFmt { + at?: number; + len?: number; + tp?: DraftyStyleType; + key?: number; +} +export interface DraftyEnt { + tp: DraftyStyleType; + data?: DraftyEntData; +} +export interface DraftyDoc { + txt?: string; + fmt?: DraftyFmt[]; + ent?: DraftyEnt[]; +} +export type DraftySource = DraftyDoc | string | null | undefined; +export interface DraftyNode { + type?: DraftyStyleType; + text?: string; + data?: DraftyEntData; + key?: number; + att?: boolean; + children?: DraftyNode[] | null; + parent?: DraftyNode; +} +export type DraftyFormatter = ( + style: DraftyStyleType | undefined, + data: DraftyEntData | undefined, + values: (R | string)[] | null, + index: number, + stack: DraftyStyleType[] | undefined +) => R | null | undefined; +type DraftyEntityCallback = ( + data: DraftyEntData | undefined, + index: number, + tp: DraftyStyleType +) => unknown; +type DraftyStyleCallback = ( + tp: DraftyStyleType | undefined, + at: number | undefined, + len: number | undefined, + key: number | undefined, + index: number +) => unknown; +type DraftyLogger = (message: string, ...args: unknown[]) => void; +type DraftyAttributes = Record< + string, + string | number | boolean | null | undefined +>; +interface ImageDesc { + mime?: string; + refurl?: string; + bits?: string; + preview?: string; + width?: number; + height?: number; + filename?: string; + size?: number; + _tempPreview?: string; + urlPromise?: Promise; +} +interface VideoDesc { + mime?: string; + refurl?: string; + bits?: string; + preview?: string; + preref?: string; + width?: number; + height?: number; + duration?: number; + filename?: string; + size?: number; + _tempPreview?: string; + urlPromise?: Promise<[string | undefined, string | undefined]>; +} +interface AudioDesc { + mime?: string; + refurl?: string; + bits?: string; + duration?: number; + preview?: string; + filename?: string; + size?: number; + urlPromise?: Promise; +} +interface AttachmentDesc { + mime?: string; + data?: string; + filename?: string; + size?: number; + refurl?: string; + urlPromise?: Promise; +} +interface LinkData { + txt: string; + url: string; +} +interface VideoCallUpdate { + state?: string; + duration?: number; + incoming?: boolean; + vc?: boolean; +} +type ButtonActionType = 'url' | 'pub'; +export declare class Drafty implements DraftyDoc { + txt: string; + fmt: DraftyFmt[]; + ent: DraftyEnt[]; + static logger?: DraftyLogger | null; + static readonly contentType = 'text/x-drafty'; + static init(plainText?: unknown): DraftyDoc | null; + static parse(content: string): DraftyDoc; + static parse(content: unknown): DraftyDoc | null; + static append(first: DraftyDoc, second: DraftySource): DraftyDoc; + static append( + first: DraftyDoc | null | undefined, + second: DraftySource + ): DraftySource; + static insertImage( + content: DraftyDoc | null | undefined, + at: number, + imageDesc: ImageDesc + ): DraftyDoc; + static insertVideo( + content: DraftyDoc | null | undefined, + at: number, + videoDesc: VideoDesc + ): DraftyDoc; + static insertAudio( + content: DraftyDoc | null | undefined, + at: number, + audioDesc: AudioDesc + ): DraftyDoc; + static videoCall(audioOnly?: boolean): DraftyDoc; + static updateVideoCall( + content: T, + params: VideoCallUpdate + ): T; + static quote(header: string, uid: string, body: DraftySource): DraftyDoc; + static mention(name: string | null | undefined, uid: string): DraftyDoc; + static appendLink( + content: DraftyDoc | null | undefined, + linkData: LinkData + ): DraftyDoc; + static appendImage( + content: DraftyDoc | null | undefined, + imageDesc: ImageDesc + ): DraftyDoc; + static appendAudio( + content: DraftyDoc | null | undefined, + audioDesc: AudioDesc + ): DraftyDoc; + static attachFile( + content: DraftyDoc | null | undefined, + attachmentDesc: AttachmentDesc + ): DraftyDoc; + static wrapInto( + content: DraftyDoc | string, + style: DraftyStyleType, + at?: number, + len?: number + ): DraftyDoc; + static wrapAsForm( + content: DraftyDoc | string, + at?: number, + len?: number + ): DraftyDoc; + static insertButton( + content: DraftySource, + at: number, + len: number, + name: string | undefined, + actionType: ButtonActionType, + actionValue?: string, + refUrl?: string + ): DraftyDoc | null; + static appendButton( + content: DraftyDoc | null | undefined, + title: string, + name: string | undefined, + actionType: ButtonActionType, + actionValue?: string, + refUrl?: string + ): DraftyDoc | null; + static attachJSON( + content: DraftyDoc | null | undefined, + data: DraftyJsonObject + ): DraftyDoc; + static appendLineBreak(content: DraftyDoc | null | undefined): DraftyDoc; + static appendTheCard( + content: DraftyDoc | null | undefined, + theCardData: CardData + ): DraftyDoc; + static UNSAFE_toHTML(doc: DraftySource): string | null; + static format( + original: DraftySource, + formatter: DraftyFormatter, + context?: unknown + ): R | null | undefined; + static shorten( + original: DraftySource, + limit: number, + light?: boolean + ): DraftyDoc; + static forwardedContent(original: DraftySource): DraftyDoc; + static replyContent(original: DraftySource, limit: number): DraftySource; + static preview( + original: DraftySource, + limit: number, + forwarding?: boolean + ): DraftyDoc; + static toPlainText(content: DraftyDoc | string): string | undefined; + static isPlainText(content: DraftyDoc | string): boolean; + static toMarkdown(content: DraftySource): string | null; + static isValid(content: unknown): boolean; + static hasAttachments(content: DraftyDoc): boolean; + static attachments( + content: DraftyDoc, + callback: DraftyEntityCallback, + context?: unknown + ): void; + static hasEntities(content: DraftySource): boolean; + static entities( + content: DraftyDoc, + callback: DraftyEntityCallback, + context?: unknown + ): void; + static styles( + content: DraftyDoc, + callback: DraftyStyleCallback, + context?: unknown + ): void; + static sanitizeEntities( + content: T + ): T; + static getDownloadUrl(entData: DraftyEntData): string | null; + static isProcessing(entData: DraftyEntData): boolean; + static getPreviewUrl(entData: DraftyEntData): string | null; + static getEntitySize(entData: DraftyEntData): number; + static getEntityMimeType(entData: DraftyEntData): string; + static tagName(style: DraftyStyleType | undefined): string | undefined; + static attrValue( + style: DraftyStyleType | undefined, + data: DraftyEntData | null | undefined + ): DraftyAttributes | null | undefined; + static getContentType(): string; + static isFormResponseType(mimeType: string | null | undefined): boolean; +} diff --git a/src/sdk/types/index.ts b/src/sdk/types/index.ts new file mode 100644 index 0000000..f1d359d --- /dev/null +++ b/src/sdk/types/index.ts @@ -0,0 +1,114 @@ +export type { + AccessMode, + AccessModeInput, + AccessModeJson, +} from './access-mode'; +export type { AutoreconnectIterationCallback, CommError } from './connection'; +export type { + Drafty, + DraftyDoc, + DraftyEnt, + DraftyEntData, + DraftyFmt, + DraftyFormatter, + DraftyNode, + DraftySource, +} from './drafty'; +export type { + LargeFileHelper, + ReactNativeFileDescriptor, + UploadData, +} from './large-file'; +export type { + LargeFileXHRProvider, + LongPollRequestLike, + LongPollXHRProvider, + NetInfoLike, + NetInfoStateLike, + TinodeNetwork, + WebSocketLike, + WebSocketProviderType, + XHRProviderType, +} from './network'; +export type { + DelLogRange, + DelLogRecord, + IndexedDBAdapter, + KeyValueAdapter, + KeyValueAdapterOptions, + KeyValueStore, + MemoryAdapter, + MessageRecord, + MMKVLike, + SeqWindow, + StorageAdapter, + SubscriptionRecord, + TopicRecord, + UserRecord, +} from './storage'; +export type { + CardComm, + CardData, + CardName, + CardOrg, + CardPhoto, + TheCard, +} from './the-card'; +export type { Tinode, TinodeConfig } from './tinode'; +export type { + ContactCallback, + FoundContactCallback, + MessageCallback, + MetaGetBuilder, + SubscriberCallback, + Topic, + TopicCallbacks, + TopicFnd, + TopicMe, + TopicMeCallbacks, +} from './topic'; +export type { + AccountParams, + AccPacket, + AuthToken, + ClientMessage, + Credential, + CtrlMessage, + CtrlParams, + DataMessage, + DefAcs, + DelPacket, + DelValues, + DelWhat, + GetDataType, + GetOptsType, + GetPacket, + GetQuery, + HiPacket, + InfoMessage, + InfoWhat, + LastSeen, + LeavePacket, + LoginPacket, + Message, + MessageHead, + MetaMessage, + NotePacket, + NoteWhat, + PresMessage, + PresWhat, + PubMessage, + PushPayload, + SeqRange, + ServerMessage, + ServerParams, + SetDesc, + SetPacket, + SetParams, + SetSub, + SubPacket, + TopicDesc, + TopicPrivate, + TopicSubscription, + TopicType, +} from './wire'; diff --git a/src/sdk/types/large-file.ts b/src/sdk/types/large-file.ts new file mode 100644 index 0000000..fb6c7c0 --- /dev/null +++ b/src/sdk/types/large-file.ts @@ -0,0 +1,60 @@ +import type { LargeFileXHRProvider, XHRLike } from './network'; +import type { Tinode } from './tinode'; + +type LargeFileTinode = Pick< + Tinode, + | '_apiKey' + | '_secure' + | '_host' + | 'getAuthToken' + | 'getNextUniqueId' + | 'logger' +>; +export interface ReactNativeFileDescriptor { + uri: string; + name: string; + type: string; +} +export type UploadData = Blob | ReactNativeFileDescriptor; +interface ServerCtrl { + code: number; + text: string; + params?: Record; +} +type ProgressCallback = (progress: number) => void; +type SuccessCallback = (ctrl: ServerCtrl) => void; +type FailureCallback = (ctrl: ServerCtrl | null) => void; +type DownloadErrorCallback = (err: unknown) => void; +export declare class LargeFileHelper { + _tinode: LargeFileTinode; + _version: string; + _apiKey: string; + _authToken: ReturnType; + xhr: XHRLike[]; + onProgress: ProgressCallback | undefined; + constructor(tinode: LargeFileTinode, version: string); + uploadWithBaseUrl( + baseUrl: string | null | undefined, + data: UploadData, + avatarFor?: string | null, + onProgress?: ProgressCallback | null, + onSuccess?: SuccessCallback | null, + onFailure?: FailureCallback | null + ): Promise; + upload( + data: UploadData, + avatarFor?: string | null, + onProgress?: ProgressCallback | null, + onSuccess?: SuccessCallback | null, + onFailure?: FailureCallback | null + ): Promise; + download( + relativeUrl: string, + filename?: string, + mimetype?: string, + onProgress?: ProgressCallback | null, + onError?: DownloadErrorCallback | null + ): Promise | undefined; + cancel(): void; + static setNetworkProvider(xhrProvider?: LargeFileXHRProvider): void; +} diff --git a/src/sdk/types/network.ts b/src/sdk/types/network.ts new file mode 100644 index 0000000..019e741 --- /dev/null +++ b/src/sdk/types/network.ts @@ -0,0 +1,64 @@ +type EventHandler = { + bivarianceHack(evt: E): void; +}['bivarianceHack']; +export interface WebSocketLike { + readonly OPEN?: number; + readyState: number; + onopen: ((evt: unknown) => void) | null; + onclose: ((evt: unknown) => void) | null; + onerror: ((evt: unknown) => void) | null; + onmessage: ((evt: { data: unknown }) => void) | null; + send(data: string): void; + close(): void; +} +export interface LongPollRequestLike { + readyState: number; + status: number; + responseText: string; + onreadystatechange: EventHandler | null; + open(method: string, url: string, async: boolean): void; + send(body?: string | null): void; + abort(): void; +} +export type WebSocketProviderType = new (url: string) => WebSocketLike; +export type LongPollXHRProvider = new () => LongPollRequestLike; + +interface UploadProgressEventLike { + lengthComputable: boolean; + loaded: number; + total: number; +} +export interface XHRLike { + readyState: number; + status: number; + statusText: string; + response: unknown; + responseType: string; + upload: { + onprogress: EventHandler | null; + }; + onload: EventHandler | null; + onerror: EventHandler | null; + onabort: EventHandler | null; + onprogress: EventHandler<{ + loaded: number; + }> | null; + open(method: string, url: string, async: boolean): void; + setRequestHeader(name: string, value: string): void; + send(body?: FormData | null): void; + abort(): void; +} +export type LargeFileXHRProvider = new () => XHRLike; + +export type XHRProviderType = LongPollXHRProvider & LargeFileXHRProvider; +export interface TinodeNetwork { + WebSocket?: WebSocketProviderType; + XMLHttpRequest?: XHRProviderType; +} + +export interface NetInfoStateLike { + isConnected: boolean | null; +} +export interface NetInfoLike { + addEventListener(listener: (state: NetInfoStateLike) => void): () => void; +} diff --git a/src/sdk/types/storage.ts b/src/sdk/types/storage.ts new file mode 100644 index 0000000..7a20cbe --- /dev/null +++ b/src/sdk/types/storage.ts @@ -0,0 +1,402 @@ +import type { SeqRange } from './wire'; + +export interface TopicRecord { + name: string; + created?: Date; + updated?: Date; + deleted?: Date; + touched?: Date; + read?: number; + recv?: number; + seq?: number; + clear?: number; + defacs?: unknown; + creds?: unknown; + public?: unknown; + trusted?: unknown; + private?: unknown; + _aux?: unknown; + _deleted?: boolean; + tags?: string[]; + acs?: unknown; +} +export interface UserRecord { + uid: string; + public: unknown; +} +export interface SubscriptionRecord { + topic: string; + uid: string; + updated?: Date; + mode?: string; + read?: number; + recv?: number; + clear?: number; + lastSeen?: unknown; + userAgent?: string; +} +export interface MessageRecord { + topic: string; + seq: number; + ts?: Date; + _status?: number; + from?: string; + head?: unknown; + content?: unknown; +} +export interface DelLogRecord { + topic: string; + clear: number; + low: number; + hi: number; +} +export interface DelLogRange { + low: number; + hi: number; +} +export interface SeqWindow { + since: number; + before: number; + limit: number; +} +export interface StorageAdapter { + open(): Promise; + close(): Promise; + destroy(): Promise; + isOpen(): boolean; + getTopics(): Promise; + getTopic(name: string): Promise; + putTopic(record: TopicRecord): Promise; + removeTopic(name: string): Promise; + getUsers(): Promise; + getUser(uid: string): Promise; + putUser(record: UserRecord): Promise; + removeUser(uid: string): Promise; + getSubscriptions(topic: string): Promise; + getSubscription( + topic: string, + uid: string + ): Promise; + putSubscription(record: SubscriptionRecord): Promise; + removeSubscription(topic: string, uid: string): Promise; + putMessage(record: MessageRecord): Promise; + updateMessageStatus( + topic: string, + seq: number, + status: number + ): Promise; + removeMessages(topic: string, low: number, hi: number): Promise; + readMessages(topic: string, window: SeqWindow): Promise; + readMessageRanges( + topic: string, + ranges: SeqRange[] + ): Promise; + addDelLog(records: DelLogRecord[]): Promise; + readDelLog(topic: string, window: SeqWindow): Promise; + readDelLogRanges(topic: string, ranges: SeqRange[]): Promise; + maxDelId(topic: string): Promise; +} + +type PersistentCacheLogger = (...args: unknown[]) => void; +type PersistentCacheErrorHandler = (error: unknown) => void; +interface CacheableTopic { + name: string; + seq: number; + read: number; + unread: number; + acs?: unknown; + _tags?: unknown; + getAccessMode(): { + jsonHelper(): unknown; + }; + setAccessMode(acs: unknown): unknown; +} +interface MessageQuery { + since?: number; + before?: number; + limit?: number; + ranges?: SeqRange[]; +} +interface CacheableMessage { + topic: string; + seq: number; +} +type CachedSubscription = SubscriptionRecord & { + user: string; +}; +interface CachedUser { + user: string; + public: unknown; +} +type EachCallback = (this: unknown, item: T) => void; +export declare class PersistentCache { + #private; + constructor( + onError: PersistentCacheErrorHandler | null | undefined, + logger: PersistentCacheLogger | null | undefined, + adapter: StorageAdapter | null + ); + get disabled(): boolean; + initDatabase(): Promise; + deleteDatabase(): Promise; + isReady(): boolean; + updTopic(topic: CacheableTopic): Promise; + markTopicAsDeleted(name: string, deleted: boolean): Promise; + remTopic(name: string): Promise; + mapTopics( + callback?: EachCallback, + context?: unknown + ): Promise; + deserializeTopic(topic: CacheableTopic, src: TopicRecord): void; + updUser(uid: string, pub?: unknown): Promise; + remUser(uid: string): Promise; + mapUsers( + callback?: EachCallback, + context?: unknown + ): Promise; + getUser(uid: string): Promise; + updSubscription(topicName: string, uid: string, sub: object): Promise; + remSubscription(topicName: string, uid: string): Promise; + mapSubscriptions( + topicName: string, + callback?: EachCallback, + context?: unknown + ): Promise; + addMessage(msg: CacheableMessage): Promise; + updMessageStatus( + topicName: string, + seq: number, + status: number + ): Promise; + remMessages(topicName: string, from?: number, to?: number): Promise; + readMessages( + topicName: string, + query?: MessageQuery | null, + callback?: EachCallback, + context?: unknown + ): Promise; + addDelLog( + topicName: string, + delId: number, + ranges: SeqRange[] + ): Promise; + readDelLog( + topicName: string, + query?: MessageQuery | null + ): Promise; + maxDelId(topicName: string): Promise; +} + +export declare class MemoryAdapter implements StorageAdapter { + #private; + open(): Promise; + close(): Promise; + destroy(): Promise; + isOpen(): boolean; + getTopics(): Promise; + getTopic(name: string): Promise; + putTopic(record: TopicRecord): Promise; + removeTopic(name: string): Promise; + getUsers(): Promise; + getUser(uid: string): Promise; + putUser(record: UserRecord): Promise; + removeUser(uid: string): Promise; + getSubscriptions(topic: string): Promise; + getSubscription( + topic: string, + uid: string + ): Promise; + putSubscription(record: SubscriptionRecord): Promise; + removeSubscription(topic: string, uid: string): Promise; + putMessage(record: MessageRecord): Promise; + updateMessageStatus( + topic: string, + seq: number, + status: number + ): Promise; + removeMessages(topic: string, low: number, hi: number): Promise; + readMessages(topic: string, window: SeqWindow): Promise; + readMessageRanges( + topic: string, + ranges: SeqRange[] + ): Promise; + addDelLog(records: DelLogRecord[]): Promise; + readDelLog(topic: string, window: SeqWindow): Promise; + readDelLogRanges(topic: string, ranges: SeqRange[]): Promise; + maxDelId(topic: string): Promise; +} + +interface IdbRequest { + result: T; + error: unknown; + onsuccess: (() => void) | null; + onerror: (() => void) | null; +} +interface IdbOpenRequest extends IdbRequest { + onupgradeneeded: (() => void) | null; + onblocked: (() => void) | null; +} +interface IdbCursor { + value: T; + continue(): void; +} +interface IdbIndex { + openCursor( + range: unknown, + direction: 'prev' + ): IdbRequest | null>; +} +interface IdbObjectStore { + indexNames: { + contains(name: string): boolean; + }; + get(key: unknown): IdbRequest; + getAll(range?: unknown): IdbRequest; + put(value: object): IdbRequest; + delete(key: unknown): IdbRequest; + openCursor( + range: unknown, + direction: 'prev' + ): IdbRequest | null>; + index(name: string): IdbIndex; + createIndex( + name: string, + keyPath: string[], + options: { + unique: boolean; + } + ): unknown; +} +interface IdbTransaction { + error: unknown; + oncomplete: (() => void) | null; + onerror: (() => void) | null; + onabort: (() => void) | null; + objectStore(name: string): IdbObjectStore; +} +interface IdbDatabase { + objectStoreNames: { + contains(name: string): boolean; + }; + onversionchange: (() => void) | null; + transaction(stores: string[], mode?: 'readwrite'): IdbTransaction; + createObjectStore( + name: string, + options: { + keyPath: string | string[]; + } + ): IdbObjectStore; + close(): void; +} +interface IdbFactory { + open(name: string, version: number): IdbOpenRequest; + deleteDatabase(name: string): IdbRequest & { + onblocked: (() => void) | null; + }; +} +interface IdbKeyRangeStatic { + only(value: unknown): unknown; + bound( + lower: unknown, + upper: unknown, + lowerOpen?: boolean, + upperOpen?: boolean + ): unknown; +} +interface IndexedDBProvider { + factory: IdbFactory; + keyRange: IdbKeyRangeStatic; +} +export declare class IndexedDBAdapter implements StorageAdapter { + #private; + constructor(provider?: IndexedDBProvider); + static isSupported(): boolean; + open(): Promise; + close(): Promise; + destroy(): Promise; + isOpen(): boolean; + getTopics(): Promise; + getTopic(name: string): Promise; + putTopic(record: TopicRecord): Promise; + removeTopic(name: string): Promise; + getUsers(): Promise; + getUser(uid: string): Promise; + putUser(record: UserRecord): Promise; + removeUser(uid: string): Promise; + getSubscriptions(topic: string): Promise; + getSubscription( + topic: string, + uid: string + ): Promise; + putSubscription(record: SubscriptionRecord): Promise; + removeSubscription(topic: string, uid: string): Promise; + putMessage(record: MessageRecord): Promise; + updateMessageStatus( + topic: string, + seq: number, + status: number + ): Promise; + removeMessages(topic: string, low: number, hi: number): Promise; + readMessages(topic: string, window: SeqWindow): Promise; + readMessageRanges( + topic: string, + ranges: SeqRange[] + ): Promise; + addDelLog(records: DelLogRecord[]): Promise; + readDelLog(topic: string, window: SeqWindow): Promise; + readDelLogRanges(topic: string, ranges: SeqRange[]): Promise; + maxDelId(topic: string): Promise; +} + +type Awaitable = T | Promise; +export interface KeyValueStore { + getItem(key: string): Awaitable; + setItem(key: string, value: string): unknown; + removeItem(key: string): unknown; + getAllKeys(): Awaitable; + getMany?( + keys: string[] + ): Awaitable>; + multiGet?( + keys: string[] + ): Awaitable; +} +interface MMKVReadWrite { + getString(key: string): string | undefined; + set(key: string, value: string): void; + getAllKeys(): string[]; +} +export type MMKVLike = MMKVReadWrite & + ( + | { + remove(key: string): unknown; + } + | { + delete(key: string): unknown; + } + ); +export interface KeyValueAdapterOptions { + prefix?: string; +} +export declare class KeyValueAdapter extends MemoryAdapter { + #private; + constructor(store: KeyValueStore, options?: KeyValueAdapterOptions); + open(): Promise; + destroy(): Promise; + putTopic(record: TopicRecord): Promise; + removeTopic(name: string): Promise; + putUser(record: UserRecord): Promise; + removeUser(uid: string): Promise; + putSubscription(record: SubscriptionRecord): Promise; + removeSubscription(topic: string, uid: string): Promise; + putMessage(record: MessageRecord): Promise; + updateMessageStatus( + topic: string, + seq: number, + status: number + ): Promise; + removeMessages(topic: string, low: number, hi: number): Promise; + addDelLog(records: DelLogRecord[]): Promise; +} diff --git a/src/sdk/types/the-card.ts b/src/sdk/types/the-card.ts new file mode 100644 index 0000000..3fcdad5 --- /dev/null +++ b/src/sdk/types/the-card.ts @@ -0,0 +1,96 @@ +type CardCommProto = 'tel' | 'email' | 'tinode' | 'http' | 'impp'; +export interface CardName { + surname?: string; + given?: string; + additional?: string; + prefix?: string; + suffix?: string; +} +export interface CardOrg { + fn?: string; + title?: string; +} +export interface CardPhoto { + type?: string; + data?: string; + ref?: string; +} +interface CardBirthday { + y?: number; + m: number; + d: number; +} +export interface CardComm { + proto: CardCommProto; + des: string[]; + value: string; +} +export interface CardData { + fn?: string; + n?: CardName; + org?: CardOrg; + note?: string; + bday?: CardBirthday; + photo?: CardPhoto | '\u2421'; + comm?: CardComm[]; +} +type MaybeCard = CardData | null | undefined; +export interface TheCard extends CardData {} +export declare class TheCard { + static contentType: string; + constructor( + fn?: string, + imageUrl?: string, + imageMimeType?: string, + note?: string + ); + merge(other: CardData): void; + get contentType(): string; + get size(): number; + static setFn(card: MaybeCard, fn?: string | null): CardData; + static getFn(card: MaybeCard): string | null; + static setNote(card: MaybeCard, note?: string | null): CardData; + static setPhoto( + card: MaybeCard, + imageUrl?: string | null, + imageMimeType?: string | null + ): CardData; + static getPhotoUrl(card: MaybeCard): string | null; + static getOrg(card: MaybeCard): string | null; + static setPhone(card: MaybeCard, phone: string, type?: string): CardData; + static setEmail(card: MaybeCard, email: string, type?: string): CardData; + static setTinodeID( + card: MaybeCard, + tinodeID: string, + type?: string + ): CardData; + static addPhone(card: MaybeCard, phone: string, type?: string): CardData; + static addEmail(card: MaybeCard, email: string, type?: string): CardData; + static addTinodeID( + card: MaybeCard, + tinodeID: string, + type?: string + ): CardData; + static clearPhone( + card: T, + phone?: string, + type?: string + ): T; + static clearEmail( + card: T, + email?: string, + type?: string + ): T; + static clearTinodeID( + card: T, + tinodeID?: string, + type?: string + ): T; + static getComm(card: MaybeCard, proto: string): CardComm[]; + static getEmails(card: MaybeCard): string[]; + static getPhones(card: MaybeCard): string[]; + static getFirstTinodeID(card: MaybeCard): string | null; + static exportVCard(card: MaybeCard): string | null; + static importVCard(vcardStr: unknown): CardData | null; + static isFileSupported(type?: string | null, name?: string | null): boolean; +} diff --git a/src/sdk/types/tinode.ts b/src/sdk/types/tinode.ts new file mode 100644 index 0000000..35af846 --- /dev/null +++ b/src/sdk/types/tinode.ts @@ -0,0 +1,276 @@ +import type { AccessMode } from './access-mode'; +import type { AutoreconnectIterationCallback, Connection } from './connection'; +import type { DraftyDoc } from './drafty'; +import type { LargeFileHelper } from './large-file'; +import type { + NetInfoLike, + TinodeNetwork, + WebSocketProviderType, + XHRProviderType, +} from './network'; +import type { PersistentCache, StorageAdapter } from './storage'; +import type { Topic, TopicFnd, TopicMe } from './topic'; +import type { + AccountParams, + AuthToken, + CtrlMessage, + Credential, + DataMessage, + GetQuery, + InfoMessage, + MetaMessage, + PresMessage, + PubMessage, + PushPayload, + SeqRange, + ServerMessage, + ServerParams, + SetParams, + TopicType, +} from './wire'; + +export interface TinodeConfig { + appName?: string; + host: string; + apiKey: string; + transport?: 'ws' | 'lp' | null; + secure?: boolean; + platform?: 'ios' | 'android' | 'web'; + persist?: boolean; + storage?: StorageAdapter | null; + netInfo?: NetInfoLike | null; + network?: TinodeNetwork; +} +interface PendingPromise { + resolve(ctrl: CtrlMessage): void; + resolveMeta?(meta: MetaMessage): void; + reject(err: Error): void; + ts: Date; +} +export declare class Tinode { + #private; + static readonly MESSAGE_STATUS_NONE = 0; + static readonly MESSAGE_STATUS_QUEUED = 10; + static readonly MESSAGE_STATUS_SENDING = 20; + static readonly MESSAGE_STATUS_FAILED = 30; + static readonly MESSAGE_STATUS_FATAL = 40; + static readonly MESSAGE_STATUS_SENT = 50; + static readonly MESSAGE_STATUS_RECEIVED = 60; + static readonly MESSAGE_STATUS_READ = 70; + static readonly MESSAGE_STATUS_TO_ME = 80; + static readonly DEL_CHAR = '\u2421'; + static readonly MAX_MESSAGE_SIZE = 'maxMessageSize'; + static readonly MAX_SUBSCRIBER_COUNT = 'maxSubscriberCount'; + static readonly MIN_TAG_LENGTH = 'minTagLength'; + static readonly MAX_TAG_LENGTH = 'maxTagLength'; + static readonly MAX_TAG_COUNT = 'maxTagCount'; + static readonly MAX_FILE_UPLOAD_SIZE = 'maxFileUploadSize'; + static readonly REQ_CRED_VALIDATORS = 'reqCred'; + static readonly MSG_DELETE_AGE = 'msgDelAge'; + static readonly URI_TOPIC_ID_PREFIX = 'tinode:///id/'; + static readonly URI_TOPIC_ALIAS_PREFIX = 'tinode:///alias/'; + static readonly TAG_ALIAS = 'alias:'; + static readonly TAG_EMAIL = 'email:'; + static readonly TAG_PHONE = 'tel:'; + _host: string; + _secure: boolean | undefined; + _appName: string; + _apiKey: string; + _browser: string; + _platform: string; + _hwos: string; + _humanLanguage: string; + _loggingEnabled: boolean; + _trimLongStrings: boolean; + _myUID: string | null; + _authenticated: boolean; + _login: string | null; + _authToken: AuthToken | null; + _inPacketCount: number; + _messageId: number; + _serverInfo: ServerParams | null; + _deviceToken: string | null; + _pendingPromises: Record; + _expirePromises: ReturnType | null; + _connection: Connection; + _persist: boolean; + _db: PersistentCache; + _cache: Record; + onWebsocketOpen: (() => void) | undefined; + onConnect: (() => void) | undefined; + onDisconnect: ((err?: Error | null) => void) | undefined; + onLogin: ((code: number, text: string | undefined) => void) | undefined; + onCtrlMessage: ((ctrl: CtrlMessage) => void) | undefined; + onDataMessage: ((data: DataMessage) => void) | undefined; + onPresMessage: ((pres: PresMessage) => void) | undefined; + onMetaMessage: ((meta: MetaMessage) => void) | undefined; + onInfoMessage: ((info: InfoMessage) => void) | undefined; + onMessage: ((pkt: ServerMessage) => void) | undefined; + onRawMessage: ((text: string) => void) | undefined; + onNetworkProbe: (() => void) | undefined; + onAutoreconnectIteration: AutoreconnectIterationCallback | undefined; + constructor(config: TinodeConfig, onComplete?: (err?: unknown) => void); + logger: (str: unknown, ...args: unknown[]) => void; + static credential( + meth?: string | Credential | null, + val?: string | null, + params?: unknown, + resp?: string | null + ): Credential[] | null; + static topicType(name: string | null | undefined): TopicType | undefined; + static isMeTopicName(name: string | null | undefined): boolean; + static isSelfTopicName(name: string | null | undefined): boolean; + static isGroupTopicName(name: string | null | undefined): boolean; + static isP2PTopicName(name: string | null | undefined): boolean; + static isCommTopicName(name: string | null | undefined): boolean; + static isNewGroupTopicName(name: string | null | undefined): boolean; + static isChannelTopicName(name: string | null | undefined): boolean; + static getVersion(): string; + /** @deprecated Pass `network: { WebSocket, XMLHttpRequest }` in the config instead. */ + static setNetworkProviders( + wsProvider?: WebSocketProviderType | null, + xhrProvider?: XHRProviderType | null + ): void; + /** @deprecated Pass `storage: new IndexedDBAdapter(provider)` in the config instead. */ + static setDatabaseProvider(idbProvider?: unknown): void; + static getLibrary(): string; + static isNullValue(str: unknown): boolean; + static isServerAssignedSeq(seq: number): boolean; + static parseTinodeUrl(tinodeUrl: unknown): string | null; + static isValidTagValue(tag: unknown): boolean; + static tagSplit(tag: string | null | undefined): { + prefix: string; + value: string; + } | null; + static setUniqueTag( + tags: string[] | null | undefined, + uniqueTag: string + ): string[]; + static clearTagPrefix( + tags: (string | null | undefined)[] | null | undefined, + prefix: string + ): string[]; + static tagByPrefix( + tags: (string | null | undefined)[] | null | undefined, + prefix: string + ): string | undefined; + getNextUniqueId(): string | undefined; + connect(host_?: string | null): Promise; + reconnect(force?: boolean): void; + disconnect(): void; + clearStorage(): Promise; + initStorage(): Promise; + networkProbe(): void; + isConnected(): boolean; + isAuthenticated(): boolean; + authorizeURL(url: T): T | string; + account( + uid: string | null, + scheme: string | null, + secret: string | null, + login?: boolean, + params?: AccountParams + ): Promise; + createAccount( + scheme: string, + secret: string, + login?: boolean, + params?: AccountParams + ): Promise; + createAccountBasic( + username: string | null | undefined, + password: string | null | undefined, + params?: AccountParams + ): Promise; + updateAccountBasic( + uid: string | null, + username: string | null | undefined, + password: string | null | undefined, + params?: AccountParams + ): Promise; + hello(): Promise; + setDeviceToken(dt: string | null | undefined | false): boolean; + login( + scheme: string, + secret: string, + cred?: Credential[] | null + ): Promise; + loginBasic( + uname: string, + password: string, + cred?: Credential[] | null + ): Promise; + loginToken(token: string, cred?: Credential[] | null): Promise; + requestResetAuthSecret( + scheme: string, + method: string, + value: string + ): Promise; + getAuthToken(): AuthToken | null; + setAuthToken(token: AuthToken | null): void; + subscribe( + topicName: string, + getParams?: GetQuery, + setParams?: SetParams + ): Promise; + leave(topic: string, unsub?: boolean): Promise; + createMessage( + topic: string, + content: DraftyDoc | string, + noEcho?: boolean + ): PubMessage; + publish( + topicName: string, + content: DraftyDoc | string, + noEcho?: boolean + ): Promise; + publishMessage( + pub: PubMessage, + attachments?: string[] | null + ): Promise; + oobNotification(data: PushPayload): void; + getMeta(topic: string, params?: GetQuery): Promise; + setMeta(topic: string, params: SetParams): Promise; + delMessages( + topic: string, + ranges: SeqRange[], + hard?: boolean + ): Promise; + delTopic(topicName: string, hard?: boolean): Promise; + delSubscription(topicName: string, user: string): Promise; + delCredential(method: string, value: string): Promise; + delCurrentUser(hard?: boolean): Promise; + note(topicName: string, what: 'recv' | 'read', seq: number): void; + noteKeyPress(topicName: string, type?: 'kp' | 'kpa' | 'kpv'): void; + videoCall( + topicName: string, + seq: number, + evt: string, + payload?: unknown + ): void; + getTopic(topicName: 'me'): TopicMe; + getTopic(topicName: 'fnd'): TopicFnd; + getTopic(topicName: string | null | undefined): Topic | undefined; + cacheGetTopic(topicName: string | null | undefined): Topic | undefined; + cacheRemTopic(topicName: string): void; + mapTopics( + func: (topic: Topic, key: string) => boolean | void, + context?: unknown + ): void; + isTopicCached(topicName: string): boolean; + newGroupTopicName(isChan?: boolean): string; + getMeTopic(): TopicMe; + getFndTopic(): TopicFnd; + getLargeFileHelper(): LargeFileHelper; + getCurrentUserID(): string | null; + isMe(uid: string | null | undefined): boolean; + getCurrentLogin(): string | null; + getServerInfo(): ServerParams | null; + report(action: string, target: string): Promise; + getServerParam(name: string, defaultValue?: unknown): unknown; + enableLogging(enabled: boolean, trimLongStrings?: boolean): void; + setHumanLanguage(hl: string | null | undefined): void; + isTopicOnline(name: string): boolean; + getTopicAccessMode(name: string): AccessMode | null; + wantAkn(status: boolean): void; +} diff --git a/src/sdk/types/topic.ts b/src/sdk/types/topic.ts new file mode 100644 index 0000000..108d1c5 --- /dev/null +++ b/src/sdk/types/topic.ts @@ -0,0 +1,346 @@ +import type { AccessMode, AccessModeInput } from './access-mode'; +import type { DraftyDoc } from './drafty'; +import type { PersistentCache } from './storage'; +import type { Tinode } from './tinode'; +import type { + CtrlMessage, + Credential, + DefAcs, + GetDataType, + GetDelType, + GetOptsType, + GetQuery, + GetSubType, + InfoMessage, + LastSeen, + Message, + MetaMessage, + PresMessage, + PresWhat, + PubMessage, + SeqRange, + SetParams, + TopicDesc, + TopicPrivate, + TopicSubscription, + TopicType, +} from './wire'; + +type Comparator = (a: T, b: T) => number; +type ForEachCallback = ( + elem: T, + prev: T | undefined, + next: T | undefined, + index: number +) => void; +type FilterCallback = (elem: T, index: number) => boolean; +declare class CBuffer { + #private; + buffer: T[]; + constructor(compare?: Comparator | null, unique?: boolean); + getAt(at: number): T | undefined; + getLast(filter?: FilterCallback | null): T | undefined; + put(items: T[]): void; + put(...items: T[]): void; + delAt(at: number): T | undefined; + delRange(since: number, before: number): T[]; + length(): number; + reset(): void; + forEach( + callback: ForEachCallback, + startIdx?: number, + beforeIdx?: number, + context?: unknown + ): void; + find(elem: T, nearest?: boolean): number; + filter(callback: FilterCallback, context?: unknown): void; + isEmpty(): boolean; +} + +export type MessageCallback = ( + data: Message, + prev: Message | undefined, + next: Message | undefined, + idx: number +) => void; +export type SubscriberCallback = ( + sub: TopicSubscription, + key: string, + all: Record +) => void; +type ReceiptKind = 'recv' | 'read'; +export interface TopicCallbacks { + onData?: (data?: Message) => void; + onMeta?: (meta: MetaMessage) => void; + onPres?: (pres: PresMessage) => void; + onInfo?: (info: InfoMessage) => void; + onMetaDesc?: (topic: Topic) => void; + onMetaSub?: (sub: TopicSubscription) => void; + onSubsUpdated?: (keys: string[], count?: number) => void; + onTagsUpdated?: (tags: string[]) => void; + onCredsUpdated?: (creds: Credential[]) => void; + onAuxUpdated?: (aux: Record) => void; + onDeleteTopic?: () => void; + onAllMessagesReceived?: (count: number) => void; +} +export declare class Topic { + #private; + name: string; + created: Date | undefined; + updated: Date | undefined; + touched: Date; + deleted: Date | undefined; + acs: AccessMode; + defacs: DefAcs | undefined; + private: TopicPrivate | null; + public: unknown; + trusted: unknown; + seq: number; + read: number; + recv: number; + unread: number; + clear: number; + subcnt: number; + online: boolean | undefined; + seen: LastSeen | undefined; + topic: string | undefined; + _users: Record; + _queuedSeqId: number; + _maxSeq: number; + _minSeq: number; + _noEarlierMsgs: boolean; + _maxDel: number; + _recvNotificationTimer: ReturnType | null; + _tags: string[]; + _credentials: Credential[]; + _aux: Record; + _messageVersions: Record>; + _messages: CBuffer; + _attached: boolean; + _lastSubsUpdate: Date; + _new?: boolean; + _deleted: boolean; + _delayedLeaveTimer: ReturnType | null; + onData: TopicCallbacks['onData']; + onMeta: TopicCallbacks['onMeta']; + onPres: TopicCallbacks['onPres']; + onInfo: TopicCallbacks['onInfo']; + onMetaDesc: TopicCallbacks['onMetaDesc']; + onMetaSub: TopicCallbacks['onMetaSub']; + onSubsUpdated: TopicCallbacks['onSubsUpdated']; + onTagsUpdated: TopicCallbacks['onTagsUpdated']; + onCredsUpdated: TopicCallbacks['onCredsUpdated']; + onAuxUpdated: TopicCallbacks['onAuxUpdated']; + onDeleteTopic: TopicCallbacks['onDeleteTopic']; + onAllMessagesReceived: TopicCallbacks['onAllMessagesReceived']; + _cacheGetUser: (uid: string) => TopicSubscription | undefined; + _cachePutUser: (uid: string, user: TopicSubscription) => void; + _cacheDelUser: (uid: string) => void; + _cachePutSelf: () => void; + _cacheDelSelf: () => void; + constructor(name: string, callbacks?: TopicCallbacks); + get _tinode(): Tinode; + set _tinode(tinode: Tinode); + static topicType(name: string | null | undefined): TopicType | undefined; + static isMeTopicName(name: string | null | undefined): boolean; + static isSelfTopicName(name: string | null | undefined): boolean; + static isGroupTopicName(name: string | null | undefined): boolean; + static isP2PTopicName(name: string | null | undefined): boolean; + static isCommTopicName(name: string | null | undefined): boolean; + static isNewGroupTopicName(name: string | null | undefined): boolean; + static isChannelTopicName(name: string | null | undefined): boolean; + isSubscribed(): boolean; + subscribe( + getParams?: GetQuery, + setParams?: SetParams + ): Promise; + createMessage(data: DraftyDoc | string, noEcho?: boolean): PubMessage; + publish( + data: DraftyDoc | string, + noEcho?: boolean + ): Promise; + publishMessage(pub: PubMessage): Promise; + publishDraft( + pub: PubMessage, + prom?: Promise | null + ): Promise; + leave(unsub?: boolean): Promise; + leaveDelayed(unsub: boolean, delay: number): void; + getMeta(params?: GetQuery): Promise; + getMessagesPage( + limit: number, + gaps: SeqRange[] | null | undefined, + min: number, + max: number, + newer: boolean + ): Promise; + getPinnedMessages(): Promise; + setMeta(params: SetParams): Promise; + updateMode(uid: string | null, update: string): Promise; + invite(uid: string, mode?: string | null): Promise; + archive(arch: boolean): Promise; + pinMessage(seq: number, pin: boolean): Promise; + pinTopic(_topic: string, _pin?: boolean): Promise; + pinnedTopicRank(_topic: string): number; + delMessages(ranges: SeqRange[], hard?: boolean): Promise; + delMessagesAll(hardDel?: boolean): Promise; + delMessagesList(list: number[], hardDel?: boolean): Promise; + delMessagesEdits(seq: number, hardDel?: boolean): Promise; + delTopic(hard?: boolean): Promise; + delSubscription(user: string): Promise; + note(what: ReceiptKind, seq: number): void; + noteRecv(seq: number): void; + noteRead(seq?: number): void; + noteKeyPress(): void; + noteRecording(audioOnly?: boolean): void; + videoCall(evt: string, seq: number, payload?: unknown): void; + _updateMyReadRecv( + what: ReceiptKind | 'msg', + seq?: number, + ts?: Date + ): boolean; + userDesc(uid: string): TopicSubscription | undefined; + p2pPeerDesc(): TopicSubscription | undefined; + subscribers(callback?: SubscriberCallback, context?: unknown): void; + tags(): string[]; + aux(key: string): unknown; + alias(): string | undefined; + subscriber(uid: string): TopicSubscription | undefined; + messageVersions( + origSeq: number, + callback?: MessageCallback, + context?: unknown + ): void; + messages( + callback?: MessageCallback, + sinceId?: number, + beforeId?: number, + context?: unknown + ): void; + findMessage(seq: number): Message | undefined; + latestMessage(): Message | undefined; + latestMsgVersion(seq: number): Message | null; + maxMsgSeq(): number; + minMsgSeq(): number; + maxClearId(): number; + messageCount(): number; + queuedMessages(callback: MessageCallback, context?: unknown): void; + msgReceiptCount(what: ReceiptKind, seq: number): number; + msgReadCount(seq: number): number; + msgRecvCount(seq: number): number; + msgHasMoreMessages(min: number, max: number, newer: boolean): SeqRange[]; + isNewMessage(seqId: number): boolean; + flushMessage(seqId: number): Message | undefined; + flushMessageRange(fromId: number, untilId: number): Message[]; + swapMessageId(pub: Message, newSeqId: number): void; + cancelSend(seqId: number): boolean; + getType(): TopicType | undefined; + getAccessMode(): AccessMode; + setAccessMode(acs?: AccessModeInput | null): AccessMode; + getDefaultAccess(): DefAcs | undefined; + startMetaQuery(): MetaGetBuilder; + isArchived(): boolean; + isMeType(): boolean; + isSelfType(): boolean; + isChannelType(): boolean; + isGroupType(): boolean; + isP2PType(): boolean; + isCommType(): boolean; + msgStatus(msg: Message, upd?: boolean): number; + _maybeUpdateMessageVersionsCache(msg: Message): void; + _routeData(data: Message): void; + _routeMeta(meta: MetaMessage): void; + _routePres(pres: PresMessage): void; + _routeInfo(info: InfoMessage): void; + _processMetaDesc(desc: TopicDesc): void; + _processMetaSubs(subs: TopicSubscription[], skipSubcnt?: boolean): void; + _processMetaTags(tags: string[] | string): void; + _processMetaCreds(_creds: Credential[], _upd?: boolean): void; + _processMetaAux(aux: Record | string | null): void; + _processDelMessages(clear: number, delseq?: SeqRange[]): void; + _allMessagesReceived(count: number): void; + _resetSub(): void; + _gone(): void; + _updateCachedUser(uid: string, obj: TopicSubscription): TopicSubscription; + _getQueuedSeqId(): number; + _loadMessages(db: PersistentCache, query?: GetDataType): Promise; + _updateReceived(seq: number | undefined, act?: string): void; +} + +interface MetaWhat { + data?: GetDataType; + sub?: GetSubType; + desc?: GetOptsType; + tags?: true; + cred?: true; + aux?: true; + del?: GetDelType; +} +type MetaWhatKey = keyof MetaWhat; +export declare class MetaGetBuilder { + #private; + topic: Topic; + what: MetaWhat; + constructor(parent: Topic); + withData(since?: number, before?: number, limit?: number): this; + withLaterData(limit?: number): this; + withDataRanges(ranges: SeqRange[], limit?: number): this; + withDataList(list: number[]): this; + withEarlierData(limit?: number): this; + withDesc(ims?: Date): this; + withLaterDesc(): this; + withSub(ims?: Date, limit?: number, userOrTopic?: string): this; + withOneSub(ims?: Date, userOrTopic?: string): this; + withLaterOneSub(userOrTopic?: string): this; + withLaterSub(limit?: number): this; + withTags(): this; + withCred(): this; + withAux(): this; + withDel(since?: number, limit?: number): this; + withLaterDel(limit?: number): this; + extract(what: K): MetaWhat[K]; + build(): GetQuery | undefined; +} + +export type FoundContactCallback = ( + contact: TopicSubscription, + key: string, + all: Record +) => void; +export declare class TopicFnd extends Topic { + _contacts: Record; + constructor(callbacks?: TopicCallbacks); + _processMetaSubs(subs: TopicSubscription[]): void; + publish(): Promise; + setMeta(params: SetParams): Promise; + checkTagUniqueness(tag: string, caller: string): Promise; + contacts(callback?: FoundContactCallback, context?: unknown): void; +} + +export type ContactCallback = (contact: Topic, key: string) => void; +export interface TopicMeCallbacks extends TopicCallbacks { + onContactUpdate?: (what: PresWhat, cont: Topic) => void; +} +export declare class TopicMe extends Topic { + onContactUpdate: TopicMeCallbacks['onContactUpdate']; + constructor(callbacks?: TopicMeCallbacks); + _processMetaDesc(desc: TopicDesc): void; + _processMetaSubs(subs: TopicSubscription[]): void; + _processMetaCreds(creds: Credential[], upd?: boolean): void; + _routePres(pres: PresMessage): void; + _refreshContact(what: PresWhat, cont: Topic): void; + publish(): Promise; + delCredential(method: string, value: string): Promise; + contacts( + callback: ContactCallback, + filter?: ((contact: Topic) => boolean) | null, + context?: unknown + ): void; + getContact(name: string): Topic | undefined; + getAccessMode(): AccessMode; + getAccessMode(name?: string): AccessMode | null; + isArchived(name?: string): boolean; + getCredentials(): Credential[]; + pinTopic(topic: string, pin?: boolean): Promise; + pinnedTopicRank(topic: string): number; +} diff --git a/src/sdk/types/wire.ts b/src/sdk/types/wire.ts new file mode 100644 index 0000000..2a70dc8 --- /dev/null +++ b/src/sdk/types/wire.ts @@ -0,0 +1,367 @@ +import type { AccessMode, AccessModeInput } from './access-mode'; +import type { DraftyDoc } from './drafty'; + +export interface SeqRange { + low: number; + hi?: number; +} + +export interface GetOptsType { + ims?: Date; + limit?: number; +} +export interface GetSubType extends GetOptsType { + user?: string; + topic?: string; +} +export interface GetDataType { + since?: number; + before?: number; + limit?: number; + ranges?: SeqRange[]; +} +export interface GetDelType { + since?: number; + limit?: number; +} +export interface GetQuery { + what?: string; + desc?: GetOptsType; + sub?: GetSubType; + data?: GetDataType; + del?: GetDelType; +} + +export type TopicType = 'me' | 'fnd' | 'grp' | 'p2p' | 'sys' | 'slf'; +export interface DefAcs { + auth?: string; + anon?: string; +} +export interface AuthToken { + token: string; + expires: Date; +} +export interface Credential { + meth: string; + val?: string; + resp?: string; + params?: unknown; + done?: boolean; +} +export interface LastSeen { + when?: Date; + ua?: string; +} +export interface TopicPrivate { + arch?: boolean; + tpin?: string[]; + comment?: string; + [key: string]: unknown; +} +export interface TopicDesc { + created?: Date; + updated?: Date; + touched?: Date; + deleted?: Date; + defacs?: DefAcs; + acs?: AccessMode; + seq?: number; + read?: number; + recv?: number; + clear?: number; + unread?: number; + subcnt?: number; + online?: boolean; + seen?: LastSeen; + public?: unknown; + private?: unknown; + trusted?: unknown; + _noForwarding?: boolean; +} +export interface TopicSubscription { + user?: string; + topic?: string; + created?: Date; + updated?: Date; + touched?: Date; + deleted?: Date; + acs?: AccessMode; + mode?: string; + seq?: number; + read?: number; + recv?: number; + clear?: number; + unread?: number; + online?: boolean; + seen?: LastSeen; + public?: unknown; + private?: unknown; + trusted?: unknown; + _noForwarding?: boolean; +} +export interface MessageHead { + 'mime'?: string; + 'replace'?: string; + 'forwarded'?: string; + 'webrtc'?: string; + 'webrtc-duration'?: number; + 'vc'?: boolean; + [key: string]: unknown; +} +export interface Message { + id?: string; + topic: string; + seq: number; + from?: string; + ts?: Date; + head?: MessageHead | null; + content?: DraftyDoc | string; + noecho?: boolean; + low?: number; + hi?: number; + _deleted?: boolean; + _sending?: boolean; + _failed?: boolean; + _fatal?: boolean; + _cancelled?: boolean; + _status?: number; + _noForwarding?: boolean; + _origTs?: Date; + _origSeq?: number; +} +export interface PubMessage extends Omit { + seq?: number; +} +export interface CtrlParams { + what?: string; + count?: number; + seq?: number; + del?: number; + acs?: AccessMode; + user?: string; + token?: string; + expires?: Date; + unsub?: boolean; + ver?: string; + build?: string; + sid?: string; + [key: string]: unknown; +} +export interface CtrlMessage { + id?: string; + topic?: string; + code: number; + text?: string; + ts?: Date; + params?: CtrlParams; +} +export interface DataMessage { + topic: string; + from?: string; + ts: Date; + seq: number; + head?: MessageHead; + content?: DraftyDoc | string; +} +export interface DelValues { + clear: number; + delseq: SeqRange[]; +} +export interface MetaMessage { + id?: string; + topic: string; + ts?: Date; + desc?: TopicDesc; + sub?: TopicSubscription[]; + tags?: string[]; + cred?: Credential[]; + del?: DelValues; + aux?: Record; +} +export type PresWhat = + | 'on' + | 'off' + | 'ua' + | 'upd' + | 'gone' + | 'acs' + | 'term' + | 'msg' + | 'read' + | 'recv' + | 'del' + | 'tags' + | 'aux'; +export interface PresMessage { + topic?: string; + src?: string; + what: PresWhat; + seq?: number; + clear?: number; + delseq?: SeqRange[]; + ua?: string; + act?: string; + tgt?: string; + dacs?: AccessModeInput; + _noForwarding?: boolean; +} +export type InfoWhat = 'kp' | 'kpa' | 'kpv' | 'recv' | 'read' | 'call'; +export interface InfoMessage { + topic?: string; + src?: string; + from?: string; + what: InfoWhat; + seq?: number; + event?: string; + payload?: unknown; + _noForwarding?: boolean; +} +export interface ServerMessage { + ctrl?: CtrlMessage; + data?: DataMessage; + meta?: MetaMessage; + pres?: PresMessage; + info?: InfoMessage; +} +export interface ServerParams { + ver?: string; + build?: string; + sid?: string; + [key: string]: unknown; +} +export interface SetDesc { + defacs?: DefAcs; + public?: unknown; + private?: unknown; + trusted?: unknown; + acs?: AccessMode; + updated?: Date; + _noForwarding?: boolean; +} +export interface SetSub { + user?: string | null; + mode?: string | null; + topic?: string; + acs?: AccessMode; + updated?: Date; + _noForwarding?: boolean; +} +export interface SetParams { + desc?: SetDesc; + sub?: SetSub; + tags?: string[]; + cred?: Credential; + aux?: Record; + attachments?: string[]; +} +export interface AccountParams { + defacs?: DefAcs; + public?: unknown; + private?: unknown; + trusted?: unknown; + tags?: string[]; + cred?: Credential[]; + scheme?: string; + secret?: string; + attachments?: string[]; +} +export interface HiPacket { + id?: string; + ver?: string; + ua?: string; + dev?: string | null; + lang?: string; + platf?: string; +} +export interface AccPacket { + id?: string; + user: string | null; + scheme: string | null; + secret: string | null; + tmpscheme?: string; + tmpsecret?: string; + login?: boolean; + tags?: string[]; + desc: SetDesc; + cred?: Credential[]; +} +export interface LoginPacket { + id?: string; + scheme: string; + secret: string; + cred?: Credential[] | null; +} +export interface SubPacket { + id?: string; + topic: string; + get?: GetQuery; + set: { + desc?: SetDesc; + sub?: SetSub; + tags?: string[]; + aux?: Record; + }; +} +export interface LeavePacket { + id?: string; + topic: string; + unsub?: boolean; +} +export interface GetPacket extends GetQuery { + id?: string; + topic: string; +} +export interface SetPacket { + id?: string; + topic: string; + desc?: SetDesc; + sub?: SetSub; + tags?: string[]; + cred?: Credential; + aux?: Record; +} +export type DelWhat = 'msg' | 'topic' | 'sub' | 'cred' | 'user'; +export interface DelPacket { + id?: string; + topic: string | null; + what: DelWhat; + delseq?: SeqRange[]; + user?: string; + cred?: { + meth: string; + val: string; + }; + hard?: boolean; +} +export type NoteWhat = 'recv' | 'read' | 'kp' | 'kpa' | 'kpv' | 'call'; +export interface NotePacket { + id?: string; + topic: string; + what: NoteWhat; + seq?: number; + event?: string; + payload?: unknown; +} +export interface ClientMessage { + hi?: HiPacket; + acc?: AccPacket; + login?: LoginPacket; + sub?: SubPacket; + leave?: LeavePacket; + pub?: PubMessage; + get?: GetPacket; + set?: SetPacket; + del?: DelPacket; + note?: NotePacket; + extra?: { + attachments: string[]; + }; +} +export interface PushPayload { + what: string; + topic?: string; + seq?: number; + xfrom?: string; + modeGiven?: string; + modeWant?: string; +} From db04dbd59caf9e56b88d4d456263784218df4520 Mon Sep 17 00:00:00 2001 From: amerllica Date: Sun, 25 Oct 2026 18:28:31 +0330 Subject: [PATCH 08/14] refactor: export fromMMKV as a typed const --- src/sdk/index.ts | 4 +--- 1 file changed, 1 insertion(+), 3 deletions(-) diff --git a/src/sdk/index.ts b/src/sdk/index.ts index c6ab8a2..203eaee 100644 --- a/src/sdk/index.ts +++ b/src/sdk/index.ts @@ -31,9 +31,7 @@ export type IndexedDBAdapter = IndexedDBAdapterClass; export const KeyValueAdapter: typeof KeyValueAdapterClass = sdk.KeyValueAdapter; export type KeyValueAdapter = KeyValueAdapterClass; -export function fromMMKV(mmkv: MMKVLike): KeyValueStore { - return sdk.fromMMKV(mmkv); -} +export const fromMMKV: (mmkv: MMKVLike) => KeyValueStore = sdk.fromMMKV; export const MESSAGE_STATUS_NONE = Tinode.MESSAGE_STATUS_NONE; export const MESSAGE_STATUS_QUEUED = Tinode.MESSAGE_STATUS_QUEUED; From 6c261f316d8c92f1605ba8b5b1f98987187daf84 Mon Sep 17 00:00:00 2001 From: amerllica Date: Sun, 25 Oct 2026 18:28:32 +0330 Subject: [PATCH 09/14] refactor: drop the grapheme fallback tables now that Hermes has \p{} escapes --- src/platform/__tests__/graphemes.test.ts | 8 +-- src/platform/graphemes.ts | 64 ++++-------------------- src/platform/intl-segmenter.ts | 4 +- 3 files changed, 15 insertions(+), 61 deletions(-) diff --git a/src/platform/__tests__/graphemes.test.ts b/src/platform/__tests__/graphemes.test.ts index 962a45e..d6c8def 100644 --- a/src/platform/__tests__/graphemes.test.ts +++ b/src/platform/__tests__/graphemes.test.ts @@ -1,11 +1,11 @@ import { describe, expect, test } from '@jest/globals'; -import { splitGraphemesFallback } from '../graphemes'; +import { splitGraphemes } from '../graphemes'; const segmentsOf = (str: string) => - splitGraphemesFallback(str).map(({ segment }) => segment); + splitGraphemes(str).map(({ segment }) => segment); -describe('splitGraphemesFallback', () => { +describe('splitGraphemes', () => { test('plain ASCII and Cyrillic', () => { expect(segmentsOf('abc')).toEqual(['a', 'b', 'c']); expect(segmentsOf('жЫр')).toEqual(['ж', 'Ы', 'р']); @@ -60,7 +60,7 @@ describe('splitGraphemesFallback', () => { }); test('segment index is the UTF-16 offset', () => { - expect(splitGraphemesFallback('a😀👋🏼b')).toEqual([ + expect(splitGraphemes('a😀👋🏼b')).toEqual([ { segment: 'a', index: 0 }, { segment: '😀', index: 1 }, { segment: '👋🏼', index: 3 }, diff --git a/src/platform/graphemes.ts b/src/platform/graphemes.ts index ab3cecf..23ce10b 100644 --- a/src/platform/graphemes.ts +++ b/src/platform/graphemes.ts @@ -4,75 +4,29 @@ export interface GraphemeSegment { } type CodePointRange = readonly [number, number]; -type CodePointTest = (codePoint: number) => boolean; const CARRIAGE_RETURN = 0x0d; const LINE_FEED = 0x0a; const ZERO_WIDTH_JOINER = 0x200d; -const COMBINING_MARK_RANGES: readonly CodePointRange[] = [ - [0x0300, 0x036f], - [0x0483, 0x0489], - [0x0591, 0x05bd], - [0x0610, 0x061a], - [0x064b, 0x065f], - [0x0900, 0x0903], - [0x093a, 0x094f], - [0x1ab0, 0x1aff], - [0x1dc0, 0x1dff], - [0x20d0, 0x20ff], - [0xfe00, 0xfe0f], - [0xfe20, 0xfe2f], - [0xe0100, 0xe01ef], -]; - -const PICTOGRAPHIC_RANGES: readonly CodePointRange[] = [ - [0x00a9, 0x00a9], - [0x00ae, 0x00ae], - [0x203c, 0x203c], - [0x2049, 0x2049], - [0x2122, 0x2122], - [0x2139, 0x2139], - [0x2194, 0x21aa], - [0x231a, 0x23ff], - [0x24c2, 0x24c2], - [0x25aa, 0x25fe], - [0x2600, 0x27bf], - [0x2934, 0x2935], - [0x2b05, 0x2b55], - [0x3030, 0x3030], - [0x303d, 0x303d], - [0x3297, 0x3297], - [0x3299, 0x3299], - [0x1f000, 0x1faff], - [0x1fc00, 0x1fffd], -]; - const REGIONAL_INDICATOR: CodePointRange = [0x1f1e6, 0x1f1ff]; const EMOJI_MODIFIER: CodePointRange = [0x1f3fb, 0x1f3ff]; const TAG_CHARACTER: CodePointRange = [0xe0020, 0xe007f]; +const COMBINING_MARK = /^\p{M}$/u; +const PICTOGRAPHIC = /^\p{Extended_Pictographic}$/u; + function inRange(codePoint: number, [low, high]: CodePointRange): boolean { return codePoint >= low && codePoint <= high; } -function unicodePropertyTest( - property: string, - fallback: readonly CodePointRange[] -): CodePointTest { - try { - const pattern = new RegExp(`^\\p{${property}}$`, 'u'); - return (codePoint) => pattern.test(String.fromCodePoint(codePoint)); - } catch { - return (codePoint) => fallback.some((range) => inRange(codePoint, range)); - } +function isCombiningMark(codePoint: number): boolean { + return COMBINING_MARK.test(String.fromCodePoint(codePoint)); } -const isCombiningMark = unicodePropertyTest('M', COMBINING_MARK_RANGES); -const isPictographic = unicodePropertyTest( - 'Extended_Pictographic', - PICTOGRAPHIC_RANGES -); +function isPictographic(codePoint: number): boolean { + return PICTOGRAPHIC.test(String.fromCodePoint(codePoint)); +} function isControl(codePoint: number): boolean { return codePoint < 0x20 || (codePoint >= 0x7f && codePoint <= 0x9f); @@ -111,7 +65,7 @@ function continuesCluster( return isRegionalIndicator(current) && regionalIndicatorRun % 2 === 1; } -export function splitGraphemesFallback(str: string): GraphemeSegment[] { +export function splitGraphemes(str: string): GraphemeSegment[] { const segments: GraphemeSegment[] = []; let segment = ''; let segmentStart = 0; diff --git a/src/platform/intl-segmenter.ts b/src/platform/intl-segmenter.ts index 7438d02..4dd0405 100644 --- a/src/platform/intl-segmenter.ts +++ b/src/platform/intl-segmenter.ts @@ -1,4 +1,4 @@ -import { splitGraphemesFallback } from './graphemes'; +import { splitGraphemes } from './graphemes'; interface GraphemeSegmentData { segment: string; @@ -8,7 +8,7 @@ interface GraphemeSegmentData { class GraphemeSegmenter { segment(input: string): GraphemeSegmentData[] { - return splitGraphemesFallback(input).map(({ segment, index }) => ({ + return splitGraphemes(input).map(({ segment, index }) => ({ segment, index, input, From e93578e6c9dca65947592b22f43600d95afc033c Mon Sep 17 00:00:00 2001 From: amerllica Date: Sun, 25 Oct 2026 18:28:34 +0330 Subject: [PATCH 10/14] refactor: install the Hermes polyfills through one helper --- src/platform/define-global.ts | 14 ++++++++++++++ src/platform/intl-segmenter.ts | 9 +++------ src/platform/text-decoder.ts | 10 ++-------- 3 files changed, 19 insertions(+), 14 deletions(-) create mode 100644 src/platform/define-global.ts diff --git a/src/platform/define-global.ts b/src/platform/define-global.ts new file mode 100644 index 0000000..7f96d58 --- /dev/null +++ b/src/platform/define-global.ts @@ -0,0 +1,14 @@ +export function defineGlobalIfMissing( + target: object, + key: string, + value: unknown +): void { + if (Reflect.has(target, key)) { + return; + } + Object.defineProperty(target, key, { + value, + configurable: true, + writable: true, + }); +} diff --git a/src/platform/intl-segmenter.ts b/src/platform/intl-segmenter.ts index 4dd0405..30e9f92 100644 --- a/src/platform/intl-segmenter.ts +++ b/src/platform/intl-segmenter.ts @@ -1,3 +1,4 @@ +import { defineGlobalIfMissing } from './define-global'; import { splitGraphemes } from './graphemes'; interface GraphemeSegmentData { @@ -21,12 +22,8 @@ class GraphemeSegmenter { } export function installIntlSegmenter(): void { - if (typeof Intl === 'undefined' || typeof Intl.Segmenter === 'function') { + if (typeof Intl === 'undefined') { return; } - Object.defineProperty(Intl, 'Segmenter', { - value: GraphemeSegmenter, - configurable: true, - writable: true, - }); + defineGlobalIfMissing(Intl, 'Segmenter', GraphemeSegmenter); } diff --git a/src/platform/text-decoder.ts b/src/platform/text-decoder.ts index f37d003..aab899a 100644 --- a/src/platform/text-decoder.ts +++ b/src/platform/text-decoder.ts @@ -1,3 +1,4 @@ +import { defineGlobalIfMissing } from './define-global'; import { decodeUtf8 } from './utf8'; const UTF8_LABELS = ['utf-8', 'utf8', 'unicode-1-1-utf-8']; @@ -25,12 +26,5 @@ class Utf8TextDecoder { } export function installTextDecoder(): void { - if (Reflect.has(globalThis, 'TextDecoder')) { - return; - } - Object.defineProperty(globalThis, 'TextDecoder', { - value: Utf8TextDecoder, - configurable: true, - writable: true, - }); + defineGlobalIfMissing(globalThis, 'TextDecoder', Utf8TextDecoder); } From d5147707e53545b869fba56841f48963f1b48864 Mon Sep 17 00:00:00 2001 From: amerllica Date: Sun, 25 Oct 2026 18:28:35 +0330 Subject: [PATCH 11/14] fix: reject other granularities in the Intl.Segmenter polyfill and add containing() --- src/platform/__tests__/intl-segmenter.test.ts | 25 ++++++++++ src/platform/intl-segmenter.ts | 46 +++++++++++++++++-- 2 files changed, 67 insertions(+), 4 deletions(-) diff --git a/src/platform/__tests__/intl-segmenter.test.ts b/src/platform/__tests__/intl-segmenter.test.ts index c0799ad..19cea3c 100644 --- a/src/platform/__tests__/intl-segmenter.test.ts +++ b/src/platform/__tests__/intl-segmenter.test.ts @@ -32,6 +32,31 @@ describe('installIntlSegmenter', () => { }); }); + test('rejects granularities other than grapheme', () => { + withoutNativeSegmenter(() => { + installIntlSegmenter(); + expect(() => new Intl.Segmenter('fa', { granularity: 'word' })).toThrow( + RangeError + ); + expect(new Intl.Segmenter('fa').resolvedOptions().locale).toBe('fa'); + expect(new Intl.Segmenter().resolvedOptions().locale).toBe('en'); + }); + }); + + test('finds the segment that contains a code unit', () => { + withoutNativeSegmenter(() => { + installIntlSegmenter(); + const input = 'a👍🏽b'; + const segments = new Intl.Segmenter().segment(input); + expect(segments.containing(3)).toEqual({ + segment: '👍🏽', + index: 1, + input, + }); + expect(segments.containing(9)).toBeUndefined(); + }); + }); + test('keeps the native segmenter', () => { installIntlSegmenter(); expect(Intl.Segmenter).toBe(nativeSegmenter); diff --git a/src/platform/intl-segmenter.ts b/src/platform/intl-segmenter.ts index 30e9f92..217dd13 100644 --- a/src/platform/intl-segmenter.ts +++ b/src/platform/intl-segmenter.ts @@ -1,23 +1,61 @@ import { defineGlobalIfMissing } from './define-global'; import { splitGraphemes } from './graphemes'; +const DEFAULT_LOCALE = 'en'; + interface GraphemeSegmentData { segment: string; index: number; input: string; } -class GraphemeSegmenter { - segment(input: string): GraphemeSegmentData[] { - return splitGraphemes(input).map(({ segment, index }) => ({ +interface GraphemeSegmenterOptions { + granularity?: string; +} + +class GraphemeSegments implements Iterable { + readonly #segments: GraphemeSegmentData[]; + + constructor(input: string) { + this.#segments = splitGraphemes(input).map(({ segment, index }) => ({ segment, index, input, })); } + containing(codeUnitIndex = 0): GraphemeSegmentData | undefined { + return this.#segments.find( + ({ segment, index }) => + codeUnitIndex >= index && codeUnitIndex < index + segment.length + ); + } + + [Symbol.iterator](): Iterator { + return this.#segments[Symbol.iterator](); + } +} + +class GraphemeSegmenter { + readonly #locale: string; + + constructor( + locales?: string | readonly string[], + options?: GraphemeSegmenterOptions + ) { + const granularity = options?.granularity ?? 'grapheme'; + if (granularity !== 'grapheme') { + throw new RangeError(`Unsupported granularity: ${granularity}`); + } + this.#locale = [locales ?? []].flat()[0] ?? DEFAULT_LOCALE; + } + + segment(input: string): GraphemeSegments { + return new GraphemeSegments(input); + } + resolvedOptions(): { locale: string; granularity: 'grapheme' } { - return { locale: 'en', granularity: 'grapheme' }; + return { locale: this.#locale, granularity: 'grapheme' }; } } From 64e1d25a0948716af4daff3b7e3eb541bfd282f2 Mon Sep 17 00:00:00 2001 From: amerllica Date: Sun, 25 Oct 2026 18:28:37 +0330 Subject: [PATCH 12/14] fix: decode malformed UTF-8 and a leading BOM like the WHATWG TextDecoder --- src/platform/__tests__/text-decoder.test.ts | 8 +++ src/platform/utf8.ts | 56 ++++++++++++++------- 2 files changed, 47 insertions(+), 17 deletions(-) diff --git a/src/platform/__tests__/text-decoder.test.ts b/src/platform/__tests__/text-decoder.test.ts index 6fa23dd..2c00455 100644 --- a/src/platform/__tests__/text-decoder.test.ts +++ b/src/platform/__tests__/text-decoder.test.ts @@ -29,6 +29,14 @@ describe('installTextDecoder', () => { expect(decoder.decode(bytes.buffer)).toBe('café € 😀'); expect(decoder.decode(new Uint8Array([0x61, 0x80, 0x62]))).toBe('a�b'); expect(decoder.decode()).toBe(''); + expect(decoder.decode(new Uint8Array([0xe2, 0x82, 0x61]))).toBe('�a'); + expect(decoder.decode(new Uint8Array([0xc0, 0x80]))).toBe('��'); + expect(decoder.decode(new Uint8Array([0xed, 0xa0, 0x80]))).toBe('���'); + expect( + decoder.decode( + new Uint8Array([0xef, 0xbb, 0xbf, 0x61, 0xef, 0xbb, 0xbf]) + ) + ).toBe('a\uFEFF'); expect(() => new TextDecoder('utf-16le')).toThrow(RangeError); }); }); diff --git a/src/platform/utf8.ts b/src/platform/utf8.ts index 4557e55..5ef5ad1 100644 --- a/src/platform/utf8.ts +++ b/src/platform/utf8.ts @@ -1,4 +1,16 @@ -const REPLACEMENT_CHAR = '\uFFFD'; +type ByteRange = readonly [number, number]; + +const REPLACEMENT_CHAR = '�'; +const BYTE_ORDER_MARK = ''; +const CONTINUATION: ByteRange = [0x80, 0xbf]; +const CONTINUATION_BITS = 64; +const LEAD_PAYLOAD_SIZE = [0x80, 0x20, 0x10, 0x08]; +const SECOND_BYTE_BY_LEAD = new Map([ + [0xe0, [0xa0, 0xbf]], + [0xed, [0x80, 0x9f]], + [0xf0, [0x90, 0xbf]], + [0xf4, [0x80, 0x8f]], +]); function continuationCount(lead: number): number { if (lead < 0x80) return 0; @@ -8,7 +20,20 @@ function continuationCount(lead: number): number { return -1; } -export function decodeUtf8(bytes: Uint8Array): string { +function inRange( + byte: number | undefined, + [low, high]: ByteRange +): byte is number { + return byte !== undefined && byte >= low && byte <= high; +} + +function continuationRange(lead: number, position: number): ByteRange { + return position === 1 + ? (SECOND_BYTE_BY_LEAD.get(lead) ?? CONTINUATION) + : CONTINUATION; +} + +function decodeBytes(bytes: Uint8Array): string { let result = ''; let i = 0; while (i < bytes.length) { @@ -19,27 +44,24 @@ export function decodeUtf8(bytes: Uint8Array): string { i++; continue; } - let codePoint = extra === 0 ? lead : lead % 2 ** (6 - extra); + let codePoint = lead % (LEAD_PAYLOAD_SIZE[extra] ?? 1); let consumed = 1; - let valid = true; - for (let k = 1; k <= extra; k++) { - const next = bytes[i + k]; - if (next === undefined || next < 0x80 || next > 0xbf) { - valid = false; + while (consumed <= extra) { + const next = bytes[i + consumed]; + if (!inRange(next, continuationRange(lead, consumed))) { break; } - codePoint = codePoint * 64 + (next - 0x80); + codePoint = codePoint * CONTINUATION_BITS + (next - CONTINUATION[0]); consumed++; } - const minimum = [0, 0x80, 0x800, 0x10000][extra] ?? 0; - const isSurrogate = codePoint >= 0xd800 && codePoint <= 0xdfff; - if (!valid || codePoint < minimum || codePoint > 0x10ffff || isSurrogate) { - result += REPLACEMENT_CHAR; - i += valid ? consumed : Math.max(consumed, 1); - continue; - } - result += String.fromCodePoint(codePoint); + result += + consumed > extra ? String.fromCodePoint(codePoint) : REPLACEMENT_CHAR; i += consumed; } return result; } + +export function decodeUtf8(bytes: Uint8Array): string { + const text = decodeBytes(bytes); + return text.startsWith(BYTE_ORDER_MARK) ? text.slice(1) : text; +} From e3d468075f1365346a399be84070c8800a816d53 Mon Sep 17 00:00:00 2001 From: amerllica Date: Sun, 25 Oct 2026 18:28:38 +0330 Subject: [PATCH 13/14] refactor: derive CreateTinodeOptions from TinodeConfig --- src/react/createTinode.ts | 47 +++++++++++++++------------------------ 1 file changed, 18 insertions(+), 29 deletions(-) diff --git a/src/react/createTinode.ts b/src/react/createTinode.ts index 1206ee1..b29f5f4 100644 --- a/src/react/createTinode.ts +++ b/src/react/createTinode.ts @@ -1,23 +1,13 @@ import { Platform } from 'react-native'; -import { - Tinode, - type NetInfoLike, - type StorageAdapter, - type TinodeNetwork, -} from '../sdk'; +import { Tinode, type TinodeConfig } from '../sdk'; export type TinodePlatform = 'ios' | 'android' | 'web'; -export interface CreateTinodeOptions { +export interface CreateTinodeOptions extends Omit< + TinodeConfig, + 'appName' | 'platform' +> { appName: string; - host: string; - apiKey: string; - secure?: boolean; - transport?: 'ws' | 'lp'; - persist?: boolean; - storage?: StorageAdapter | null; - netInfo?: NetInfoLike | null; - network?: TinodeNetwork; language?: string; logging?: boolean; onStorageReady?: (error?: unknown) => void; @@ -27,25 +17,24 @@ export function detectPlatform(os: string = Platform.OS): TinodePlatform { return os === 'ios' || os === 'android' ? os : 'web'; } -export function createTinode(options: CreateTinodeOptions): Tinode { +export function createTinode({ + language, + logging = false, + onStorageReady, + ...config +}: CreateTinodeOptions): Tinode { const client = new Tinode( { - appName: options.appName, - host: options.host, - apiKey: options.apiKey, - secure: options.secure ?? true, - transport: options.transport, + ...config, + secure: config.secure ?? true, + persist: config.persist ?? false, platform: detectPlatform(), - persist: options.persist ?? false, - storage: options.storage, - netInfo: options.netInfo, - network: options.network, }, - options.onStorageReady + onStorageReady ); - if (options.language) { - client.setHumanLanguage(options.language); + if (language) { + client.setHumanLanguage(language); } - client.enableLogging(options.logging ?? false, true); + client.enableLogging(logging, true); return client; } From ac82e1f9b7c60ec55142f75098cdb59d3ea0a7c0 Mon Sep 17 00:00:00 2001 From: amerllica Date: Sun, 25 Oct 2026 18:28:39 +0330 Subject: [PATCH 14/14] docs: note the GitHub install and why the AppState reconnect stays in the provider --- README.md | 3 ++- docs/DECISIONS.md | 6 +++++- 2 files changed, 7 insertions(+), 2 deletions(-) diff --git a/README.md b/README.md index f5bf383..d729272 100644 --- a/README.md +++ b/README.md @@ -16,7 +16,8 @@ yarn add react-native-tinode `tinode-sdk` comes with it. Until the next `tinode-sdk` release is on npm, it is installed from a pinned commit of the [tinode-js](https://github.com/tinode/tinode-js) `devel` branch, so installing needs `git` and `npm` on the -machine (both are on CI runners and EAS build images). +machine and access to github.com (all three are on CI runners and EAS build images). Networks that block git or +GitHub cannot install it until then. ## Quick start diff --git a/docs/DECISIONS.md b/docs/DECISIONS.md index 871f274..d4f3598 100644 --- a/docs/DECISIONS.md +++ b/docs/DECISIONS.md @@ -18,6 +18,9 @@ The merged work is on the tinode-js `devel` branch and not on npm yet, so `packa stores the packed checksum in `yarn.lock`, so CI installs are reproducible. When a release with the change is on npm, replace the pin with a version range. +The pin also reaches every app that installs this package: their install fetches tinode-js from GitHub and needs +`git` and `npm`. Each release note says so until the pin is gone. + ## 3. Types live in `src/sdk` `tinode-sdk` is plain JavaScript and ships no types. @@ -60,7 +63,8 @@ multiplexer instead of overwriting app callbacks. NetInfo is not a dependency, not even an optional one. A guarded `require` of an optional package breaks bare React Native builds, because Metro defaults `allowOptionalDependencies` to `false`. Apps that want a fast reconnect pass their NetInfo module in the config (`netInfo: NetInfo`); the SDK then retries at once when the network comes back. -The provider still reconnects on `AppState` change. +The provider still reconnects on `AppState` change: `AppState` is React Native only, and the SDK has no app +lifecycle hook, so the foreground reconnect belongs to the React layer. ## 6. Storage