@choksheak/ts-utils 0.3.3 → 0.3.5

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.
Files changed (131) hide show
  1. package/README.md +9 -3
  2. package/asNumber.cjs +6 -6
  3. package/asNumber.d.mts +1 -1
  4. package/asNumber.d.ts +1 -1
  5. package/asNumber.min.cjs +1 -1
  6. package/asNumber.min.cjs.map +1 -1
  7. package/asNumber.min.mjs +1 -1
  8. package/asNumber.min.mjs.map +1 -1
  9. package/asNumber.mjs +6 -6
  10. package/capLength.cjs +80 -0
  11. package/capLength.d.mts +3 -0
  12. package/capLength.d.ts +3 -0
  13. package/capLength.min.cjs +6 -0
  14. package/capLength.min.cjs.map +1 -0
  15. package/capLength.min.mjs +6 -0
  16. package/capLength.min.mjs.map +1 -0
  17. package/capLength.mjs +53 -0
  18. package/{iterators.cjs → concatIterators.cjs} +4 -4
  19. package/{iterators.min.cjs → concatIterators.min.cjs} +1 -1
  20. package/concatIterators.min.cjs.map +1 -0
  21. package/{iterators.min.mjs → concatIterators.min.mjs} +1 -1
  22. package/concatIterators.min.mjs.map +1 -0
  23. package/{iterators.mjs → concatIterators.mjs} +1 -1
  24. package/duration.min.cjs +1 -1
  25. package/duration.min.mjs +1 -1
  26. package/kvStore.cjs +230 -239
  27. package/kvStore.d.mts +142 -44
  28. package/kvStore.d.ts +142 -44
  29. package/kvStore.min.cjs +1 -1
  30. package/kvStore.min.cjs.map +1 -1
  31. package/kvStore.min.mjs +1 -1
  32. package/kvStore.min.mjs.map +1 -1
  33. package/kvStore.mjs +229 -237
  34. package/localStore.cjs +187 -186
  35. package/localStore.d.mts +135 -34
  36. package/localStore.d.ts +135 -34
  37. package/localStore.min.cjs +1 -1
  38. package/localStore.min.cjs.map +1 -1
  39. package/localStore.min.mjs +1 -1
  40. package/localStore.min.mjs.map +1 -1
  41. package/localStore.mjs +186 -184
  42. package/mean.cjs +6 -6
  43. package/mean.min.cjs +1 -1
  44. package/mean.min.cjs.map +1 -1
  45. package/mean.min.mjs +1 -1
  46. package/mean.min.mjs.map +1 -1
  47. package/mean.mjs +6 -6
  48. package/median.cjs +7 -7
  49. package/median.min.cjs +1 -1
  50. package/median.min.cjs.map +1 -1
  51. package/median.min.mjs +1 -1
  52. package/median.min.mjs.map +1 -1
  53. package/median.mjs +7 -7
  54. package/package.json +67 -82
  55. package/round.cjs +2 -10
  56. package/round.d.mts +2 -8
  57. package/round.d.ts +2 -8
  58. package/round.min.cjs +1 -1
  59. package/round.min.cjs.map +1 -1
  60. package/round.min.mjs +1 -1
  61. package/round.min.mjs.map +1 -1
  62. package/round.mjs +1 -8
  63. package/{safeParseInt.cjs → roundToString.cjs} +19 -9
  64. package/roundToString.d.mts +8 -0
  65. package/roundToString.d.ts +8 -0
  66. package/roundToString.min.cjs +2 -0
  67. package/roundToString.min.cjs.map +1 -0
  68. package/roundToString.min.mjs +2 -0
  69. package/roundToString.min.mjs.map +1 -0
  70. package/roundToString.mjs +16 -0
  71. package/safeBtoa.d.mts +7 -0
  72. package/safeBtoa.d.ts +7 -0
  73. package/safeBtoa.min.cjs.map +1 -1
  74. package/safeBtoa.min.mjs.map +1 -1
  75. package/sum.cjs +6 -6
  76. package/sum.min.cjs +1 -1
  77. package/sum.min.cjs.map +1 -1
  78. package/sum.min.mjs +1 -1
  79. package/sum.min.mjs.map +1 -1
  80. package/sum.mjs +6 -6
  81. package/timer.cjs +19 -24
  82. package/timer.d.mts +9 -6
  83. package/timer.d.ts +9 -6
  84. package/timer.min.cjs +1 -1
  85. package/timer.min.cjs.map +1 -1
  86. package/timer.min.mjs +1 -1
  87. package/timer.min.mjs.map +1 -1
  88. package/timer.mjs +19 -23
  89. package/toReadableString.cjs +69 -0
  90. package/toReadableString.d.mts +10 -0
  91. package/toReadableString.d.ts +10 -0
  92. package/toReadableString.min.cjs +6 -0
  93. package/toReadableString.min.cjs.map +1 -0
  94. package/toReadableString.min.mjs +6 -0
  95. package/toReadableString.min.mjs.map +1 -0
  96. package/toReadableString.mjs +44 -0
  97. package/average.cjs +0 -55
  98. package/average.d.mts +0 -7
  99. package/average.d.ts +0 -7
  100. package/average.min.cjs +0 -2
  101. package/average.min.cjs.map +0 -1
  102. package/average.min.mjs +0 -2
  103. package/average.min.mjs.map +0 -1
  104. package/average.mjs +0 -28
  105. package/iterators.min.cjs.map +0 -1
  106. package/iterators.min.mjs.map +0 -1
  107. package/logging.cjs +0 -47
  108. package/logging.d.mts +0 -4
  109. package/logging.d.ts +0 -4
  110. package/logging.min.cjs +0 -2
  111. package/logging.min.cjs.map +0 -1
  112. package/logging.min.mjs +0 -2
  113. package/logging.min.mjs.map +0 -1
  114. package/logging.mjs +0 -21
  115. package/safeParseFloat.cjs +0 -33
  116. package/safeParseFloat.d.mts +0 -6
  117. package/safeParseFloat.d.ts +0 -6
  118. package/safeParseFloat.min.cjs +0 -2
  119. package/safeParseFloat.min.cjs.map +0 -1
  120. package/safeParseFloat.min.mjs +0 -2
  121. package/safeParseFloat.min.mjs.map +0 -1
  122. package/safeParseFloat.mjs +0 -8
  123. package/safeParseInt.d.mts +0 -6
  124. package/safeParseInt.d.ts +0 -6
  125. package/safeParseInt.min.cjs +0 -2
  126. package/safeParseInt.min.cjs.map +0 -1
  127. package/safeParseInt.min.mjs +0 -2
  128. package/safeParseInt.min.mjs.map +0 -1
  129. package/safeParseInt.mjs +0 -8
  130. /package/{iterators.d.mts → concatIterators.d.mts} +0 -0
  131. /package/{iterators.d.ts → concatIterators.d.ts} +0 -0
