Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

@uppy/golden-retriever: migrate to TS #4989

Merged
merged 5 commits into from
Mar 18, 2024
Merged
Show file tree
Hide file tree
Changes from 4 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions packages/@uppy/core/src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,10 +2,11 @@
export {
default as Uppy,
type State,
type UploadResult,

Check failure on line 5 in packages/@uppy/core/src/index.ts

View workflow job for this annotation

GitHub Actions / Lint JavaScript/TypeScript

Multiple exports of name 'UploadResult'

Check failure on line 5 in packages/@uppy/core/src/index.ts

View workflow job for this annotation

GitHub Actions / Type tests

Duplicate identifier 'UploadResult'.

Check failure on line 5 in packages/@uppy/core/src/index.ts

View workflow job for this annotation

GitHub Actions / Type tests

Duplicate identifier 'UploadResult'.
aduh95 marked this conversation as resolved.
Show resolved Hide resolved
type UnknownPlugin,
type UnknownProviderPlugin,
type UnknownSearchProviderPlugin,
type UploadResult,

Check failure on line 9 in packages/@uppy/core/src/index.ts

View workflow job for this annotation

GitHub Actions / Lint JavaScript/TypeScript

Multiple exports of name 'UploadResult'

Check failure on line 9 in packages/@uppy/core/src/index.ts

View workflow job for this annotation

GitHub Actions / Type tests

Duplicate identifier 'UploadResult'.

Check failure on line 9 in packages/@uppy/core/src/index.ts

View workflow job for this annotation

GitHub Actions / Type tests

Duplicate identifier 'UploadResult'.
type UppyEventMap,
} from './Uppy.ts'
export { default as UIPlugin } from './UIPlugin.ts'
Expand Down
1 change: 1 addition & 0 deletions packages/@uppy/golden-retriever/.npmignore
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
tsconfig.*
Original file line number Diff line number Diff line change
@@ -1,8 +1,16 @@
/**
* @type {typeof window.indexedDB}
*/
const indexedDB = typeof window !== 'undefined'
&& (window.indexedDB || window.webkitIndexedDB || window.mozIndexedDB || window.OIndexedDB || window.msIndexedDB)
import type { UppyFile } from '@uppy/utils/lib/UppyFile'

const indexedDB =
typeof window !== 'undefined' &&
(window.indexedDB ||
// @ts-expect-error unknown
window.webkitIndexedDB ||
// @ts-expect-error unknown
window.mozIndexedDB ||
// @ts-expect-error unknown
window.OIndexedDB ||
// @ts-expect-error unknown
window.msIndexedDB)

const isSupported = !!indexedDB

Expand All @@ -14,13 +22,11 @@ const MiB = 0x10_00_00

