### Basic FetchEngine Setup with Error Handling (JavaScript) Source: https://typedoc.logosdx.dev/classes/_logosdx_react.fetch._internal_.FetchEngine Demonstrates the basic setup of FetchEngine with essential configurations like baseUrl and defaultType. It also shows how to use the `attempt` function for basic error handling when making a GET request. ```javascript const api = new FetchEngine({ baseUrl: 'https://api.example.com', defaultType: 'json', headers: { 'Authorization': 'Bearer token' } }); const [user, err] = await attempt(() => api.get('/users/123')); if (err) { console.error('Failed to fetch user:', err); return; } ``` -------------------------------- ### Instantiate and Use MapCacheAdapter Source: https://typedoc.logosdx.dev/classes/_logosdx_utils.MapCacheAdapter Demonstrates how to create an instance of MapCacheAdapter and perform basic cache operations like setting and getting items. This example highlights the asynchronous nature of the adapter's methods. ```typescript const adapter = new MapCacheAdapter({ maxSize: 500, cleanupInterval: 30000 }); await adapter.set('key', item, Date.now() + 60000); const cached = await adapter.get('key'); ``` -------------------------------- ### Plugin Installation Source: https://typedoc.logosdx.dev/classes/_logosdx_react.fetch._internal_.FetchEngine Installs a plugin at runtime. ```APIDOC ## POST /use ### Description Installs a plugin at runtime. The plugin's `install()` method is called with this engine instance. Returns an unsubscribe function that removes the plugin's hooks. ### Method POST ### Endpoint /use ### Parameters #### Query Parameters - **plugin** (FetchPlugin) - Required - The plugin to install. ### Response #### Success Response (200) - **() => void** - A cleanup function to uninstall the plugin. #### Response Example ```json { "uninstall": "function" } ``` ``` -------------------------------- ### Waiting and Consuming Tokens Source: https://typedoc.logosdx.dev/classes/_logosdx_fetch._internal_.RateLimitTokenBucket Demonstrates the `waitAndConsume` method, which pauses execution until tokens are available and then consumes them atomically. An optional callback can be provided to handle rate limit exceeded scenarios. This example assumes a basic bucket setup. ```typescript const bucket = new RateLimitTokenBucket({ capacity: 10, refillIntervalMs: 1000 }); await bucket.waitAndConsume(() => { console.log('Rate limit exceeded'); }); console.log('Token acquired and consumed'); ``` -------------------------------- ### Plugin Management - use Source: https://typedoc.logosdx.dev/classes/_logosdx_fetch.FetchEngine Installs a plugin at runtime. The plugin's `install()` method is called with the engine instance. Returns an unsubscribe function. ```APIDOC ## POST /plugins/use ### Description Installs a plugin at runtime. ### Method POST ### Endpoint /plugins/use ### Parameters #### Query Parameters - **plugin** (FetchPlugin) - Required - The plugin to install. ### Response #### Success Response (200) - **() => void** (function) - A cleanup function to uninstall the plugin. #### Response Example ```json { "uninstall": "" } ``` ``` -------------------------------- ### RateLimitTokenBucket with Persistence (Redis) Source: https://typedoc.logosdx.dev/classes/_logosdx_fetch._internal_.RateLimitTokenBucket Illustrates how to use RateLimitTokenBucket with a persistence layer, specifically using Redis as an example. This involves providing `save` and `load` functions to manage the bucket's state. It requires a Redis client setup. ```typescript const bucket = new RateLimitTokenBucket({ capacity: 100, refillIntervalMs: 60000, save: async (state) => { await redis.set('rate-limit:user:123', JSON.stringify(state)); }, load: async () => { const data = await redis.get('rate-limit:user:123'); return data ? JSON.parse(data) : undefined; } }); // Load state from backend before using await bucket.load(); // Check and consume if (bucket.hasTokens()) { bucket.consume(); await bucket.save(); } ``` -------------------------------- ### Install Fetch Plugin at Runtime Source: https://typedoc.logosdx.dev/classes/_logosdx_react.fetch._internal_.FetchEngine Installs a fetch plugin into the engine at runtime. The plugin's install method is invoked, and an unsubscribe function is returned to remove the plugin's hooks. ```typescript use(plugin: FetchPlugin): () => void ``` -------------------------------- ### Copy Listeners Example (TypeScript) Source: https://typedoc.logosdx.dev/classes/_logosdx_observer.ObserverEngine Example demonstrating how to copy all listeners from one ObserverEngine to another, and an example showing how to copy listeners while excluding specific event patterns. ```typescript const primary = new ObserverEngine(); const mirror = new ObserverEngine(); primary.on('update', handler); ObserverEngine.copy(primary, mirror); // Both engines now have the 'update' listener // Copy everything except internal events ObserverEngine.copy(primary, mirror, { exclude: [/^__/] }); ``` -------------------------------- ### Example FetchPlugin Implementation (TypeScript) Source: https://typedoc.logosdx.dev/interfaces/_logosdx_react.fetch._internal_.FetchPlugin Demonstrates how to create a custom FetchPlugin for authentication. This plugin intercepts requests before they are sent and adds an Authorization header using a provided token retrieval function. It utilizes the `install` method to register a `beforeRequest` hook with the FetchEngine. ```typescript function authPlugin(getToken: () => Promise) { return { name: 'auth', install(engine) { return engine.hooks.add('beforeRequest', async (url, opts, ctx) => { const token = await getToken(); ctx.args(url, { ...opts, headers: { ...opts.headers, Authorization: `Bearer ${token}` } }); }); } } } ``` ```typescript interface FetchPlugin { hooks?: HookEngine; name: string; install(engine: FetchEnginePublic): () => void; } ``` -------------------------------- ### Advanced FetchEngine Setup with Plugins (JavaScript) Source: https://typedoc.logosdx.dev/classes/_logosdx_react.fetch._internal_.FetchEngine Illustrates an advanced setup of FetchEngine, incorporating various plugins for enhanced functionality. This includes retry logic, caching, and request deduplication, showcasing the extensibility of the FetchEngine. ```javascript const api = new FetchEngine({ baseUrl: 'https://api.example.com', plugins: [ retryPlugin({ maxAttempts: 3, baseDelay: 1000 }), cachePlugin({ ttl: 60000 }), dedupePlugin(true) ] }); ``` -------------------------------- ### Transfer Listeners Example (TypeScript) Source: https://typedoc.logosdx.dev/classes/_logosdx_observer.ObserverEngine Example demonstrating how to transfer all listeners from one ObserverEngine to another, and an example showing how to transfer only specific events based on a filter. ```typescript const old = new ObserverEngine(); const next = new ObserverEngine(); old.on('ready', handler); ObserverEngine.transfer(old, next); // `next` now owns the 'ready' listener; `old` has none // Transfer only specific events ObserverEngine.transfer(old, next, { filter: ['ready', /^user\./] }); ``` -------------------------------- ### Start Queue (TypeScript) Source: https://typedoc.logosdx.dev/classes/_logosdx_fetch._internal_.EventQueue The 'start' method initiates the queue's operation if it is not already running. It returns a Promise that resolves when the queue is started, or undefined if the queue is already active. ```typescript start(): Promise | undefined ``` -------------------------------- ### Create Instance Function Example Source: https://typedoc.logosdx.dev/types/_logosdx_fetch._internal_.ClassType An example function 'createInstance' that demonstrates how to create an instance of a class using a generic constructor type. It takes a constructor and arguments, returning an instance of the provided class type. ```typescript function createInstance(ctor: T, ...args: any[]): InstanceType ``` -------------------------------- ### Listen for Specific Events with ObserverEngine (Event Generator Example) Source: https://typedoc.logosdx.dev/interfaces/_logosdx_react.fetch._internal_.FetchEnginePublic This example shows how to use the `on` method to get an event generator, wait for an event, and emit events. ```javascript const obs = new ObserverEngine(); const something = obs.on('something'); const data = await something.next(); // waits for next event something.emit('special'); // emits data to listeners something.cleanup(); // stops listening for events ``` ```javascript const obs = new ObserverEngine(); const something = obs.on('something'); const data = await something.next(); // waits for next event something.emit('special'); // emits data to listeners something.cleanup(); // stops listening for events ``` ```javascript const obs = new ObserverEngine(); const onEvent = obs.on(/some/); const { event, data } = await onEvent.next(); // waits for next event onEvent.emit('something'); // emits data to listeners onEvent.cleanup(); // stops listening for events ``` -------------------------------- ### Get Start Time (SVGAnimationElement - TypeScript) Source: https://typedoc.logosdx.dev/interfaces/_logosdx_dom._internal_.SVGSetElement Returns the start time in seconds for the current interval of an SVG animation element. This method is useful for understanding animation timing. ```typescript getStartTime(): number; ``` -------------------------------- ### Get Start Time (SVGAnimationElement) Source: https://typedoc.logosdx.dev/interfaces/_logosdx_dom._internal_.SVGAnimationElement Returns the start time in seconds for the current interval of an SVG animation element. This value is returned regardless of whether the interval has begun. ```typescript getStartTime(): number ``` -------------------------------- ### Initialize FetchEngine with Basic Configuration (TypeScript) Source: https://typedoc.logosdx.dev/classes/_logosdx_fetch.FetchEngine Demonstrates the basic setup of FetchEngine with essential configuration options such as baseUrl, defaultType, and headers. It also shows how to use the `attempt` utility for error handling when making requests. ```typescript import { FetchEngine } from '@logosdx/fetch'; import { attempt } from './utils'; // Assuming 'attempt' is imported from a local utility file // Basic setup with error handling const api = new FetchEngine({ baseUrl: 'https://api.example.com', defaultType: 'json', headers: { 'Authorization': 'Bearer token' } }); const [user, err] = await attempt(() => api.get('/users/123')); if (err) { console.error('Failed to fetch user:', err); return; } console.log('User data:', user); ``` -------------------------------- ### ObserverEngine Constructor and Basic Usage Source: https://typedoc.logosdx.dev/classes/_logosdx_observer.ObserverEngine Demonstrates how to instantiate the ObserverEngine and set up basic event observation. This includes creating an instance, observing a component, and attaching event listeners. ```typescript const obs = new ObserverEngine(); const modal = {}; obs.observe(modal); modal.on('modal-open', () => {}); obs.trigger('modal-open'); // opens modal modal.trigger('modal-open'); // opens modal modal.cleanup(); // clears all event listeners ``` -------------------------------- ### Implement CacheAdapter get Method (TypeScript) Source: https://typedoc.logosdx.dev/interfaces/_logosdx_fetch._internal_.CacheAdapter The `get` method retrieves a cache item by its key. It returns a Promise that resolves to the `CacheItem` if found, or `null` if the key does not exist. The example illustrates the method signature and its return type. ```typescript get(key: string): Promise | null> ``` -------------------------------- ### Get Tag Name of HTMLElement (TypeScript) Source: https://typedoc.logosdx.dev/interfaces/_logosdx_dom._internal_.HTMLHeadingElement Returns the tag name of the HTMLElement in uppercase. For example, for a `