package/kvStore.d.mts CHANGED
@@ -1,5 +1,5 @@
1
1
  import { Duration } from './duration.mjs';
2
- import { StoredObject, FullStorageAdapter, StorageAdapter } from './storageAdapter.mjs';
2
+ import { StoredObject, StorageAdapter } from './storageAdapter.mjs';
3
3
 
4
4
  /**
5
5
  * Indexed DB key-value store with support for auto-expirations.
@@ -50,90 +50,188 @@ type KvStoredObject<T> = StoredObject<T> & {
50
50
  * You can create multiple KvStores if you want, but most likely you will only
51
51
  * need to use the default `kvStore` instance.
52
52
  */
53
- declare class KvStore implements FullStorageAdapter<any> {
53
+ declare function createKvStore(dbName: string, options?: {
54
+ dbVersion?: number;
55
+ storeName?: string;
56
+ defaultExpiryMs?: number | Duration;
57
+ gcIntervalMs?: number | Duration;
58
+ }): {
59
+ /** Input name for the DB. */
54
60
  readonly dbName: string;
55
- /** We'll init the DB only on first use. */
56
- private db;
57
- /** Local storage key name for the last GC completed timestamp. */
58
- readonly gcMsStorageKey: string;
61
+ /** Input version for the DB. */
59
62
  readonly dbVersion: number;
63
+ /** Input name for the DB store. */
60
64
  readonly storeName: string;
65
+ /** Default expiry to use if not specified in set(). */
61
66
  readonly defaultExpiryMs: number;
67
+ /** Time interval for when GC's occur. */
62
68
  readonly gcIntervalMs: number;
63
- constructor(dbName: string, options?: {
64
- dbVersion?: number;
65
- storeName?: string;
66
- defaultExpiryMs?: number | Duration;
67
- gcIntervalMs?: number | Duration;
68
- });
69
- private getOrCreateDb;
70
- private transact;
69
+ /** Local storage key name for the last GC completed timestamp. */
70
+ readonly gcMsStorageKey: string;
71
71
  /** Set a value in the store. */
72
- set<T>(key: string, value: T, expiryDeltaMs?: number | Duration): Promise<T>;
72
+ readonly set: <T>(key: string, value: T, expiryDeltaMs?: number | Duration) => Promise<T>;
73
73
  /** Delete one or multiple keys. */
74
- delete(key: string | string[]): Promise<void>;
74
+ readonly delete: (key: string | string[]) => Promise<void>;
75
75
  /** Mainly used to get the expiration timestamp of an object. */
76
- getStoredObject<T>(key: string): Promise<KvStoredObject<T> | undefined>;
76
+ readonly getStoredObject: <T>(key: string) => Promise<KvStoredObject<T> | undefined>;
77
77
  /** Get a value by key, or undefined if it does not exist. */
78
- get<T>(key: string): Promise<T | undefined>;
78
+ readonly get: <T>(key: string) => Promise<T | undefined>;
79
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>;
80
+ readonly forEach: <T>(callback: (key: string, value: T, expiryMs: number, storedMs: number) => void | Promise<void>) => Promise<void>;
81
81
  /**
82
82
  * Returns the number of items in the store. Note that getting the size
83
83
  * requires iterating through the entire store because the items could expire
84
84
  * at any time, and hence the size is a dynamic number.
85
85
  */
86
- size(): Promise<number>;
86
+ readonly size: () => Promise<number>;
87
87
  /** Remove all items from the store. */
88
- clear(): Promise<void>;
88
+ readonly clear: () => Promise<void>;
89
89
  /**
90
90
  * Returns all items as map of key to value, mainly used for debugging dumps.
91
91
  * The type T is applied to all values, even though they might not be of type
92
92
  * T (in the case when you store different data types in the same store).
93
93
  */
94
- asMap<T>(): Promise<Map<string, StoredObject<T>>>;
94
+ readonly asMap: <T>() => Promise<Map<string, StoredObject<T>>>;
95
95
  /** Returns the ms timestamp for the last GC (garbage collection). */
96
- get lastGcMs(): number;
96
+ readonly getLastGcMs: () => number;
97
97
  /** Set the ms timestamp for the last GC (garbage collection). */
98
- set lastGcMs(ms: number);
98
+ readonly setLastGcMs: (ms: number) => void;
99
99
  /** Perform garbage-collection if due, else do nothing. */
100
- gc(): Promise<void>;
100
+ readonly gc: () => Promise<void>;
101
101
  /**
102
102
  * Perform garbage collection immediately without checking whether we are
103
103
  * due for the next GC or not.
104
104
  */
105
- gcNow(): Promise<void>;
105
+ readonly gcNow: () => Promise<void>;
106
106
  /** Returns `this` casted into a StorageAdapter<T>. */
107
- asStorageAdapter<T>(): StorageAdapter<T>;
108
- }
107
+ readonly asStorageAdapter: <T>() => StorageAdapter<T>;
108
+ };
109
+ type KvStore = ReturnType<typeof createKvStore>;
109
110
  /**
110
111
  * Default KV store ready for immediate use. You can create new instances if
111
112
  * you want, but most likely you will only need one store instance.
112
113
  */
