import { Models } from './models'; import { Channel, ActionableChannel, ResolvedChannel } from './channel'; import { flattenParam, normalizeQueries, type QueryInput } from './query'; import { ID } from './id'; import JSONbigModule from 'json-bigint'; const JSONbigParser = JSONbigModule({ storeAsString: false }); const JSONbigSerializer = JSONbigModule({ useNativeBigInt: true }); const MAX_SAFE = BigInt(Number.MAX_SAFE_INTEGER); const MIN_SAFE = BigInt(Number.MIN_SAFE_INTEGER); const MAX_INT64 = BigInt('9223372036854775807'); const MIN_INT64 = BigInt('-9223372036854775808'); function isBigNumber(value: any): boolean { return ( value !== null && typeof value === 'object' && value._isBigNumber === true && typeof value.isInteger === 'function' && typeof value.toFixed === 'function' && typeof value.toNumber === 'function' ); } function reviver(_key: string, value: any): any { if (isBigNumber(value)) { if (value.isInteger()) { const str = value.toFixed(); const bi = BigInt(str); if (bi >= MIN_SAFE && bi <= MAX_SAFE) { return Number(str); } if (bi >= MIN_INT64 && bi <= MAX_INT64) { return bi; } return value.toNumber(); } return value.toNumber(); } return value; } export const JSONbig = { parse: (text: string) => JSONbigParser.parse(text, reviver), stringify: JSONbigSerializer.stringify, }; type DefaultsShape = string | { items: DefaultsShape }; type DefaultsModel = { defaults?: Record; properties?: Record; }; type Defaults = { root: DefaultsShape; models: Record; }; export function applyDefaults(value: T, tree: Defaults): T { return fillDefaults(value, tree.root, tree.models) as T; } function cloneDefault(value: unknown): unknown { if (Array.isArray(value)) { return value.map(cloneDefault); } if (typeof value === 'object' && value !== null) { const copy: Record = {}; for (const [key, member] of Object.entries(value)) { copy[key] = cloneDefault(member); } return copy; } return value; } function fillDefaults( value: unknown, shape: DefaultsShape, models: Record, ): unknown { if (typeof shape !== 'string') { if (!Array.isArray(value)) { return value; } const items = shape.items; return value.map((item) => fillDefaults(item, items, models)); } const model = models[shape]; if (!model || typeof value !== 'object' || value === null) { return value; } if (Array.isArray(value)) { return value; } const result: Record = { ...model.defaults, ...value }; // Each item gets its own copy of a filled-in list or object, so mutating one doesn't change the rest for (const key of Object.keys(model.defaults ?? {})) { if (!Object.prototype.hasOwnProperty.call(value, key)) { result[key] = cloneDefault(result[key]); } } for (const [key, child] of Object.entries(model.properties ?? {})) { if (key in result) { result[key] = fillDefaults(result[key], child, models); } } // The spread drops the non-enumerable JSON toString that Client.call attaches. if (Object.prototype.hasOwnProperty.call(value, 'toString')) { Object.defineProperty(result, 'toString', { value: () => JSONbig.stringify(result), writable: true, enumerable: false, configurable: true, }); } return result; } /** * Payload type representing a key-value pair with string keys and any values. */ type Payload = { [key: string]: any; }; /** * Headers type representing a key-value pair with string keys and string values. */ type Headers = { [key: string]: string; }; /** * Realtime response structure with different types. */ type RealtimeResponse = { /** * Type of the response: 'error', 'event', 'connected', 'response' or 'pong'. */ type: 'error' | 'event' | 'connected' | 'response' | 'pong'; /** * Data associated with the response based on the response type. */ data: | RealtimeResponseAuthenticated | RealtimeResponseConnected | RealtimeResponseError | RealtimeResponseEvent | undefined; }; /** * Realtime request structure for authentication. */ type RealtimeRequest = { /** * Type of the request: 'authentication' or 'subscribe'. */ type: 'authentication' | 'subscribe'; /** * Data required for authentication. */ data: RealtimeRequestAuthenticate | RealtimeRequestSubscribe[]; }; type RealtimeRequestSubscribe = { subscriptionId: string; channels: string[]; queries: string[]; }; /** * Realtime event response structure with generic payload type. */ type RealtimeResponseEvent = { /** * List of event names associated with the response. */ events: string[]; /** * List of channel names associated with the response. */ channels: string[]; /** * Timestamp indicating the time of the event. */ timestamp: string; /** * Payload containing event-specific data. */ payload: T; /** * Subscription IDs this event matches (from backend, optional). */ subscriptions?: string[]; }; /** * Realtime response structure for errors. */ type RealtimeResponseError = { /** * Numeric error code indicating the type of error. */ code: number; /** * Error message describing the encountered error. */ message: string; }; /** * Realtime response structure for a successful connection. */ type RealtimeResponseConnected = { /** * List of channels the user is connected to. */ channels: string[]; /** * User object representing the connected user (optional). */ user?: object; }; /** * Realtime response structure for authenticated connections. */ type RealtimeResponseAuthenticated = { /** * Destination channel for the response. */ to: string; /** * Boolean indicating the success of the authentication process. */ success: boolean; /** * User object representing the authenticated user. */ user: object; }; /** * Realtime request structure for authentication. */ type RealtimeRequestAuthenticate = { /** * Session identifier for authentication. */ session: string; }; type TimeoutHandle = ReturnType | number; /** * Realtime interface representing the structure of a realtime communication object. */ type Realtime = { /** * WebSocket instance for realtime communication. */ socket?: WebSocket; /** * Timeout for reconnect operations. */ timeout?: TimeoutHandle; /** * Heartbeat interval for the realtime connection. */ heartbeat?: TimeoutHandle; /** * URL for establishing the WebSocket connection. */ url?: string; /** * Last received message from the realtime server. */ lastMessage?: RealtimeResponse; /** * Set of channel names the client is subscribed to. */ channels: Set; /** * Map of subscriptions keyed by client-generated subscriptionId. */ subscriptions: Map< string, { channels: string[]; queries: string[]; callback: (payload: RealtimeResponseEvent) => void; } >; /** * Pending subscribe rows keyed by subscriptionId. Flushed and cleared on each send. */ pendingSubscribes: Map; /** * Boolean indicating whether automatic reconnection is enabled. */ reconnect: boolean; /** * Number of reconnection attempts made. */ reconnectAttempts: number; /** * Function to get the timeout duration for communication operations. */ getTimeout: () => number; /** * Function to establish a WebSocket connection. */ connect: () => void; /** * Function to create a new WebSocket instance. */ createSocket: () => void; /** * Function to create a new heartbeat interval. */ createHeartbeat: () => void; sendPendingSubscribes: () => void; /** * Function to handle incoming messages from the WebSocket connection. * * @param {MessageEvent} event - Event containing the received message. */ onMessage: (event: MessageEvent) => void; }; /** * Type representing upload progress information. */ type UploadProgress = { /** * Identifier for the upload progress. */ $id: string; /** * Current progress of the upload (in percentage). */ progress: number; /** * Total size uploaded (in bytes) during the upload process. */ sizeUploaded: number; /** * Total number of chunks that need to be uploaded. */ chunksTotal: number; /** * Number of chunks that have been successfully uploaded. */ chunksUploaded: number; }; /** * Exception thrown by the package */ class AppwriteException extends Error { /** * The error code associated with the exception. */ code: number; /** * The response string associated with the exception. */ response: string; /** * Error type. * See [Error Types](https://appwrite.io/docs/response-codes#errorTypes) for more information. */ type: string; /** * Initializes a Appwrite Exception. * * @param {string} message - The error message. * @param {number} code - The error code. Default is 0. * @param {string} type - The error type. Default is an empty string. * @param {string} response - The response string. Default is an empty string. */ constructor( message: string, code: number = 0, type: string = '', response: string = '', ) { super(message); this.name = 'AppwriteException'; this.message = message; this.code = code; this.type = type; this.response = response; } } export function encodePath(value: unknown): string { const segment = String(value); if (segment === '.' || segment === '..') { throw new AppwriteException('Path parameter cannot be "." or ".."'); } return encodeURIComponent(segment); } /** * Client that handles requests to Appwrite */ class Client { static CHUNK_SIZE = 1024 * 1024 * 5; /** * Holds configuration such as project. */ config: { endpoint: string; endpointRealtime: string; endpointPush: string; pushClientId: string; project: string; jwt: string; bearer: string; locale: string; environment: string; session: string; cookie: string; impersonateuserid: string; impersonateuseremail: string; impersonateuserphone: string; } = { endpoint: 'https://cloud.appwrite.io/v1', endpointRealtime: '', endpointPush: '', pushClientId: '', project: '', jwt: '', bearer: '', locale: '', environment: '', session: '', cookie: '', impersonateuserid: '', impersonateuseremail: '', impersonateuserphone: '', }; /** * Custom headers for API requests. */ headers: Headers = { 'x-sdk-name': 'Web', 'x-sdk-platform': 'client', 'x-sdk-language': 'web', 'x-sdk-version': '29.5.0', 'X-Appwrite-Response-Format': '2.7.2', }; /** * Get Headers * * Returns a copy of the current request headers, including any * authentication headers. Handle with care. * * @returns {Headers} */ getHeaders(): Headers { return { ...this.headers }; } /** * Set Endpoint * * Your project endpoint * * @param {string} endpoint * * @returns {this} */ setEndpoint(endpoint: string): this { if (!endpoint || typeof endpoint !== 'string') { throw new AppwriteException('Endpoint must be a valid string'); } if ( !endpoint.startsWith('http://') && !endpoint.startsWith('https://') ) { throw new AppwriteException('Invalid endpoint URL: ' + endpoint); } this.config.endpoint = endpoint; this.config.endpointRealtime = endpoint .replace('https://', 'wss://') .replace('http://', 'ws://'); return this; } /** * Set Realtime Endpoint * * @param {string} endpointRealtime * * @returns {this} */ setEndpointRealtime(endpointRealtime: string): this { if (!endpointRealtime || typeof endpointRealtime !== 'string') { throw new AppwriteException('Endpoint must be a valid string'); } if ( !endpointRealtime.startsWith('ws://') && !endpointRealtime.startsWith('wss://') ) { throw new AppwriteException( 'Invalid realtime endpoint URL: ' + endpointRealtime, ); } this.config.endpointRealtime = endpointRealtime; return this; } /** * Set Push Endpoint * * The MQTT-over-WebSocket URL the AppwritePush service connects to. * * @param {string} endpointPush * * @returns {this} */ setPushEndpoint(endpointPush: string): this { if (!endpointPush || typeof endpointPush !== 'string') { throw new AppwriteException('Endpoint must be a valid string'); } if ( !endpointPush.startsWith('ws://') && !endpointPush.startsWith('wss://') ) { throw new AppwriteException( 'Invalid push endpoint URL: ' + endpointPush, ); } this.config.endpointPush = endpointPush; return this; } /** * Set Push Client Id * * A stable client id for the AppwritePush service. The broker keys its * offline-replay cursor on this id, so pass a stable value to resume replay across * reloads/restarts. Defaults, when unset, to one per user and tab: stable across reloads of * the tab, different in every other tab, and distinct for each connection open at the same * time, so no two connections take over each other's session. An explicit id shared by * several tabs or connections makes them do that. * * @param {string} pushClientId * * @returns {this} */ setPushClientId(pushClientId: string): this { if (!pushClientId || typeof pushClientId !== 'string') { throw new AppwriteException('Client id must be a valid string'); } this.config.pushClientId = pushClientId; return this; } /** * Set Project * * Your project ID * * @param value string * * @return {this} */ setProject(value: string): this { this.config.project = value; return this; } /** * Set JWT * * Your secret JSON Web Token * * @param value string * * @return {this} */ setJWT(value: string): this { this.headers['X-Appwrite-JWT'] = value; this.config.jwt = value; return this; } /** * Set Bearer * * The OAuth access token to authenticate with * * @param value string * * @return {this} */ setBearer(value: string): this { this.headers['Authorization'] = `Bearer ${value}`; this.config.bearer = value; return this; } /** * Set Locale * * @param value string * * @return {this} */ setLocale(value: string): this { this.headers['X-Appwrite-Locale'] = value; this.config.locale = value; return this; } /** * Set Environment * * The ID of the project environment to act in, alongside the project ID. Used with Appwrite Cloud projects that have environments. * * @param value string * * @return {this} */ setEnvironment(value: string): this { this.headers['X-Appwrite-Environment'] = value; this.config.environment = value; return this; } /** * Set Session * * The user session to authenticate with * * @param value string * * @return {this} */ setSession(value: string): this { this.headers['X-Appwrite-Session'] = value; this.config.session = value; return this; } /** * Set Cookie * * The user cookie to authenticate with. Used by SDKs that forward an incoming Cookie header in server-side runtimes. * * @param value string * * @return {this} */ setCookie(value: string): this { this.headers['Cookie'] = value; this.config.cookie = value; return this; } /** * Set ImpersonateUserId * * Impersonate a user by ID * * @param value string * * @return {this} */ setImpersonateUserId(value: string): this { this.headers['X-Appwrite-Impersonate-User-Id'] = value; this.config.impersonateuserid = value; return this; } /** * Set ImpersonateUserEmail * * Impersonate a user by email * * @param value string * * @return {this} */ setImpersonateUserEmail(value: string): this { this.headers['X-Appwrite-Impersonate-User-Email'] = value; this.config.impersonateuseremail = value; return this; } /** * Set ImpersonateUserPhone * * Impersonate a user by phone * * @param value string * * @return {this} */ setImpersonateUserPhone(value: string): this { this.headers['X-Appwrite-Impersonate-User-Phone'] = value; this.config.impersonateuserphone = value; return this; } private realtime: Realtime = { socket: undefined, timeout: undefined, heartbeat: undefined, url: '', channels: new Set(), subscriptions: new Map(), pendingSubscribes: new Map(), reconnect: true, reconnectAttempts: 0, lastMessage: undefined, connect: () => { clearTimeout(this.realtime.timeout); this.realtime.timeout = window?.setTimeout(() => { this.realtime.createSocket(); }, 50); }, getTimeout: () => { switch (true) { case this.realtime.reconnectAttempts < 5: return 1000; case this.realtime.reconnectAttempts < 15: return 5000; case this.realtime.reconnectAttempts < 100: return 10_000; default: return 60_000; } }, createHeartbeat: () => { if (this.realtime.heartbeat) { clearTimeout(this.realtime.heartbeat); } this.realtime.heartbeat = window?.setInterval(() => { this.realtime.socket?.send( JSONbig.stringify({ type: 'ping', }), ); }, 20_000); }, createSocket: () => { if (this.realtime.subscriptions.size < 1) { this.realtime.reconnect = false; this.realtime.socket?.close(); return; } const encodedProject = encodeURIComponent( (this.config.project as string) ?? '', ); // URL carries only the project; channels/queries are sent via subscribe message. let queryParams = 'project=' + encodedProject; if (this.config.jwt) { queryParams += '&jwt=' + encodeURIComponent(this.config.jwt as string); } if (this.config.environment) { queryParams += '&environment=' + encodeURIComponent(this.config.environment); } const url = this.config.endpointRealtime + '/realtime?' + queryParams; if ( url !== this.realtime.url || // Check if URL is present !this.realtime.socket || // Check if WebSocket has not been created this.realtime.socket?.readyState > WebSocket.OPEN // Check if WebSocket is CLOSING (3) or CLOSED (4) ) { if ( this.realtime.socket && this.realtime.socket?.readyState < WebSocket.CLOSING // Close WebSocket if it is CONNECTING (0) or OPEN (1) ) { this.realtime.reconnect = false; this.realtime.socket.close(); } this.realtime.url = url; this.realtime.socket = new WebSocket(url); this.realtime.socket.addEventListener( 'message', this.realtime.onMessage, ); this.realtime.socket.addEventListener('open', (_event) => { this.realtime.reconnectAttempts = 0; this.realtime.createHeartbeat(); }); this.realtime.socket.addEventListener('close', (event) => { if ( !this.realtime.reconnect || (this.realtime?.lastMessage?.type === 'error' && // Check if last message was of type error (( this.realtime?.lastMessage.data )).code === 1008) // Check for policy violation 1008 ) { this.realtime.reconnect = true; return; } const timeout = this.realtime.getTimeout(); console.error( `Realtime got disconnected. Reconnect will be attempted in ${timeout / 1000} seconds.`, event.reason, ); setTimeout(() => { this.realtime.reconnectAttempts++; this.realtime.createSocket(); }, timeout); }); } else if (this.realtime.socket?.readyState === WebSocket.OPEN) { this.realtime.sendPendingSubscribes(); } }, sendPendingSubscribes: () => { if ( !this.realtime.socket || this.realtime.socket.readyState !== WebSocket.OPEN ) { return; } if (this.realtime.pendingSubscribes.size < 1) { return; } const rows = Array.from(this.realtime.pendingSubscribes.values()); this.realtime.pendingSubscribes.clear(); this.realtime.socket.send( JSONbig.stringify({ type: 'subscribe', data: rows, }), ); }, onMessage: (event) => { try { const message: RealtimeResponse = JSONbig.parse(event.data); this.realtime.lastMessage = message; switch (message.type) { case 'connected': { const messageData = ( message.data ); let session = this.config.session; if (!session) { const cookie = JSONbig.parse( window.localStorage.getItem('cookieFallback') ?? '{}', ); // An environment's session is named by its project and environment IDs. const { project, environment } = this.config; const name = environment ? `a_session_${project}_env_${environment}` : `a_session_${project}`; session = cookie?.[name]; } if (session && !messageData?.user) { this.realtime.socket?.send( JSONbig.stringify({ type: 'authentication', data: { session, }, }), ); } this.realtime.subscriptions.forEach( (sub, subscriptionId) => { this.realtime.pendingSubscribes.set( subscriptionId, { subscriptionId, channels: sub.channels, queries: sub.queries ?? [], }, ); }, ); this.realtime.sendPendingSubscribes(); break; } case 'response': // The SDK generates subscriptionIds client-side and sends them on every // subscribe/unsubscribe, so subscribe/unsubscribe acks carry no state // the SDK needs to reconcile. break; case 'event': { const data = >( message.data ); if (!data?.channels) break; const eventSubIds = data.subscriptions; if (eventSubIds && eventSubIds.length > 0) { for (const subscriptionId of eventSubIds) { const subscription = this.realtime.subscriptions.get( subscriptionId, ); if (subscription) { setTimeout(() => subscription.callback(data), ); } } } else { const isSubscribed = data.channels.some((channel) => this.realtime.channels.has(channel), ); if (!isSubscribed) break; this.realtime.subscriptions.forEach( (subscription) => { if ( data.channels.some((channel) => subscription.channels.includes( channel, ), ) ) { setTimeout(() => subscription.callback(data), ); } }, ); } break; } case 'pong': break; // Handle pong response if needed case 'error': throw message.data; default: break; } } catch (e) { console.error(e); } }, }; /** * Subscribes to Appwrite events and passes you the payload in realtime. * * @deprecated Use the Realtime service instead. * @see Realtime * * @param {string|string[]|Channel|ActionableChannel|ResolvedChannel|(Channel|ActionableChannel|ResolvedChannel)[]} channels * Channel to subscribe - pass a single channel as a string or Channel builder instance, or multiple with an array. * * Possible channels are: * - account * - collections * - collections.[ID] * - collections.[ID].documents * - documents * - documents.[ID] * - files * - files.[ID] * - executions * - executions.[ID] * - functions.[ID] * - teams * - teams.[ID] * - memberships * - memberships.[ID] * * You can also use Channel builders: * - Channel.database('db').collection('col').document('doc').create() * - Channel.bucket('bucket').file('file').update() * - Channel.function('func').execution('exec').delete() * - Channel.team('team').create() * - Channel.membership('membership').update() * @param {(payload: RealtimeMessage) => void} callback Is called on every realtime update. * @returns {() => void} Unsubscribes from events. */ subscribe( channels: | string | string[] | Channel | ActionableChannel | ResolvedChannel | (Channel | ActionableChannel | ResolvedChannel)[], callback: (payload: RealtimeResponseEvent) => void, queries: QueryInput = [], ): () => void { const channelArray = Array.isArray(channels) ? channels : [channels]; // Convert Channel instances to strings const channelStrings = channelArray.map((ch) => { if (typeof ch === 'string') { return ch; } // All Channel instances have toString() method if (ch && typeof (ch as Channel).toString === 'function') { return (ch as Channel).toString(); } // Fallback to generic string conversion return String(ch); }); channelStrings.forEach((channel) => this.realtime.channels.add(channel), ); const queryStrings = normalizeQueries(queries); let subscriptionId = ''; const attempts = this.realtime.subscriptions.size + 1; for (let i = 0; i < attempts; i++) { const candidate = ID.unique(); if (!this.realtime.subscriptions.has(candidate)) { subscriptionId = candidate; break; } } if (subscriptionId === '') { throw new AppwriteException( 'Failed to generate unique subscription id', ); } this.realtime.subscriptions.set(subscriptionId, { channels: channelStrings, queries: queryStrings, callback, }); this.realtime.pendingSubscribes.set(subscriptionId, { subscriptionId, channels: channelStrings, queries: queryStrings, }); this.realtime.connect(); return () => { this.realtime.subscriptions.delete(subscriptionId); this.realtime.pendingSubscribes.delete(subscriptionId); const stillUsed = new Set(); this.realtime.subscriptions.forEach((sub) => { sub.channels.forEach((channel) => stillUsed.add(channel)); }); this.realtime.channels.forEach((channel) => { if (!stillUsed.has(channel)) { this.realtime.channels.delete(channel); } }); this.realtime.connect(); }; } prepareRequest( method: string, url: URL, headers: Headers = {}, params: Payload = {}, ): { uri: string; options: RequestInit } { method = method.toUpperCase(); for (const key of Object.keys(params)) { params[key] = flattenParam(params[key]); } headers = Object.assign({}, this.headers, headers); if (typeof window !== 'undefined' && window.localStorage) { const cookieFallback = window.localStorage.getItem('cookieFallback'); if (cookieFallback) { headers['X-Fallback-Cookies'] = cookieFallback; } } const options: RequestInit = { method, headers, credentials: 'include', }; if (method === 'GET') { for (const [key, value] of Object.entries(Client.flatten(params))) { url.searchParams.append(key, value); } } else { switch (headers['content-type']) { case 'application/json': options.body = JSONbig.stringify(params); break; case 'multipart/form-data': { const formData = new FormData(); for (const [key, value] of Object.entries(params)) { if (value instanceof File) { formData.append(key, value, value.name); } else if (Array.isArray(value)) { for (const nestedValue of value) { formData.append(`${key}[]`, nestedValue); } } else if ( value !== null && typeof value === 'object' ) { formData.append(key, JSONbig.stringify(value)); } else { formData.append(key, value); } } options.body = formData; delete headers['content-type']; break; } } } return { uri: url.toString(), options }; } async chunkedUpload( method: string, url: URL, headers: Headers = {}, originalPayload: Payload = {}, onProgress: (progress: UploadProgress) => void, responseType = 'json', ) { const [fileParam, file] = Object.entries(originalPayload).find( ([_, value]) => value instanceof File, ) ?? []; if (!file || !fileParam) { return await this.call( method, url, headers, originalPayload, responseType, ); } if (file.size <= Client.CHUNK_SIZE || responseType === 'text') { return await this.call( method, url, headers, originalPayload, responseType, ); } const totalChunks = Math.ceil(file.size / Client.CHUNK_SIZE); // Upload first chunk alone to get the upload ID const firstChunkEnd = Math.min(Client.CHUNK_SIZE, file.size); const firstChunkHeaders = { ...headers, 'content-range': `bytes 0-${firstChunkEnd - 1}/${file.size}`, }; const firstChunk = file.slice(0, firstChunkEnd); const firstPayload = { ...originalPayload }; firstPayload[fileParam] = new File([firstChunk], file.name); const response = await this.call( method, url, firstChunkHeaders, firstPayload, responseType, ); const uploadId = response?.$id; if (onProgress && typeof onProgress === 'function') { onProgress({ $id: uploadId, progress: Math.round((firstChunkEnd / file.size) * 100), sizeUploaded: firstChunkEnd, chunksTotal: totalChunks, chunksUploaded: 1, }); } if (totalChunks === 1) { return response; } // Prepare remaining chunks const chunks: { start: number; end: number }[] = []; for (let i = 1; i < totalChunks; i++) { const start = i * Client.CHUNK_SIZE; const end = Math.min(start + Client.CHUNK_SIZE, file.size); chunks.push({ start, end }); } // Upload remaining chunks with max concurrency of 8 const CONCURRENCY = 8; let completedCount = 1; let uploadedBytes = firstChunkEnd; let lastResponse = response; let finalResponse = null; let rejected = false; const isUploadComplete = (chunkResponse: any) => { const chunksUploaded = chunkResponse?.chunksUploaded; const chunksTotal = chunkResponse?.chunksTotal ?? totalChunks; return ( typeof chunksUploaded === 'number' && typeof chunksTotal === 'number' && chunksUploaded >= chunksTotal ); }; const uploadChunk = async (chunk: (typeof chunks)[0]) => { const chunkHeaders = { ...headers }; if (uploadId) { chunkHeaders['x-appwrite-id'] = uploadId; } chunkHeaders['content-range'] = `bytes ${chunk.start}-${chunk.end - 1}/${file.size}`; const chunkBlob = file.slice(chunk.start, chunk.end); const chunkPayload = { ...originalPayload }; chunkPayload[fileParam] = new File([chunkBlob], file.name); const chunkResponse = await this.call( method, url, chunkHeaders, chunkPayload, responseType, ); if (rejected) { return chunkResponse; } completedCount++; uploadedBytes += chunk.end - chunk.start; lastResponse = chunkResponse; if (isUploadComplete(chunkResponse)) { finalResponse = chunkResponse; } if (onProgress && typeof onProgress === 'function') { onProgress({ $id: uploadId, progress: Math.round((uploadedBytes / file.size) * 100), sizeUploaded: uploadedBytes, chunksTotal: totalChunks, chunksUploaded: completedCount, }); } return chunkResponse; }; await new Promise((resolve, reject) => { let nextChunk = 0; let inFlight = 0; let completed = 0; const uploadNext = () => { if (rejected) { return; } if (completed === chunks.length) { resolve(); return; } while (inFlight < CONCURRENCY && nextChunk < chunks.length) { const chunk = chunks[nextChunk++]; inFlight++; uploadChunk(chunk) .then(() => { inFlight--; completed++; uploadNext(); }) .catch((error) => { rejected = true; reject(error); }); } }; uploadNext(); }); return finalResponse ?? lastResponse; } async ping(): Promise { return this.call('GET', new URL(this.config.endpoint + '/ping'), { 'X-Appwrite-Project': this.config.project, accept: 'application/json', }); } async call( method: string, url: URL, headers: Headers = {}, params: Payload = {}, responseType = 'json', ): Promise { const { uri, options } = this.prepareRequest( method, url, headers, params, ); let data: any = null; const response = await fetch(uri, options); // type opaque: No-CORS, different-origin response (CORS-issue) if (response.type === 'opaque') { throw new AppwriteException( `Invalid Origin. Register your new client (${window.location.host}) as a new Web platform on your project console dashboard`, 403, 'forbidden', '', ); } const warnings = response.headers.get('x-appwrite-warning'); if (warnings) { warnings .split(';') .forEach((warning: string) => console.warn('Warning: ' + warning), ); } if (responseType === 'text' && response.status < 400) { data = await response.text(); } else if ( response.headers.get('content-type')?.includes('application/json') ) { data = JSONbig.parse(await response.text()); } else if (responseType === 'arrayBuffer') { data = await response.arrayBuffer(); } else { data = { message: await response.text(), }; } if (400 <= response.status) { let responseText; if ( response.headers .get('content-type') ?.includes('application/json') || responseType === 'arrayBuffer' ) { responseText = JSONbig.stringify(data); } else { responseText = data?.message; } throw new AppwriteException( data?.message ?? responseText, response.status, data?.type, responseText, ); } const cookieFallback = response.headers.get('X-Fallback-Cookies'); if ( typeof window !== 'undefined' && window.localStorage && cookieFallback ) { window.console.warn( 'Appwrite is using localStorage for session management. Increase your security by adding a custom domain as your API endpoint.', ); window.localStorage.setItem('cookieFallback', cookieFallback); } if (data && typeof data === 'object') { Object.defineProperty(data, 'toString', { value: () => JSONbig.stringify(data), writable: true, enumerable: false, configurable: true, }); } return data; } static flatten(data: Payload, prefix = ''): Payload { let output: Payload = {}; for (const [key, value] of Object.entries(data)) { const finalKey = prefix ? prefix + '[' + key + ']' : key; if (Array.isArray(value)) { output = { ...output, ...Client.flatten(value, finalKey) }; } else { output[finalKey] = value; } } return output; } } export { Client, AppwriteException }; export { Query, QueryBuilder, flattenParam } from './query'; export type { Models, Payload, UploadProgress }; export type { RealtimeResponseEvent }; export type { QueryTypes, QueryTypesList, QueryInput } from './query';