` element, it returns 'P'. This property is read-only and returns a string. ```typescript tagName: string; ``` -------------------------------- ### FetchEnginePublic Methods - once() Example (TypeScript) Source: https://typedoc.logosdx.dev/interfaces/_logosdx_react.fetch._internal_.FetchEnginePublic Demonstrates registering a listener that will only be called once for a specific event on a FetchEnginePublic instance. Useful for one-time setup or confirmation events. ```typescript fetchEnginePublicInstance.once('initialLoadComplete', (data) => { console.log('Initial load finished:', data); }); // Using once with a promise-like interface fetchEnginePublicInstance.once('requestComplete').then((response) => { console.log('Request completed:', response); }); ``` -------------------------------- ### Get Prefix of HTMLElement (TypeScript) Source: https://typedoc.logosdx.dev/interfaces/_logosdx_dom._internal_.HTMLHeadingElement Returns the namespace prefix of the element, if any. For example, in ``, the prefix is 'svg'. Returns `null` if the element has no namespace prefix. This property is read-only. ```typescript prefix: string | null; ``` -------------------------------- ### Constructor Source: https://typedoc.logosdx.dev/classes/_logosdx_hooks.HookEngine Initializes a new instance of HookEngine. ```APIDOC ## Constructors ### constructor * new HookEngine(options?: HookEngine.Options): HookEngine #### Type Parameters * Lifecycle = DefaultLifecycle Interface defining the lifecycle hooks * FailArgs extends unknown[] = [string] Arguments type for ctx.fail() (default: [string]) #### Parameters * options: HookEngine.Options = {} #### Returns HookEngine ``` -------------------------------- ### FetchEngine Constructor Source: https://typedoc.logosdx.dev/classes/_logosdx_fetch.FetchEngine Initializes a new instance of FetchEngine with configurable options for creating a resilient HTTP client. ```APIDOC ## new FetchEngine(opts: EngineConfig): FetchEngine ### Description Create a new FetchEngine instance. ### Method `constructor` ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Type Parameters * `H` = FetchEngine.InstanceHeaders - Type of request headers * `P` = FetchEngine.InstanceParams - Type of request params * `S` = FetchEngine.InstanceState - Type of instance state * `RH` = FetchEngine.InstanceResponseHeaders - Type of response headers #### Parameters * `opts` (EngineConfig) - Required - Configuration options ### Request Example ```typescript // Basic setup with error handling const api = new FetchEngine({ baseUrl: 'https://api.example.com', defaultType: 'json', headers: { 'Authorization': 'Bearer token' } }); const [user, err] = await attempt(() => api.get('/users/123')); if (err) { console.error('Failed to fetch user:', err); return; } ``` ```typescript // Advanced setup with plugins const api = new FetchEngine({ baseUrl: 'https://api.example.com', plugins: [ retryPlugin({ maxAttempts: 3, baseDelay: 1000 }), cachePlugin({ ttl: 60000 }), dedupePlugin(true) ] }); ``` ### Response #### Success Response (200) * `FetchEngine` - The newly created FetchEngine instance. #### Response Example ```json { "instance": "FetchEngine" } ``` ``` -------------------------------- ### IDBTransaction Event Listener Setup (JavaScript) Source: https://typedoc.logosdx.dev/interfaces/_logosdx_dom._internal_.IDBTransaction Provides an example of how to attach event listeners to an IDBTransaction for `oncomplete`, `onabort`, and `onerror` events. This enables handling the outcome of the transaction. ```javascript const transaction = db.transaction(['myObjectStore'], 'readwrite'); transaction.oncomplete = (event) => { console.log('Transaction completed!'); }; transaction.onabort = (event) => { console.error('Transaction aborted:', transaction.error); }; transaction.onerror = (event) => { console.error('Transaction error:', transaction.error); }; ``` -------------------------------- ### HookEngine Example: Fetch Lifecycle Source: https://typedoc.logosdx.dev/classes/_logosdx_fetch._internal_.HookEngine Demonstrates how to use HookEngine to manage lifecycle events for a fetch operation. It shows how to define lifecycle interfaces, add callbacks for events like 'beforeRequest', and run these hooks to modify requests or handle caching. ```typescript interface FetchLifecycle { beforeRequest(url: string, options: RequestInit): Promise; afterRequest(response: Response, url: string): Promise; } const hooks = new HookEngine(); hooks.add('beforeRequest', (url, opts, ctx) => { ctx.args(url, { ...opts, headers: { ...opts.headers, 'X-Token': token } }); }); hooks.add('beforeRequest', (url, opts, ctx) => { const cached = cache.get(url); if (cached) return ctx.returns(cached); }); const pre = await hooks.run('beforeRequest', url, options); if (pre.returned) return pre.result; const response = await fetch(...pre.args); ``` -------------------------------- ### FetchState Constructor Source: https://typedoc.logosdx.dev/classes/_logosdx_fetch.FetchState Initializes a new instance of FetchState. ```APIDOC ## Constructors ### constructor * new FetchState(engine: FetchEngineCore): FetchState #### Type Parameters * S State type #### Parameters * engine: FetchEngineCore #### Returns FetchState ``` -------------------------------- ### Get Elements by Class Name with `getElementsByClassName()` Source: https://typedoc.logosdx.dev/interfaces/_logosdx_dom._internal_.HTMLSpanElement The `getElementsByClassName()` method returns a live `HTMLCollection` of all descendant elements that have the specified class names. It searches the entire DOM tree starting from the element it's called on. ```javascript const elements = parentElement.getElementsByClassName('class-name'); ``` -------------------------------- ### TimeRanges Interface Definition (TypeScript) Source: https://typedoc.logosdx.dev/interfaces/_logosdx_dom._internal_.TimeRanges Defines the structure of the TimeRanges interface, which represents time ranges in media resources. It includes properties for the number of ranges and methods to get the start and end times of specific ranges. ```typescript interface TimeRanges { length: number; end(index: number): number; start(index: number): number; } ``` -------------------------------- ### Initialize FetchEngine with Advanced Plugins (TypeScript) Source: https://typedoc.logosdx.dev/classes/_logosdx_fetch.FetchEngine Illustrates an advanced FetchEngine setup utilizing various plugins for enhanced functionality. This includes retry logic, caching, and request deduplication, configured directly within the FetchEngine constructor. ```typescript import { FetchEngine } from '@logosdx/fetch'; import { retryPlugin } from '@logosdx/fetch/plugins'; import { cachePlugin } from '@logosdx/fetch/plugins'; import { dedupePlugin } from '@logosdx/fetch/plugins'; // Advanced setup with plugins const api = new FetchEngine({ baseUrl: 'https://api.example.com', plugins: [ retryPlugin({ maxAttempts: 3, baseDelay: 1000 }), cachePlugin({ ttl: 60000 }), dedupePlugin(true) ] }); // Example usage of the advanced API instance would follow... ``` -------------------------------- ### Get Elements by Class Name (JavaScript) Source: https://typedoc.logosdx.dev/interfaces/_logosdx_dom._internal_.HTMLAnchorElement The getElementsByClassName() method returns a live HTMLCollection of all child elements that have the specified class name(s). It searches the entire DOM tree starting from the element it's called on. ```javascript element.getElementsByClassName(classNames); ``` -------------------------------- ### StorageAdapter Constructor Source: https://typedoc.logosdx.dev/classes/_logosdx_storage.StorageAdapter Initializes a new instance of the StorageAdapter. ```APIDOC ## Constructor StorageAdapter ### Description Initializes a new instance of the StorageAdapter. ### Method CONSTRUCTOR ### Endpoint N/A ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example ```json { "config": { ... } // StorageAdapter.Config object } ``` ### Response #### Success Response (200) Returns an instance of StorageAdapter. #### Response Example ```json { "instance": "StorageAdapter" } ``` ``` -------------------------------- ### Using the Provider and Hook Source: https://typedoc.logosdx.dev/functions/_logosdx_react.fetch.createFetchContext Demonstrates how to set up the ApiFetch provider and use the useApiFetch hook for making API requests. ```APIDOC ## Setup and Usage ### Wrapping Your App Wrap your application or relevant component tree with the `ApiFetch` provider. ```javascript // In your App.js or index.js import { ApiFetch } from './api'; // Assuming you created it in api.js function App() { return ( {/* Your application components */} ); } ``` ### Queries (Auto-fetching) Use the `get` method from the `useApiFetch` hook to fetch data automatically when a component mounts or dependencies change. ```javascript import React from 'react'; import { useApiFetch } from './api'; function UserList() { const { get } = useApiFetch(); // Fetches immediately, returns reactive state const [cancel, isLoading, res, error] = get('/users'); // Example with typed response headers const [, , res2] = get('/posts'); // Access typed headers: res2?.headers['x-total'] if (isLoading) return ; if (error) return ; return

    {res?.data.map(u =>
  • {u.name}
  • )}