113
- declare const kvStore: KvStore;
114
- /**
115
- * Class to represent one key in the store with a default expiration.
116
- */
117
- declare class KvStoreItem<T> {
118
- readonly key: string;
119
- readonly store: KvStore;
114
+ declare const kvStore: {
115
+ /** Input name for the DB. */
116
+ readonly dbName: string;
117
+ /** Input version for the DB. */
118
+ readonly dbVersion: number;
119
+ /** Input name for the DB store. */
120
+ readonly storeName: string;
121
+ /** Default expiry to use if not specified in set(). */
120
122
  readonly defaultExpiryMs: number;
121
- constructor(key: string, defaultExpiryMs?: number | Duration, store?: KvStore);
123
+ /** Time interval for when GC's occur. */
124
+ readonly gcIntervalMs: number;
125
+ /** Local storage key name for the last GC completed timestamp. */
126
+ readonly gcMsStorageKey: string;
122
127
  /** Set a value in the store. */
123
- set(value: T, expiryDeltaMs?: number | undefined): Promise<void>;
128
+ readonly set: <T>(key: string, value: T, expiryDeltaMs?: number | Duration) => Promise<T>;
129
+ /** Delete one or multiple keys. */
130
+ readonly delete: (key: string | string[]) => Promise<void>;
131
+ /** Mainly used to get the expiration timestamp of an object. */
132
+ readonly getStoredObject: <T>(key: string) => Promise<KvStoredObject<T> | undefined>;
133
+ /** Get a value by key, or undefined if it does not exist. */
134
+ readonly get: <T>(key: string) => Promise<T | undefined>;
135
+ /** Generic way to iterate through all entries. */
136
+ readonly forEach: <T>(callback: (key: string, value: T, expiryMs: number, storedMs: number) => void | Promise<void>) => Promise<void>;
137
+ /**
138
+ * Returns the number of items in the store. Note that getting the size
139
+ * requires iterating through the entire store because the items could expire
140
+ * at any time, and hence the size is a dynamic number.
141
+ */
142
+ readonly size: () => Promise<number>;
143
+ /** Remove all items from the store. */
144
+ readonly clear: () => Promise<void>;
145
+ /**
146
+ * Returns all items as map of key to value, mainly used for debugging dumps.
147
+ * The type T is applied to all values, even though they might not be of type
148
+ * T (in the case when you store different data types in the same store).
149
+ */
150
+ readonly asMap: <T>() => Promise<Map<string, StoredObject<T>>>;
151
+ /** Returns the ms timestamp for the last GC (garbage collection). */
152
+ readonly getLastGcMs: () => number;
153
+ /** Set the ms timestamp for the last GC (garbage collection). */
154
+ readonly setLastGcMs: (ms: number) => void;
155
+ /** Perform garbage-collection if due, else do nothing. */
156
+ readonly gc: () => Promise<void>;
157
+ /**
158
+ * Perform garbage collection immediately without checking whether we are
159
+ * due for the next GC or not.
160
+ */
161
+ readonly gcNow: () => Promise<void>;
162
+ /** Returns `this` casted into a StorageAdapter<T>. */
163
+ readonly asStorageAdapter: <T>() => StorageAdapter<T>;
164
+ };
165
+ /** Create a KV store item with a key and a default expiration. */
166
+ declare function kvStoreItem<T>(key: string, expiryMs?: number | Duration, store?: KvStore): {
167
+ readonly key: string;
168
+ readonly defaultExpiryMs: number | undefined;
169
+ readonly store: {
170
+ /** Input name for the DB. */
171
+ readonly dbName: string;
172
+ /** Input version for the DB. */
173
+ readonly dbVersion: number;
174
+ /** Input name for the DB store. */
175
+ readonly storeName: string;
176
+ /** Default expiry to use if not specified in set(). */
177
+ readonly defaultExpiryMs: number;
178
+ /** Time interval for when GC's occur. */
179
+ readonly gcIntervalMs: number;
180
+ /** Local storage key name for the last GC completed timestamp. */
181
+ readonly gcMsStorageKey: string;
182
+ /** Set a value in the store. */
183
+ readonly set: <T_1>(key: string, value: T_1, expiryDeltaMs?: number | Duration) => Promise<T_1>;
184
+ /** Delete one or multiple keys. */
185
+ readonly delete: (key: string | string[]) => Promise<void>;
186
+ /** Mainly used to get the expiration timestamp of an object. */
187
+ readonly getStoredObject: <T_1>(key: string) => Promise<KvStoredObject<T_1> | undefined>;
188
+ /** Get a value by key, or undefined if it does not exist. */
189
+ readonly get: <T_1>(key: string) => Promise<T_1 | undefined>;
190
+ /** Generic way to iterate through all entries. */
191
+ readonly forEach: <T_1>(callback: (key: string, value: T_1, expiryMs: number, storedMs: number) => void | Promise<void>) => Promise<void>;
192
+ /**
193
+ * Returns the number of items in the store. Note that getting the size
194
+ * requires iterating through the entire store because the items could expire
195
+ * at any time, and hence the size is a dynamic number.
196
+ */
197
+ readonly size: () => Promise<number>;
198
+ /** Remove all items from the store. */
199
+ readonly clear: () => Promise<void>;
200
+ /**
201
+ * Returns all items as map of key to value, mainly used for debugging dumps.
202
+ * The type T is applied to all values, even though they might not be of type
203
+ * T (in the case when you store different data types in the same store).
204
+ */
205
+ readonly asMap: <T_1>() => Promise<Map<string, StoredObject<T_1>>>;
206
+ /** Returns the ms timestamp for the last GC (garbage collection). */
207
+ readonly getLastGcMs: () => number;
208
+ /** Set the ms timestamp for the last GC (garbage collection). */
209
+ readonly setLastGcMs: (ms: number) => void;
210
+ /** Perform garbage-collection if due, else do nothing. */
211
+ readonly gc: () => Promise<void>;
212
+ /**
213
+ * Perform garbage collection immediately without checking whether we are
214
+ * due for the next GC or not.
215
+ */
216
+ readonly gcNow: () => Promise<void>;
217
+ /** Returns `this` casted into a StorageAdapter<T>. */
218
+ readonly asStorageAdapter: <T_1>() => StorageAdapter<T_1>;
219
+ };
220
+ /** Set a value in the store. */
221
+ readonly set: (value: T, expiryDeltaMs?: number | undefined) => Promise<void>;
124
222
  /**
125
223
  * Example usage:
126
224
  *
127
225
  * const { value, storedMs, expiryMs, storedMs } =
128
226
  * await myKvItem.getStoredObject();
129
227
  */
130
- getStoredObject(): Promise<KvStoredObject<T> | undefined>;
228
+ readonly getStoredObject: () => Promise<KvStoredObject<T> | undefined>;
131
229
  /** Get a value by key, or undefined if it does not exist. */
132
- get(): Promise<T | undefined>;
230
+ readonly get: () => Promise<T | undefined>;
133
231
  /** Delete this key from the store. */
134
- delete(): Promise<void>;
135
- }
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>;
232
+ readonly delete: () => Promise<void>;
233
+ };
234
+ /** Class to represent one key in the store with a default expiration. */
235
+ type KvStoreItem<T> = ReturnType<typeof kvStoreItem<T>>;
138
236
 