/**
* Set default `expires` dates on existing stored blobs.
*
* @param {IDBObjectStore} store
*/
function migrateExpiration (store) {
function migrateExpiration(store: IDBObjectStore) {
const request = store.openCursor()
request.onsuccess = (event) => {
const cursor = event.target.result
const cursor = (event.target as IDBRequest).result
if (!cursor) {
return
}
Expand All @@ -30,22 +36,14 @@ function migrateExpiration (store) {
}
}

/**
* @param {string} dbName
* @returns {Promise<IDBDatabase>}
*/
function connect (dbName) {
const request = indexedDB.open(dbName, DB_VERSION)
function connect(dbName: string): Promise<IDBDatabase> {
const request = (indexedDB as IDBFactory).open(dbName, DB_VERSION)
return new Promise((resolve, reject) => {
request.onupgradeneeded = (event) => {
/**
* @type {IDBDatabase}
*/
const db = event.target.result
/**
* @type {IDBTransaction}
*/
const { transaction } = event.currentTarget
const db: IDBDatabase = (event.target as IDBOpenDBRequest).result
// eslint-disable-next-line prefer-destructuring
const transaction = (event.currentTarget as IDBOpenDBRequest)
.transaction as IDBTransaction

if (event.oldVersion < 2) {
// Added in v2: DB structure changed to a single shared object store
Expand All @@ -66,34 +64,48 @@ function connect (dbName) {
}
}
request.onsuccess = (event) => {
resolve(event.target.result)
resolve((event.target as IDBRequest).result)
}
request.onerror = reject
})
}

/**
* @template T
* @param {IDBRequest<T>} request
* @returns {Promise<T>}
*/
function waitForRequest (request) {
function waitForRequest<T>(request: IDBRequest): Promise<T> {
return new Promise((resolve, reject) => {
request.onsuccess = (event) => {
resolve(event.target.result)
resolve((event.target as IDBRequest).result)
}
request.onerror = reject
})
}

type IndexedDBStoredFile = {
id: string
fileID: string
store: string
expires: number
data: Blob
}

type IndexedDBStoreOptions = {
dbName?: string
storeName?: string
expires?: number
maxFileSize?: number
maxTotalSize?: number
}

let cleanedUp = false
class IndexedDBStore {
/**
* @type {Promise<IDBDatabase> | IDBDatabase}
*/
#ready
#ready: Promise<IDBDatabase> | IDBDatabase

constructor (opts) {
opts: Required<IndexedDBStoreOptions>

name: string

static isSupported: boolean

constructor(opts?: IndexedDBStoreOptions) {
this.opts = {
dbName: DB_NAME,
storeName: 'default',
Expand All @@ -113,48 +125,50 @@ class IndexedDBStore {

if (!cleanedUp) {
cleanedUp = true
this.#ready = IndexedDBStore.cleanup()
.then(createConnection, createConnection)
this.#ready = IndexedDBStore.cleanup().then(
createConnection,
createConnection,
)
} else {
this.#ready = createConnection()
}
}

get ready () {
get ready(): Promise<IDBDatabase> {
return Promise.resolve(this.#ready)
}

// TODO: remove this setter in the next major
set ready (val) {
set ready(val: IDBDatabase) {
this.#ready = val
}

key (fileID) {
key(fileID: string): string {
return `${this.name}!${fileID}`
}

/**
* List all file blobs currently in the store.
*/
async list () {
async list(): Promise<Record<string, IndexedDBStoredFile['data']>> {
const db = await this.#ready
const transaction = db.transaction([STORE_NAME], 'readonly')
const store = transaction.objectStore(STORE_NAME)
const request = store.index('store')
.getAll(IDBKeyRange.only(this.name))
const files = await waitForRequest(request)
return Object.fromEntries(files.map(file => [file.fileID, file.data]))
const request = store.index('store').getAll(IDBKeyRange.only(this.name))
const files = await waitForRequest<IndexedDBStoredFile[]>(request)
return Object.fromEntries(files.map((file) => [file.fileID, file.data]))
}

/**
* Get one file blob from the store.
*/
async get (fileID) {
async get(fileID: string): Promise<{ id: string; data: Blob }> {
const db = await this.#ready
const transaction = db.transaction([STORE_NAME], 'readonly')
const request = transaction.objectStore(STORE_NAME)
.get(this.key(fileID))
const { data } = await waitForRequest(request)
const request = transaction.objectStore(STORE_NAME).get(this.key(fileID))
const { data } = await waitForRequest<{
data: { data: Blob; fileID: string }
}>(request)
return {
id: data.fileID,
data: data.data,
Expand All @@ -163,20 +177,16 @@ class IndexedDBStore {

/**
* Get the total size of all stored files.
*
* @private
* @returns {Promise<number>}
*/
async getSize () {
async getSize(): Promise<number> {
const db = await this.#ready
const transaction = db.transaction([STORE_NAME], 'readonly')
const store = transaction.objectStore(STORE_NAME)
const request = store.index('store')
.openCursor(IDBKeyRange.only(this.name))
const request = store.index('store').openCursor(IDBKeyRange.only(this.name))
return new Promise((resolve, reject) => {
let size = 0
request.onsuccess = (event) => {
const cursor = event.target.result
const cursor = (event.target as IDBRequest).result
if (cursor) {
size += cursor.value.data.size
cursor.continue()
Expand All @@ -193,15 +203,15 @@ class IndexedDBStore {
/**
* Save a file in the store.
*/
async put (file) {
async put<T>(file: UppyFile<any, any>): Promise<T> {
if (file.data.size > this.opts.maxFileSize) {
throw new Error('File is too big to store.')
}
const size = await this.getSize()
if (size > this.opts.maxTotalSize) {
throw new Error('No space left')
}
const db = this.#ready
const db = await this.#ready
const transaction = db.transaction([STORE_NAME], 'readwrite')
const request = transaction.objectStore(STORE_NAME).add({
id: this.key(file.id),
Expand All @@ -216,27 +226,27 @@ class IndexedDBStore {
/**
* Delete a file blob from the store.
*/
async delete (fileID) {
async delete(fileID: string): Promise<unknown> {
const db = await this.#ready
const transaction = db.transaction([STORE_NAME], 'readwrite')
const request = transaction.objectStore(STORE_NAME)
.delete(this.key(fileID))
const request = transaction.objectStore(STORE_NAME).delete(this.key(fileID))
return waitForRequest(request)
}

/**
* Delete all stored blobs that have an expiry date that is before Date.now().
* This is a static method because it deletes expired blobs from _all_ Uppy instances.
*/
static async cleanup () {
static async cleanup(): Promise<void> {
const db = await connect(DB_NAME)
const transaction = db.transaction([STORE_NAME], 'readwrite')
const store = transaction.objectStore(STORE_NAME)
const request = store.index('expires')
const request = store
.index('expires')
.openCursor(IDBKeyRange.upperBound(Date.now()))
await new Promise((resolve, reject) => {
await new Promise<void>((resolve, reject) => {
request.onsuccess = (event) => {
const cursor = event.target.result
const cursor = (event.target as IDBRequest).result
if (cursor) {
cursor.delete() // Ignoring return value … it's not terrible if this goes wrong.
cursor.continue()
Expand Down
Original file line number Diff line number Diff line change
@@ -1,11 +1,23 @@
import type { State as UppyState } from '@uppy/core'
import type { Meta, Body } from '@uppy/utils/lib/UppyFile'

export type StoredState<M extends Meta, B extends Body> = {
expires: number
metadata: {
currentUploads: UppyState<M, B>['currentUploads']
files: UppyState<M, B>['files']
pluginData: Record<string, unknown>
}
}

/**
* Get uppy instance IDs for which state is stored.
*/
function findUppyInstances () {
const instances = []
function findUppyInstances(): string[] {
const instances: string[] = []
for (let i = 0; i < localStorage.length; i++) {
const key = localStorage.key(i)
if (key.startsWith('uppyState:')) {
if (key?.startsWith('uppyState:')) {
instances.push(key.slice('uppyState:'.length))
}
}
Expand All @@ -15,17 +27,28 @@ function findUppyInstances () {
/**
* Try to JSON-parse a string, return null on failure.
*/
function maybeParse (str) {
function maybeParse<M extends Meta, B extends Body>(
str: string,
): StoredState<M, B> | null {
try {
return JSON.parse(str)
} catch {
return null
}
}

type MetaDataStoreOptions = {
storeName: string
expires?: number
}

let cleanedUp = false
export default class MetaDataStore {
constructor (opts) {
export default class MetaDataStore<M extends Meta, B extends Body> {
opts: Required<MetaDataStoreOptions>

name: string

constructor(opts: MetaDataStoreOptions) {
this.opts = {
expires: 24 * 60 * 60 * 1000, // 24 hours
...opts,
Expand All @@ -41,23 +64,16 @@ export default class MetaDataStore {
/**
*
*/
load () {
load(): StoredState<M, B>['metadata'] | null {
const savedState = localStorage.getItem(this.name)
if (!savedState) return null
const data = maybeParse(savedState)
const data = maybeParse<M, B>(savedState)
if (!data) return null

// Upgrade pre-0.20.0 uppyState: it used to be just a flat object,
// without `expires`.
if (!data.metadata) {
this.save(data)
return data
}

return data.metadata
}

save (metadata) {
save(metadata: Record<string, unknown>): void {
const expires = Date.now() + this.opts.expires
const state = JSON.stringify({
metadata,
Expand All @@ -69,7 +85,7 @@ export default class MetaDataStore {
/**
* Remove all expired state.
*/
static cleanup (instanceID) {
static cleanup(instanceID?: string): void {
if (instanceID) {
localStorage.removeItem(`uppyState:${instanceID}`)
return
Expand Down
Loading
Loading