; } ``` ### Mutations (On-demand) Use methods like `post`, `put`, `del`, `patch` from `useApiFetch` for actions that are triggered manually. ```javascript import React from 'react'; import { useApiFetch } from './api'; function CreateComment() { const { post, del } = useApiFetch(); const [submit, cancelSubmit, isSubmitting, result, submitErr] = post('/comments'); const [remove, cancelRemove, isRemoving, _, removeErr] = del('/comments/123'); const handleSubmit = async () => { await submit({ text: 'Hello' }); }; return (
{result &&

Comment created: {result.data.id}

} {submitErr &&

Failed ({submitErr.status}): {submitErr.message}

}
); } ``` ### Escape Hatch (Raw FetchEngine Access) Access the underlying `FetchEngine` instance for imperative requests. ```javascript import React from 'react'; import { useApiFetch } from './api'; import { attempt } from '@logosdx/fetch'; // Assuming attempt is exported function ExportButton() { const { instance } = useApiFetch(); const handleExport = async () => { const [res, err] = await attempt(() => instance.get('/export')); if (err) { console.error('Export failed:', err); } else { console.log('Export successful:', res); } }; return ; } ``` ### Rules * `get`, `post`, `put`, `del`, and `patch` are hooks and must be called at the top level of your React component, not conditionally or inside loops. ``` -------------------------------- ### Get Point at Length on SVG Path (TypeScript) Source: https://typedoc.logosdx.dev/interfaces/_logosdx_dom._internal_.SVGEllipseElement Calculates and returns a DOMPoint representing a specific point along an SVG path, based on a given distance from the start of the path. This is useful for geometric calculations on SVG shapes. ```typescript declare function getPointAtLength(distance: number): DOMPoint; ``` -------------------------------- ### Window Navigation and Control Methods Source: https://typedoc.logosdx.dev/interfaces/_logosdx_dom._internal_.Window Provides examples of methods for controlling the browser window, including navigation, resizing, and opening/closing windows. These are fundamental for creating interactive web applications. ```typescript blur(): void; close(): void; focus(): void; moveBy(x: number, y: number): void; moveTo(x: number, y: number): void; open(url?: string | URL, target?: string, features?: string): Window | null; print(): void; resizeBy(x: number, y: number): void; resizeTo(width: number, height: number): void; stop(): void; ``` -------------------------------- ### FileHandle: Get Stats Example Source: https://typedoc.logosdx.dev/interfaces/_logosdx_storage._internal_.node_fs_promises.FileHandle Shows how to retrieve file status information using the `stat` method. This includes details like file size, modification times, and permissions. It can return either standard `Stats` or `BigIntStats` based on the `bigint` option. ```javascript import { open } from 'node:fs/promises'; const filehandle = await open('thefile.txt', 'r'); // Get standard stats const stats = await filehandle.stat(); console.log('File size:', stats.size); // Get stats with bigint const bigIntStats = await filehandle.stat({ bigint: true }); console.log('File size (bigint):', bigIntStats.size); await filehandle.close(); ``` -------------------------------- ### Accessing and Setting ConfigStore Options (TypeScript) Source: https://typedoc.logosdx.dev/classes/_logosdx_react.fetch._internal_.ConfigStore Demonstrates how to access and modify configuration options within the ConfigStore using the engine.config object. It shows examples of getting specific values by path, setting individual options, and merging partial configuration objects. This functionality is crucial for runtime configuration adjustments. ```typescript const engine = ...; // Access via engine.config const baseUrl = engine.config.get('baseUrl'); // string const maxAttempts = engine.config.get('retry.maxAttempts'); // number // Set options (runtime configurable) engine.config.set('baseUrl', 'https://new-api.com'); engine.config.set('retry.maxAttempts', 5); // Merge partial options engine.config.set({ retry: { maxAttempts: 5 } }); ``` -------------------------------- ### constructor Source: https://typedoc.logosdx.dev/classes/_logosdx_utils.SingleFlight Creates a new SingleFlight instance. ```APIDOC ## constructor * new SingleFlight(opts?: SingleFlightOptions): SingleFlight Creates a new SingleFlight instance. #### Type Parameters * T = unknown The type of values to cache/track #### Parameters * `Optional`opts: SingleFlightOptions Configuration options #### Returns SingleFlight ``` -------------------------------- ### Basic RateLimitTokenBucket Usage Source: https://typedoc.logosdx.dev/classes/_logosdx_fetch._internal_.RateLimitTokenBucket Demonstrates the basic usage of the RateLimitTokenBucket for rate limiting. It shows how to initialize the bucket, consume tokens, and wait for tokens if none are available. This requires no external dependencies. ```typescript const bucket = new RateLimitTokenBucket({ capacity: 10, refillIntervalMs: 1000 }); bucket.consume(); bucket.consume(); const rateLimited = async () => { // 0 ms if tokens are available // 1000 / 10 = 100 ms if tokens are not available await bucket.waitAndConsume(); return 'success'; } ``` -------------------------------- ### GET /api/data Source: https://typedoc.logosdx.dev/variables/_logosdx_fetch.get The 'get' function is used to make an HTTP GET request to a specified path. It allows for optional configuration of request headers, parameters, and state management. ```APIDOC ## GET /api/data ### Description Makes a GET request to retrieve data from the specified path. This function is part of the Logos DX fetch module. ### Method GET ### Endpoint `/api/data` (This is a placeholder; the actual path is provided as a parameter) ### Parameters #### Path Parameters - **path** (string) - Required - The URL path to make the GET request to. #### Query Parameters None directly defined for this function, but can be included in `options.params`. #### Request Body Not applicable for GET requests. ### Request Example ```json { "path": "/users/123", "options": { "headers": { "Authorization": "Bearer YOUR_TOKEN" }, "params": { "include_details": true } } } ``` ### Response #### Success Response (200) - **Res** (unknown) - The data returned from the GET request. The type can be specified when calling the function. - **DictAndT** - Headers associated with the response. - **DictAndT** - Parameters associated with the response. - **ResHdr** (FetchEngine.InstanceResponseHeaders) - Custom response headers. #### Response Example ```json { "data": { "id": 123, "name": "John Doe" }, "headers": { "Content-Type": "application/json" }, "params": { "include_details": true }, "responseHeaders": { "X-RateLimit-Limit": "1000" } } ``` ``` -------------------------------- ### Wait for Token Availability with RateLimitTokenBucket Source: https://typedoc.logosdx.dev/classes/_logosdx_fetch._internal_.RateLimitTokenBucket Demonstrates how to use the waitForToken method to pause execution until a rate limit token is available. This example initializes a RateLimitTokenBucket and then waits for a token, logging messages to indicate the state of the token availability and consumption. ```typescript const bucket = new RateLimitTokenBucket({ capacity: 10, refillIntervalMs: 1000 }); await bucket.waitForToken(() => { console.log('Rate limit exceeded'); }); console.log('Token available'); bucket.consume(); console.log('Token consumed'); ``` -------------------------------- ### Use Storage Hook in React Components Source: https://typedoc.logosdx.dev/functions/_logosdx_react.storage.createStorageContext This example illustrates how to use the `useAppStorage` hook within a React component to access and modify storage values. The hook provides methods like `get` and `set`. Any mutation to the storage via these methods automatically triggers a re-render of the component, ensuring the UI is always up-to-date with the storage state. ```javascript function ThemeSwitcher() { const { get, set } = useAppStorage(); // Reads current value — re-renders when any storage key changes const theme = get('theme'); return ( ); } ``` -------------------------------- ### StorageAdapter Methods Source: https://typedoc.logosdx.dev/classes/_logosdx_storage.StorageAdapter Documentation for various methods available on the StorageAdapter. ```APIDOC ## Methods ### assign #### Description Assigns a partial value to a specific key. #### Method POST #### Endpoint `/assign` (Conceptual - actual endpoint depends on implementation) #### Parameters ##### Path Parameters None ##### Query Parameters None ##### Request Body - **key** (string | number | symbol) - Required - The key to assign the value to. - **val** (Partial) - Required - The partial value to assign. ### Response #### Success Response (200) Indicates successful assignment. ### clear #### Description Clears all data from the storage. #### Method POST #### Endpoint `/clear` (Conceptual - actual endpoint depends on implementation) #### Parameters None ### Response #### Success Response (200) Indicates successful clearing. ### entries #### Description Retrieves all key-value pairs from storage. #### Method GET #### Endpoint `/entries` (Conceptual - actual endpoint depends on implementation) #### Parameters None #### Response ##### Success Response (200) - **entries** (Array<[keyof Values, Values[keyof Values]]>) - An array of key-value pairs. ### get #### Description Retrieves data from storage. #### Method GET #### Endpoint `/get` (Conceptual - actual endpoint depends on implementation) #### Parameters ##### Query Parameters - **key** (string | number | symbol) - Optional - The key to retrieve. - **keys** (Array) - Optional - An array of keys to retrieve. #### Response ##### Success Response (200) - **value** (Values | Values[K] | null | Partial) - The retrieved value(s). ### has #### Description Checks if one or more keys exist in storage. #### Method GET #### Endpoint `/has` (Conceptual - actual endpoint depends on implementation) #### Parameters ##### Query Parameters - **key** (string | number | symbol) - Optional - The key to check. - **keys** (Array) - Optional - An array of keys to check. #### Response ##### Success Response (200) - **exists** (boolean | boolean[]) - True if the key(s) exist, false otherwise. ### keys #### Description Retrieves all keys from storage. #### Method GET #### Endpoint `/keys` (Conceptual - actual endpoint depends on implementation) #### Parameters None #### Response ##### Success Response (200) - **keys** (Array) - An array of keys. ### off #### Description Removes an event listener. #### Method POST #### Endpoint `/off` (Conceptual - actual endpoint depends on implementation) #### Parameters ##### Request Body - **event** (StorageEventName) - Required - The name of the event. - **listener** (StorageEventListener) - Required - The listener function to remove. ### Response #### Success Response (200) Indicates successful removal of the listener. ### on #### Description Adds an event listener. #### Method POST #### Endpoint `/on` (Conceptual - actual endpoint depends on implementation) #### Parameters ##### Request Body - **event** (StorageEventName) - Required - The name of the event. - **listener** (StorageEventListener) - Required - The listener function to add. #### Response ##### Success Response (200) - **eventGenerator** (EventGenerator, any>) - An event generator. ### rm #### Description Removes one or more keys from storage. #### Method DELETE #### Endpoint `/rm` (Conceptual - actual endpoint depends on implementation) #### Parameters ##### Query Parameters - **keyOrKeys** (string | number | symbol | Array) - Required - The key or keys to remove. ### Response #### Success Response (200) Indicates successful removal. ### scope #### Description Creates a scoped key for accessing nested data. #### Method GET #### Endpoint `/scope` (Conceptual - actual endpoint depends on implementation) #### Parameters ##### Query Parameters - **key** (string | number | symbol) - Required - The key to scope. #### Response ##### Success Response (200) - **scopedKey** (ScopedKey) - The scoped key object. ### set #### Description Sets one or more values in storage. #### Method POST #### Endpoint `/set` (Conceptual - actual endpoint depends on implementation) #### Parameters ##### Request Body - **values** (Partial & Record) - Required - The values to set. - **key** (string | number | symbol) - Required - The key to set the value for. - **value** (Values[K]) - Required - The value to set. ### Response #### Success Response (200) Indicates successful setting of values. ### values #### Description Retrieves all values from storage. #### Method GET #### Endpoint `/values` (Conceptual - actual endpoint depends on implementation) #### Parameters None #### Response ##### Success Response (200) - **values** (Array) - An array of values. ``` -------------------------------- ### Create React Context and Hook with StorageAdapter Source: https://typedoc.logosdx.dev/functions/_logosdx_react.storage.createStorageContext This snippet demonstrates how to create a React context and hook pair using `createStorageContext`. It binds a `StorageAdapter` instance to the context, allowing components to access and manipulate storage. The setup involves defining the storage interface, initializing the `StorageAdapter` with a driver and prefix, and then calling `createStorageContext` to get the `Provider` and `useHook` components. ```javascript import { StorageAdapter } from '@logosdx/storage'; import { createStorageContext } from '@logosdx/react'; interface AppStore { theme: 'light' | 'dark'; userId: string; preferences: { lang: string; notifications: boolean }; } const storage = new StorageAdapter({ driver: new WebStorageDriver(localStorage), prefix: 'myapp', }); export const [AppStorage, useAppStorage] = createStorageContext(storage); ``` -------------------------------- ### GET Request Function in TypeScript Source: https://typedoc.logosdx.dev/variables/_logosdx_fetch.get The 'get' function is used to make an HTTP GET request. It takes a path and optional configuration options. It returns a FetchPromise that resolves with the response data and headers. This function is a wrapper around FetchEngine.get. ```typescript import { FetchPromise, CallConfig } from "@logosdx/fetch"; import { FetchEngine } from "@logosdx/fetch/engine"; // Assuming InstanceHeaders, InstanceParams, and InstanceState are defined elsewhere const get = ( path: string, options?: CallConfig< FetchEngine.InstanceHeaders, FetchEngine.InstanceParams, InstanceState, >, ): FetchPromise< Res, DictAndT, DictAndT, ResHdr, > => { // Implementation details would go here, likely calling FetchEngine.get // For example: // return FetchEngine.get(path, options); throw new Error("Not implemented"); }; // Example Usage (assuming FetchEngine.get is implemented and available): /* async function fetchData() { try { const response = await get<{ message: string }>('/api/data'); console.log(response.data.message); } catch (error) { console.error("Failed to fetch data:", error); } } */ ``` -------------------------------- ### FetchEngine and InstanceParams Source: https://typedoc.logosdx.dev/interfaces/_logosdx_fetch.FetchEngine.InstanceParams Details about the FetchEngine and the InstanceParams interface for configuring fetch operations. ```APIDOC ## Logos DX Fetch Engine ### Description This section details the core components of the Logos DX Fetch Engine, including the `FetchEngine` class and the `InstanceParams` interface. ### Components #### FetchEngine * **Description**: The main engine for handling fetch requests. * **Usage**: Instantiate and use for making HTTP requests. #### InstanceParams Interface * **Description**: Base parameters interface that users can augment to customize fetch engine instances. * **Hierarchy**: `InstanceParams` extends `InstanceParams` (This indicates a potential self-referential or base interface definition). ### Parameters #### InstanceParams Fields * **[Specific fields for InstanceParams would be listed here if available in the source text]** ### Example Usage (Conceptual) ```typescript // Assuming FetchEngine and InstanceParams are imported // Example of augmenting InstanceParams interface MyCustomParams extends InstanceParams { customTimeout: number; } // Example of using FetchEngine with custom parameters const fetchEngine = new FetchEngine(/* initial params */); fetchEngine.request({ url: '/api/data', method: 'GET', params: { customTimeout: 5000, // other InstanceParams fields } }); ``` ### Response * **Success Response**: Depends on the specific fetch operation performed by `FetchEngine`. * **Error Response**: Depends on the specific fetch operation and error handling within `FetchEngine`. ``` -------------------------------- ### Instantiate QueueStats Source: https://typedoc.logosdx.dev/classes/_logosdx_observer._internal_.QueueStats Demonstrates how to create a new instance of the QueueStats class. It requires an ObserverEngine and a queue name as arguments. ```typescript import { QueueStats } from "@logosdx/observer"; import { ObserverEngine } from "@logosdx/observer"; const observer: ObserverEngine = /* ... obtain an ObserverEngine instance ... */; const queueName: string = "myQueue"; const queueStats = new QueueStats(observer, queueName); ``` -------------------------------- ### ObserverEngine.queue() Source: https://typedoc.logosdx.dev/interfaces/_logosdx_react.fetch._internal_.FetchEngineCore Sets up an event queue to process events matching a specific pattern. ```APIDOC ## POST /queue ### Description Sets up an event queue to process events matching a specific pattern. ### Method POST ### Endpoint /queue ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body - **event** (RegExp | string) - Required - The event name or regular expression to match. - **process** (function) - Required - The function to process the event data. - **options** (object) - Required - Queue options. ### Request Example ```json { "event": "/data_update/", "process": "(data) => { console.log('Processing:', data); }", "options": { "concurrency": 5 } } ``` ### Response #### Success Response (200) - **eventQueue** (object) - An object representing the event queue with methods to manage it. #### Response Example ```json { "eventQueue": { "pause": "() => void", "resume": "() => void", "clear": "() => void" } } ``` ``` -------------------------------- ### Element Get Bounding Client Rect Source: https://typedoc.logosdx.dev/interfaces/_logosdx_dom._internal_.HTMLImageElement Gets the size and position of an element relative to the viewport. ```APIDOC ## getBoundingClientRect ### Description The `Element.getBoundingClientRect()` method returns a position relative to the viewport. ### Method GET ### Endpoint N/A (Method of an Element object) ### Parameters None ### Response #### Success Response (200) - **DOMRect**: An object with `top`, `right`, `bottom`, `left`, `width`, and `height` properties. #### Response Example ```json { "example": { "top": 10, "right": 100, "bottom": 50, "left": 20, "width": 80, "height": 40 } } ``` ``` -------------------------------- ### React Component Constructor Example Source: https://typedoc.logosdx.dev/classes/_logosdx_react.._internal_.Component Demonstrates the constructor for the React Component class, showing how to initialize a component with props and context. It highlights the generic type parameters P, S, and SS for props, state, and snapshot respectively. ```typescript new Component