139
- export { KvStore, KvStoreConfig, KvStoreItem, type KvStoredObject, configureKvStore, kvStore, kvStoreItem };
237
+ export { type KvStore, KvStoreConfig, type KvStoreItem, type KvStoredObject, configureKvStore, createKvStore, kvStore, kvStoreItem };
package/kvStore.d.ts CHANGED
@@ -1,5 +1,5 @@
1
1
  import { Duration } from './duration.js';
2
- import { StoredObject, FullStorageAdapter, StorageAdapter } from './storageAdapter.js';
2
+ import { StoredObject, StorageAdapter } from './storageAdapter.js';
3
3
 
4
4
  /**
5
5
  * Indexed DB key-value store with support for auto-expirations.
@@ -50,90 +50,188 @@ type KvStoredObject<T> = StoredObject<T> & {
50
50
  * You can create multiple KvStores if you want, but most likely you will only
51
51
  * need to use the default `kvStore` instance.
52
52
  */
53
- declare class KvStore implements FullStorageAdapter<any> {
53
+ declare function createKvStore(dbName: string, options?: {
54
+ dbVersion?: number;
55
+ storeName?: string;
56
+ defaultExpiryMs?: number | Duration;
57
+ gcIntervalMs?: number | Duration;
58
+ }): {
59
+ /** Input name for the DB. */
54
60
  readonly dbName: string;
55
- /** We'll init the DB only on first use. */
56
- private db;
57
- /** Local storage key name for the last GC completed timestamp. */
58
- readonly gcMsStorageKey: string;
61
+ /** Input version for the DB. */
59
62
  readonly dbVersion: number;
63
+ /** Input name for the DB store. */
60
64
  readonly storeName: string;
65
+ /** Default expiry to use if not specified in set(). */
61
66
  readonly defaultExpiryMs: number;
67
+ /** Time interval for when GC's occur. */
62
68
  readonly gcIntervalMs: number;
63
- constructor(dbName: string, options?: {
64
- dbVersion?: number;
65
- storeName?: string;
66
- defaultExpiryMs?: number | Duration;
67
- gcIntervalMs?: number | Duration;
68
- });
69
- private getOrCreateDb;
70
- private transact;
69
+ /** Local storage key name for the last GC completed timestamp. */
70
+ readonly gcMsStorageKey: string;
71
71
  /** Set a value in the store. */
72
- set<T>(key: string, value: T, expiryDeltaMs?: number | Duration): Promise<T>;
72
+ readonly set: <T>(key: string, value: T, expiryDeltaMs?: number | Duration) => Promise<T>;
73
73
  /** Delete one or multiple keys. */
74
- delete(key: string | string[]): Promise<void>;
74
+ readonly delete: (key: string | string[]) => Promise<void>;
75
75
  /** Mainly used to get the expiration timestamp of an object. */
76
- getStoredObject<T>(key: string): Promise<KvStoredObject<T> | undefined>;
76
+ readonly getStoredObject: <T>(key: string) => Promise<KvStoredObject<T> | undefined>;
77
77
  /** Get a value by key, or undefined if it does not exist. */
78
- get<T>(key: string): Promise<T | undefined>;
78
+ readonly get: <T>(key: string) => Promise<T | undefined>;
79
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>;
80
+ readonly forEach: <T>(callback: (key: string, value: T, expiryMs: number, storedMs: number) => void | Promise<void>) => Promise<void>;
81
81
  /**
82
82
  * Returns the number of items in the store. Note that getting the size
83
83
  * requires iterating through the entire store because the items could expire
84
84
  * at any time, and hence the size is a dynamic number.
85
85
  */
86
- size(): Promise<number>;
86
+ readonly size: () => Promise<number>;
87
87
  /** Remove all items from the store. */
88
- clear(): Promise<void>;
88
+ readonly clear: () => Promise<void>;
89
89
  /**
90
90
  * Returns all items as map of key to value, mainly used for debugging dumps.
91
91
  * The type T is applied to all values, even though they might not be of type
92
92
  * T (in the case when you store different data types in the same store).
93
93
  */
94
- asMap<T>(): Promise<Map<string, StoredObject<T>>>;
94
+ readonly asMap: <T>() => Promise<Map<string, StoredObject<T>>>;
95
95
  /** Returns the ms timestamp for the last GC (garbage collection). */
96
- get lastGcMs(): number;
96
+ readonly getLastGcMs: () => number;
97
97
  /** Set the ms timestamp for the last GC (garbage collection). */
98
- set lastGcMs(ms: number);
98
+ readonly setLastGcMs: (ms: number) => void;
99
99
  /** Perform garbage-collection if due, else do nothing. */
100
- gc(): Promise<void>;
100
+ readonly gc: () => Promise<void>;
101
101
  /**
102
102
  * Perform garbage collection immediately without checking whether we are
103
103
  * due for the next GC or not.
104
104
  */
105
- gcNow(): Promise<void>;
105
+ readonly gcNow: () => Promise<void>;
106
106
  /** Returns `this` casted into a StorageAdapter<T>. */
107
- asStorageAdapter<T>(): StorageAdapter<T>;
108
- }
107
+ readonly asStorageAdapter: <T>() => StorageAdapter<T>;
108
+ };
109
+ type KvStore = ReturnType<typeof createKvStore>;
109
110
  /**
110
111
  * Default KV store ready for immediate use. You can create new instances if
111
112
  * you want, but most likely you will only need one store instance.
112
113
  */
