import { DestroyError } from "../utils/errors"; import { WeavyClient, type WeavyType } from "./weavy"; import { assign } from "../utils/objects"; import { defaultFetchSettings } from "../utils/data"; import type { Constructor } from "../types/generic.types"; import { type FetchOptions, HeaderContentType, HttpMethodType, type HttpUploadMethodType } from "../types/http.types"; import { FileType } from "../types/files.types"; export interface WeavyFetchProps { /** * Gets defaulted fetch options that includes authorization headers for the current user. * * @param options { FetchOptions } - Any RequestInit compatible fetch options that should be defaulted and updated with current Authorization. * @param authorized { boolean } - Whether to embed authorization token for the endpoint. Set to `false` for any endpoint that doesn't require authorization. Defaults to `true`. * @returns {Promise} Options for Fetch or Request */ fetchOptions: (options?: FetchOptions, authorized?: boolean) => Promise; /** * Fetch data from the Web API. Includes token handling and acts on behalf of the current user. * * @param url { string | URL } - The URL to the Web API endpoint. Note: Only Web API URL:s are supported. * @param options { FetchOptions } Optional RequestInit compatible fetch options. Note that `method` is limited to "GET" | "POST" | "PUT" | "DELETE" | "PATCH". * @returns { Promise } A standard fetch() Response */ fetch: (url: string | URL, options?: FetchOptions) => Promise; /** * Fetch file data from the server. Includes file access token handling and acts on behalf of the current user. * * @param url { string | URL } - The URL to the file. Note: Only file URL:s are supported. * @param options { FetchOptions } Optional RequestInit compatible fetch options. Note that `method` is limited to "GET" | "POST" | "PUT" | "DELETE" | "PATCH". * @returns { Promise } A standard fetch() Response */ fetchFile: (url: string | URL, options?: FetchOptions) => Promise; /** * Upload data to the Web API using a progress callback function to monitor the progress. * * @param url { string | URL } - The URL to the Web API endpoint. Note: Only Web API URL:s are supported. * @param method { "POST" | "PUT" | "PATCH" } - The http method to use. * @param body { string | FormData } - The data to send. * @param [contentType] {HeaderContentType} - Optional content type of the body. Defaults to "application/json;charset=utf-8" * @param onProgress {(progress: number) => void} Callback function for the progress. The progress parameter is provided as 0-100 percent. * @param signal {AbortSignal} Optional abort signal for cancelling the upload. * @returns { Promise } A standard fetch() Response */ upload: ( /** The URL to the Web API endpoint. Note: Only Web API URL:s are supported. */ url: string | URL, /** The http method to use. */ method: HttpUploadMethodType, /** The data to send. */ body: string | FormData, /** Optional content type of the body. Defaults to "application/json;charset=utf-8" */ contentType?: HeaderContentType, /** * Callback function for the progress. The progress parameter is provided as 0-100 percent. * @param progress { number } - The progress provided as 0-100 percent. **/ onProgress?: (progress: number) => void, /** * Optional abort signal for cancelling the upload. */ signal?: AbortSignal, ) => Promise; /** * DEPRECATED: Use `.fetch(url)` instead. * * Gets an Web API URL and returns a Response. * * @deprecated Use .fetch(url) instead. * @param url { string | URL } - The URL to the API endpoint. * @returns { Promise } A standard fetch() Response */ get: (url: string | URL) => Promise; /** * DEPRECATED: Use `.fetch(url, options)` instead. * * Posts data to the Web API and returns a Response. * * @deprecated Use .fetch(url, options) instead. * @param url {string | URL} - The URL of the API endpoint * @param method { "GET" | "POST" | "PUT" | "DELETE" | "PATCH" } - The http method to use. * @param [body] {BodyInit} - The body data to send. JSON must be encoded as a string. * @param [contentType] {HeaderContentType} - The content type of the body. Defaults to "application/json;charset=utf-8". * @returns { Promise } A standard fetch() Response */ post: ( url: string | URL, method: HttpMethodType, body?: BodyInit, contentType?: HeaderContentType, ) => Promise; } // WeavyFetch mixin/decorator export const WeavyFetchMixin = >(Base: TBase) => { return class WeavyFetch extends Base implements WeavyFetchProps { // FETCH async fetchOptions( this: this & WeavyType, options: FetchOptions = {}, authorized: boolean = true ): Promise { if (this.isDestroyed) { throw new DestroyError(); } const fetchSettings: FetchOptions = { headers: { "X-Weavy-Source": `${WeavyClient.sourceName}@${WeavyClient.version}`, "Content-Type": HeaderContentType.JSON, }, method: "GET", }; const defaultedOptions = assign(assign(defaultFetchSettings, fetchSettings, true), options, true); const overriddenOptions = authorized ? assign( defaultedOptions, { headers: { Authorization: "Bearer " + (await this.getToken()), }, }, true ) : defaultedOptions; return overriddenOptions; } async fetch( this: this & WeavyType, url: string | URL, options?: FetchOptions, retry: boolean = true ): Promise { if (this.isDestroyed) { throw new DestroyError(); } const fetchOptions: RequestInit = await this.fetchOptions(options); const parsedUrl = new URL(url, this.url); this.networkStateIsPending = true; const response = await fetch(parsedUrl, fetchOptions); if (!response.ok) { if (response.status === 401 || response.status === 403) { if (retry) { await this.getToken(true); return await this.fetch(parsedUrl, options, false); } else { this.networkStateIsPending = false; this.serverState = "unauthorized"; } } else { this.networkStateIsPending = false; } //console.error(this.weavyId, `Error calling endpoint ${url}`, response) } else { this.networkStateIsPending = false; this.serverState = "ok"; } if (response.status === 204) { // Chromium reports an unread 204 body as net::ERR_ABORTED when the Response is garbage collected, so drain it // here and return a body-less Response that callers can still safely read. await response.arrayBuffer(); return new Response(null, { status: response.status, statusText: response.statusText, headers: response.headers }); } return response; } async fetchFile( this: this & WeavyType, url: string | URL, options?: FetchOptions, retry: boolean = true ): Promise { if (this.isDestroyed) { throw new DestroyError(); } const fetchOptions: RequestInit = await this.fetchOptions(options, false); const parsedUrl = new URL(url, this.url); const fileId = Number.parseInt(/\/f(\d+)\/.*$/.exec(parsedUrl.pathname)?.[1] || ''); if (isNaN(fileId)) { throw new Error("No valid file url provided"); } this.networkStateIsPending = true; const response = await fetch(parsedUrl, fetchOptions); if (!response.ok) { if (response.status === 401 || response.status === 403) { if (retry) { const fileApiResponse = await this.fetch(`/api/files/${fileId}`); if (fileApiResponse.ok) { const file = await fileApiResponse.json() as FileType; if (file.download_url) { const fileToken = /[&?]t=([a-zA-Z0-9]+)(?=&|$)/.exec(file.download_url)?.[1]; if (fileToken) { // Update current url with new token parsedUrl.searchParams.set("t", fileToken); return await this.fetchFile(parsedUrl, options, false); } } } } else { this.networkStateIsPending = false; this.serverState = "unauthorized"; } } else { this.networkStateIsPending = false; } //console.error(this.weavyId, `Error calling endpoint ${url}`, response) } else { this.networkStateIsPending = false; this.serverState = "ok"; } return response; } async upload( this: this & WeavyType, url: string | URL, method: HttpUploadMethodType, body: string | FormData, contentType: HeaderContentType = HeaderContentType.JSON, onProgress?: (progress: number) => void, signal?: AbortSignal, retry: boolean = true ) { if (this.isDestroyed) { throw new DestroyError(); } const token = await this.getToken(); return await new Promise((resolve, reject) => { // XMLHttpRequest instead of fetch because we want to track progress const xhr = new XMLHttpRequest(); xhr.open(method, new URL(url, this.url), true); xhr.setRequestHeader("Authorization", "Bearer " + token); xhr.setRequestHeader("X-Weavy-Source", `${WeavyClient.sourceName}@${WeavyClient.version}`); if (contentType) { xhr.setRequestHeader("Content-Type", contentType); } if (onProgress) { xhr.upload.addEventListener("progress", (e: ProgressEvent) => { onProgress((e.loaded / e.total) * 100 || 100); }); } xhr.onload = (_evt: ProgressEvent) => { if (retry && (xhr.status === 401 || xhr.status === 401)) { this.getToken(true) .then(() => this.upload(url, method, body, contentType, onProgress, signal, false)) .then(resolve) .catch(reject); } else { resolve(new Response(xhr.response as BodyInit, { status: xhr.status, statusText: xhr.statusText })); } }; xhr.onerror = reject; xhr.onabort = reject; signal?.addEventListener('abort', () => { xhr.abort(); }) xhr.send(body); }); } // DEPRECATED async get(this: this & WeavyType, url: string | URL) { console.warn(`weavy.get() is deprecated, use weavy.fetch("${url}") instead.`); return this.fetch(url); } // DEPRECATED async post( this: this & WeavyType, url: string | URL, method: HttpMethodType, body?: BodyInit, contentType?: HeaderContentType ) { console.warn( `weavy.post() is deprecated, use weavy.fetch("${url}", { method: "${method}"}) instead.` ); const headers = contentType ? ({ "Content-Type": contentType } as HeadersInit) : undefined; return this.fetch(url, { method, body, headers }); } }; };