(props: P): Component new Component

( props: P, context: any, ): Component ``` -------------------------------- ### Media Load Start Event Handler Source: https://typedoc.logosdx.dev/interfaces/_logosdx_dom._internal_.SVGSymbolElement Handles the event when the media loading process starts. ```APIDOC ## Event Handler: Media Load Start ### Description This event handler is triggered when the media resource begins to load. ### Method Event Listener Attachment (e.g., `addEventListener`) ### Endpoints N/A (This is an event property, not an API endpoint) ### Parameters N/A ### Request Example ```javascript const audio = document.getElementById('myAudio'); audio.onloadstart = (event) => { console.log('Media loading started.'); }; ``` ### Response #### Success Response N/A (Event handlers execute callback functions) #### Response Example N/A ``` -------------------------------- ### IDBObjectStore Methods: get, getAll, getAllKeys Source: https://typedoc.logosdx.dev/interfaces/_logosdx_dom._internal_.IDBObjectStore Shows the 'get', 'getAll', and 'getAllKeys' methods for retrieving data from an IDBObjectStore. 'get' retrieves a single record, 'getAll' retrieves multiple records, and 'getAllKeys' retrieves the keys of multiple records. ```typescript // Get a single record by key get(query: IDBValidKey | IDBKeyRange): IDBRequest; // Get all records matching a query getAll( query?: IDBValidKey | IDBKeyRange | null, count?: number, ): IDBRequest; // Get all keys matching a query getAllKeys( query?: IDBValidKey | IDBKeyRange | null, count?: number, ): IDBRequest; ``` -------------------------------- ### Create and Use Cache Plugin with FetchEngine (TypeScript) Source: https://typedoc.logosdx.dev/functions/_logosdx_fetch.cachePlugin Demonstrates how to create a cache plugin using `cachePlugin` and integrate it into a `FetchEngine` instance. It also shows how to access and use the cache management methods directly from the plugin instance. ```typescript import { FetchEngine } from '@logosdx/fetch'; import { cachePlugin } from '@logosdx/fetch'; // Create a cache plugin with specified TTL and stale-while-revalidate time const cache = cachePlugin({ ttl: 300000, staleIn: 60000 }); // Initialize FetchEngine with the cache plugin const api = new FetchEngine({ baseUrl: 'https://api.example.com', plugins: [cache] }); // Access cache methods directly on the plugin instance cache.clearCache(); cache.stats(); console.log('Cache plugin created and integrated successfully.'); ``` -------------------------------- ### GET Request API Source: https://typedoc.logosdx.dev/functions/_logosdx_react.fetch.createFetchContext Handles GET requests to specified paths with configurable options. ```APIDOC ## GET /api/resource ### Description This endpoint is used to retrieve a resource from the specified path. It returns a tuple containing a function to trigger the request, the loading state, the response, and any potential errors. ### Method GET ### Endpoint /api/resource ### Parameters #### Path Parameters - **path** (string) - Required - The path of the resource to retrieve. #### Query Parameters - **options** (CallConfig) - Optional - Configuration options for the API call. ### Response #### Success Response (200) - **Function to trigger request** (() => void) - **Loading state** (boolean) - **Fetch response** (FetchResponse | null) - **Fetch error** (FetchError | null) #### Response Example ```json { "success": true, "data": { ... } } ``` ``` -------------------------------- ### FileSystem Constructor and Prototype Source: https://typedoc.logosdx.dev/variables/_logosdx_dom._internal_.FileSystem Details the FileSystem class constructor and its prototype, which also represents the FileSystem type. ```APIDOC ## FileSystem ### Description Represents the FileSystem class, used for file system operations. This documentation details its constructor and prototype. ### Method N/A (Class definition) ### Endpoint N/A (Class definition) ### Parameters N/A ### Request Example N/A ### Response #### Type Declaration - **FileSystem** (object) - Represents the FileSystem class. - **prototype** (object) - The prototype of the FileSystem class, which is also of type FileSystem. - **new** (function) - Constructor for the FileSystem class. - **Returns** (object) - An instance of FileSystem. #### Response Example ```json { "FileSystem": { "prototype": { "new": "function" } } } ``` ``` -------------------------------- ### Properties Source: https://typedoc.logosdx.dev/classes/_logosdx_fetch._internal_.RequestExecutor Provides access to the underlying FetchEngine instance. ```APIDOC ## Properties ### engine engine: FetchEngineCore Reference to the FetchEngine instance ``` -------------------------------- ### Range Methods: setStart, setStartAfter, setStartBefore Source: https://typedoc.logosdx.dev/interfaces/_logosdx_dom._internal_.Range These methods modify the start boundary of the `Range`. `setStart()` sets the start to a specific `node` and `offset`. `setStartAfter()` sets the start boundary after a given `node`, and `setStartBefore()` sets it before a given `node`. ```javascript // Example usage (conceptual): const range = document.createRange(); const startNode = document.getElementById('someElement'); range.setStart(startNode, 0); // Set start to node at offset 0 range.setStartAfter(startNode); // Set start after the node range.setStartBefore(startNode); // Set start before the node ```