113
- declare const kvStore: KvStore;
114
- /**
115
- * Class to represent one key in the store with a default expiration.
116
- */
117
- declare class KvStoreItem<T> {
118
- readonly key: string;
119
- readonly store: KvStore;
114
+ declare const kvStore: {
115
+ /** Input name for the DB. */
116
+ readonly dbName: string;
117
+ /** Input version for the DB. */
118
+ readonly dbVersion: number;
119
+ /** Input name for the DB store. */
120
+ readonly storeName: string;
121
+ /** Default expiry to use if not specified in set(). */
120
122
  readonly defaultExpiryMs: number;
121
- constructor(key: string, defaultExpiryMs?: number | Duration, store?: KvStore);
123
+ /** Time interval for when GC's occur. */
124
+ readonly gcIntervalMs: number;
125
+ /** Local storage key name for the last GC completed timestamp. */
126
+ readonly gcMsStorageKey: string;
122
127
  /** Set a value in the store. */
123
- set(value: T, expiryDeltaMs?: number | undefined): Promise<void>;
128
+ readonly set: <T>(key: string, value: T, expiryDeltaMs?: number | Duration) => Promise<T>;
129
+ /** Delete one or multiple keys. */
130
+ readonly delete: (key: string | string[]) => Promise<void>;
131
+ /** Mainly used to get the expiration timestamp of an object. */
132
+ readonly getStoredObject: <T>(key: string) => Promise<KvStoredObject<T> | undefined>;
133
+ /** Get a value by key, or undefined if it does not exist. */
134
+ readonly get: <T>(key: string) => Promise<T | undefined>;
135
+ /** Generic way to iterate through all entries. */
136
+ readonly forEach: <T>(callback: (key: string, value: T, expiryMs: number, storedMs: number) => void | Promise<void>) => Promise<void>;
137
+ /**
138
+ * Returns the number of items in the store. Note that getting the size
139
+ * requires iterating through the entire store because the items could expire
140
+ * at any time, and hence the size is a dynamic number.
141
+ */
142
+ readonly size: () => Promise<number>;
143
+ /** Remove all items from the store. */
144
+ readonly clear: () => Promise<void>;
145
+ /**
146
+ * Returns all items as map of key to value, mainly used for debugging dumps.
147
+ * The type T is applied to all values, even though they might not be of type
148
+ * T (in the case when you store different data types in the same store).
149
+ */
150
+ readonly asMap: <T>() => Promise<Map<string, StoredObject<T>>>;
151
+ /** Returns the ms timestamp for the last GC (garbage collection). */
152
+ readonly getLastGcMs: () => number;
153
+ /** Set the ms timestamp for the last GC (garbage collection). */
154
+ readonly setLastGcMs: (ms: number) => void;
155
+ /** Perform garbage-collection if due, else do nothing. */
156
+ readonly gc: () => Promise<void>;
157
+ /**
158
+ * Perform garbage collection immediately without checking whether we are
159
+ * due for the next GC or not.
160
+ */
161
+ readonly gcNow: () => Promise<void>;
162
+ /** Returns `this` casted into a StorageAdapter<T>. */
163
+ readonly asStorageAdapter: <T>() => StorageAdapter<T>;
164
+ };
165
+ /** Create a KV store item with a key and a default expiration. */
166
+ declare function kvStoreItem<T>(key: string, expiryMs?: number | Duration, store?: KvStore): {
167
+ readonly key: string;
168
+ readonly defaultExpiryMs: number | undefined;
169
+ readonly store: {
170
+ /** Input name for the DB. */
171
+ readonly dbName: string;
172
+ /** Input version for the DB. */
173
+ readonly dbVersion: number;
174
+ /** Input name for the DB store. */
175
+ readonly storeName: string;
176
+ /** Default expiry to use if not specified in set(). */
177
+ readonly defaultExpiryMs: number;
178
+ /** Time interval for when GC's occur. */
179
+ readonly gcIntervalMs: number;
180
+ /** Local storage key name for the last GC completed timestamp. */
181
+ readonly gcMsStorageKey: string;
182
+ /** Set a value in the store. */
183
+ readonly set: <T_1>(key: string, value: T_1, expiryDeltaMs?: number | Duration) => Promise<T_1>;
184
+ /** Delete one or multiple keys. */
185
+ readonly delete: (key: string | string[]) => Promise<void>;
186
+ /** Mainly used to get the expiration timestamp of an object. */
187
+ readonly getStoredObject: <T_1>(key: string) => Promise<KvStoredObject<T_1> | undefined>;
188
+ /** Get a value by key, or undefined if it does not exist. */
189
+ readonly get: <T_1>(key: string) => Promise<T_1 | undefined>;
190
+ /** Generic way to iterate through all entries. */
191
+ readonly forEach: <T_1>(callback: (key: string, value: T_1, expiryMs: number, storedMs: number) => void | Promise<void>) => Promise<void>;
192
+ /**
193
+ * Returns the number of items in the store. Note that getting the size
194
+ * requires iterating through the entire store because the items could expire
195
+ * at any time, and hence the size is a dynamic number.
196
+ */
197
+ readonly size: () => Promise<number>;
198
+ /** Remove all items from the store. */
199
+ readonly clear: () => Promise<void>;
200
+ /**
201
+ * Returns all items as map of key to value, mainly used for debugging dumps.
202
+ * The type T is applied to all values, even though they might not be of type
203
+ * T (in the case when you store different data types in the same store).
204
+ */
205
+ readonly asMap: <T_1>() => Promise<Map<string, StoredObject<T_1>>>;
206
+ /** Returns the ms timestamp for the last GC (garbage collection). */
207
+ readonly getLastGcMs: () => number;
208
+ /** Set the ms timestamp for the last GC (garbage collection). */
209
+ readonly setLastGcMs: (ms: number) => void;
210
+ /** Perform garbage-collection if due, else do nothing. */
211
+ readonly gc: () => Promise<void>;
212
+ /**
213
+ * Perform garbage collection immediately without checking whether we are
214
+ * due for the next GC or not.
215
+ */
216
+ readonly gcNow: () => Promise<void>;
217
+ /** Returns `this` casted into a StorageAdapter<T>. */
218
+ readonly asStorageAdapter: <T_1>() => StorageAdapter<T_1>;
219
+ };
220
+ /** Set a value in the store. */
221
+ readonly set: (value: T, expiryDeltaMs?: number | undefined) => Promise<void>;
124
222
  /**
125
223
  * Example usage:
126
224
  *
127
225
  * const { value, storedMs, expiryMs, storedMs } =
128
226
  * await myKvItem.getStoredObject();
129
227
  */
130
- getStoredObject(): Promise<KvStoredObject<T> | undefined>;
228
+ readonly getStoredObject: () => Promise<KvStoredObject<T> | undefined>;
131
229
  /** Get a value by key, or undefined if it does not exist. */
132
- get(): Promise<T | undefined>;
230
+ readonly get: () => Promise<T | undefined>;
133
231
  /** Delete this key from the store. */
134
- delete(): Promise<void>;
135
- }
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>;
232
+ readonly delete: () => Promise<void>;
233
+ };
234
+ /** Class to represent one key in the store with a default expiration. */
235
+ type KvStoreItem<T> = ReturnType<typeof kvStoreItem<T>>;
138
236
 
