@choksheak/ts-utils 0.2.9 → 0.3.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +2 -0
- package/{arrayBuffer.js → arrayBuffer.cjs} +0 -1
- package/arrayBuffer.d.mts +10 -0
- package/arrayBuffer.d.ts +4 -2
- package/arrayBuffer.min.cjs +2 -0
- package/arrayBuffer.min.cjs.map +1 -0
- package/arrayBuffer.min.mjs +2 -0
- package/{arrayBuffer.js.map → arrayBuffer.min.mjs.map} +1 -1
- package/arrayBuffer.mjs +14 -0
- package/{assert.js → assert.cjs} +0 -1
- package/assert.d.mts +7 -0
- package/assert.d.ts +3 -1
- package/assert.min.cjs +2 -0
- package/assert.min.cjs.map +1 -0
- package/assert.min.mjs +2 -0
- package/{assert.js.map → assert.min.mjs.map} +1 -1
- package/assert.mjs +11 -0
- package/{average.js → average.cjs} +0 -1
- package/average.d.mts +7 -0
- package/average.d.ts +3 -1
- package/average.min.cjs +2 -0
- package/{average.js.map → average.min.cjs.map} +1 -1
- package/average.min.mjs +2 -0
- package/average.min.mjs.map +1 -0
- package/average.mjs +20 -0
- package/{base64Url.js → base64Url.cjs} +0 -1
- package/base64Url.d.mts +10 -0
- package/base64Url.d.ts +4 -2
- package/base64Url.min.cjs +2 -0
- package/base64Url.min.cjs.map +1 -0
- package/base64Url.min.mjs +2 -0
- package/{base64Url.js.map → base64Url.min.mjs.map} +1 -1
- package/base64Url.mjs +14 -0
- package/{dateTimeStr.js → dateTimeStr.cjs} +0 -1
- package/dateTimeStr.d.mts +85 -0
- package/dateTimeStr.d.ts +15 -13
- package/dateTimeStr.min.cjs +2 -0
- package/dateTimeStr.min.cjs.map +1 -0
- package/dateTimeStr.min.mjs +2 -0
- package/{dateTimeStr.js.map → dateTimeStr.min.mjs.map} +1 -1
- package/dateTimeStr.mjs +83 -0
- package/{duration.js → duration.cjs} +9 -11
- package/duration.d.mts +78 -0
- package/duration.d.ts +15 -13
- package/duration.min.cjs +2 -0
- package/duration.min.cjs.map +1 -0
- package/duration.min.mjs +2 -0
- package/duration.min.mjs.map +1 -0
- package/duration.mjs +154 -0
- package/{isEmpty.js → isEmpty.cjs} +0 -1
- package/isEmpty.d.mts +6 -0
- package/isEmpty.d.ts +3 -1
- package/isEmpty.min.cjs +2 -0
- package/isEmpty.min.cjs.map +1 -0
- package/isEmpty.min.mjs +2 -0
- package/{isEmpty.js.map → isEmpty.min.mjs.map} +1 -1
- package/isEmpty.mjs +22 -0
- package/iterators.cjs +34 -0
- package/iterators.d.mts +4 -0
- package/iterators.d.ts +4 -0
- package/iterators.min.cjs +2 -0
- package/iterators.min.cjs.map +1 -0
- package/iterators.min.mjs +2 -0
- package/iterators.min.mjs.map +1 -0
- package/iterators.mjs +9 -0
- package/kvStore.cjs +365 -0
- package/kvStore.d.mts +139 -0
- package/kvStore.d.ts +95 -50
- package/kvStore.min.cjs +2 -0
- package/kvStore.min.cjs.map +1 -0
- package/kvStore.min.mjs +2 -0
- package/kvStore.min.mjs.map +1 -0
- package/kvStore.mjs +333 -0
- package/localStore.cjs +267 -0
- package/localStore.d.mts +119 -0
- package/localStore.d.ts +119 -0
- package/localStore.min.cjs +2 -0
- package/localStore.min.cjs.map +1 -0
- package/localStore.min.mjs +2 -0
- package/localStore.min.mjs.map +1 -0
- package/localStore.mjs +235 -0
- package/{logging.js → logging.cjs} +0 -1
- package/logging.d.mts +4 -0
- package/logging.d.ts +4 -2
- package/logging.min.cjs +2 -0
- package/logging.min.cjs.map +1 -0
- package/logging.min.mjs +2 -0
- package/{logging.js.map → logging.min.mjs.map} +1 -1
- package/logging.mjs +21 -0
- package/{nonEmpty.js → nonEmpty.cjs} +0 -1
- package/nonEmpty.d.mts +10 -0
- package/nonEmpty.d.ts +3 -1
- package/nonEmpty.min.cjs +2 -0
- package/{nonEmpty.js.map → nonEmpty.min.cjs.map} +1 -1
- package/nonEmpty.min.mjs +2 -0
- package/nonEmpty.min.mjs.map +1 -0
- package/nonEmpty.mjs +30 -0
- package/{nonNil.js → nonNil.cjs} +0 -1
- package/{src/nonNil.ts → nonNil.d.mts} +3 -6
- package/nonNil.d.ts +3 -1
- package/nonNil.min.cjs +2 -0
- package/nonNil.min.cjs.map +1 -0
- package/nonNil.min.mjs +2 -0
- package/{nonNil.js.map → nonNil.min.mjs.map} +1 -1
- package/nonNil.mjs +10 -0
- package/package.json +447 -24
- package/{round.js → round.cjs} +0 -1
- package/{src/round.ts → round.d.mts} +4 -8
- package/round.d.ts +4 -2
- package/round.min.cjs +2 -0
- package/round.min.cjs.map +1 -0
- package/round.min.mjs +2 -0
- package/{round.js.map → round.min.mjs.map} +1 -1
- package/round.mjs +12 -0
- package/{safeBtoa.js → safeBtoa.cjs} +0 -1
- package/safeBtoa.d.mts +6 -0
- package/safeBtoa.d.ts +3 -1
- package/safeBtoa.min.cjs +2 -0
- package/safeBtoa.min.cjs.map +1 -0
- package/safeBtoa.min.mjs +2 -0
- package/{safeBtoa.js.map → safeBtoa.min.mjs.map} +1 -1
- package/safeBtoa.mjs +9 -0
- package/{safeParseFloat.js → safeParseFloat.cjs} +0 -1
- package/safeParseFloat.d.mts +6 -0
- package/safeParseFloat.d.ts +3 -1
- package/safeParseFloat.min.cjs +2 -0
- package/safeParseFloat.min.cjs.map +1 -0
- package/safeParseFloat.min.mjs +2 -0
- package/{safeParseFloat.js.map → safeParseFloat.min.mjs.map} +1 -1
- package/safeParseFloat.mjs +8 -0
- package/{safeParseInt.js → safeParseInt.cjs} +0 -1
- package/safeParseInt.d.mts +6 -0
- package/safeParseInt.d.ts +3 -1
- package/safeParseInt.min.cjs +2 -0
- package/safeParseInt.min.cjs.map +1 -0
- package/safeParseInt.min.mjs +2 -0
- package/{safeParseInt.js.map → safeParseInt.min.mjs.map} +1 -1
- package/safeParseInt.mjs +8 -0
- package/sha256.cjs +35 -0
- package/sha256.d.mts +6 -0
- package/sha256.d.ts +3 -1
- package/sha256.min.cjs +2 -0
- package/sha256.min.cjs.map +1 -0
- package/sha256.min.mjs +2 -0
- package/{sha256.js.map → sha256.min.mjs.map} +1 -1
- package/sha256.mjs +10 -0
- package/{sleep.js → sleep.cjs} +0 -1
- package/{src/sleep.ts → sleep.d.mts} +3 -3
- package/sleep.d.ts +3 -1
- package/sleep.min.cjs +2 -0
- package/sleep.min.cjs.map +1 -0
- package/sleep.min.mjs +2 -0
- package/{sleep.js.map → sleep.min.mjs.map} +1 -1
- package/sleep.mjs +7 -0
- package/storageAdapter.cjs +18 -0
- package/storageAdapter.d.mts +33 -0
- package/storageAdapter.d.ts +33 -0
- package/storageAdapter.min.cjs +2 -0
- package/storageAdapter.min.cjs.map +1 -0
- package/storageAdapter.min.mjs +1 -0
- package/storageAdapter.min.mjs.map +1 -0
- package/storageAdapter.mjs +0 -0
- package/{sum.js → sum.cjs} +0 -1
- package/sum.d.mts +7 -0
- package/sum.d.ts +3 -1
- package/sum.min.cjs +2 -0
- package/sum.min.cjs.map +1 -0
- package/sum.min.mjs +2 -0
- package/{sum.js.map → sum.min.mjs.map} +1 -1
- package/sum.mjs +13 -0
- package/{timeConstants.js → timeConstants.cjs} +0 -1
- package/timeConstants.d.mts +20 -0
- package/timeConstants.d.ts +16 -14
- package/timeConstants.min.cjs +2 -0
- package/timeConstants.min.cjs.map +1 -0
- package/timeConstants.min.mjs +2 -0
- package/{timeConstants.js.map → timeConstants.min.mjs.map} +1 -1
- package/timeConstants.mjs +31 -0
- package/{timer.js → timer.cjs} +6 -6
- package/timer.d.mts +13 -0
- package/timer.d.ts +4 -2
- package/timer.min.cjs +2 -0
- package/timer.min.cjs.map +1 -0
- package/timer.min.mjs +2 -0
- package/timer.min.mjs.map +1 -0
- package/timer.mjs +161 -0
- package/docs/.nojekyll +0 -1
- package/docs/assets/hierarchy.js +0 -1
- package/docs/assets/highlight.css +0 -22
- package/docs/assets/icons.js +0 -18
- package/docs/assets/icons.svg +0 -1
- package/docs/assets/main.js +0 -60
- package/docs/assets/navigation.js +0 -1
- package/docs/assets/search.js +0 -1
- package/docs/assets/style.css +0 -1640
- package/docs/classes/kvStore.KVStore.html +0 -26
- package/docs/classes/kvStore.KVStoreField.html +0 -7
- package/docs/classes/timer.Timer.html +0 -8
- package/docs/functions/arrayBuffer.arrayBufferToBase64.html +0 -2
- package/docs/functions/arrayBuffer.arrayBufferToHex.html +0 -2
- package/docs/functions/assert.assert.html +0 -3
- package/docs/functions/average.average.html +0 -3
- package/docs/functions/base64Url.base64ToBase64URL.html +0 -2
- package/docs/functions/base64Url.base64UrlToBase64.html +0 -2
- package/docs/functions/dateTimeStr.getDisplayDateTime.html +0 -3
- package/docs/functions/dateTimeStr.getLongMonthNameOneIndexed.html +0 -4
- package/docs/functions/dateTimeStr.getLongMonthNameZeroIndexed.html +0 -4
- package/docs/functions/dateTimeStr.getShortMonthNameOneIndexed.html +0 -4
- package/docs/functions/dateTimeStr.getShortMonthNameZeroIndexed.html +0 -4
- package/docs/functions/dateTimeStr.hhMm.html +0 -4
- package/docs/functions/dateTimeStr.hhMmSs.html +0 -4
- package/docs/functions/dateTimeStr.hhMmSsMs.html +0 -5
- package/docs/functions/dateTimeStr.toDate.html +0 -4
- package/docs/functions/dateTimeStr.tzShort.html +0 -4
- package/docs/functions/dateTimeStr.yyyyMm.html +0 -4
- package/docs/functions/dateTimeStr.yyyyMmDd.html +0 -4
- package/docs/functions/duration.durationOrMsToMs.html +0 -2
- package/docs/functions/duration.durationToMs.html +0 -2
- package/docs/functions/duration.elapsed.html +0 -2
- package/docs/functions/duration.formatDuration.html +0 -4
- package/docs/functions/duration.msToDuration.html +0 -5
- package/docs/functions/duration.readableDuration.html +0 -4
- package/docs/functions/isEmpty.isEmpty.html +0 -2
- package/docs/functions/kvStore.kvStoreItem.html +0 -2
- package/docs/functions/localStorageCache.storeItem.html +0 -15
- package/docs/functions/logging.capLength.html +0 -1
- package/docs/functions/logging.stringify.html +0 -1
- package/docs/functions/nonEmpty.nonEmpty.html +0 -5
- package/docs/functions/nonNil.nonNil.html +0 -5
- package/docs/functions/round.round.html +0 -5
- package/docs/functions/round.roundS.html +0 -3
- package/docs/functions/safeBtoa.safeBtoa.html +0 -2
- package/docs/functions/safeParseFloat.safeParseFloat.html +0 -2
- package/docs/functions/safeParseInt.safeParseInt.html +0 -2
- package/docs/functions/sha256.sha256.html +0 -2
- package/docs/functions/sleep.sleep.html +0 -3
- package/docs/functions/sum.sum.html +0 -3
- package/docs/functions/timer.timer.html +0 -2
- package/docs/hierarchy.html +0 -1
- package/docs/index.html +0 -4
- package/docs/modules/arrayBuffer.html +0 -1
- package/docs/modules/assert.html +0 -1
- package/docs/modules/average.html +0 -1
- package/docs/modules/base64Url.html +0 -1
- package/docs/modules/dateTimeStr.html +0 -1
- package/docs/modules/duration.html +0 -1
- package/docs/modules/isEmpty.html +0 -1
- package/docs/modules/kvStore.html +0 -1
- package/docs/modules/localStorageCache.html +0 -1
- package/docs/modules/logging.html +0 -1
- package/docs/modules/nonEmpty.html +0 -1
- package/docs/modules/nonNil.html +0 -1
- package/docs/modules/round.html +0 -1
- package/docs/modules/safeBtoa.html +0 -1
- package/docs/modules/safeParseFloat.html +0 -1
- package/docs/modules/safeParseInt.html +0 -1
- package/docs/modules/sha256.html +0 -1
- package/docs/modules/sleep.html +0 -1
- package/docs/modules/sum.html +0 -1
- package/docs/modules/timeConstants.html +0 -1
- package/docs/modules/timer.html +0 -1
- package/docs/modules.html +0 -1
- package/docs/types/dateTimeStr.AnyDateTime.html +0 -1
- package/docs/types/duration.Duration.html +0 -6
- package/docs/types/duration.DurationStyle.html +0 -6
- package/docs/types/duration.DurationSuffixMap.html +0 -6
- package/docs/types/duration.DurationSuffixType.html +0 -1
- package/docs/types/duration.DurationType.html +0 -2
- package/docs/types/localStorageCache.StoredItem.html +0 -4
- package/docs/variables/duration.DURATION_STYLE_SUFFIX_MAP.html +0 -1
- package/docs/variables/duration.DURATION_TYPE_SEQUENCE.html +0 -2
- package/docs/variables/kvStore.DEFAULT_EXPIRY_DELTA_MS.html +0 -2
- package/docs/variables/kvStore.GC_INTERVAL_MS.html +0 -2
- package/docs/variables/kvStore.MILLIS_PER_DAY.html +0 -2
- package/docs/variables/kvStore.kvStore.html +0 -3
- package/docs/variables/timeConstants.HOURS_PER_DAY.html +0 -1
- package/docs/variables/timeConstants.HOURS_PER_WEEK.html +0 -1
- package/docs/variables/timeConstants.MINUTES_PER_DAY.html +0 -1
- package/docs/variables/timeConstants.MINUTES_PER_HOUR.html +0 -1
- package/docs/variables/timeConstants.MINUTES_PER_WEEK.html +0 -1
- package/docs/variables/timeConstants.MS_PER_DAY.html +0 -1
- package/docs/variables/timeConstants.MS_PER_HOUR.html +0 -1
- package/docs/variables/timeConstants.MS_PER_MINUTE.html +0 -1
- package/docs/variables/timeConstants.MS_PER_SECOND.html +0 -3
- package/docs/variables/timeConstants.MS_PER_WEEK.html +0 -1
- package/docs/variables/timeConstants.SECONDS_PER_DAY.html +0 -1
- package/docs/variables/timeConstants.SECONDS_PER_HOUR.html +0 -1
- package/docs/variables/timeConstants.SECONDS_PER_MINUTE.html +0 -1
- package/docs/variables/timeConstants.SECONDS_PER_WEEK.html +0 -1
- package/duration.js.map +0 -1
- package/kvStore.js +0 -383
- package/kvStore.js.map +0 -1
- package/localStorageCache.d.ts +0 -55
- package/localStorageCache.js +0 -121
- package/localStorageCache.js.map +0 -1
- package/sha256.js +0 -58
- package/src/arrayBuffer.ts +0 -29
- package/src/assert.ts +0 -14
- package/src/average.ts +0 -13
- package/src/base64Url.ts +0 -20
- package/src/dateTimeStr.ts +0 -184
- package/src/duration.ts +0 -260
- package/src/isEmpty.ts +0 -32
- package/src/kvStore.ts +0 -444
- package/src/localStorageCache.ts +0 -121
- package/src/logging.ts +0 -26
- package/src/nonEmpty.ts +0 -18
- package/src/safeBtoa.ts +0 -15
- package/src/safeParseFloat.ts +0 -10
- package/src/safeParseInt.ts +0 -10
- package/src/sha256.ts +0 -13
- package/src/sum.ts +0 -17
- package/src/timeConstants.ts +0 -22
- package/src/timer.ts +0 -33
- package/timer.js.map +0 -1
package/kvStore.d.ts
CHANGED
|
@@ -1,94 +1,139 @@
|
|
|
1
|
+
import { Duration } from './duration.js';
|
|
2
|
+
import { StoredObject, FullStorageAdapter, StorageAdapter } from './storageAdapter.js';
|
|
3
|
+
|
|
1
4
|
/**
|
|
2
5
|
* Indexed DB key-value store with support for auto-expirations.
|
|
3
6
|
*
|
|
4
7
|
* Why use this?
|
|
5
|
-
* 1.
|
|
6
|
-
* 2.
|
|
7
|
-
* 3.
|
|
8
|
-
* 4. Any serializable data type can be stored (except undefined).
|
|
8
|
+
* 1. Extremely simple interface to use indexed DBs.
|
|
9
|
+
* 2. Auto-expirations with GC frees you from worrying about data clean-up.
|
|
10
|
+
* 3. Any serializable data type can be stored (except undefined).
|
|
9
11
|
*
|
|
10
12
|
* How to use?
|
|
11
|
-
* Just use the `kvStore` global constant like the local storage
|
|
13
|
+
* Just use the `kvStore` global constant like the local storage, but with
|
|
14
|
+
* async interface functions as required by indexed DB.
|
|
15
|
+
*
|
|
16
|
+
* Why not use the indexed DB directly?
|
|
17
|
+
* It will require you to write a lot of code to reinvent the wheel.
|
|
12
18
|
*/
|
|
13
|
-
|
|
14
|
-
/**
|
|
15
|
-
|
|
16
|
-
/**
|
|
17
|
-
|
|
18
|
-
|
|
19
|
-
|
|
20
|
-
|
|
21
|
-
|
|
22
|
-
|
|
23
|
-
|
|
19
|
+
|
|
20
|
+
/** Global defaults can be updated directly. */
|
|
21
|
+
declare const KvStoreConfig: {
|
|
22
|
+
/**
|
|
23
|
+
* Name of the DB in the indexed DB.
|
|
24
|
+
* Updating the DB name will cause all old entries to be gone.
|
|
25
|
+
*/
|
|
26
|
+
dbName: string;
|
|
27
|
+
/**
|
|
28
|
+
* Version of the DB schema. Most likely you will never want to change this.
|
|
29
|
+
* Updating the version will cause all old entries to be gone.
|
|
30
|
+
*/
|
|
31
|
+
dbVersion: number;
|
|
32
|
+
/**
|
|
33
|
+
* Name of the store within the indexed DB. Each DB can have multiple stores.
|
|
34
|
+
* In practice, it doesn't matter what you name this to be.
|
|
35
|
+
*/
|
|
36
|
+
storeName: string;
|
|
37
|
+
/** 30 days in ms. */
|
|
24
38
|
expiryMs: number;
|
|
39
|
+
/** Do GC once per day. */
|
|
40
|
+
gcIntervalMs: number;
|
|
41
|
+
};
|
|
42
|
+
type KvStoreConfig = typeof KvStoreConfig;
|
|
43
|
+
/** Convenience function to update global defaults. */
|
|
44
|
+
declare function configureKvStore(config: Partial<KvStoreConfig>): void;
|
|
45
|
+
/** Type to represent a full object with metadata stored in the store. */
|
|
46
|
+
type KvStoredObject<T> = StoredObject<T> & {
|
|
47
|
+
key: string;
|
|
25
48
|
};
|
|
26
|
-
export declare class KVStoreField<T> {
|
|
27
|
-
readonly store: KVStore;
|
|
28
|
-
readonly key: string;
|
|
29
|
-
constructor(store: KVStore, key: string);
|
|
30
|
-
get(): Promise<T | undefined>;
|
|
31
|
-
set(t: T): Promise<T>;
|
|
32
|
-
delete(): Promise<void>;
|
|
33
|
-
}
|
|
34
49
|
/**
|
|
35
|
-
* You can create multiple
|
|
50
|
+
* You can create multiple KvStores if you want, but most likely you will only
|
|
36
51
|
* need to use the default `kvStore` instance.
|
|
37
52
|
*/
|
|
38
|
-
|
|
53
|
+
declare class KvStore implements FullStorageAdapter<any> {
|
|
39
54
|
readonly dbName: string;
|
|
40
|
-
|
|
41
|
-
readonly defaultExpiryDeltaMs: number;
|
|
55
|
+
/** We'll init the DB only on first use. */
|
|
42
56
|
private db;
|
|
57
|
+
/** Local storage key name for the last GC completed timestamp. */
|
|
43
58
|
readonly gcMsStorageKey: string;
|
|
44
|
-
|
|
59
|
+
readonly dbVersion: number;
|
|
60
|
+
readonly storeName: string;
|
|
61
|
+
readonly defaultExpiryMs: number;
|
|
62
|
+
readonly gcIntervalMs: number;
|
|
63
|
+
constructor(dbName: string, options?: {
|
|
64
|
+
dbVersion?: number;
|
|
65
|
+
storeName?: string;
|
|
66
|
+
defaultExpiryMs?: number | Duration;
|
|
67
|
+
gcIntervalMs?: number | Duration;
|
|
68
|
+
});
|
|
45
69
|
private getOrCreateDb;
|
|
46
70
|
private transact;
|
|
71
|
+
/** Set a value in the store. */
|
|
47
72
|
set<T>(key: string, value: T, expiryDeltaMs?: number | Duration): Promise<T>;
|
|
48
73
|
/** Delete one or multiple keys. */
|
|
49
74
|
delete(key: string | string[]): Promise<void>;
|
|
50
|
-
|
|
75
|
+
/** Mainly used to get the expiration timestamp of an object. */
|
|
76
|
+
getStoredObject<T>(key: string): Promise<KvStoredObject<T> | undefined>;
|
|
77
|
+
/** Get a value by key, or undefined if it does not exist. */
|
|
51
78
|
get<T>(key: string): Promise<T | undefined>;
|
|
52
|
-
|
|
53
|
-
|
|
79
|
+
/** Generic way to iterate through all entries. */
|
|
80
|
+
forEach<T>(callback: (key: string, value: T, expiryMs: number, storedMs: number) => void | Promise<void>): Promise<void>;
|
|
81
|
+
/**
|
|
82
|
+
* Returns the number of items in the store. Note that getting the size
|
|
83
|
+
* requires iterating through the entire store because the items could expire
|
|
84
|
+
* at any time, and hence the size is a dynamic number.
|
|
85
|
+
*/
|
|
54
86
|
size(): Promise<number>;
|
|
87
|
+
/** Remove all items from the store. */
|
|
55
88
|
clear(): Promise<void>;
|
|
56
|
-
/**
|
|
57
|
-
|
|
89
|
+
/**
|
|
90
|
+
* Returns all items as map of key to value, mainly used for debugging dumps.
|
|
91
|
+
* The type T is applied to all values, even though they might not be of type
|
|
92
|
+
* T (in the case when you store different data types in the same store).
|
|
93
|
+
*/
|
|
94
|
+
asMap<T>(): Promise<Map<string, StoredObject<T>>>;
|
|
95
|
+
/** Returns the ms timestamp for the last GC (garbage collection). */
|
|
58
96
|
get lastGcMs(): number;
|
|
97
|
+
/** Set the ms timestamp for the last GC (garbage collection). */
|
|
59
98
|
set lastGcMs(ms: number);
|
|
60
|
-
/** Perform garbage-collection if due. */
|
|
99
|
+
/** Perform garbage-collection if due, else do nothing. */
|
|
61
100
|
gc(): Promise<void>;
|
|
62
|
-
/**
|
|
101
|
+
/**
|
|
102
|
+
* Perform garbage collection immediately without checking whether we are
|
|
103
|
+
* due for the next GC or not.
|
|
104
|
+
*/
|
|
63
105
|
gcNow(): Promise<void>;
|
|
64
|
-
/**
|
|
65
|
-
|
|
106
|
+
/** Returns `this` casted into a StorageAdapter<T>. */
|
|
107
|
+
asStorageAdapter<T>(): StorageAdapter<T>;
|
|
66
108
|
}
|
|
67
109
|
/**
|
|
68
110
|
* Default KV store ready for immediate use. You can create new instances if
|
|
69
111
|
* you want, but most likely you will only need one store instance.
|
|
70
112
|
*/
|
|
71
|
-
|
|
113
|
+
declare const kvStore: KvStore;
|
|
72
114
|
/**
|
|
73
115
|
* Class to represent one key in the store with a default expiration.
|
|
74
116
|
*/
|
|
75
117
|
declare class KvStoreItem<T> {
|
|
76
118
|
readonly key: string;
|
|
77
|
-
readonly
|
|
78
|
-
readonly
|
|
79
|
-
constructor(key: string,
|
|
119
|
+
readonly store: KvStore;
|
|
120
|
+
readonly defaultExpiryMs: number;
|
|
121
|
+
constructor(key: string, defaultExpiryMs?: number | Duration, store?: KvStore);
|
|
122
|
+
/** Set a value in the store. */
|
|
123
|
+
set(value: T, expiryDeltaMs?: number | undefined): Promise<void>;
|
|
80
124
|
/**
|
|
81
125
|
* Example usage:
|
|
82
126
|
*
|
|
83
|
-
* const { value, storedMs, expiryMs } =
|
|
127
|
+
* const { value, storedMs, expiryMs, storedMs } =
|
|
128
|
+
* await myKvItem.getStoredObject();
|
|
84
129
|
*/
|
|
85
|
-
getStoredObject(): Promise<
|
|
130
|
+
getStoredObject(): Promise<KvStoredObject<T> | undefined>;
|
|
131
|
+
/** Get a value by key, or undefined if it does not exist. */
|
|
86
132
|
get(): Promise<T | undefined>;
|
|
87
|
-
|
|
133
|
+
/** Delete this key from the store. */
|
|
88
134
|
delete(): Promise<void>;
|
|
89
135
|
}
|
|
90
|
-
/**
|
|
91
|
-
|
|
92
|
-
|
|
93
|
-
export
|
|
94
|
-
export {};
|
|
136
|
+
/** Create a KV store item with a key and a default expiration. */
|
|
137
|
+
declare function kvStoreItem<T>(key: string, expiryMs?: number | Duration, store?: KvStore): KvStoreItem<T>;
|
|
138
|
+
|
|
139
|
+
export { KvStore, KvStoreConfig, KvStoreItem, type KvStoredObject, configureKvStore, kvStore, kvStoreItem };
|
package/kvStore.min.cjs
ADDED
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
"use strict";var f=Object.defineProperty;var S=Object.getOwnPropertyDescriptor;var M=Object.getOwnPropertyNames;var D=Object.prototype.hasOwnProperty;var T=(r,t)=>{for(var e in t)f(r,e,{get:t[e],enumerable:!0})},E=(r,t,e,s)=>{if(t&&typeof t=="object"||typeof t=="function")for(let n of M(t))!D.call(r,n)&&n!==e&&f(r,n,{get:()=>t[n],enumerable:!(s=S(t,n))||s.enumerable});return r};var _=r=>E(f({},"__esModule",{value:!0}),r);var R={};T(R,{KvStore:()=>b,KvStoreConfig:()=>c,KvStoreItem:()=>g,configureKvStore:()=>O,kvStore:()=>h,kvStoreItem:()=>N});module.exports=_(R);function P(r){let t=(r.days??0)*864e5,e=(r.hours??0)*36e5,s=(r.minutes??0)*6e4,n=(r.seconds??0)*1e3,o=r.milliseconds??0;return t+e+s+n+o}function d(r){return typeof r=="number"?r:P(r)}var c={dbName:"KVStore",dbVersion:1,storeName:"kvStore",expiryMs:864e5*30,gcIntervalMs:864e5};function O(r){Object.assign(c,r)}function m(r){if(!(!r||typeof r!="object"||typeof r.key!="string"||r.value===void 0||typeof r.storedMs!="number"||typeof r.expiryMs!="number"||Date.now()>=r.expiryMs))return r}function l(r,t){return r.onerror=e=>{t(e)},r}var b=class{constructor(t,e){this.dbName=t;this.dbVersion=e?.dbVersion??c.dbVersion,this.storeName=e?.storeName??c.storeName,this.defaultExpiryMs=e?.defaultExpiryMs?d(e.defaultExpiryMs):c.expiryMs,this.gcIntervalMs=e?.gcIntervalMs?d(e.gcIntervalMs):c.gcIntervalMs,this.gcMsStorageKey=`__kvStore:lastGcMs:${t}:v${this.dbVersion}:${this.storeName}`}db;gcMsStorageKey;dbVersion;storeName;defaultExpiryMs;gcIntervalMs;async getOrCreateDb(){return this.db||(this.db=await new Promise((t,e)=>{let s=l(globalThis.indexedDB.open(this.dbName,this.dbVersion),e);s.onupgradeneeded=n=>{n.target.result.createObjectStore(this.storeName,{keyPath:"key"}).createIndex("key","key",{unique:!0})},s.onsuccess=n=>{let o=n.target.result;t(o)}})),this.db}async transact(t,e){let s=await this.getOrCreateDb();return await new Promise((n,o)=>{let i=l(s.transaction(this.storeName,t),o);i.onabort=u=>{o(u)};let a=i.objectStore(this.storeName);e(a,n,o)})}async set(t,e,s=this.defaultExpiryMs){let n=Date.now(),o={key:t,value:e,storedMs:n,expiryMs:n+d(s)};return await this.transact("readwrite",(i,a,u)=>{let y=l(i.put(o),u);y.onsuccess=()=>{a(e),this.gc()}})}async delete(t){return await this.transact("readwrite",(e,s,n)=>{if(e.transaction.oncomplete=()=>{s()},typeof t=="string")l(e.delete(t),n);else for(let o of t)l(e.delete(o),n)})}async getStoredObject(t){let e=await this.transact("readonly",(s,n,o)=>{let i=l(s.get(t),o);i.onsuccess=()=>{n(i.result)}});if(e)try{let s=m(e);if(!s){await this.delete(t),this.gc();return}return s}catch(s){console.error(`Invalid kv value: ${t}=${JSON.stringify(e)}:`,s),await this.delete(t),this.gc();return}}async get(t){return(await this.getStoredObject(t))?.value}async forEach(t){await this.transact("readonly",(e,s,n)=>{let o=l(e.openCursor(),n);o.onsuccess=async i=>{let a=i.target.result;if(a){if(a.key){let u=m(a.value);u!==void 0&&await t(String(a.key),u.value,u.expiryMs,u.storedMs)}a.continue()}else s()}})}async size(){let t=0;return await this.forEach(()=>{t++}),t}async clear(){let t=[];await this.forEach(e=>{t.push(e)}),await this.delete(t)}async asMap(){let t=new Map;return await this.forEach((e,s,n,o)=>{t.set(e,{value:s,expiryMs:n,storedMs:o})}),t}get lastGcMs(){let t=globalThis.localStorage.getItem(this.gcMsStorageKey);if(!t)return 0;let e=Number(t);return isNaN(e)?0:e}set lastGcMs(t){globalThis.localStorage.setItem(this.gcMsStorageKey,String(t))}async gc(){let t=this.lastGcMs;if(!t){this.lastGcMs=Date.now();return}Date.now()<t+this.gcIntervalMs||await this.gcNow()}async gcNow(){console.log(`Starting kvStore GC on ${this.dbName} v${this.dbVersion}...`),this.lastGcMs=Date.now();let t=[];await this.forEach(async(e,s,n)=>{(s===void 0||Date.now()>=n)&&t.push(e)}),t.length&&await this.delete(t),console.log(`Finished kvStore GC on ${this.dbName} v${this.dbVersion} - deleted ${t.length} keys`),this.lastGcMs=Date.now()}asStorageAdapter(){return this}},h=new b(c.dbName),g=class{constructor(t,e=c.expiryMs,s=h){this.key=t;this.store=s;this.defaultExpiryMs=e&&d(e)}defaultExpiryMs;async set(t,e=this.defaultExpiryMs){await this.store.set(this.key,t,e)}async getStoredObject(){return await this.store.getStoredObject(this.key)}async get(){return await this.store.get(this.key)}async delete(){await this.store.delete(this.key)}};function N(r,t,e=h){return t=t&&d(t),new g(r,t,e)}0&&(module.exports={KvStore,KvStoreConfig,KvStoreItem,configureKvStore,kvStore,kvStoreItem});
|
|
2
|
+
//# sourceMappingURL=kvStore.min.cjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/kvStore.ts","../src/duration.ts"],"sourcesContent":["/**\n * Indexed DB key-value store with support for auto-expirations.\n *\n * Why use this?\n * 1. Extremely simple interface to use indexed DBs.\n * 2. Auto-expirations with GC frees you from worrying about data clean-up.\n * 3. Any serializable data type can be stored (except undefined).\n *\n * How to use?\n * Just use the `kvStore` global constant like the local storage, but with\n * async interface functions as required by indexed DB.\n *\n * Why not use the indexed DB directly?\n * It will require you to write a lot of code to reinvent the wheel.\n */\n\nimport { Duration, durationOrMsToMs } from \"./duration\";\nimport {\n FullStorageAdapter,\n StorageAdapter,\n StoredObject,\n} from \"./storageAdapter\";\nimport { MS_PER_DAY } from \"./timeConstants\";\n\n/** Global defaults can be updated directly. */\nexport const KvStoreConfig = {\n /**\n * Name of the DB in the indexed DB.\n * Updating the DB name will cause all old entries to be gone.\n */\n dbName: \"KVStore\",\n\n /**\n * Version of the DB schema. Most likely you will never want to change this.\n * Updating the version will cause all old entries to be gone.\n */\n dbVersion: 1,\n\n /**\n * Name of the store within the indexed DB. Each DB can have multiple stores.\n * In practice, it doesn't matter what you name this to be.\n */\n storeName: \"kvStore\",\n\n /** 30 days in ms. */\n expiryMs: MS_PER_DAY * 30,\n\n /** Do GC once per day. */\n gcIntervalMs: MS_PER_DAY,\n};\n\nexport type KvStoreConfig = typeof KvStoreConfig;\n\n/** Convenience function to update global defaults. */\nexport function configureKvStore(config: Partial<KvStoreConfig>) {\n Object.assign(KvStoreConfig, config);\n}\n\n/** Type to represent a full object with metadata stored in the store. */\nexport type KvStoredObject<T> = StoredObject<T> & {\n // The key is required by the ObjectStore.\n key: string;\n};\n\n/**\n * Parse a stored value string. Returns undefined if invalid or expired.\n * Throws an error if the string cannot be parsed as JSON.\n */\nfunction validateStoredObject<T>(\n obj: KvStoredObject<T>,\n): KvStoredObject<T> | undefined {\n if (\n !obj ||\n typeof obj !== \"object\" ||\n typeof obj.key !== \"string\" ||\n obj.value === undefined ||\n typeof obj.storedMs !== \"number\" ||\n typeof obj.expiryMs !== \"number\" ||\n Date.now() >= obj.expiryMs\n ) {\n return undefined;\n }\n\n return obj;\n}\n\n/** Add an `onerror` handler to the request. */\nfunction withOnError<T extends IDBRequest | IDBTransaction>(\n request: T,\n reject: (reason?: unknown) => void,\n): T {\n request.onerror = (event) => {\n reject(event);\n };\n\n return request;\n}\n\n/**\n * You can create multiple KvStores if you want, but most likely you will only\n * need to use the default `kvStore` instance.\n */\n// Using `any` because the store could store any type of data for each key,\n// but the caller can specify a more specific type when calling each of the\n// methods.\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\nexport class KvStore implements FullStorageAdapter<any> {\n /** We'll init the DB only on first use. */\n private db: IDBDatabase | undefined;\n\n /** Local storage key name for the last GC completed timestamp. */\n public readonly gcMsStorageKey: string;\n\n public readonly dbVersion: number;\n public readonly storeName: string;\n public readonly defaultExpiryMs: number;\n public readonly gcIntervalMs: number;\n\n public constructor(\n public readonly dbName: string,\n options?: {\n dbVersion?: number;\n storeName?: string;\n defaultExpiryMs?: number | Duration;\n gcIntervalMs?: number | Duration;\n },\n ) {\n this.dbVersion = options?.dbVersion ?? KvStoreConfig.dbVersion;\n this.storeName = options?.storeName ?? KvStoreConfig.storeName;\n\n this.defaultExpiryMs = options?.defaultExpiryMs\n ? durationOrMsToMs(options.defaultExpiryMs)\n : KvStoreConfig.expiryMs;\n\n this.gcIntervalMs = options?.gcIntervalMs\n ? durationOrMsToMs(options.gcIntervalMs)\n : KvStoreConfig.gcIntervalMs;\n\n this.gcMsStorageKey = `__kvStore:lastGcMs:${dbName}:v${this.dbVersion}:${this.storeName}`;\n }\n\n private async getOrCreateDb() {\n if (!this.db) {\n this.db = await new Promise<IDBDatabase>((resolve, reject) => {\n const request = withOnError(\n globalThis.indexedDB.open(this.dbName, this.dbVersion),\n reject,\n );\n\n request.onupgradeneeded = (event) => {\n const db = (event.target as unknown as { result: IDBDatabase })\n .result;\n\n // Create the store on DB init.\n const objectStore = db.createObjectStore(this.storeName, {\n keyPath: \"key\",\n });\n\n objectStore.createIndex(\"key\", \"key\", {\n unique: true,\n });\n };\n\n request.onsuccess = (event) => {\n const db = (event.target as unknown as { result: IDBDatabase })\n .result;\n resolve(db);\n };\n });\n }\n\n return this.db;\n }\n\n private async transact<T>(\n mode: IDBTransactionMode,\n callback: (\n objectStore: IDBObjectStore,\n resolve: (t: T) => void,\n reject: (reason?: unknown) => void,\n ) => void,\n ): Promise<T> {\n const db = await this.getOrCreateDb();\n\n return await new Promise<T>((resolve, reject) => {\n const transaction = withOnError(\n db.transaction(this.storeName, mode),\n reject,\n );\n\n transaction.onabort = (event) => {\n reject(event);\n };\n\n const objectStore = transaction.objectStore(this.storeName);\n\n callback(objectStore, resolve, reject);\n });\n }\n\n /** Set a value in the store. */\n public async set<T>(\n key: string,\n value: T,\n expiryDeltaMs: number | Duration = this.defaultExpiryMs,\n ): Promise<T> {\n const nowMs = Date.now();\n const obj: KvStoredObject<T> = {\n key,\n value,\n storedMs: nowMs,\n expiryMs: nowMs + durationOrMsToMs(expiryDeltaMs),\n };\n\n return await this.transact<T>(\n \"readwrite\",\n (objectStore, resolve, reject) => {\n const request = withOnError(objectStore.put(obj), reject);\n\n request.onsuccess = () => {\n resolve(value);\n\n this.gc(); // check GC on every write\n };\n },\n );\n }\n\n /** Delete one or multiple keys. */\n public async delete(key: string | string[]): Promise<void> {\n return await this.transact<void>(\n \"readwrite\",\n (objectStore, resolve, reject) => {\n objectStore.transaction.oncomplete = () => {\n resolve();\n };\n\n if (typeof key === \"string\") {\n withOnError(objectStore.delete(key), reject);\n } else {\n for (const k of key) {\n withOnError(objectStore.delete(k), reject);\n }\n }\n },\n );\n }\n\n /** Mainly used to get the expiration timestamp of an object. */\n public async getStoredObject<T>(\n key: string,\n ): Promise<KvStoredObject<T> | undefined> {\n const stored = await this.transact<KvStoredObject<T> | undefined>(\n \"readonly\",\n (objectStore, resolve, reject) => {\n const request = withOnError(objectStore.get(key), reject);\n\n request.onsuccess = () => {\n resolve(request.result);\n };\n },\n );\n\n if (!stored) {\n return undefined;\n }\n\n try {\n const obj = validateStoredObject(stored);\n if (!obj) {\n await this.delete(key);\n\n this.gc(); // check GC on every read of an expired key\n\n return undefined;\n }\n\n return obj;\n } catch (e) {\n console.error(`Invalid kv value: ${key}=${JSON.stringify(stored)}:`, e);\n await this.delete(key);\n\n this.gc(); // check GC on every read of an invalid key\n\n return undefined;\n }\n }\n\n /** Get a value by key, or undefined if it does not exist. */\n public async get<T>(key: string): Promise<T | undefined> {\n const obj = await this.getStoredObject<T>(key);\n\n return obj?.value;\n }\n\n /** Generic way to iterate through all entries. */\n public async forEach<T>(\n callback: (\n key: string,\n value: T,\n expiryMs: number,\n storedMs: number,\n ) => void | Promise<void>,\n ): Promise<void> {\n await this.transact<void>(\"readonly\", (objectStore, resolve, reject) => {\n const request = withOnError(objectStore.openCursor(), reject);\n\n request.onsuccess = async (event) => {\n const cursor = (\n event.target as unknown as { result: IDBCursorWithValue }\n ).result;\n\n if (cursor) {\n if (cursor.key) {\n const obj = validateStoredObject(cursor.value);\n if (obj !== undefined) {\n await callback(\n String(cursor.key),\n obj.value as T,\n obj.expiryMs,\n obj.storedMs,\n );\n }\n }\n cursor.continue();\n } else {\n resolve();\n }\n };\n });\n }\n\n /**\n * Returns the number of items in the store. Note that getting the size\n * requires iterating through the entire store because the items could expire\n * at any time, and hence the size is a dynamic number.\n */\n public async size(): Promise<number> {\n let count = 0;\n await this.forEach(() => {\n count++;\n });\n return count;\n }\n\n /** Remove all items from the store. */\n public async clear(): Promise<void> {\n const keys: string[] = [];\n await this.forEach((key) => {\n keys.push(key);\n });\n\n await this.delete(keys);\n }\n\n /**\n * Returns all items as map of key to value, mainly used for debugging dumps.\n * The type T is applied to all values, even though they might not be of type\n * T (in the case when you store different data types in the same store).\n */\n public async asMap<T>(): Promise<Map<string, StoredObject<T>>> {\n const map = new Map<string, StoredObject<T>>();\n await this.forEach((key, value, expiryMs, storedMs) => {\n map.set(key, { value: value as T, expiryMs, storedMs });\n });\n return map;\n }\n\n /** Returns the ms timestamp for the last GC (garbage collection). */\n public get lastGcMs(): number {\n const lastGcMsStr = globalThis.localStorage.getItem(this.gcMsStorageKey);\n if (!lastGcMsStr) return 0;\n\n const ms = Number(lastGcMsStr);\n return isNaN(ms) ? 0 : ms;\n }\n\n /** Set the ms timestamp for the last GC (garbage collection). */\n public set lastGcMs(ms: number) {\n globalThis.localStorage.setItem(this.gcMsStorageKey, String(ms));\n }\n\n /** Perform garbage-collection if due, else do nothing. */\n public async gc(): Promise<void> {\n const lastGcMs = this.lastGcMs;\n\n // Set initial timestamp - no need GC now.\n if (!lastGcMs) {\n this.lastGcMs = Date.now();\n return;\n }\n\n if (Date.now() < lastGcMs + this.gcIntervalMs) {\n return; // not due for next GC yet\n }\n\n // GC is due now, so run it.\n await this.gcNow();\n }\n\n /**\n * Perform garbage collection immediately without checking whether we are\n * due for the next GC or not.\n */\n public async gcNow(): Promise<void> {\n console.log(`Starting kvStore GC on ${this.dbName} v${this.dbVersion}...`);\n\n // Prevent concurrent GC runs.\n this.lastGcMs = Date.now();\n\n const keysToDelete: string[] = [];\n await this.forEach(\n async (key: string, value: unknown, expiryMs: number) => {\n if (value === undefined || Date.now() >= expiryMs) {\n keysToDelete.push(key);\n }\n },\n );\n\n if (keysToDelete.length) {\n await this.delete(keysToDelete);\n }\n\n console.log(\n `Finished kvStore GC on ${this.dbName} v${this.dbVersion} ` +\n `- deleted ${keysToDelete.length} keys`,\n );\n\n // Mark the end time as last GC time.\n this.lastGcMs = Date.now();\n }\n\n /** Returns `this` casted into a StorageAdapter<T>. */\n public asStorageAdapter<T>(): StorageAdapter<T> {\n return this as StorageAdapter<T>;\n }\n}\n\n/**\n * Default KV store ready for immediate use. You can create new instances if\n * you want, but most likely you will only need one store instance.\n */\nexport const kvStore = new KvStore(KvStoreConfig.dbName);\n\n/**\n * Class to represent one key in the store with a default expiration.\n */\nexport class KvStoreItem<T> {\n public readonly defaultExpiryMs: number;\n\n public constructor(\n public readonly key: string,\n defaultExpiryMs: number | Duration = KvStoreConfig.expiryMs,\n public readonly store = kvStore,\n ) {\n this.defaultExpiryMs = defaultExpiryMs && durationOrMsToMs(defaultExpiryMs);\n }\n\n /** Set a value in the store. */\n public async set(\n value: T,\n expiryDeltaMs: number | undefined = this.defaultExpiryMs,\n ): Promise<void> {\n await this.store.set(this.key, value, expiryDeltaMs);\n }\n\n /**\n * Example usage:\n *\n * const { value, storedMs, expiryMs, storedMs } =\n * await myKvItem.getStoredObject();\n */\n public async getStoredObject(): Promise<KvStoredObject<T> | undefined> {\n return await this.store.getStoredObject(this.key);\n }\n\n /** Get a value by key, or undefined if it does not exist. */\n public async get(): Promise<T | undefined> {\n return await this.store.get(this.key);\n }\n\n /** Delete this key from the store. */\n public async delete(): Promise<void> {\n await this.store.delete(this.key);\n }\n}\n\n/** Create a KV store item with a key and a default expiration. */\nexport function kvStoreItem<T>(\n key: string,\n expiryMs?: number | Duration,\n store = kvStore,\n): KvStoreItem<T> {\n expiryMs = expiryMs && durationOrMsToMs(expiryMs);\n\n return new KvStoreItem<T>(key, expiryMs, store);\n}\n","/**\n * Bunch of miscellaneous constants and utility functions related to handling\n * date and time durations.\n *\n * Note that month and year do not have fixed durations, and hence are excluded\n * from this file. Weeks have fixed durations, but are excluded because we\n * use days as the max duration supported.\n */\n\nimport {\n HOURS_PER_DAY,\n MINUTES_PER_HOUR,\n MS_PER_DAY,\n MS_PER_HOUR,\n MS_PER_MINUTE,\n MS_PER_SECOND,\n SECONDS_PER_MINUTE,\n} from \"./timeConstants\";\n\nexport type Duration = {\n days?: number;\n hours?: number;\n minutes?: number;\n seconds?: number;\n milliseconds?: number;\n};\n\n/**\n * One of: days, hours, minutes, seconds, milliseconds\n */\nexport type DurationType = keyof Duration;\n\n/**\n * Order in which the duration type appears in the duration string.\n */\nexport const DURATION_TYPE_SEQUENCE: DurationType[] = [\n \"days\",\n \"hours\",\n \"minutes\",\n \"seconds\",\n \"milliseconds\",\n];\n\n/**\n * Follows the same format as Intl.DurationFormat.prototype.format().\n *\n * Short: 1 yr, 2 mths, 3 wks, 3 days, 4 hr, 5 min, 6 sec, 7 ms, 8 μs, 9 ns\n * Long: 1 year, 2 months, 3 weeks, 3 days, 4 hours, 5 minutes, 6 seconds,\n * 7 milliseconds, 8 microseconds, 9 nanoseconds\n * Narrow: 1y 2mo 3w 3d 4h 5m 6s 7ms 8μs 9ns\n */\nexport type DurationStyle = \"short\" | \"long\" | \"narrow\";\n\nexport type DurationSuffixMap = {\n short: string;\n shorts: string;\n long: string;\n longs: string;\n narrow: string;\n};\n\nexport type DurationSuffixType = keyof DurationSuffixMap;\n\nexport const DURATION_STYLE_SUFFIX_MAP: Record<\n DurationType,\n DurationSuffixMap\n> = {\n days: {\n short: \"day\",\n shorts: \"days\",\n long: \"day\",\n longs: \"days\",\n narrow: \"d\",\n },\n hours: {\n short: \"hr\",\n shorts: \"hrs\",\n long: \"hour\",\n longs: \"hours\",\n narrow: \"h\",\n },\n minutes: {\n short: \"min\",\n shorts: \"mins\",\n long: \"minute\",\n longs: \"minutes\",\n narrow: \"m\",\n },\n seconds: {\n short: \"sec\",\n shorts: \"secs\",\n long: \"second\",\n longs: \"seconds\",\n narrow: \"s\",\n },\n milliseconds: {\n short: \"ms\",\n shorts: \"ms\",\n long: \"millisecond\",\n longs: \"milliseconds\",\n narrow: \"ms\",\n },\n};\n\nfunction getDurationStyleForPlural(style: DurationStyle): DurationSuffixType {\n return style == \"short\" ? \"shorts\" : style === \"long\" ? \"longs\" : style;\n}\n\nfunction getValueAndUnitSeparator(style: DurationStyle): string {\n return style === \"narrow\" ? \"\" : \" \";\n}\n\nfunction getDurationTypeSeparator(style: DurationStyle): string {\n return style === \"narrow\" ? \" \" : \", \";\n}\n\n/**\n * Convert a milliseconds duration into a Duration object. If the given ms is\n * zero, then return an object with a single field of zero with duration type\n * of durationTypeForZero.\n *\n * @param durationTypeForZero Defaults to 'milliseconds'\n */\nexport function msToDuration(\n ms: number,\n durationTypeForZero?: DurationType,\n): Duration {\n if (ms === 0) {\n durationTypeForZero = durationTypeForZero ?? \"milliseconds\";\n return { [durationTypeForZero]: 0 };\n }\n\n const duration: Duration = {};\n\n for (let i = 0; i < 1; i++) {\n let seconds = Math.floor(ms / MS_PER_SECOND);\n const millis = ms - seconds * MS_PER_SECOND;\n\n if (millis > 0) {\n duration[\"milliseconds\"] = millis;\n }\n\n if (seconds === 0) {\n break;\n }\n\n let minutes = Math.floor(seconds / SECONDS_PER_MINUTE);\n seconds -= minutes * SECONDS_PER_MINUTE;\n\n if (seconds > 0) {\n duration[\"seconds\"] = seconds;\n }\n\n if (minutes === 0) {\n break;\n }\n\n let hours = Math.floor(minutes / MINUTES_PER_HOUR);\n minutes -= hours * MINUTES_PER_HOUR;\n\n if (minutes > 0) {\n duration[\"minutes\"] = minutes;\n }\n\n if (hours === 0) {\n break;\n }\n\n const days = Math.floor(hours / HOURS_PER_DAY);\n hours -= days * HOURS_PER_DAY;\n\n if (hours > 0) {\n duration[\"hours\"] = hours;\n }\n\n if (days > 0) {\n duration[\"days\"] = days;\n }\n }\n\n return duration;\n}\n\n/**\n * Returns the number of milliseconds for the given duration.\n */\nexport function durationToMs(duration: Duration): number {\n const daysMs = (duration.days ?? 0) * MS_PER_DAY;\n const hoursMs = (duration.hours ?? 0) * MS_PER_HOUR;\n const minsMs = (duration.minutes ?? 0) * MS_PER_MINUTE;\n const secsMs = (duration.seconds ?? 0) * MS_PER_SECOND;\n const msMs = duration.milliseconds ?? 0;\n\n return daysMs + hoursMs + minsMs + secsMs + msMs;\n}\n\n/**\n * Convenience function to return a duration given an ms or Duration.\n */\nexport function durationOrMsToMs(duration: number | Duration): number {\n return typeof duration === \"number\" ? duration : durationToMs(duration);\n}\n\n/**\n * Format a given Duration object into a string. If the object has no fields,\n * then returns an empty string.\n *\n * @param style Defaults to 'short'\n */\nexport function formatDuration(duration: Duration, style?: DurationStyle) {\n style = style ?? \"short\";\n const stylePlural = getDurationStyleForPlural(style);\n\n const space = getValueAndUnitSeparator(style);\n\n const a: string[] = [];\n\n for (const unit of DURATION_TYPE_SEQUENCE) {\n const value = duration[unit];\n if (value === undefined) continue;\n\n const suffixMap = DURATION_STYLE_SUFFIX_MAP[unit];\n const suffix = value === 1 ? suffixMap[style] : suffixMap[stylePlural];\n a.push(value + space + suffix);\n }\n\n const separator = getDurationTypeSeparator(style);\n return a.join(separator);\n}\n\n/**\n * Convert a millisecond duration into a human-readable duration string.\n *\n * @param options.durationTypeForZero - Defaults to 'milliseconds'\n * @param options.style - Defaults to 'short'\n */\nexport function readableDuration(\n ms: number,\n options?: { durationTypeForZero?: DurationType; style?: DurationStyle },\n): string {\n const duration = msToDuration(ms, options?.durationTypeForZero);\n\n return formatDuration(duration, options?.style);\n}\n\n/** A shortened duration string useful for logging timings. */\nexport function elapsed(ms: number): string {\n // Use long format for 1 minute or over.\n if (ms > MS_PER_MINUTE) {\n return readableDuration(ms);\n }\n\n // Use seconds format for over 100ms.\n if (ms > 100) {\n return `${(ms / 1000).toFixed(3)}s`;\n }\n\n // Use milliseconds format.\n return ms + \"ms\";\n}\n"],"mappings":"yaAAA,IAAAA,EAAA,GAAAC,EAAAD,EAAA,aAAAE,EAAA,kBAAAC,EAAA,gBAAAC,EAAA,qBAAAC,EAAA,YAAAC,EAAA,gBAAAC,IAAA,eAAAC,EAAAR,GC0LO,SAASS,EAAaC,EAA4B,CACvD,IAAMC,GAAUD,EAAS,MAAQ,GAAK,MAChCE,GAAWF,EAAS,OAAS,GAAK,KAClCG,GAAUH,EAAS,SAAW,GAAK,IACnCI,GAAUJ,EAAS,SAAW,GAAK,IACnCK,EAAOL,EAAS,cAAgB,EAEtC,OAAOC,EAASC,EAAUC,EAASC,EAASC,CAC9C,CAKO,SAASC,EAAiBN,EAAqC,CACpE,OAAO,OAAOA,GAAa,SAAWA,EAAWD,EAAaC,CAAQ,CACxE,CDhLO,IAAMO,EAAgB,CAK3B,OAAQ,UAMR,UAAW,EAMX,UAAW,UAGX,SAAU,MAAa,GAGvB,aAAc,KAChB,EAKO,SAASC,EAAiBC,EAAgC,CAC/D,OAAO,OAAOF,EAAeE,CAAM,CACrC,CAYA,SAASC,EACPC,EAC+B,CAC/B,GACE,GAACA,GACD,OAAOA,GAAQ,UACf,OAAOA,EAAI,KAAQ,UACnBA,EAAI,QAAU,QACd,OAAOA,EAAI,UAAa,UACxB,OAAOA,EAAI,UAAa,UACxB,KAAK,IAAI,GAAKA,EAAI,UAKpB,OAAOA,CACT,CAGA,SAASC,EACPC,EACAC,EACG,CACH,OAAAD,EAAQ,QAAWE,GAAU,CAC3BD,EAAOC,CAAK,CACd,EAEOF,CACT,CAUO,IAAMG,EAAN,KAAiD,CAY/C,YACWC,EAChBC,EAMA,CAPgB,YAAAD,EAQhB,KAAK,UAAYC,G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__export","KvStore","KvStoreConfig","KvStoreItem","configureKvStore","kvStore","kvStoreItem","__toCommonJS","durationToMs","duration","daysMs","hoursMs","minsMs","secsMs","msMs","durationOrMsToMs","KvStoreConfig","configureKvStore","config","validateStoredObject","obj","withOnError","request","reject","event","KvStore","dbName","options","durationOrMsToMs","resolve","db","mode","callback","transaction","objectStore","key","value","expiryDeltaMs","nowMs","k","stored","e","cursor","count","keys","map","expiryMs","storedMs","lastGcMsStr","ms","lastGcMs","keysToDelete","kvStore","KvStoreItem","defaultExpiryMs","store","kvStoreItem"]}
|
package/kvStore.min.mjs
ADDED
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
function D(r){let t=(r.days??0)*864e5,e=(r.hours??0)*36e5,s=(r.minutes??0)*6e4,n=(r.seconds??0)*1e3,o=r.milliseconds??0;return t+e+s+n+o}function d(r){return typeof r=="number"?r:D(r)}var l={dbName:"KVStore",dbVersion:1,storeName:"kvStore",expiryMs:864e5*30,gcIntervalMs:864e5};function R(r){Object.assign(l,r)}function f(r){if(!(!r||typeof r!="object"||typeof r.key!="string"||r.value===void 0||typeof r.storedMs!="number"||typeof r.expiryMs!="number"||Date.now()>=r.expiryMs))return r}function c(r,t){return r.onerror=e=>{t(e)},r}var b=class{constructor(t,e){this.dbName=t;this.dbVersion=e?.dbVersion??l.dbVersion,this.storeName=e?.storeName??l.storeName,this.defaultExpiryMs=e?.defaultExpiryMs?d(e.defaultExpiryMs):l.expiryMs,this.gcIntervalMs=e?.gcIntervalMs?d(e.gcIntervalMs):l.gcIntervalMs,this.gcMsStorageKey=`__kvStore:lastGcMs:${t}:v${this.dbVersion}:${this.storeName}`}db;gcMsStorageKey;dbVersion;storeName;defaultExpiryMs;gcIntervalMs;async getOrCreateDb(){return this.db||(this.db=await new Promise((t,e)=>{let s=c(globalThis.indexedDB.open(this.dbName,this.dbVersion),e);s.onupgradeneeded=n=>{n.target.result.createObjectStore(this.storeName,{keyPath:"key"}).createIndex("key","key",{unique:!0})},s.onsuccess=n=>{let o=n.target.result;t(o)}})),this.db}async transact(t,e){let s=await this.getOrCreateDb();return await new Promise((n,o)=>{let i=c(s.transaction(this.storeName,t),o);i.onabort=u=>{o(u)};let a=i.objectStore(this.storeName);e(a,n,o)})}async set(t,e,s=this.defaultExpiryMs){let n=Date.now(),o={key:t,value:e,storedMs:n,expiryMs:n+d(s)};return await this.transact("readwrite",(i,a,u)=>{let m=c(i.put(o),u);m.onsuccess=()=>{a(e),this.gc()}})}async delete(t){return await this.transact("readwrite",(e,s,n)=>{if(e.transaction.oncomplete=()=>{s()},typeof t=="string")c(e.delete(t),n);else for(let o of t)c(e.delete(o),n)})}async getStoredObject(t){let e=await this.transact("readonly",(s,n,o)=>{let i=c(s.get(t),o);i.onsuccess=()=>{n(i.result)}});if(e)try{let s=f(e);if(!s){await this.delete(t),this.gc();return}return s}catch(s){console.error(`Invalid kv value: ${t}=${JSON.stringify(e)}:`,s),await this.delete(t),this.gc();return}}async get(t){return(await this.getStoredObject(t))?.value}async forEach(t){await this.transact("readonly",(e,s,n)=>{let o=c(e.openCursor(),n);o.onsuccess=async i=>{let a=i.target.result;if(a){if(a.key){let u=f(a.value);u!==void 0&&await t(String(a.key),u.value,u.expiryMs,u.storedMs)}a.continue()}else s()}})}async size(){let t=0;return await this.forEach(()=>{t++}),t}async clear(){let t=[];await this.forEach(e=>{t.push(e)}),await this.delete(t)}async asMap(){let t=new Map;return await this.forEach((e,s,n,o)=>{t.set(e,{value:s,expiryMs:n,storedMs:o})}),t}get lastGcMs(){let t=globalThis.localStorage.getItem(this.gcMsStorageKey);if(!t)return 0;let e=Number(t);return isNaN(e)?0:e}set lastGcMs(t){globalThis.localStorage.setItem(this.gcMsStorageKey,String(t))}async gc(){let t=this.lastGcMs;if(!t){this.lastGcMs=Date.now();return}Date.now()<t+this.gcIntervalMs||await this.gcNow()}async gcNow(){console.log(`Starting kvStore GC on ${this.dbName} v${this.dbVersion}...`),this.lastGcMs=Date.now();let t=[];await this.forEach(async(e,s,n)=>{(s===void 0||Date.now()>=n)&&t.push(e)}),t.length&&await this.delete(t),console.log(`Finished kvStore GC on ${this.dbName} v${this.dbVersion} - deleted ${t.length} keys`),this.lastGcMs=Date.now()}asStorageAdapter(){return this}},h=new b(l.dbName),g=class{constructor(t,e=l.expiryMs,s=h){this.key=t;this.store=s;this.defaultExpiryMs=e&&d(e)}defaultExpiryMs;async set(t,e=this.defaultExpiryMs){await this.store.set(this.key,t,e)}async getStoredObject(){return await this.store.getStoredObject(this.key)}async get(){return await this.store.get(this.key)}async delete(){await this.store.delete(this.key)}};function I(r,t,e=h){return t=t&&d(t),new g(r,t,e)}export{b as KvStore,l as KvStoreConfig,g as KvStoreItem,R as configureKvStore,h as kvStore,I as kvStoreItem};
|
|
2
|
+
//# sourceMappingURL=kvStore.min.mjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/duration.ts","../src/kvStore.ts"],"sourcesContent":["/**\n * Bunch of miscellaneous constants and utility functions related to handling\n * date and time durations.\n *\n * Note that month and year do not have fixed durations, and hence are excluded\n * from this file. Weeks have fixed durations, but are excluded because we\n * use days as the max duration supported.\n */\n\nimport {\n HOURS_PER_DAY,\n MINUTES_PER_HOUR,\n MS_PER_DAY,\n MS_PER_HOUR,\n MS_PER_MINUTE,\n MS_PER_SECOND,\n SECONDS_PER_MINUTE,\n} from \"./timeConstants\";\n\nexport type Duration = {\n days?: number;\n hours?: number;\n minutes?: number;\n seconds?: number;\n milliseconds?: number;\n};\n\n/**\n * One of: days, hours, minutes, seconds, milliseconds\n */\nexport type DurationType = keyof Duration;\n\n/**\n * Order in which the duration type appears in the duration string.\n */\nexport const DURATION_TYPE_SEQUENCE: DurationType[] = [\n \"days\",\n \"hours\",\n \"minutes\",\n \"seconds\",\n \"milliseconds\",\n];\n\n/**\n * Follows the same format as Intl.DurationFormat.prototype.format().\n *\n * Short: 1 yr, 2 mths, 3 wks, 3 days, 4 hr, 5 min, 6 sec, 7 ms, 8 μs, 9 ns\n * Long: 1 year, 2 months, 3 weeks, 3 days, 4 hours, 5 minutes, 6 seconds,\n * 7 milliseconds, 8 microseconds, 9 nanoseconds\n * Narrow: 1y 2mo 3w 3d 4h 5m 6s 7ms 8μs 9ns\n */\nexport type DurationStyle = \"short\" | \"long\" | \"narrow\";\n\nexport type DurationSuffixMap = {\n short: string;\n shorts: string;\n long: string;\n longs: string;\n narrow: string;\n};\n\nexport type DurationSuffixType = keyof DurationSuffixMap;\n\nexport const DURATION_STYLE_SUFFIX_MAP: Record<\n DurationType,\n DurationSuffixMap\n> = {\n days: {\n short: \"day\",\n shorts: \"days\",\n long: \"day\",\n longs: \"days\",\n narrow: \"d\",\n },\n hours: {\n short: \"hr\",\n shorts: \"hrs\",\n long: \"hour\",\n longs: \"hours\",\n narrow: \"h\",\n },\n minutes: {\n short: \"min\",\n shorts: \"mins\",\n long: \"minute\",\n longs: \"minutes\",\n narrow: \"m\",\n },\n seconds: {\n short: \"sec\",\n shorts: \"secs\",\n long: \"second\",\n longs: \"seconds\",\n narrow: \"s\",\n },\n milliseconds: {\n short: \"ms\",\n shorts: \"ms\",\n long: \"millisecond\",\n longs: \"milliseconds\",\n narrow: \"ms\",\n },\n};\n\nfunction getDurationStyleForPlural(style: DurationStyle): DurationSuffixType {\n return style == \"short\" ? \"shorts\" : style === \"long\" ? \"longs\" : style;\n}\n\nfunction getValueAndUnitSeparator(style: DurationStyle): string {\n return style === \"narrow\" ? \"\" : \" \";\n}\n\nfunction getDurationTypeSeparator(style: DurationStyle): string {\n return style === \"narrow\" ? \" \" : \", \";\n}\n\n/**\n * Convert a milliseconds duration into a Duration object. If the given ms is\n * zero, then return an object with a single field of zero with duration type\n * of durationTypeForZero.\n *\n * @param durationTypeForZero Defaults to 'milliseconds'\n */\nexport function msToDuration(\n ms: number,\n durationTypeForZero?: DurationType,\n): Duration {\n if (ms === 0) {\n durationTypeForZero = durationTypeForZero ?? \"milliseconds\";\n return { [durationTypeForZero]: 0 };\n }\n\n const duration: Duration = {};\n\n for (let i = 0; i < 1; i++) {\n let seconds = Math.floor(ms / MS_PER_SECOND);\n const millis = ms - seconds * MS_PER_SECOND;\n\n if (millis > 0) {\n duration[\"milliseconds\"] = millis;\n }\n\n if (seconds === 0) {\n break;\n }\n\n let minutes = Math.floor(seconds / SECONDS_PER_MINUTE);\n seconds -= minutes * SECONDS_PER_MINUTE;\n\n if (seconds > 0) {\n duration[\"seconds\"] = seconds;\n }\n\n if (minutes === 0) {\n break;\n }\n\n let hours = Math.floor(minutes / MINUTES_PER_HOUR);\n minutes -= hours * MINUTES_PER_HOUR;\n\n if (minutes > 0) {\n duration[\"minutes\"] = minutes;\n }\n\n if (hours === 0) {\n break;\n }\n\n const days = Math.floor(hours / HOURS_PER_DAY);\n hours -= days * HOURS_PER_DAY;\n\n if (hours > 0) {\n duration[\"hours\"] = hours;\n }\n\n if (days > 0) {\n duration[\"days\"] = days;\n }\n }\n\n return duration;\n}\n\n/**\n * Returns the number of milliseconds for the given duration.\n */\nexport function durationToMs(duration: Duration): number {\n const daysMs = (duration.days ?? 0) * MS_PER_DAY;\n const hoursMs = (duration.hours ?? 0) * MS_PER_HOUR;\n const minsMs = (duration.minutes ?? 0) * MS_PER_MINUTE;\n const secsMs = (duration.seconds ?? 0) * MS_PER_SECOND;\n const msMs = duration.milliseconds ?? 0;\n\n return daysMs + hoursMs + minsMs + secsMs + msMs;\n}\n\n/**\n * Convenience function to return a duration given an ms or Duration.\n */\nexport function durationOrMsToMs(duration: number | Duration): number {\n return typeof duration === \"number\" ? duration : durationToMs(duration);\n}\n\n/**\n * Format a given Duration object into a string. If the object has no fields,\n * then returns an empty string.\n *\n * @param style Defaults to 'short'\n */\nexport function formatDuration(duration: Duration, style?: DurationStyle) {\n style = style ?? \"short\";\n const stylePlural = getDurationStyleForPlural(style);\n\n const space = getValueAndUnitSeparator(style);\n\n const a: string[] = [];\n\n for (const unit of DURATION_TYPE_SEQUENCE) {\n const value = duration[unit];\n if (value === undefined) continue;\n\n const suffixMap = DURATION_STYLE_SUFFIX_MAP[unit];\n const suffix = value === 1 ? suffixMap[style] : suffixMap[stylePlural];\n a.push(value + space + suffix);\n }\n\n const separator = getDurationTypeSeparator(style);\n return a.join(separator);\n}\n\n/**\n * Convert a millisecond duration into a human-readable duration string.\n *\n * @param options.durationTypeForZero - Defaults to 'milliseconds'\n * @param options.style - Defaults to 'short'\n */\nexport function readableDuration(\n ms: number,\n options?: { durationTypeForZero?: DurationType; style?: DurationStyle },\n): string {\n const duration = msToDuration(ms, options?.durationTypeForZero);\n\n return formatDuration(duration, options?.style);\n}\n\n/** A shortened duration string useful for logging timings. */\nexport function elapsed(ms: number): string {\n // Use long format for 1 minute or over.\n if (ms > MS_PER_MINUTE) {\n return readableDuration(ms);\n }\n\n // Use seconds format for over 100ms.\n if (ms > 100) {\n return `${(ms / 1000).toFixed(3)}s`;\n }\n\n // Use milliseconds format.\n return ms + \"ms\";\n}\n","/**\n * Indexed DB key-value store with support for auto-expirations.\n *\n * Why use this?\n * 1. Extremely simple interface to use indexed DBs.\n * 2. Auto-expirations with GC frees you from worrying about data clean-up.\n * 3. Any serializable data type can be stored (except undefined).\n *\n * How to use?\n * Just use the `kvStore` global constant like the local storage, but with\n * async interface functions as required by indexed DB.\n *\n * Why not use the indexed DB directly?\n * It will require you to write a lot of code to reinvent the wheel.\n */\n\nimport { Duration, durationOrMsToMs } from \"./duration\";\nimport {\n FullStorageAdapter,\n StorageAdapter,\n StoredObject,\n} from \"./storageAdapter\";\nimport { MS_PER_DAY } from \"./timeConstants\";\n\n/** Global defaults can be updated directly. */\nexport const KvStoreConfig = {\n /**\n * Name of the DB in the indexed DB.\n * Updating the DB name will cause all old entries to be gone.\n */\n dbName: \"KVStore\",\n\n /**\n * Version of the DB schema. Most likely you will never want to change this.\n * Updating the version will cause all old entries to be gone.\n */\n dbVersion: 1,\n\n /**\n * Name of the store within the indexed DB. Each DB can have multiple stores.\n * In practice, it doesn't matter what you name this to be.\n */\n storeName: \"kvStore\",\n\n /** 30 days in ms. */\n expiryMs: MS_PER_DAY * 30,\n\n /** Do GC once per day. */\n gcIntervalMs: MS_PER_DAY,\n};\n\nexport type KvStoreConfig = typeof KvStoreConfig;\n\n/** Convenience function to update global defaults. */\nexport function configureKvStore(config: Partial<KvStoreConfig>) {\n Object.assign(KvStoreConfig, config);\n}\n\n/** Type to represent a full object with metadata stored in the store. */\nexport type KvStoredObject<T> = StoredObject<T> & {\n // The key is required by the ObjectStore.\n key: string;\n};\n\n/**\n * Parse a stored value string. Returns undefined if invalid or expired.\n * Throws an error if the string cannot be parsed as JSON.\n */\nfunction validateStoredObject<T>(\n obj: KvStoredObject<T>,\n): KvStoredObject<T> | undefined {\n if (\n !obj ||\n typeof obj !== \"object\" ||\n typeof obj.key !== \"string\" ||\n obj.value === undefined ||\n typeof obj.storedMs !== \"number\" ||\n typeof obj.expiryMs !== \"number\" ||\n Date.now() >= obj.expiryMs\n ) {\n return undefined;\n }\n\n return obj;\n}\n\n/** Add an `onerror` handler to the request. */\nfunction withOnError<T extends IDBRequest | IDBTransaction>(\n request: T,\n reject: (reason?: unknown) => void,\n): T {\n request.onerror = (event) => {\n reject(event);\n };\n\n return request;\n}\n\n/**\n * You can create multiple KvStores if you want, but most likely you will only\n * need to use the default `kvStore` instance.\n */\n// Using `any` because the store could store any type of data for each key,\n// but the caller can specify a more specific type when calling each of the\n// methods.\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\nexport class KvStore implements FullStorageAdapter<any> {\n /** We'll init the DB only on first use. */\n private db: IDBDatabase | undefined;\n\n /** Local storage key name for the last GC completed timestamp. */\n public readonly gcMsStorageKey: string;\n\n public readonly dbVersion: number;\n public readonly storeName: string;\n public readonly defaultExpiryMs: number;\n public readonly gcIntervalMs: number;\n\n public constructor(\n public readonly dbName: string,\n options?: {\n dbVersion?: number;\n storeName?: string;\n defaultExpiryMs?: number | Duration;\n gcIntervalMs?: number | Duration;\n },\n ) {\n this.dbVersion = options?.dbVersion ?? KvStoreConfig.dbVersion;\n this.storeName = options?.storeName ?? KvStoreConfig.storeName;\n\n this.defaultExpiryMs = options?.defaultExpiryMs\n ? durationOrMsToMs(options.defaultExpiryMs)\n : KvStoreConfig.expiryMs;\n\n this.gcIntervalMs = options?.gcIntervalMs\n ? durationOrMsToMs(options.gcIntervalMs)\n : KvStoreConfig.gcIntervalMs;\n\n this.gcMsStorageKey = `__kvStore:lastGcMs:${dbName}:v${this.dbVersion}:${this.storeName}`;\n }\n\n private async getOrCreateDb() {\n if (!this.db) {\n this.db = await new Promise<IDBDatabase>((resolve, reject) => {\n const request = withOnError(\n globalThis.indexedDB.open(this.dbName, this.dbVersion),\n reject,\n );\n\n request.onupgradeneeded = (event) => {\n const db = (event.target as unknown as { result: IDBDatabase })\n .result;\n\n // Create the store on DB init.\n const objectStore = db.createObjectStore(this.storeName, {\n keyPath: \"key\",\n });\n\n objectStore.createIndex(\"key\", \"key\", {\n unique: true,\n });\n };\n\n request.onsuccess = (event) => {\n const db = (event.target as unknown as { result: IDBDatabase })\n .result;\n resolve(db);\n };\n });\n }\n\n return this.db;\n }\n\n private async transact<T>(\n mode: IDBTransactionMode,\n callback: (\n objectStore: IDBObjectStore,\n resolve: (t: T) => void,\n reject: (reason?: unknown) => void,\n ) => void,\n ): Promise<T> {\n const db = await this.getOrCreateDb();\n\n return await new Promise<T>((resolve, reject) => {\n const transaction = withOnError(\n db.transaction(this.storeName, mode),\n reject,\n );\n\n transaction.onabort = (event) => {\n reject(event);\n };\n\n const objectStore = transaction.objectStore(this.storeName);\n\n callback(objectStore, resolve, reject);\n });\n }\n\n /** Set a value in the store. */\n public async set<T>(\n key: string,\n value: T,\n expiryDeltaMs: number | Duration = this.defaultExpiryMs,\n ): Promise<T> {\n const nowMs = Date.now();\n const obj: KvStoredObject<T> = {\n key,\n value,\n storedMs: nowMs,\n expiryMs: nowMs + durationOrMsToMs(expiryDeltaMs),\n };\n\n return await this.transact<T>(\n \"readwrite\",\n (objectStore, resolve, reject) => {\n const request = withOnError(objectStore.put(obj), reject);\n\n request.onsuccess = () => {\n resolve(value);\n\n this.gc(); // check GC on every write\n };\n },\n );\n }\n\n /** Delete one or multiple keys. */\n public async delete(key: string | string[]): Promise<void> {\n return await this.transact<void>(\n \"readwrite\",\n (objectStore, resolve, reject) => {\n objectStore.transaction.oncomplete = () => {\n resolve();\n };\n\n if (typeof key === \"string\") {\n withOnError(objectStore.delete(key), reject);\n } else {\n for (const k of key) {\n withOnError(objectStore.delete(k), reject);\n }\n }\n },\n );\n }\n\n /** Mainly used to get the expiration timestamp of an object. */\n public async getStoredObject<T>(\n key: string,\n ): Promise<KvStoredObject<T> | undefined> {\n const stored = await this.transact<KvStoredObject<T> | undefined>(\n \"readonly\",\n (objectStore, resolve, reject) => {\n const request = withOnError(objectStore.get(key), reject);\n\n request.onsuccess = () => {\n resolve(request.result);\n };\n },\n );\n\n if (!stored) {\n return undefined;\n }\n\n try {\n const obj = validateStoredObject(stored);\n if (!obj) {\n await this.delete(key);\n\n this.gc(); // check GC on every read of an expired key\n\n return undefined;\n }\n\n return obj;\n } catch (e) {\n console.error(`Invalid kv value: ${key}=${JSON.stringify(stored)}:`, e);\n await this.delete(key);\n\n this.gc(); // check GC on every read of an invalid key\n\n return undefined;\n }\n }\n\n /** Get a value by key, or undefined if it does not exist. */\n public async get<T>(key: string): Promise<T | undefined> {\n const obj = await this.getStoredObject<T>(key);\n\n return obj?.value;\n }\n\n /** Generic way to iterate through all entries. */\n public async forEach<T>(\n callback: (\n key: string,\n value: T,\n expiryMs: number,\n storedMs: number,\n ) => void | Promise<void>,\n ): Promise<void> {\n await this.transact<void>(\"readonly\", (objectStore, resolve, reject) => {\n const request = withOnError(objectStore.openCursor(), reject);\n\n request.onsuccess = async (event) => {\n const cursor = (\n event.target as unknown as { result: IDBCursorWithValue }\n ).result;\n\n if (cursor) {\n if (cursor.key) {\n const obj = validateStoredObject(cursor.value);\n if (obj !== undefined) {\n await callback(\n String(cursor.key),\n obj.value as T,\n obj.expiryMs,\n obj.storedMs,\n );\n }\n }\n cursor.continue();\n } else {\n resolve();\n }\n };\n });\n }\n\n /**\n * Returns the number of items in the store. Note that getting the size\n * requires iterating through the entire store because the items could expire\n * at any time, and hence the size is a dynamic number.\n */\n public async size(): Promise<number> {\n let count = 0;\n await this.forEach(() => {\n count++;\n });\n return count;\n }\n\n /** Remove all items from the store. */\n public async clear(): Promise<void> {\n const keys: string[] = [];\n await this.forEach((key) => {\n keys.push(key);\n });\n\n await this.delete(keys);\n }\n\n /**\n * Returns all items as map of key to value, mainly used for debugging dumps.\n * The type T is applied to all values, even though they might not be of type\n * T (in the case when you store different data types in the same store).\n */\n public async asMap<T>(): Promise<Map<string, StoredObject<T>>> {\n const map = new Map<string, StoredObject<T>>();\n await this.forEach((key, value, expiryMs, storedMs) => {\n map.set(key, { value: value as T, expiryMs, storedMs });\n });\n return map;\n }\n\n /** Returns the ms timestamp for the last GC (garbage collection). */\n public get lastGcMs(): number {\n const lastGcMsStr = globalThis.localStorage.getItem(this.gcMsStorageKey);\n if (!lastGcMsStr) return 0;\n\n const ms = Number(lastGcMsStr);\n return isNaN(ms) ? 0 : ms;\n }\n\n /** Set the ms timestamp for the last GC (garbage collection). */\n public set lastGcMs(ms: number) {\n globalThis.localStorage.setItem(this.gcMsStorageKey, String(ms));\n }\n\n /** Perform garbage-collection if due, else do nothing. */\n public async gc(): Promise<void> {\n const lastGcMs = this.lastGcMs;\n\n // Set initial timestamp - no need GC now.\n if (!lastGcMs) {\n this.lastGcMs = Date.now();\n return;\n }\n\n if (Date.now() < lastGcMs + this.gcIntervalMs) {\n return; // not due for next GC yet\n }\n\n // GC is due now, so run it.\n await this.gcNow();\n }\n\n /**\n * Perform garbage collection immediately without checking whether we are\n * due for the next GC or not.\n */\n public async gcNow(): Promise<void> {\n console.log(`Starting kvStore GC on ${this.dbName} v${this.dbVersion}...`);\n\n // Prevent concurrent GC runs.\n this.lastGcMs = Date.now();\n\n const keysToDelete: string[] = [];\n await this.forEach(\n async (key: string, value: unknown, expiryMs: number) => {\n if (value === undefined || Date.now() >= expiryMs) {\n keysToDelete.push(key);\n }\n },\n );\n\n if (keysToDelete.length) {\n await this.delete(keysToDelete);\n }\n\n console.log(\n `Finished kvStore GC on ${this.dbName} v${this.dbVersion} ` +\n `- deleted ${keysToDelete.length} keys`,\n );\n\n // Mark the end time as last GC time.\n this.lastGcMs = Date.now();\n }\n\n /** Returns `this` casted into a StorageAdapter<T>. */\n public asStorageAdapter<T>(): StorageAdapter<T> {\n return this as StorageAdapter<T>;\n }\n}\n\n/**\n * Default KV store ready for immediate use. You can create new instances if\n * you want, but most likely you will only need one store instance.\n */\nexport const kvStore = new KvStore(KvStoreConfig.dbName);\n\n/**\n * Class to represent one key in the store with a default expiration.\n */\nexport class KvStoreItem<T> {\n public readonly defaultExpiryMs: number;\n\n public constructor(\n public readonly key: string,\n defaultExpiryMs: number | Duration = KvStoreConfig.expiryMs,\n public readonly store = kvStore,\n ) {\n this.defaultExpiryMs = defaultExpiryMs && durationOrMsToMs(defaultExpiryMs);\n }\n\n /** Set a value in the store. */\n public async set(\n value: T,\n expiryDeltaMs: number | undefined = this.defaultExpiryMs,\n ): Promise<void> {\n await this.store.set(this.key, value, expiryDeltaMs);\n }\n\n /**\n * Example usage:\n *\n * const { value, storedMs, expiryMs, storedMs } =\n * await myKvItem.getStoredObject();\n */\n public async getStoredObject(): Promise<KvStoredObject<T> | undefined> {\n return await this.store.getStoredObject(this.key);\n }\n\n /** Get a value by key, or undefined if it does not exist. */\n public async get(): Promise<T | undefined> {\n return await this.store.get(this.key);\n }\n\n /** Delete this key from the store. */\n public async delete(): Promise<void> {\n await this.store.delete(this.key);\n }\n}\n\n/** Create a KV store item with a key and a default expiration. */\nexport function kvStoreItem<T>(\n key: string,\n expiryMs?: number | Duration,\n store = kvStore,\n): KvStoreItem<T> {\n expiryMs = expiryMs && durationOrMsToMs(expiryMs);\n\n return new KvStoreItem<T>(key, expiryMs, store);\n}\n"],"mappings":"AA0LO,SAASA,EAAa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AOA,CAAY,EAGhC,QAAQ,IACN,0BAA0B,KAAK,MAAM,KAAK,KAAK,SAAS,cACzCA,EAAa,MAAM,OACpC,EAGA,KAAK,SAAW,KAAK,IAAI,CAC3B,CAGO,kBAAyC,CAC9C,OAAO,IACT,CACF,EAMaC,EAAU,IAAI3B,EAAQT,EAAc,MAAM,EAK1CqC,EAAN,KAAqB,CAGnB,YACWlB,EAChBmB,EAAqCtC,EAAc,SACnCuC,EAAQH,EACxB,CAHgB,SAAAjB,EAEA,WAAAoB,EAEhB,KAAK,gBAAkBD,GAAmB1B,EAAiB0B,CAAe,CAC5E,CARgB,gBAWhB,MAAa,IACXlB,EACAC,EAAoC,KAAK,gBAC1B,CACf,MAAM,KAAK,MAAM,IAAI,KAAK,IAAKD,EAAOC,CAAa,CACrD,CAQA,MAAa,iBAA0D,CACrE,OAAO,MAAM,KAAK,MAAM,gBAAgB,KAAK,GAAG,CAClD,CAGA,MAAa,KAA8B,CACzC,OAAO,MAAM,KAAK,MAAM,IAAI,KAAK,GAAG,CACtC,CAGA,MAAa,QAAwB,CACnC,MAAM,KAAK,MAAM,OAAO,KAAK,GAAG,CAClC,CACF,EAGO,SAASmB,EACdrB,EACAW,EACAS,EAAQH,EACQ,CAChB,OAAAN,EAAWA,GAAYlB,EAAiBkB,CAAQ,EAEzC,IAAIO,EAAelB,EAAKW,EAAUS,CAAK,CAChD","names":["durationToMs","duration","daysMs","hoursMs","minsMs","secsMs","msMs","durationOrMsToMs","KvStoreConfig","configureKvStore","config","validateStoredObject","obj","withOnError","request","reject","event","KvStore","dbName","options","durationOrMsToMs","resolve","db","mode","callback","transaction","objectStore","key","value","expiryDeltaMs","nowMs","k","stored","e","cursor","count","keys","map","expiryMs","storedMs","lastGcMsStr","ms","lastGcMs","keysToDelete","kvStore","KvStoreItem","defaultExpiryMs","store","kvStoreItem"]}
|