From bb0a9888de40cd616a4278d0663b7b68f1cf552c Mon Sep 17 00:00:00 2001 From: thororen1234 <78185467+thororen1234@users.noreply.github.com> Date: Tue, 19 Nov 2024 17:08:13 -0500 Subject: [PATCH] Fix Tests --- package.json | 3 +- pnpm-lock.yaml | 8 + .../messageLoggerEnhanced/db.ts | 3 +- .../messageLoggerEnhanced/utils/idb/LICENSE | 6 - .../utils/idb/async-iterators.ts | 78 -- .../utils/idb/database-extras.ts | 75 -- .../messageLoggerEnhanced/utils/idb/entry.ts | 1142 ----------------- .../messageLoggerEnhanced/utils/idb/index.ts | 5 - .../messageLoggerEnhanced/utils/idb/util.ts | 9 - .../utils/idb/wrap-idb-value.ts | 227 ---- .../utils/saveImage/ImageManager.ts | 2 +- 11 files changed, 13 insertions(+), 1545 deletions(-) delete mode 100644 src/equicordplugins/messageLoggerEnhanced/utils/idb/LICENSE delete mode 100644 src/equicordplugins/messageLoggerEnhanced/utils/idb/async-iterators.ts delete mode 100644 src/equicordplugins/messageLoggerEnhanced/utils/idb/database-extras.ts delete mode 100644 src/equicordplugins/messageLoggerEnhanced/utils/idb/entry.ts delete mode 100644 src/equicordplugins/messageLoggerEnhanced/utils/idb/index.ts delete mode 100644 src/equicordplugins/messageLoggerEnhanced/utils/idb/util.ts delete mode 100644 src/equicordplugins/messageLoggerEnhanced/utils/idb/wrap-idb-value.ts diff --git a/package.json b/package.json index 182e143f..2602feda 100644 --- a/package.json +++ b/package.json @@ -48,6 +48,7 @@ "fflate": "^0.8.2", "gifenc": "github:mattdesl/gifenc#64842fca317b112a8590f8fef2bf3825da8f6fe3", "jsqr": "1.4.0", + "idb": "8.0.0", "monaco-editor": "^0.50.0", "nanoid": "^5.0.7", "usercss-meta": "^0.12.0", @@ -120,4 +121,4 @@ "node": ">=18", "pnpm": ">=9" } -} +} \ No newline at end of file diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml index 5731d37e..55bb387a 100644 --- a/pnpm-lock.yaml +++ b/pnpm-lock.yaml @@ -49,6 +49,9 @@ importers: gifenc: specifier: github:mattdesl/gifenc#64842fca317b112a8590f8fef2bf3825da8f6fe3 version: https://codeload.github.com/mattdesl/gifenc/tar.gz/64842fca317b112a8590f8fef2bf3825da8f6fe3 + idb: + specifier: 8.0.0 + version: 8.0.0 jsqr: specifier: 1.4.0 version: 1.4.0 @@ -1544,6 +1547,9 @@ packages: humanize-ms@1.2.1: resolution: {integrity: sha512-Fl70vYtsAFb/C06PTS9dZBo7ihau+Tu/DNCk/OyHhea07S+aeMWpFFkUaXRa8fI+ScZbEI8dfSxwY7gxZ9SAVQ==} + idb@8.0.0: + resolution: {integrity: sha512-l//qvlAKGmQO31Qn7xdzagVPPaHTxXx199MhrAFuVBTPqydcPYBWjkrbv4Y0ktB+GmWOiwHl237UUOrLmQxLvw==} + ieee754@1.2.1: resolution: {integrity: sha512-dcyqhDvX1C46lXZcVqCpK+FtMRQVdIMN6/Df5js2zouUsqG7I6sFxitIC+7KYK29KdXOLHdu9zL4sFnoVQnqaA==} @@ -3848,6 +3854,8 @@ snapshots: dependencies: ms: 2.1.2 + idb@8.0.0: {} + ieee754@1.2.1: {} ignore@5.2.4: {} diff --git a/src/equicordplugins/messageLoggerEnhanced/db.ts b/src/equicordplugins/messageLoggerEnhanced/db.ts index 90b850fa..6288f1d5 100644 --- a/src/equicordplugins/messageLoggerEnhanced/db.ts +++ b/src/equicordplugins/messageLoggerEnhanced/db.ts @@ -4,10 +4,11 @@ * SPDX-License-Identifier: GPL-3.0-or-later */ +import { DBSchema, IDBPDatabase, openDB } from "idb"; + import { LoggedMessageJSON } from "./types"; import { getMessageStatus } from "./utils"; import { DB_NAME, DB_VERSION } from "./utils/constants"; -import { DBSchema, IDBPDatabase, openDB } from "./utils/idb"; import { getAttachmentBlobUrl } from "./utils/saveImage"; export enum DBMessageStatus { diff --git a/src/equicordplugins/messageLoggerEnhanced/utils/idb/LICENSE b/src/equicordplugins/messageLoggerEnhanced/utils/idb/LICENSE deleted file mode 100644 index f8b22cee..00000000 --- a/src/equicordplugins/messageLoggerEnhanced/utils/idb/LICENSE +++ /dev/null @@ -1,6 +0,0 @@ -ISC License (ISC) -Copyright (c) 2016, Jake Archibald - -Permission to use, copy, modify, and/or distribute this software for any purpose with or without fee is hereby granted, provided that the above copyright notice and this permission notice appear in all copies. - -THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. diff --git a/src/equicordplugins/messageLoggerEnhanced/utils/idb/async-iterators.ts b/src/equicordplugins/messageLoggerEnhanced/utils/idb/async-iterators.ts deleted file mode 100644 index 97709e37..00000000 --- a/src/equicordplugins/messageLoggerEnhanced/utils/idb/async-iterators.ts +++ /dev/null @@ -1,78 +0,0 @@ -/* eslint-disable simple-header/header */ - -import { IDBPCursor, IDBPIndex, IDBPObjectStore } from "./entry.js"; -import { Func, instanceOfAny } from "./util.js"; -import { replaceTraps, reverseTransformCache, unwrap } from "./wrap-idb-value.js"; - -const advanceMethodProps = ["continue", "continuePrimaryKey", "advance"]; -const methodMap: { [s: string]: Func; } = {}; -const advanceResults = new WeakMap>(); -const ittrProxiedCursorToOriginalProxy = new WeakMap(); - -const cursorIteratorTraps: ProxyHandler = { - get(target, prop) { - if (!advanceMethodProps.includes(prop as string)) return target[prop]; - - let cachedFunc = methodMap[prop as string]; - - if (!cachedFunc) { - cachedFunc = methodMap[prop as string] = function ( - this: IDBPCursor, - ...args: any - ) { - advanceResults.set( - this, - (ittrProxiedCursorToOriginalProxy.get(this) as any)[prop](...args), - ); - }; - } - - return cachedFunc; - }, -}; - -async function* iterate( - this: IDBPObjectStore | IDBPIndex | IDBPCursor, - ...args: any[] -): AsyncIterableIterator { - // tslint:disable-next-line:no-this-assignment - let cursor: typeof this | null = this; - - if (!(cursor instanceof IDBCursor)) { - cursor = await (cursor as IDBPObjectStore | IDBPIndex).openCursor(...args); - } - - if (!cursor) return; - - cursor = cursor as IDBPCursor; - const proxiedCursor = new Proxy(cursor, cursorIteratorTraps); - ittrProxiedCursorToOriginalProxy.set(proxiedCursor, cursor); - // Map this double-proxy back to the original, so other cursor methods work. - reverseTransformCache.set(proxiedCursor, unwrap(cursor)); - - while (cursor) { - yield proxiedCursor; - // If one of the advancing methods was not called, call continue(). - cursor = await (advanceResults.get(proxiedCursor) || cursor.continue()); - advanceResults.delete(proxiedCursor); - } -} - -function isIteratorProp(target: any, prop: number | string | symbol) { - return ( - (prop === Symbol.asyncIterator && - instanceOfAny(target, [IDBIndex, IDBObjectStore, IDBCursor])) || - (prop === "iterate" && instanceOfAny(target, [IDBIndex, IDBObjectStore])) - ); -} - -replaceTraps(oldTraps => ({ - ...oldTraps, - get(target, prop, receiver) { - if (isIteratorProp(target, prop)) return iterate; - return oldTraps.get!(target, prop, receiver); - }, - has(target, prop) { - return isIteratorProp(target, prop) || oldTraps.has!(target, prop); - }, -})); diff --git a/src/equicordplugins/messageLoggerEnhanced/utils/idb/database-extras.ts b/src/equicordplugins/messageLoggerEnhanced/utils/idb/database-extras.ts deleted file mode 100644 index 26e6a7e8..00000000 --- a/src/equicordplugins/messageLoggerEnhanced/utils/idb/database-extras.ts +++ /dev/null @@ -1,75 +0,0 @@ -/* eslint-disable simple-header/header */ - -import { IDBPDatabase, IDBPIndex } from "./entry.js"; -import { Func } from "./util.js"; -import { replaceTraps } from "./wrap-idb-value.js"; - -const readMethods = ["get", "getKey", "getAll", "getAllKeys", "count"]; -const writeMethods = ["put", "add", "delete", "clear"]; -const cachedMethods = new Map(); - -function getMethod( - target: any, - prop: string | number | symbol, -): Func | undefined { - if ( - !( - target instanceof IDBDatabase && - !(prop in target) && - typeof prop === "string" - ) - ) { - return; - } - - if (cachedMethods.get(prop)) return cachedMethods.get(prop); - - const targetFuncName: string = prop.replace(/FromIndex$/, ""); - const useIndex = prop !== targetFuncName; - const isWrite = writeMethods.includes(targetFuncName); - - if ( - // Bail if the target doesn't exist on the target. Eg, getAll isn't in Edge. - !(targetFuncName in (useIndex ? IDBIndex : IDBObjectStore).prototype) || - !(isWrite || readMethods.includes(targetFuncName)) - ) { - return; - } - - const method = async function ( - this: IDBPDatabase, - storeName: string, - ...args: any[] - ) { - // isWrite ? 'readwrite' : undefined gzipps better, but fails in Edge :( - const tx = this.transaction(storeName, isWrite ? "readwrite" : "readonly"); - let target: - | typeof tx.store - | IDBPIndex = - tx.store; - if (useIndex) target = target.index(args.shift()); - - // Must reject if op rejects. - // If it's a write operation, must reject if tx.done rejects. - // Must reject with op rejection first. - // Must resolve with op value. - // Must handle both promises (no unhandled rejections) - return ( - await Promise.all([ - (target as any)[targetFuncName](...args), - isWrite && tx.done, - ]) - )[0]; - }; - - cachedMethods.set(prop, method); - return method; -} - -replaceTraps(oldTraps => ({ - ...oldTraps, - get: (target, prop, receiver) => - getMethod(target, prop) || oldTraps.get!(target, prop, receiver), - has: (target, prop) => - !!getMethod(target, prop) || oldTraps.has!(target, prop), -})); diff --git a/src/equicordplugins/messageLoggerEnhanced/utils/idb/entry.ts b/src/equicordplugins/messageLoggerEnhanced/utils/idb/entry.ts deleted file mode 100644 index c22ff4ff..00000000 --- a/src/equicordplugins/messageLoggerEnhanced/utils/idb/entry.ts +++ /dev/null @@ -1,1142 +0,0 @@ -/* eslint-disable simple-header/header */ - -import { wrap } from "./wrap-idb-value.js"; - -export interface OpenDBCallbacks { - /** - * Called if this version of the database has never been opened before. Use it to specify the - * schema for the database. - * - * @param database A database instance that you can use to add/remove stores and indexes. - * @param oldVersion Last version of the database opened by the user. - * @param newVersion Whatever new version you provided. - * @param transaction The transaction for this upgrade. - * This is useful if you need to get data from other stores as part of a migration. - * @param event The event object for the associated 'upgradeneeded' event. - */ - upgrade?( - database: IDBPDatabase, - oldVersion: number, - newVersion: number | null, - transaction: IDBPTransaction< - DBTypes, - StoreNames[], - "versionchange" - >, - event: IDBVersionChangeEvent, - ): void; - /** - * Called if there are older versions of the database open on the origin, so this version cannot - * open. - * - * @param currentVersion Version of the database that's blocking this one. - * @param blockedVersion The version of the database being blocked (whatever version you provided to `openDB`). - * @param event The event object for the associated `blocked` event. - */ - blocked?( - currentVersion: number, - blockedVersion: number | null, - event: IDBVersionChangeEvent, - ): void; - /** - * Called if this connection is blocking a future version of the database from opening. - * - * @param currentVersion Version of the open database (whatever version you provided to `openDB`). - * @param blockedVersion The version of the database that's being blocked. - * @param event The event object for the associated `versionchange` event. - */ - blocking?( - currentVersion: number, - blockedVersion: number | null, - event: IDBVersionChangeEvent, - ): void; - /** - * Called if the browser abnormally terminates the connection. - * This is not called when `db.close()` is called. - */ - terminated?(): void; -} - -/** - * Open a database. - * - * @param name Name of the database. - * @param version Schema version. - * @param callbacks Additional callbacks. - */ -export function openDB( - name: string, - version?: number, - { blocked, upgrade, blocking, terminated }: OpenDBCallbacks = {}, -): Promise> { - const request = indexedDB.open(name, version); - const openPromise = wrap(request) as Promise>; - - if (upgrade) { - request.addEventListener("upgradeneeded", event => { - upgrade( - wrap(request.result) as IDBPDatabase, - event.oldVersion, - event.newVersion, - wrap(request.transaction!) as unknown as IDBPTransaction< - DBTypes, - StoreNames[], - "versionchange" - >, - event, - ); - }); - } - - if (blocked) { - request.addEventListener("blocked", event => - blocked( - // Casting due to https://github.com/microsoft/TypeScript-DOM-lib-generator/pull/1405 - (event as IDBVersionChangeEvent).oldVersion, - (event as IDBVersionChangeEvent).newVersion, - event as IDBVersionChangeEvent, - ), - ); - } - - openPromise - .then(db => { - if (terminated) db.addEventListener("close", () => terminated()); - if (blocking) { - db.addEventListener("versionchange", event => - blocking(event.oldVersion, event.newVersion, event), - ); - } - }) - .catch(() => { }); - - return openPromise; -} - -export interface DeleteDBCallbacks { - /** - * Called if there are connections to this database open, so it cannot be deleted. - * - * @param currentVersion Version of the database that's blocking the delete operation. - * @param event The event object for the associated `blocked` event. - */ - blocked?(currentVersion: number, event: IDBVersionChangeEvent): void; -} - -/** - * Delete a database. - * - * @param name Name of the database. - */ -export function deleteDB( - name: string, - { blocked }: DeleteDBCallbacks = {}, -): Promise { - const request = indexedDB.deleteDatabase(name); - - if (blocked) { - request.addEventListener("blocked", event => - blocked( - // Casting due to https://github.com/microsoft/TypeScript-DOM-lib-generator/pull/1405 - (event as IDBVersionChangeEvent).oldVersion, - event as IDBVersionChangeEvent, - ), - ); - } - - return wrap(request).then(() => undefined); -} - -export { unwrap, wrap } from "./wrap-idb-value.js"; - -// === The rest of this file is type defs === -type KeyToKeyNoIndex = { - [K in keyof T]: string extends K ? never : number extends K ? never : K; -}; -type ValuesOf = T extends { [K in keyof T]: infer U } ? U : never; -type KnownKeys = ValuesOf>; - -type Omit = Pick>; - -export interface DBSchema { - [s: string]: DBSchemaValue; -} - -interface IndexKeys { - [s: string]: IDBValidKey; -} - -interface DBSchemaValue { - key: IDBValidKey; - value: any; - indexes?: IndexKeys; -} - -/** - * Extract known object store names from the DB schema type. - * - * @template DBTypes DB schema type, or unknown if the DB isn't typed. - */ -export type StoreNames = - DBTypes extends DBSchema ? KnownKeys : string; - -/** - * Extract database value types from the DB schema type. - * - * @template DBTypes DB schema type, or unknown if the DB isn't typed. - * @template StoreName Names of the object stores to get the types of. - */ -export type StoreValue< - DBTypes extends DBSchema | unknown, - StoreName extends StoreNames, -> = DBTypes extends DBSchema ? DBTypes[StoreName]["value"] : any; - -/** - * Extract database key types from the DB schema type. - * - * @template DBTypes DB schema type, or unknown if the DB isn't typed. - * @template StoreName Names of the object stores to get the types of. - */ -export type StoreKey< - DBTypes extends DBSchema | unknown, - StoreName extends StoreNames, -> = DBTypes extends DBSchema ? DBTypes[StoreName]["key"] : IDBValidKey; - -/** - * Extract the names of indexes in certain object stores from the DB schema type. - * - * @template DBTypes DB schema type, or unknown if the DB isn't typed. - * @template StoreName Names of the object stores to get the types of. - */ -export type IndexNames< - DBTypes extends DBSchema | unknown, - StoreName extends StoreNames, -> = DBTypes extends DBSchema ? keyof DBTypes[StoreName]["indexes"] : string; - -/** - * Extract the types of indexes in certain object stores from the DB schema type. - * - * @template DBTypes DB schema type, or unknown if the DB isn't typed. - * @template StoreName Names of the object stores to get the types of. - * @template IndexName Names of the indexes to get the types of. - */ -export type IndexKey< - DBTypes extends DBSchema | unknown, - StoreName extends StoreNames, - IndexName extends IndexNames, -> = DBTypes extends DBSchema - ? IndexName extends keyof DBTypes[StoreName]["indexes"] - ? DBTypes[StoreName]["indexes"][IndexName] - : IDBValidKey - : IDBValidKey; - -type CursorSource< - DBTypes extends DBSchema | unknown, - TxStores extends ArrayLike>, - StoreName extends StoreNames, - IndexName extends IndexNames | unknown, - Mode extends IDBTransactionMode = "readonly", -> = IndexName extends IndexNames - ? IDBPIndex - : IDBPObjectStore; - -type CursorKey< - DBTypes extends DBSchema | unknown, - StoreName extends StoreNames, - IndexName extends IndexNames | unknown, -> = IndexName extends IndexNames - ? IndexKey - : StoreKey; - -type IDBPDatabaseExtends = Omit< - IDBDatabase, - "createObjectStore" | "deleteObjectStore" | "transaction" | "objectStoreNames" ->; - -/** - * A variation of DOMStringList with precise string types - */ -export interface TypedDOMStringList extends DOMStringList { - contains(string: T): boolean; - item(index: number): T | null; - [index: number]: T; - [Symbol.iterator](): ArrayIterator; -} - -interface IDBTransactionOptions { - /** - * The durability of the transaction. - * - * The default is "default". Using "relaxed" provides better performance, but with fewer - * guarantees. Web applications are encouraged to use "relaxed" for ephemeral data such as caches - * or quickly changing records, and "strict" in cases where reducing the risk of data loss - * outweighs the impact to performance and power. - */ - durability?: "default" | "strict" | "relaxed"; -} - -export interface IDBPDatabase - extends IDBPDatabaseExtends { - /** - * The names of stores in the database. - */ - readonly objectStoreNames: TypedDOMStringList>; - /** - * Creates a new object store. - * - * Throws a "InvalidStateError" DOMException if not called within an upgrade transaction. - */ - createObjectStore>( - name: Name, - optionalParameters?: IDBObjectStoreParameters, - ): IDBPObjectStore< - DBTypes, - ArrayLike>, - Name, - "versionchange" - >; - /** - * Deletes the object store with the given name. - * - * Throws a "InvalidStateError" DOMException if not called within an upgrade transaction. - */ - deleteObjectStore(name: StoreNames): void; - /** - * Start a new transaction. - * - * @param storeNames The object store(s) this transaction needs. - * @param mode - * @param options - */ - transaction< - Name extends StoreNames, - Mode extends IDBTransactionMode = "readonly", - >( - storeNames: Name, - mode?: Mode, - options?: IDBTransactionOptions, - ): IDBPTransaction; - transaction< - Names extends ArrayLike>, - Mode extends IDBTransactionMode = "readonly", - >( - storeNames: Names, - mode?: Mode, - options?: IDBTransactionOptions, - ): IDBPTransaction; - - // Shortcut methods - - /** - * Add a value to a store. - * - * Rejects if an item of a given key already exists in the store. - * - * This is a shortcut that creates a transaction for this single action. If you need to do more - * than one action, create a transaction instead. - * - * @param storeName Name of the store. - * @param value - * @param key - */ - add>( - storeName: Name, - value: StoreValue, - key?: StoreKey | IDBKeyRange, - ): Promise>; - /** - * Deletes all records in a store. - * - * This is a shortcut that creates a transaction for this single action. If you need to do more - * than one action, create a transaction instead. - * - * @param storeName Name of the store. - */ - clear(name: StoreNames): Promise; - /** - * Retrieves the number of records matching the given query in a store. - * - * This is a shortcut that creates a transaction for this single action. If you need to do more - * than one action, create a transaction instead. - * - * @param storeName Name of the store. - * @param key - */ - count>( - storeName: Name, - key?: StoreKey | IDBKeyRange | null, - ): Promise; - /** - * Retrieves the number of records matching the given query in an index. - * - * This is a shortcut that creates a transaction for this single action. If you need to do more - * than one action, create a transaction instead. - * - * @param storeName Name of the store. - * @param indexName Name of the index within the store. - * @param key - */ - countFromIndex< - Name extends StoreNames, - IndexName extends IndexNames, - >( - storeName: Name, - indexName: IndexName, - key?: IndexKey | IDBKeyRange | null, - ): Promise; - /** - * Deletes records in a store matching the given query. - * - * This is a shortcut that creates a transaction for this single action. If you need to do more - * than one action, create a transaction instead. - * - * @param storeName Name of the store. - * @param key - */ - delete>( - storeName: Name, - key: StoreKey | IDBKeyRange, - ): Promise; - /** - * Retrieves the value of the first record in a store matching the query. - * - * Resolves with undefined if no match is found. - * - * This is a shortcut that creates a transaction for this single action. If you need to do more - * than one action, create a transaction instead. - * - * @param storeName Name of the store. - * @param query - */ - get>( - storeName: Name, - query: StoreKey | IDBKeyRange, - ): Promise | undefined>; - /** - * Retrieves the value of the first record in an index matching the query. - * - * Resolves with undefined if no match is found. - * - * This is a shortcut that creates a transaction for this single action. If you need to do more - * than one action, create a transaction instead. - * - * @param storeName Name of the store. - * @param indexName Name of the index within the store. - * @param query - */ - getFromIndex< - Name extends StoreNames, - IndexName extends IndexNames, - >( - storeName: Name, - indexName: IndexName, - query: IndexKey | IDBKeyRange, - ): Promise | undefined>; - /** - * Retrieves all values in a store that match the query. - * - * This is a shortcut that creates a transaction for this single action. If you need to do more - * than one action, create a transaction instead. - * - * @param storeName Name of the store. - * @param query - * @param count Maximum number of values to return. - */ - getAll>( - storeName: Name, - query?: StoreKey | IDBKeyRange | null, - count?: number, - ): Promise[]>; - /** - * Retrieves all values in an index that match the query. - * - * This is a shortcut that creates a transaction for this single action. If you need to do more - * than one action, create a transaction instead. - * - * @param storeName Name of the store. - * @param indexName Name of the index within the store. - * @param query - * @param count Maximum number of values to return. - */ - getAllFromIndex< - Name extends StoreNames, - IndexName extends IndexNames, - >( - storeName: Name, - indexName: IndexName, - query?: IndexKey | IDBKeyRange | null, - count?: number, - ): Promise[]>; - /** - * Retrieves the keys of records in a store matching the query. - * - * This is a shortcut that creates a transaction for this single action. If you need to do more - * than one action, create a transaction instead. - * - * @param storeName Name of the store. - * @param query - * @param count Maximum number of keys to return. - */ - getAllKeys>( - storeName: Name, - query?: StoreKey | IDBKeyRange | null, - count?: number, - ): Promise[]>; - /** - * Retrieves the keys of records in an index matching the query. - * - * This is a shortcut that creates a transaction for this single action. If you need to do more - * than one action, create a transaction instead. - * - * @param storeName Name of the store. - * @param indexName Name of the index within the store. - * @param query - * @param count Maximum number of keys to return. - */ - getAllKeysFromIndex< - Name extends StoreNames, - IndexName extends IndexNames, - >( - storeName: Name, - indexName: IndexName, - query?: IndexKey | IDBKeyRange | null, - count?: number, - ): Promise[]>; - /** - * Retrieves the key of the first record in a store that matches the query. - * - * Resolves with undefined if no match is found. - * - * This is a shortcut that creates a transaction for this single action. If you need to do more - * than one action, create a transaction instead. - * - * @param storeName Name of the store. - * @param query - */ - getKey>( - storeName: Name, - query: StoreKey | IDBKeyRange, - ): Promise | undefined>; - /** - * Retrieves the key of the first record in an index that matches the query. - * - * Resolves with undefined if no match is found. - * - * This is a shortcut that creates a transaction for this single action. If you need to do more - * than one action, create a transaction instead. - * - * @param storeName Name of the store. - * @param indexName Name of the index within the store. - * @param query - */ - getKeyFromIndex< - Name extends StoreNames, - IndexName extends IndexNames, - >( - storeName: Name, - indexName: IndexName, - query: IndexKey | IDBKeyRange, - ): Promise | undefined>; - /** - * Put an item in the database. - * - * Replaces any item with the same key. - * - * This is a shortcut that creates a transaction for this single action. If you need to do more - * than one action, create a transaction instead. - * - * @param storeName Name of the store. - * @param value - * @param key - */ - put>( - storeName: Name, - value: StoreValue, - key?: StoreKey | IDBKeyRange, - ): Promise>; -} - -type IDBPTransactionExtends = Omit< - IDBTransaction, - "db" | "objectStore" | "objectStoreNames" ->; - -export interface IDBPTransaction< - DBTypes extends DBSchema | unknown = unknown, - TxStores extends ArrayLike> = ArrayLike< - StoreNames - >, - Mode extends IDBTransactionMode = "readonly", -> extends IDBPTransactionExtends { - /** - * The transaction's mode. - */ - readonly mode: Mode; - /** - * The names of stores in scope for this transaction. - */ - readonly objectStoreNames: TypedDOMStringList; - /** - * The transaction's connection. - */ - readonly db: IDBPDatabase; - /** - * Promise for the completion of this transaction. - */ - readonly done: Promise; - /** - * The associated object store, if the transaction covers a single store, otherwise undefined. - */ - readonly store: TxStores[1] extends undefined - ? IDBPObjectStore - : undefined; - /** - * Returns an IDBObjectStore in the transaction's scope. - */ - objectStore( - name: StoreName, - ): IDBPObjectStore; -} - -type IDBPObjectStoreExtends = Omit< - IDBObjectStore, - | "transaction" - | "add" - | "clear" - | "count" - | "createIndex" - | "delete" - | "get" - | "getAll" - | "getAllKeys" - | "getKey" - | "index" - | "openCursor" - | "openKeyCursor" - | "put" - | "indexNames" ->; - -export interface IDBPObjectStore< - DBTypes extends DBSchema | unknown = unknown, - TxStores extends ArrayLike> = ArrayLike< - StoreNames - >, - StoreName extends StoreNames = StoreNames, - Mode extends IDBTransactionMode = "readonly", -> extends IDBPObjectStoreExtends { - /** - * The names of indexes in the store. - */ - readonly indexNames: TypedDOMStringList>; - /** - * The associated transaction. - */ - readonly transaction: IDBPTransaction; - /** - * Add a value to the store. - * - * Rejects if an item of a given key already exists in the store. - */ - add: Mode extends "readonly" - ? undefined - : ( - value: StoreValue, - key?: StoreKey | IDBKeyRange, - ) => Promise>; - /** - * Deletes all records in store. - */ - clear: Mode extends "readonly" ? undefined : () => Promise; - /** - * Retrieves the number of records matching the given query. - */ - count( - key?: StoreKey | IDBKeyRange | null, - ): Promise; - /** - * Creates a new index in store. - * - * Throws an "InvalidStateError" DOMException if not called within an upgrade transaction. - */ - createIndex: Mode extends "versionchange" - ? >( - name: IndexName, - keyPath: string | string[], - options?: IDBIndexParameters, - ) => IDBPIndex - : undefined; - /** - * Deletes records in store matching the given query. - */ - delete: Mode extends "readonly" - ? undefined - : (key: StoreKey | IDBKeyRange) => Promise; - /** - * Retrieves the value of the first record matching the query. - * - * Resolves with undefined if no match is found. - */ - get( - query: StoreKey | IDBKeyRange, - ): Promise | undefined>; - /** - * Retrieves all values that match the query. - * - * @param query - * @param count Maximum number of values to return. - */ - getAll( - query?: StoreKey | IDBKeyRange | null, - count?: number, - ): Promise[]>; - /** - * Retrieves the keys of records matching the query. - * - * @param query - * @param count Maximum number of keys to return. - */ - getAllKeys( - query?: StoreKey | IDBKeyRange | null, - count?: number, - ): Promise[]>; - /** - * Retrieves the key of the first record that matches the query. - * - * Resolves with undefined if no match is found. - */ - getKey( - query: StoreKey | IDBKeyRange, - ): Promise | undefined>; - /** - * Get a query of a given name. - */ - index>( - name: IndexName, - ): IDBPIndex; - /** - * Opens a cursor over the records matching the query. - * - * Resolves with null if no matches are found. - * - * @param query If null, all records match. - * @param direction - */ - openCursor( - query?: StoreKey | IDBKeyRange | null, - direction?: IDBCursorDirection, - ): Promise | null>; - /** - * Opens a cursor over the keys matching the query. - * - * Resolves with null if no matches are found. - * - * @param query If null, all records match. - * @param direction - */ - openKeyCursor( - query?: StoreKey | IDBKeyRange | null, - direction?: IDBCursorDirection, - ): Promise | null>; - /** - * Put an item in the store. - * - * Replaces any item with the same key. - */ - put: Mode extends "readonly" - ? undefined - : ( - value: StoreValue, - key?: StoreKey | IDBKeyRange, - ) => Promise>; - /** - * Iterate over the store. - */ - [Symbol.asyncIterator](): AsyncIterableIterator< - IDBPCursorWithValueIteratorValue< - DBTypes, - TxStores, - StoreName, - unknown, - Mode - > - >; - /** - * Iterate over the records matching the query. - * - * @param query If null, all records match. - * @param direction - */ - iterate( - query?: StoreKey | IDBKeyRange | null, - direction?: IDBCursorDirection, - ): AsyncIterableIterator< - IDBPCursorWithValueIteratorValue< - DBTypes, - TxStores, - StoreName, - unknown, - Mode - > - >; -} - -type IDBPIndexExtends = Omit< - IDBIndex, - | "objectStore" - | "count" - | "get" - | "getAll" - | "getAllKeys" - | "getKey" - | "openCursor" - | "openKeyCursor" ->; - -export interface IDBPIndex< - DBTypes extends DBSchema | unknown = unknown, - TxStores extends ArrayLike> = ArrayLike< - StoreNames - >, - StoreName extends StoreNames = StoreNames, - IndexName extends IndexNames = IndexNames< - DBTypes, - StoreName - >, - Mode extends IDBTransactionMode = "readonly", -> extends IDBPIndexExtends { - /** - * The IDBObjectStore the index belongs to. - */ - readonly objectStore: IDBPObjectStore; - - /** - * Retrieves the number of records matching the given query. - */ - count( - key?: IndexKey | IDBKeyRange | null, - ): Promise; - /** - * Retrieves the value of the first record matching the query. - * - * Resolves with undefined if no match is found. - */ - get( - query: IndexKey | IDBKeyRange, - ): Promise | undefined>; - /** - * Retrieves all values that match the query. - * - * @param query - * @param count Maximum number of values to return. - */ - getAll( - query?: IndexKey | IDBKeyRange | null, - count?: number, - ): Promise[]>; - /** - * Retrieves the keys of records matching the query. - * - * @param query - * @param count Maximum number of keys to return. - */ - getAllKeys( - query?: IndexKey | IDBKeyRange | null, - count?: number, - ): Promise[]>; - /** - * Retrieves the key of the first record that matches the query. - * - * Resolves with undefined if no match is found. - */ - getKey( - query: IndexKey | IDBKeyRange, - ): Promise | undefined>; - /** - * Opens a cursor over the records matching the query. - * - * Resolves with null if no matches are found. - * - * @param query If null, all records match. - * @param direction - */ - openCursor( - query?: IndexKey | IDBKeyRange | null, - direction?: IDBCursorDirection, - ): Promise | null>; - /** - * Opens a cursor over the keys matching the query. - * - * Resolves with null if no matches are found. - * - * @param query If null, all records match. - * @param direction - */ - openKeyCursor( - query?: IndexKey | IDBKeyRange | null, - direction?: IDBCursorDirection, - ): Promise | null>; - /** - * Iterate over the index. - */ - [Symbol.asyncIterator](): AsyncIterableIterator< - IDBPCursorWithValueIteratorValue< - DBTypes, - TxStores, - StoreName, - IndexName, - Mode - > - >; - /** - * Iterate over the records matching the query. - * - * Resolves with null if no matches are found. - * - * @param query If null, all records match. - * @param direction - */ - iterate( - query?: IndexKey | IDBKeyRange | null, - direction?: IDBCursorDirection, - ): AsyncIterableIterator< - IDBPCursorWithValueIteratorValue< - DBTypes, - TxStores, - StoreName, - IndexName, - Mode - > - >; -} - -type IDBPCursorExtends = Omit< - IDBCursor, - | "key" - | "primaryKey" - | "source" - | "advance" - | "continue" - | "continuePrimaryKey" - | "delete" - | "update" ->; - -export interface IDBPCursor< - DBTypes extends DBSchema | unknown = unknown, - TxStores extends ArrayLike> = ArrayLike< - StoreNames - >, - StoreName extends StoreNames = StoreNames, - IndexName extends IndexNames | unknown = unknown, - Mode extends IDBTransactionMode = "readonly", -> extends IDBPCursorExtends { - /** - * The key of the current index or object store item. - */ - readonly key: CursorKey; - /** - * The key of the current object store item. - */ - readonly primaryKey: StoreKey; - /** - * Returns the IDBObjectStore or IDBIndex the cursor was opened from. - */ - readonly source: CursorSource; - /** - * Advances the cursor a given number of records. - * - * Resolves to null if no matching records remain. - */ - advance(this: T, count: number): Promise; - /** - * Advance the cursor by one record (unless 'key' is provided). - * - * Resolves to null if no matching records remain. - * - * @param key Advance to the index or object store with a key equal to or greater than this value. - */ - continue( - this: T, - key?: CursorKey, - ): Promise; - /** - * Advance the cursor by given keys. - * - * The operation is 'and' – both keys must be satisfied. - * - * Resolves to null if no matching records remain. - * - * @param key Advance to the index or object store with a key equal to or greater than this value. - * @param primaryKey and where the object store has a key equal to or greater than this value. - */ - continuePrimaryKey( - this: T, - key: CursorKey, - primaryKey: StoreKey, - ): Promise; - /** - * Delete the current record. - */ - delete: Mode extends "readonly" ? undefined : () => Promise; - /** - * Updated the current record. - */ - update: Mode extends "readonly" - ? undefined - : ( - value: StoreValue, - ) => Promise>; - /** - * Iterate over the cursor. - */ - [Symbol.asyncIterator](): AsyncIterableIterator< - IDBPCursorIteratorValue - >; -} - -type IDBPCursorIteratorValueExtends< - DBTypes extends DBSchema | unknown = unknown, - TxStores extends ArrayLike> = ArrayLike< - StoreNames - >, - StoreName extends StoreNames = StoreNames, - IndexName extends IndexNames | unknown = unknown, - Mode extends IDBTransactionMode = "readonly", -> = Omit< - IDBPCursor, - "advance" | "continue" | "continuePrimaryKey" ->; - -export interface IDBPCursorIteratorValue< - DBTypes extends DBSchema | unknown = unknown, - TxStores extends ArrayLike> = ArrayLike< - StoreNames - >, - StoreName extends StoreNames = StoreNames, - IndexName extends IndexNames | unknown = unknown, - Mode extends IDBTransactionMode = "readonly", -> extends IDBPCursorIteratorValueExtends< - DBTypes, - TxStores, - StoreName, - IndexName, - Mode -> { - /** - * Advances the cursor a given number of records. - */ - advance(this: T, count: number): void; - /** - * Advance the cursor by one record (unless 'key' is provided). - * - * @param key Advance to the index or object store with a key equal to or greater than this value. - */ - continue(this: T, key?: CursorKey): void; - /** - * Advance the cursor by given keys. - * - * The operation is 'and' – both keys must be satisfied. - * - * @param key Advance to the index or object store with a key equal to or greater than this value. - * @param primaryKey and where the object store has a key equal to or greater than this value. - */ - continuePrimaryKey( - this: T, - key: CursorKey, - primaryKey: StoreKey, - ): void; -} - -export interface IDBPCursorWithValue< - DBTypes extends DBSchema | unknown = unknown, - TxStores extends ArrayLike> = ArrayLike< - StoreNames - >, - StoreName extends StoreNames = StoreNames, - IndexName extends IndexNames | unknown = unknown, - Mode extends IDBTransactionMode = "readonly", -> extends IDBPCursor { - /** - * The value of the current item. - */ - readonly value: StoreValue; - /** - * Iterate over the cursor. - */ - [Symbol.asyncIterator](): AsyncIterableIterator< - IDBPCursorWithValueIteratorValue< - DBTypes, - TxStores, - StoreName, - IndexName, - Mode - > - >; -} - -// Some of that sweeeeet Java-esque naming. -type IDBPCursorWithValueIteratorValueExtends< - DBTypes extends DBSchema | unknown = unknown, - TxStores extends ArrayLike> = ArrayLike< - StoreNames - >, - StoreName extends StoreNames = StoreNames, - IndexName extends IndexNames | unknown = unknown, - Mode extends IDBTransactionMode = "readonly", -> = Omit< - IDBPCursorWithValue, - "advance" | "continue" | "continuePrimaryKey" ->; - -export interface IDBPCursorWithValueIteratorValue< - DBTypes extends DBSchema | unknown = unknown, - TxStores extends ArrayLike> = ArrayLike< - StoreNames - >, - StoreName extends StoreNames = StoreNames, - IndexName extends IndexNames | unknown = unknown, - Mode extends IDBTransactionMode = "readonly", -> extends IDBPCursorWithValueIteratorValueExtends< - DBTypes, - TxStores, - StoreName, - IndexName, - Mode -> { - /** - * Advances the cursor a given number of records. - */ - advance(this: T, count: number): void; - /** - * Advance the cursor by one record (unless 'key' is provided). - * - * @param key Advance to the index or object store with a key equal to or greater than this value. - */ - continue(this: T, key?: CursorKey): void; - /** - * Advance the cursor by given keys. - * - * The operation is 'and' – both keys must be satisfied. - * - * @param key Advance to the index or object store with a key equal to or greater than this value. - * @param primaryKey and where the object store has a key equal to or greater than this value. - */ - continuePrimaryKey( - this: T, - key: CursorKey, - primaryKey: StoreKey, - ): void; -} diff --git a/src/equicordplugins/messageLoggerEnhanced/utils/idb/index.ts b/src/equicordplugins/messageLoggerEnhanced/utils/idb/index.ts deleted file mode 100644 index 4bc654a1..00000000 --- a/src/equicordplugins/messageLoggerEnhanced/utils/idb/index.ts +++ /dev/null @@ -1,5 +0,0 @@ -/* eslint-disable simple-header/header */ - -export * from "./entry.js"; -import "./database-extras.js"; -import "./async-iterators.js"; diff --git a/src/equicordplugins/messageLoggerEnhanced/utils/idb/util.ts b/src/equicordplugins/messageLoggerEnhanced/utils/idb/util.ts deleted file mode 100644 index 5de6907f..00000000 --- a/src/equicordplugins/messageLoggerEnhanced/utils/idb/util.ts +++ /dev/null @@ -1,9 +0,0 @@ -/* eslint-disable simple-header/header */ - -export type Constructor = new (...args: any[]) => any; -export type Func = (...args: any[]) => any; - -export const instanceOfAny = ( - object: any, - constructors: Constructor[], -): boolean => constructors.some(c => object instanceof c); diff --git a/src/equicordplugins/messageLoggerEnhanced/utils/idb/wrap-idb-value.ts b/src/equicordplugins/messageLoggerEnhanced/utils/idb/wrap-idb-value.ts deleted file mode 100644 index 748b0ae5..00000000 --- a/src/equicordplugins/messageLoggerEnhanced/utils/idb/wrap-idb-value.ts +++ /dev/null @@ -1,227 +0,0 @@ -/* eslint-disable simple-header/header */ - -import { - IDBPCursor, - IDBPCursorWithValue, - IDBPDatabase, - IDBPIndex, - IDBPObjectStore, - IDBPTransaction, -} from "./entry.js"; -import { Constructor, Func, instanceOfAny } from "./util.js"; - -let idbProxyableTypes: Constructor[]; -let cursorAdvanceMethods: Func[]; - -// This is a function to prevent it throwing up in node environments. -function getIdbProxyableTypes(): Constructor[] { - return ( - idbProxyableTypes || - (idbProxyableTypes = [ - IDBDatabase, - IDBObjectStore, - IDBIndex, - IDBCursor, - IDBTransaction, - ]) - ); -} - -// This is a function to prevent it throwing up in node environments. -function getCursorAdvanceMethods(): Func[] { - return ( - cursorAdvanceMethods || - (cursorAdvanceMethods = [ - IDBCursor.prototype.advance, - IDBCursor.prototype.continue, - IDBCursor.prototype.continuePrimaryKey, - ]) - ); -} - -const transactionDoneMap: WeakMap< - IDBTransaction, - Promise -> = new WeakMap(); -const transformCache = new WeakMap(); -export const reverseTransformCache = new WeakMap(); - -function promisifyRequest(request: IDBRequest): Promise { - const promise = new Promise((resolve, reject) => { - const unlisten = () => { - request.removeEventListener("success", success); - request.removeEventListener("error", error); - }; - const success = () => { - resolve(wrap(request.result as any) as any); - unlisten(); - }; - const error = () => { - reject(request.error); - unlisten(); - }; - request.addEventListener("success", success); - request.addEventListener("error", error); - }); - - // This mapping exists in reverseTransformCache but doesn't doesn't exist in transformCache. This - // is because we create many promises from a single IDBRequest. - reverseTransformCache.set(promise, request); - return promise; -} - -function cacheDonePromiseForTransaction(tx: IDBTransaction): void { - // Early bail if we've already created a done promise for this transaction. - if (transactionDoneMap.has(tx)) return; - - const done = new Promise((resolve, reject) => { - const unlisten = () => { - tx.removeEventListener("complete", complete); - tx.removeEventListener("error", error); - tx.removeEventListener("abort", error); - }; - const complete = () => { - resolve(); - unlisten(); - }; - const error = () => { - reject(tx.error || new DOMException("AbortError", "AbortError")); - unlisten(); - }; - tx.addEventListener("complete", complete); - tx.addEventListener("error", error); - tx.addEventListener("abort", error); - }); - - // Cache it for later retrieval. - transactionDoneMap.set(tx, done); -} - -let idbProxyTraps: ProxyHandler = { - get(target, prop, receiver) { - if (target instanceof IDBTransaction) { - // Special handling for transaction.done. - if (prop === "done") return transactionDoneMap.get(target); - // Make tx.store return the only store in the transaction, or undefined if there are many. - if (prop === "store") { - return receiver.objectStoreNames[1] - ? undefined - : receiver.objectStore(receiver.objectStoreNames[0]); - } - } - // Else transform whatever we get back. - return wrap(target[prop]); - }, - set(target, prop, value) { - target[prop] = value; - return true; - }, - has(target, prop) { - if ( - target instanceof IDBTransaction && - (prop === "done" || prop === "store") - ) { - return true; - } - return prop in target; - }, -}; - -export function replaceTraps( - callback: (currentTraps: ProxyHandler) => ProxyHandler, -): void { - idbProxyTraps = callback(idbProxyTraps); -} - -function wrapFunction(func: T): Function { - // Due to expected object equality (which is enforced by the caching in `wrap`), we - // only create one new func per func. - - // Cursor methods are special, as the behaviour is a little more different to standard IDB. In - // IDB, you advance the cursor and wait for a new 'success' on the IDBRequest that gave you the - // cursor. It's kinda like a promise that can resolve with many values. That doesn't make sense - // with real promises, so each advance methods returns a new promise for the cursor object, or - // undefined if the end of the cursor has been reached. - if (getCursorAdvanceMethods().includes(func)) { - return function (this: IDBPCursor, ...args: Parameters) { - // Calling the original function with the proxy as 'this' causes ILLEGAL INVOCATION, so we use - // the original object. - func.apply(unwrap(this), args); - return wrap(this.request); - }; - } - - return function (this: any, ...args: Parameters) { - // Calling the original function with the proxy as 'this' causes ILLEGAL INVOCATION, so we use - // the original object. - return wrap(func.apply(unwrap(this), args)); - }; -} - -function transformCachableValue(value: any): any { - if (typeof value === "function") return wrapFunction(value); - - // This doesn't return, it just creates a 'done' promise for the transaction, - // which is later returned for transaction.done (see idbObjectHandler). - if (value instanceof IDBTransaction) cacheDonePromiseForTransaction(value); - - if (instanceOfAny(value, getIdbProxyableTypes())) - return new Proxy(value, idbProxyTraps); - - // Return the same value back if we're not going to transform it. - return value; -} - -/** - * Enhance an IDB object with helpers. - * - * @param value The thing to enhance. - */ -export function wrap(value: IDBDatabase): IDBPDatabase; -export function wrap(value: IDBIndex): IDBPIndex; -export function wrap(value: IDBObjectStore): IDBPObjectStore; -export function wrap(value: IDBTransaction): IDBPTransaction; -export function wrap( - value: IDBOpenDBRequest, -): Promise; -export function wrap(value: IDBRequest): Promise; -export function wrap(value: any): any { - // We sometimes generate multiple promises from a single IDBRequest (eg when cursoring), because - // IDB is weird and a single IDBRequest can yield many responses, so these can't be cached. - if (value instanceof IDBRequest) return promisifyRequest(value); - - // If we've already transformed this value before, reuse the transformed value. - // This is faster, but it also provides object equality. - if (transformCache.has(value)) return transformCache.get(value); - const newValue = transformCachableValue(value); - - // Not all types are transformed. - // These may be primitive types, so they can't be WeakMap keys. - if (newValue !== value) { - transformCache.set(value, newValue); - reverseTransformCache.set(newValue, value); - } - - return newValue; -} - -/** - * Revert an enhanced IDB object to a plain old miserable IDB one. - * - * Will also revert a promise back to an IDBRequest. - * - * @param value The enhanced object to revert. - */ -interface Unwrap { - (value: IDBPCursorWithValue): IDBCursorWithValue; - (value: IDBPCursor): IDBCursor; - (value: IDBPDatabase): IDBDatabase; - (value: IDBPIndex): IDBIndex; - (value: IDBPObjectStore): IDBObjectStore; - (value: IDBPTransaction): IDBTransaction; - (value: Promise>): IDBOpenDBRequest; - (value: Promise): IDBOpenDBRequest; - (value: Promise): IDBRequest; -} -export const unwrap: Unwrap = (value: any): any => - reverseTransformCache.get(value); diff --git a/src/equicordplugins/messageLoggerEnhanced/utils/saveImage/ImageManager.ts b/src/equicordplugins/messageLoggerEnhanced/utils/saveImage/ImageManager.ts index 97ecf273..a271e51e 100644 --- a/src/equicordplugins/messageLoggerEnhanced/utils/saveImage/ImageManager.ts +++ b/src/equicordplugins/messageLoggerEnhanced/utils/saveImage/ImageManager.ts @@ -24,9 +24,9 @@ import { set, } from "@api/DataStore"; import { sleep } from "@utils/misc"; -import { LoggedAttachment } from "userplugins/vc-message-logger-enhanced/types"; import { Flogger, Native } from "../.."; +import { LoggedAttachment } from "../../types"; import { DEFAULT_IMAGE_CACHE_DIR } from "../constants"; const ImageStore = createStore("MessageLoggerImageData", "MessageLoggerImageStore");