139
- export { KvStore, KvStoreConfig, KvStoreItem, type KvStoredObject, configureKvStore, kvStore, kvStoreItem };
237
+ export { type KvStore, KvStoreConfig, type KvStoreItem, type KvStoredObject, configureKvStore, createKvStore, kvStore, kvStoreItem };
package/kvStore.min.cjs CHANGED
@@ -1,2 +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:()=>l,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 l={dbName:"KVStore",dbVersion:1,storeName:"kvStore",expiryMs:864e5*30,gcIntervalMs:864e5};function O(r){Object.assign(l,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 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 y=c(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")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=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=c(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(){await this.transact("readwrite",(t,e,s)=>{let n=c(t.clear(),s);n.onsuccess=()=>{e()}})}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 N(r,t,e=h){return t=t&&d(t),new g(r,t,e)}0&&(module.exports={KvStore,KvStoreConfig,KvStoreItem,configureKvStore,kvStore,kvStoreItem});
1
+ "use strict";var T=Object.defineProperty;var E=Object.getOwnPropertyDescriptor;var I=Object.getOwnPropertyNames;var _=Object.prototype.hasOwnProperty;var k=(e,n)=>{for(var a in n)T(e,a,{get:n[a],enumerable:!0})},K=(e,n,a,d)=>{if(n&&typeof n=="object"||typeof n=="function")for(let c of I(n))!_.call(e,c)&&c!==a&&T(e,c,{get:()=>n[c],enumerable:!(d=E(n,c))||d.enumerable});return e};var j=e=>K(T({},"__esModule",{value:!0}),e);var C={};k(C,{KvStoreConfig:()=>p,configureKvStore:()=>R,createKvStore:()=>h,kvStore:()=>x,kvStoreItem:()=>A});module.exports=j(C);function N(e){let n=(e.days??0)*864e5,a=(e.hours??0)*36e5,d=(e.minutes??0)*6e4,c=(e.seconds??0)*1e3,y=e.milliseconds??0;return n+a+d+c+y}function b(e){return typeof e=="number"?e:N(e)}var p={dbName:"KVStore",dbVersion:1,storeName:"kvStore",expiryMs:864e5*30,gcIntervalMs:864e5};function R(e){Object.assign(p,e)}function w(e){if(!(!e||typeof e!="object"||typeof e.key!="string"||e.value===void 0||typeof e.storedMs!="number"||typeof e.expiryMs!="number"||Date.now()>=e.expiryMs))return e}function m(e,n){return e.onerror=a=>{n(a)},e}function h(e,n){let a,d=n?.dbVersion??p.dbVersion,c=n?.storeName??p.storeName,y=n?.defaultExpiryMs?b(n.defaultExpiryMs):p.expiryMs,D=n?.gcIntervalMs?b(n.gcIntervalMs):p.gcIntervalMs,M=`__kvStore:lastGcMs:${e}:v${d}:${c}`;async function P(){return a||(a=await new Promise((t,r)=>{let o=m(indexedDB.open(e,d),r);o.onupgradeneeded=s=>{s.target.result.createObjectStore(c,{keyPath:"key"}).createIndex("key","key",{unique:!0})},o.onsuccess=s=>{let u=s.target.result;t(u)}})),a}async function S(t,r){let o=await P();return await new Promise((s,u)=>{let l=m(o.transaction(c,t),u);l.onabort=g=>{u(g)};let f=l.objectStore(c);r(f,s,u)})}let i={dbName:e,dbVersion:d,storeName:c,defaultExpiryMs:y,gcIntervalMs:D,gcMsStorageKey:M,async set(t,r,o){let s=Date.now(),u={key:t,value:r,storedMs:s,expiryMs:s+b(o??y)};return await S("readwrite",(l,f,g)=>{let O=m(l.put(u),g);O.onsuccess=()=>{f(r),i.gc()}})},async delete(t){return await S("readwrite",(r,o,s)=>{if(r.transaction.oncomplete=()=>{o()},typeof t=="string")m(r.delete(t),s);else for(let u of t)m(r.delete(u),s)})},async getStoredObject(t){let r=await S("readonly",(o,s,u)=>{let l=m(o.get(t),u);l.onsuccess=()=>{s(l.result)}});if(r)try{let o=w(r);if(!o){await i.delete(t),i.gc();return}return o}catch(o){console.error(`Invalid kv value: ${t}=${JSON.stringify(r)}:`,o),await i.delete(t),i.gc();return}},async get(t){return(await i.getStoredObject(t))?.value},async forEach(t){await S("readonly",(r,o,s)=>{let u=m(r.openCursor(),s);u.onsuccess=async l=>{let f=l.target.result;if(f){if(f.key){let g=w(f.value);g!==void 0&&await t(String(f.key),g.value,g.expiryMs,g.storedMs)}f.continue()}else o()}})},async size(){let t=0;return await i.forEach(()=>{t++}),t},async clear(){await S("readwrite",(t,r,o)=>{let s=m(t.clear(),o);s.onsuccess=()=>{r()}})},async asMap(){let t=new Map;return await i.forEach((r,o,s,u)=>{t.set(r,{value:o,expiryMs:s,storedMs:u})}),t},getLastGcMs(){let t=localStorage.getItem(M);if(!t)return 0;let r=Number(t);return isNaN(r)?0:r},setLastGcMs(t){localStorage.setItem(M,String(t))},async gc(){let t=i.getLastGcMs();if(!t){i.setLastGcMs(Date.now());return}Date.now()<t+D||await i.gcNow()},async gcNow(){console.log(`Starting kvStore GC on ${e} v${d}...`),i.setLastGcMs(Date.now());let t=[];await i.forEach(async(r,o,s)=>{(o===void 0||Date.now()>=s)&&t.push(r)}),t.length&&await i.delete(t),console.log(`Finished kvStore GC on ${e} v${d} - deleted ${t.length} keys`),i.setLastGcMs(Date.now())},asStorageAdapter(){return i}};return i}var x=h(p.dbName);function A(e,n,a=x){let d=n&&b(n);return{key:e,defaultExpiryMs:d,store:a,async set(y,D){await a.set(e,y,D??d)},async getStoredObject(){return await a.getStoredObject(e)},async get(){return await a.get(e)},async delete(){await a.delete(e)}}}0&&(module.exports={KvStoreConfig,configureKvStore,createKvStore,kvStore,kvStoreItem});
2
2
  //# sourceMappingURL=kvStore.min.cjs.map