@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.
Files changed (315) hide show
  1. package/README.md +2 -0
  2. package/{arrayBuffer.js → arrayBuffer.cjs} +0 -1
  3. package/arrayBuffer.d.mts +10 -0
  4. package/arrayBuffer.d.ts +4 -2
  5. package/arrayBuffer.min.cjs +2 -0
  6. package/arrayBuffer.min.cjs.map +1 -0
  7. package/arrayBuffer.min.mjs +2 -0
  8. package/{arrayBuffer.js.map → arrayBuffer.min.mjs.map} +1 -1
  9. package/arrayBuffer.mjs +14 -0
  10. package/{assert.js → assert.cjs} +0 -1
  11. package/assert.d.mts +7 -0
  12. package/assert.d.ts +3 -1
  13. package/assert.min.cjs +2 -0
  14. package/assert.min.cjs.map +1 -0
  15. package/assert.min.mjs +2 -0
  16. package/{assert.js.map → assert.min.mjs.map} +1 -1
  17. package/assert.mjs +11 -0
  18. package/{average.js → average.cjs} +0 -1
  19. package/average.d.mts +7 -0
  20. package/average.d.ts +3 -1
  21. package/average.min.cjs +2 -0
  22. package/{average.js.map → average.min.cjs.map} +1 -1
  23. package/average.min.mjs +2 -0
  24. package/average.min.mjs.map +1 -0
  25. package/average.mjs +20 -0
  26. package/{base64Url.js → base64Url.cjs} +0 -1
  27. package/base64Url.d.mts +10 -0
  28. package/base64Url.d.ts +4 -2
  29. package/base64Url.min.cjs +2 -0
  30. package/base64Url.min.cjs.map +1 -0
  31. package/base64Url.min.mjs +2 -0
  32. package/{base64Url.js.map → base64Url.min.mjs.map} +1 -1
  33. package/base64Url.mjs +14 -0
  34. package/{dateTimeStr.js → dateTimeStr.cjs} +0 -1
  35. package/dateTimeStr.d.mts +85 -0
  36. package/dateTimeStr.d.ts +15 -13
  37. package/dateTimeStr.min.cjs +2 -0
  38. package/dateTimeStr.min.cjs.map +1 -0
  39. package/dateTimeStr.min.mjs +2 -0
  40. package/{dateTimeStr.js.map → dateTimeStr.min.mjs.map} +1 -1
  41. package/dateTimeStr.mjs +83 -0
  42. package/{duration.js → duration.cjs} +9 -11
  43. package/duration.d.mts +78 -0
  44. package/duration.d.ts +15 -13
  45. package/duration.min.cjs +2 -0
  46. package/duration.min.cjs.map +1 -0
  47. package/duration.min.mjs +2 -0
  48. package/duration.min.mjs.map +1 -0
  49. package/duration.mjs +154 -0
  50. package/{isEmpty.js → isEmpty.cjs} +0 -1
  51. package/isEmpty.d.mts +6 -0
  52. package/isEmpty.d.ts +3 -1
  53. package/isEmpty.min.cjs +2 -0
  54. package/isEmpty.min.cjs.map +1 -0
  55. package/isEmpty.min.mjs +2 -0
  56. package/{isEmpty.js.map → isEmpty.min.mjs.map} +1 -1
  57. package/isEmpty.mjs +22 -0
  58. package/iterators.cjs +34 -0
  59. package/iterators.d.mts +4 -0
  60. package/iterators.d.ts +4 -0
  61. package/iterators.min.cjs +2 -0
  62. package/iterators.min.cjs.map +1 -0
  63. package/iterators.min.mjs +2 -0
  64. package/iterators.min.mjs.map +1 -0
  65. package/iterators.mjs +9 -0
  66. package/kvStore.cjs +365 -0
  67. package/kvStore.d.mts +139 -0
  68. package/kvStore.d.ts +95 -50
  69. package/kvStore.min.cjs +2 -0
  70. package/kvStore.min.cjs.map +1 -0
  71. package/kvStore.min.mjs +2 -0
  72. package/kvStore.min.mjs.map +1 -0
  73. package/kvStore.mjs +333 -0
  74. package/localStore.cjs +267 -0
  75. package/localStore.d.mts +119 -0
  76. package/localStore.d.ts +119 -0
  77. package/localStore.min.cjs +2 -0
  78. package/localStore.min.cjs.map +1 -0
  79. package/localStore.min.mjs +2 -0
  80. package/localStore.min.mjs.map +1 -0
  81. package/localStore.mjs +235 -0
  82. package/{logging.js → logging.cjs} +0 -1
  83. package/logging.d.mts +4 -0
  84. package/logging.d.ts +4 -2
  85. package/logging.min.cjs +2 -0
  86. package/logging.min.cjs.map +1 -0
  87. package/logging.min.mjs +2 -0
  88. package/{logging.js.map → logging.min.mjs.map} +1 -1
  89. package/logging.mjs +21 -0
  90. package/{nonEmpty.js → nonEmpty.cjs} +0 -1
  91. package/nonEmpty.d.mts +10 -0
  92. package/nonEmpty.d.ts +3 -1
  93. package/nonEmpty.min.cjs +2 -0
  94. package/{nonEmpty.js.map → nonEmpty.min.cjs.map} +1 -1
  95. package/nonEmpty.min.mjs +2 -0
  96. package/nonEmpty.min.mjs.map +1 -0
  97. package/nonEmpty.mjs +30 -0
  98. package/{nonNil.js → nonNil.cjs} +0 -1
  99. package/{src/nonNil.ts → nonNil.d.mts} +3 -6
  100. package/nonNil.d.ts +3 -1
  101. package/nonNil.min.cjs +2 -0
  102. package/nonNil.min.cjs.map +1 -0
  103. package/nonNil.min.mjs +2 -0
  104. package/{nonNil.js.map → nonNil.min.mjs.map} +1 -1
  105. package/nonNil.mjs +10 -0
  106. package/package.json +447 -24
  107. package/{round.js → round.cjs} +0 -1
  108. package/{src/round.ts → round.d.mts} +4 -8
  109. package/round.d.ts +4 -2
  110. package/round.min.cjs +2 -0
  111. package/round.min.cjs.map +1 -0
  112. package/round.min.mjs +2 -0
  113. package/{round.js.map → round.min.mjs.map} +1 -1
  114. package/round.mjs +12 -0
  115. package/{safeBtoa.js → safeBtoa.cjs} +0 -1
  116. package/safeBtoa.d.mts +6 -0
  117. package/safeBtoa.d.ts +3 -1
  118. package/safeBtoa.min.cjs +2 -0
  119. package/safeBtoa.min.cjs.map +1 -0
  120. package/safeBtoa.min.mjs +2 -0
  121. package/{safeBtoa.js.map → safeBtoa.min.mjs.map} +1 -1
  122. package/safeBtoa.mjs +9 -0
  123. package/{safeParseFloat.js → safeParseFloat.cjs} +0 -1
  124. package/safeParseFloat.d.mts +6 -0
  125. package/safeParseFloat.d.ts +3 -1
  126. package/safeParseFloat.min.cjs +2 -0
  127. package/safeParseFloat.min.cjs.map +1 -0
  128. package/safeParseFloat.min.mjs +2 -0
  129. package/{safeParseFloat.js.map → safeParseFloat.min.mjs.map} +1 -1
  130. package/safeParseFloat.mjs +8 -0
  131. package/{safeParseInt.js → safeParseInt.cjs} +0 -1
  132. package/safeParseInt.d.mts +6 -0
  133. package/safeParseInt.d.ts +3 -1
  134. package/safeParseInt.min.cjs +2 -0
  135. package/safeParseInt.min.cjs.map +1 -0
  136. package/safeParseInt.min.mjs +2 -0
  137. package/{safeParseInt.js.map → safeParseInt.min.mjs.map} +1 -1
  138. package/safeParseInt.mjs +8 -0
  139. package/sha256.cjs +35 -0
  140. package/sha256.d.mts +6 -0
  141. package/sha256.d.ts +3 -1
  142. package/sha256.min.cjs +2 -0
  143. package/sha256.min.cjs.map +1 -0
  144. package/sha256.min.mjs +2 -0
  145. package/{sha256.js.map → sha256.min.mjs.map} +1 -1
  146. package/sha256.mjs +10 -0
  147. package/{sleep.js → sleep.cjs} +0 -1
  148. package/{src/sleep.ts → sleep.d.mts} +3 -3
  149. package/sleep.d.ts +3 -1
  150. package/sleep.min.cjs +2 -0
  151. package/sleep.min.cjs.map +1 -0
  152. package/sleep.min.mjs +2 -0
  153. package/{sleep.js.map → sleep.min.mjs.map} +1 -1
  154. package/sleep.mjs +7 -0
  155. package/storageAdapter.cjs +18 -0
  156. package/storageAdapter.d.mts +33 -0
  157. package/storageAdapter.d.ts +33 -0
  158. package/storageAdapter.min.cjs +2 -0
  159. package/storageAdapter.min.cjs.map +1 -0
  160. package/storageAdapter.min.mjs +1 -0
  161. package/storageAdapter.min.mjs.map +1 -0
  162. package/storageAdapter.mjs +0 -0
  163. package/{sum.js → sum.cjs} +0 -1
  164. package/sum.d.mts +7 -0
  165. package/sum.d.ts +3 -1
  166. package/sum.min.cjs +2 -0
  167. package/sum.min.cjs.map +1 -0
  168. package/sum.min.mjs +2 -0
  169. package/{sum.js.map → sum.min.mjs.map} +1 -1
  170. package/sum.mjs +13 -0
  171. package/{timeConstants.js → timeConstants.cjs} +0 -1
  172. package/timeConstants.d.mts +20 -0
  173. package/timeConstants.d.ts +16 -14
  174. package/timeConstants.min.cjs +2 -0
  175. package/timeConstants.min.cjs.map +1 -0
  176. package/timeConstants.min.mjs +2 -0
  177. package/{timeConstants.js.map → timeConstants.min.mjs.map} +1 -1
  178. package/timeConstants.mjs +31 -0
  179. package/{timer.js → timer.cjs} +6 -6
  180. package/timer.d.mts +13 -0
  181. package/timer.d.ts +4 -2
  182. package/timer.min.cjs +2 -0
  183. package/timer.min.cjs.map +1 -0
  184. package/timer.min.mjs +2 -0
  185. package/timer.min.mjs.map +1 -0
  186. package/timer.mjs +161 -0
  187. package/docs/.nojekyll +0 -1
  188. package/docs/assets/hierarchy.js +0 -1
  189. package/docs/assets/highlight.css +0 -22
  190. package/docs/assets/icons.js +0 -18
  191. package/docs/assets/icons.svg +0 -1
  192. package/docs/assets/main.js +0 -60
  193. package/docs/assets/navigation.js +0 -1
  194. package/docs/assets/search.js +0 -1
  195. package/docs/assets/style.css +0 -1640
  196. package/docs/classes/kvStore.KVStore.html +0 -26
  197. package/docs/classes/kvStore.KVStoreField.html +0 -7
  198. package/docs/classes/timer.Timer.html +0 -8
  199. package/docs/functions/arrayBuffer.arrayBufferToBase64.html +0 -2
  200. package/docs/functions/arrayBuffer.arrayBufferToHex.html +0 -2
  201. package/docs/functions/assert.assert.html +0 -3
  202. package/docs/functions/average.average.html +0 -3
  203. package/docs/functions/base64Url.base64ToBase64URL.html +0 -2
  204. package/docs/functions/base64Url.base64UrlToBase64.html +0 -2
  205. package/docs/functions/dateTimeStr.getDisplayDateTime.html +0 -3
  206. package/docs/functions/dateTimeStr.getLongMonthNameOneIndexed.html +0 -4
  207. package/docs/functions/dateTimeStr.getLongMonthNameZeroIndexed.html +0 -4
  208. package/docs/functions/dateTimeStr.getShortMonthNameOneIndexed.html +0 -4
  209. package/docs/functions/dateTimeStr.getShortMonthNameZeroIndexed.html +0 -4
  210. package/docs/functions/dateTimeStr.hhMm.html +0 -4
  211. package/docs/functions/dateTimeStr.hhMmSs.html +0 -4
  212. package/docs/functions/dateTimeStr.hhMmSsMs.html +0 -5
  213. package/docs/functions/dateTimeStr.toDate.html +0 -4
  214. package/docs/functions/dateTimeStr.tzShort.html +0 -4
  215. package/docs/functions/dateTimeStr.yyyyMm.html +0 -4
  216. package/docs/functions/dateTimeStr.yyyyMmDd.html +0 -4
  217. package/docs/functions/duration.durationOrMsToMs.html +0 -2
  218. package/docs/functions/duration.durationToMs.html +0 -2
  219. package/docs/functions/duration.elapsed.html +0 -2
  220. package/docs/functions/duration.formatDuration.html +0 -4
  221. package/docs/functions/duration.msToDuration.html +0 -5
  222. package/docs/functions/duration.readableDuration.html +0 -4
  223. package/docs/functions/isEmpty.isEmpty.html +0 -2
  224. package/docs/functions/kvStore.kvStoreItem.html +0 -2
  225. package/docs/functions/localStorageCache.storeItem.html +0 -15
  226. package/docs/functions/logging.capLength.html +0 -1
  227. package/docs/functions/logging.stringify.html +0 -1
  228. package/docs/functions/nonEmpty.nonEmpty.html +0 -5
  229. package/docs/functions/nonNil.nonNil.html +0 -5
  230. package/docs/functions/round.round.html +0 -5
  231. package/docs/functions/round.roundS.html +0 -3
  232. package/docs/functions/safeBtoa.safeBtoa.html +0 -2
  233. package/docs/functions/safeParseFloat.safeParseFloat.html +0 -2
  234. package/docs/functions/safeParseInt.safeParseInt.html +0 -2
  235. package/docs/functions/sha256.sha256.html +0 -2
  236. package/docs/functions/sleep.sleep.html +0 -3
  237. package/docs/functions/sum.sum.html +0 -3
  238. package/docs/functions/timer.timer.html +0 -2
  239. package/docs/hierarchy.html +0 -1
  240. package/docs/index.html +0 -4
  241. package/docs/modules/arrayBuffer.html +0 -1
  242. package/docs/modules/assert.html +0 -1
  243. package/docs/modules/average.html +0 -1
  244. package/docs/modules/base64Url.html +0 -1
  245. package/docs/modules/dateTimeStr.html +0 -1
  246. package/docs/modules/duration.html +0 -1
  247. package/docs/modules/isEmpty.html +0 -1
  248. package/docs/modules/kvStore.html +0 -1
  249. package/docs/modules/localStorageCache.html +0 -1
  250. package/docs/modules/logging.html +0 -1
  251. package/docs/modules/nonEmpty.html +0 -1
  252. package/docs/modules/nonNil.html +0 -1
  253. package/docs/modules/round.html +0 -1
  254. package/docs/modules/safeBtoa.html +0 -1
  255. package/docs/modules/safeParseFloat.html +0 -1
  256. package/docs/modules/safeParseInt.html +0 -1
  257. package/docs/modules/sha256.html +0 -1
  258. package/docs/modules/sleep.html +0 -1
  259. package/docs/modules/sum.html +0 -1
  260. package/docs/modules/timeConstants.html +0 -1
  261. package/docs/modules/timer.html +0 -1
  262. package/docs/modules.html +0 -1
  263. package/docs/types/dateTimeStr.AnyDateTime.html +0 -1
  264. package/docs/types/duration.Duration.html +0 -6
  265. package/docs/types/duration.DurationStyle.html +0 -6
  266. package/docs/types/duration.DurationSuffixMap.html +0 -6
  267. package/docs/types/duration.DurationSuffixType.html +0 -1
  268. package/docs/types/duration.DurationType.html +0 -2
  269. package/docs/types/localStorageCache.StoredItem.html +0 -4
  270. package/docs/variables/duration.DURATION_STYLE_SUFFIX_MAP.html +0 -1
  271. package/docs/variables/duration.DURATION_TYPE_SEQUENCE.html +0 -2
  272. package/docs/variables/kvStore.DEFAULT_EXPIRY_DELTA_MS.html +0 -2
  273. package/docs/variables/kvStore.GC_INTERVAL_MS.html +0 -2
  274. package/docs/variables/kvStore.MILLIS_PER_DAY.html +0 -2
  275. package/docs/variables/kvStore.kvStore.html +0 -3
  276. package/docs/variables/timeConstants.HOURS_PER_DAY.html +0 -1
  277. package/docs/variables/timeConstants.HOURS_PER_WEEK.html +0 -1
  278. package/docs/variables/timeConstants.MINUTES_PER_DAY.html +0 -1
  279. package/docs/variables/timeConstants.MINUTES_PER_HOUR.html +0 -1
  280. package/docs/variables/timeConstants.MINUTES_PER_WEEK.html +0 -1
  281. package/docs/variables/timeConstants.MS_PER_DAY.html +0 -1
  282. package/docs/variables/timeConstants.MS_PER_HOUR.html +0 -1
  283. package/docs/variables/timeConstants.MS_PER_MINUTE.html +0 -1
  284. package/docs/variables/timeConstants.MS_PER_SECOND.html +0 -3
  285. package/docs/variables/timeConstants.MS_PER_WEEK.html +0 -1
  286. package/docs/variables/timeConstants.SECONDS_PER_DAY.html +0 -1
  287. package/docs/variables/timeConstants.SECONDS_PER_HOUR.html +0 -1
  288. package/docs/variables/timeConstants.SECONDS_PER_MINUTE.html +0 -1
  289. package/docs/variables/timeConstants.SECONDS_PER_WEEK.html +0 -1
  290. package/duration.js.map +0 -1
  291. package/kvStore.js +0 -383
  292. package/kvStore.js.map +0 -1
  293. package/localStorageCache.d.ts +0 -55
  294. package/localStorageCache.js +0 -121
  295. package/localStorageCache.js.map +0 -1
  296. package/sha256.js +0 -58
  297. package/src/arrayBuffer.ts +0 -29
  298. package/src/assert.ts +0 -14
  299. package/src/average.ts +0 -13
  300. package/src/base64Url.ts +0 -20
  301. package/src/dateTimeStr.ts +0 -184
  302. package/src/duration.ts +0 -260
  303. package/src/isEmpty.ts +0 -32
  304. package/src/kvStore.ts +0 -444
  305. package/src/localStorageCache.ts +0 -121
  306. package/src/logging.ts +0 -26
  307. package/src/nonEmpty.ts +0 -18
  308. package/src/safeBtoa.ts +0 -15
  309. package/src/safeParseFloat.ts +0 -10
  310. package/src/safeParseInt.ts +0 -10
  311. package/src/sha256.ts +0 -13
  312. package/src/sum.ts +0 -17
  313. package/src/timeConstants.ts +0 -22
  314. package/src/timer.ts +0 -33
  315. package/timer.js.map +0 -1
package/kvStore.mjs ADDED
@@ -0,0 +1,333 @@
1
+ // src/timeConstants.ts
2
+ var MS_PER_SECOND = 1e3;
3
+ var MS_PER_MINUTE = 6e4;
4
+ var MS_PER_HOUR = 36e5;
5
+ var MS_PER_DAY = 864e5;
6
+
7
+ // src/duration.ts
8
+ function durationToMs(duration) {
9
+ const daysMs = (duration.days ?? 0) * MS_PER_DAY;
10
+ const hoursMs = (duration.hours ?? 0) * MS_PER_HOUR;
11
+ const minsMs = (duration.minutes ?? 0) * MS_PER_MINUTE;
12
+ const secsMs = (duration.seconds ?? 0) * MS_PER_SECOND;
13
+ const msMs = duration.milliseconds ?? 0;
14
+ return daysMs + hoursMs + minsMs + secsMs + msMs;
15
+ }
16
+ function durationOrMsToMs(duration) {
17
+ return typeof duration === "number" ? duration : durationToMs(duration);
18
+ }
19
+
20
+ // src/kvStore.ts
21
+ var 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: "KVStore",
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: 1,
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: "kvStore",
37
+ /** 30 days in ms. */
38
+ expiryMs: MS_PER_DAY * 30,
39
+ /** Do GC once per day. */
40
+ gcIntervalMs: MS_PER_DAY
41
+ };
42
+ function configureKvStore(config) {
43
+ Object.assign(KvStoreConfig, config);
44
+ }
45
+ function validateStoredObject(obj) {
46
+ if (!obj || typeof obj !== "object" || typeof obj.key !== "string" || obj.value === void 0 || typeof obj.storedMs !== "number" || typeof obj.expiryMs !== "number" || Date.now() >= obj.expiryMs) {
47
+ return void 0;
48
+ }
49
+ return obj;
50
+ }
51
+ function withOnError(request, reject) {
52
+ request.onerror = (event) => {
53
+ reject(event);
54
+ };
55
+ return request;
56
+ }
57
+ var KvStore = class {
58
+ constructor(dbName, options) {
59
+ this.dbName = dbName;
60
+ this.dbVersion = options?.dbVersion ?? KvStoreConfig.dbVersion;
61
+ this.storeName = options?.storeName ?? KvStoreConfig.storeName;
62
+ this.defaultExpiryMs = options?.defaultExpiryMs ? durationOrMsToMs(options.defaultExpiryMs) : KvStoreConfig.expiryMs;
63
+ this.gcIntervalMs = options?.gcIntervalMs ? durationOrMsToMs(options.gcIntervalMs) : KvStoreConfig.gcIntervalMs;
64
+ this.gcMsStorageKey = `__kvStore:lastGcMs:${dbName}:v${this.dbVersion}:${this.storeName}`;
65
+ }
66
+ /** We'll init the DB only on first use. */
67
+ db;
68
+ /** Local storage key name for the last GC completed timestamp. */
69
+ gcMsStorageKey;
70
+ dbVersion;
71
+ storeName;
72
+ defaultExpiryMs;
73
+ gcIntervalMs;
74
+ async getOrCreateDb() {
75
+ if (!this.db) {
76
+ this.db = await new Promise((resolve, reject) => {
77
+ const request = withOnError(
78
+ globalThis.indexedDB.open(this.dbName, this.dbVersion),
79
+ reject
80
+ );
81
+ request.onupgradeneeded = (event) => {
82
+ const db = event.target.result;
83
+ const objectStore = db.createObjectStore(this.storeName, {
84
+ keyPath: "key"
85
+ });
86
+ objectStore.createIndex("key", "key", {
87
+ unique: true
88
+ });
89
+ };
90
+ request.onsuccess = (event) => {
91
+ const db = event.target.result;
92
+ resolve(db);
93
+ };
94
+ });
95
+ }
96
+ return this.db;
97
+ }
98
+ async transact(mode, callback) {
99
+ const db = await this.getOrCreateDb();
100
+ return await new Promise((resolve, reject) => {
101
+ const transaction = withOnError(
102
+ db.transaction(this.storeName, mode),
103
+ reject
104
+ );
105
+ transaction.onabort = (event) => {
106
+ reject(event);
107
+ };
108
+ const objectStore = transaction.objectStore(this.storeName);
109
+ callback(objectStore, resolve, reject);
110
+ });
111
+ }
112
+ /** Set a value in the store. */
113
+ async set(key, value, expiryDeltaMs = this.defaultExpiryMs) {
114
+ const nowMs = Date.now();
115
+ const obj = {
116
+ key,
117
+ value,
118
+ storedMs: nowMs,
119
+ expiryMs: nowMs + durationOrMsToMs(expiryDeltaMs)
120
+ };
121
+ return await this.transact(
122
+ "readwrite",
123
+ (objectStore, resolve, reject) => {
124
+ const request = withOnError(objectStore.put(obj), reject);
125
+ request.onsuccess = () => {
126
+ resolve(value);
127
+ this.gc();
128
+ };
129
+ }
130
+ );
131
+ }
132
+ /** Delete one or multiple keys. */
133
+ async delete(key) {
134
+ return await this.transact(
135
+ "readwrite",
136
+ (objectStore, resolve, reject) => {
137
+ objectStore.transaction.oncomplete = () => {
138
+ resolve();
139
+ };
140
+ if (typeof key === "string") {
141
+ withOnError(objectStore.delete(key), reject);
142
+ } else {
143
+ for (const k of key) {
144
+ withOnError(objectStore.delete(k), reject);
145
+ }
146
+ }
147
+ }
148
+ );
149
+ }
150
+ /** Mainly used to get the expiration timestamp of an object. */
151
+ async getStoredObject(key) {
152
+ const stored = await this.transact(
153
+ "readonly",
154
+ (objectStore, resolve, reject) => {
155
+ const request = withOnError(objectStore.get(key), reject);
156
+ request.onsuccess = () => {
157
+ resolve(request.result);
158
+ };
159
+ }
160
+ );
161
+ if (!stored) {
162
+ return void 0;
163
+ }
164
+ try {
165
+ const obj = validateStoredObject(stored);
166
+ if (!obj) {
167
+ await this.delete(key);
168
+ this.gc();
169
+ return void 0;
170
+ }
171
+ return obj;
172
+ } catch (e) {
173
+ console.error(`Invalid kv value: ${key}=${JSON.stringify(stored)}:`, e);
174
+ await this.delete(key);
175
+ this.gc();
176
+ return void 0;
177
+ }
178
+ }
179
+ /** Get a value by key, or undefined if it does not exist. */
180
+ async get(key) {
181
+ const obj = await this.getStoredObject(key);
182
+ return obj?.value;
183
+ }
184
+ /** Generic way to iterate through all entries. */
185
+ async forEach(callback) {
186
+ await this.transact("readonly", (objectStore, resolve, reject) => {
187
+ const request = withOnError(objectStore.openCursor(), reject);
188
+ request.onsuccess = async (event) => {
189
+ const cursor = event.target.result;
190
+ if (cursor) {
191
+ if (cursor.key) {
192
+ const obj = validateStoredObject(cursor.value);
193
+ if (obj !== void 0) {
194
+ await callback(
195
+ String(cursor.key),
196
+ obj.value,
197
+ obj.expiryMs,
198
+ obj.storedMs
199
+ );
200
+ }
201
+ }
202
+ cursor.continue();
203
+ } else {
204
+ resolve();
205
+ }
206
+ };
207
+ });
208
+ }
209
+ /**
210
+ * Returns the number of items in the store. Note that getting the size
211
+ * requires iterating through the entire store because the items could expire
212
+ * at any time, and hence the size is a dynamic number.
213
+ */
214
+ async size() {
215
+ let count = 0;
216
+ await this.forEach(() => {
217
+ count++;
218
+ });
219
+ return count;
220
+ }
221
+ /** Remove all items from the store. */
222
+ async clear() {
223
+ const keys = [];
224
+ await this.forEach((key) => {
225
+ keys.push(key);
226
+ });
227
+ await this.delete(keys);
228
+ }
229
+ /**
230
+ * Returns all items as map of key to value, mainly used for debugging dumps.
231
+ * The type T is applied to all values, even though they might not be of type
232
+ * T (in the case when you store different data types in the same store).
233
+ */
234
+ async asMap() {
235
+ const map = /* @__PURE__ */ new Map();
236
+ await this.forEach((key, value, expiryMs, storedMs) => {
237
+ map.set(key, { value, expiryMs, storedMs });
238
+ });
239
+ return map;
240
+ }
241
+ /** Returns the ms timestamp for the last GC (garbage collection). */
242
+ get lastGcMs() {
243
+ const lastGcMsStr = globalThis.localStorage.getItem(this.gcMsStorageKey);
244
+ if (!lastGcMsStr) return 0;
245
+ const ms = Number(lastGcMsStr);
246
+ return isNaN(ms) ? 0 : ms;
247
+ }
248
+ /** Set the ms timestamp for the last GC (garbage collection). */
249
+ set lastGcMs(ms) {
250
+ globalThis.localStorage.setItem(this.gcMsStorageKey, String(ms));
251
+ }
252
+ /** Perform garbage-collection if due, else do nothing. */
253
+ async gc() {
254
+ const lastGcMs = this.lastGcMs;
255
+ if (!lastGcMs) {
256
+ this.lastGcMs = Date.now();
257
+ return;
258
+ }
259
+ if (Date.now() < lastGcMs + this.gcIntervalMs) {
260
+ return;
261
+ }
262
+ await this.gcNow();
263
+ }
264
+ /**
265
+ * Perform garbage collection immediately without checking whether we are
266
+ * due for the next GC or not.
267
+ */
268
+ async gcNow() {
269
+ console.log(`Starting kvStore GC on ${this.dbName} v${this.dbVersion}...`);
270
+ this.lastGcMs = Date.now();
271
+ const keysToDelete = [];
272
+ await this.forEach(
273
+ async (key, value, expiryMs) => {
274
+ if (value === void 0 || Date.now() >= expiryMs) {
275
+ keysToDelete.push(key);
276
+ }
277
+ }
278
+ );
279
+ if (keysToDelete.length) {
280
+ await this.delete(keysToDelete);
281
+ }
282
+ console.log(
283
+ `Finished kvStore GC on ${this.dbName} v${this.dbVersion} - deleted ${keysToDelete.length} keys`
284
+ );
285
+ this.lastGcMs = Date.now();
286
+ }
287
+ /** Returns `this` casted into a StorageAdapter<T>. */
288
+ asStorageAdapter() {
289
+ return this;
290
+ }
291
+ };
292
+ var kvStore = new KvStore(KvStoreConfig.dbName);
293
+ var KvStoreItem = class {
294
+ constructor(key, defaultExpiryMs = KvStoreConfig.expiryMs, store = kvStore) {
295
+ this.key = key;
296
+ this.store = store;
297
+ this.defaultExpiryMs = defaultExpiryMs && durationOrMsToMs(defaultExpiryMs);
298
+ }
299
+ defaultExpiryMs;
300
+ /** Set a value in the store. */
301
+ async set(value, expiryDeltaMs = this.defaultExpiryMs) {
302
+ await this.store.set(this.key, value, expiryDeltaMs);
303
+ }
304
+ /**
305
+ * Example usage:
306
+ *
307
+ * const { value, storedMs, expiryMs, storedMs } =
308
+ * await myKvItem.getStoredObject();
309
+ */
310
+ async getStoredObject() {
311
+ return await this.store.getStoredObject(this.key);
312
+ }
313
+ /** Get a value by key, or undefined if it does not exist. */
314
+ async get() {
315
+ return await this.store.get(this.key);
316
+ }
317
+ /** Delete this key from the store. */
318
+ async delete() {
319
+ await this.store.delete(this.key);
320
+ }
321
+ };
322
+ function kvStoreItem(key, expiryMs, store = kvStore) {
323
+ expiryMs = expiryMs && durationOrMsToMs(expiryMs);
324
+ return new KvStoreItem(key, expiryMs, store);
325
+ }
326
+ export {
327
+ KvStore,
328
+ KvStoreConfig,
329
+ KvStoreItem,
330
+ configureKvStore,
331
+ kvStore,
332
+ kvStoreItem
333
+ };
package/localStore.cjs ADDED
@@ -0,0 +1,267 @@
1
+ "use strict";
2
+ var __defProp = Object.defineProperty;
3
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
4
+ var __getOwnPropNames = Object.getOwnPropertyNames;
5
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
6
+ var __export = (target, all) => {
7
+ for (var name in all)
8
+ __defProp(target, name, { get: all[name], enumerable: true });
9
+ };
10
+ var __copyProps = (to, from, except, desc) => {
11
+ if (from && typeof from === "object" || typeof from === "function") {
12
+ for (let key of __getOwnPropNames(from))
13
+ if (!__hasOwnProp.call(to, key) && key !== except)
14
+ __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
15
+ }
16
+ return to;
17
+ };
18
+ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
19
+
20
+ // src/localStore.ts
21
+ var localStore_exports = {};
22
+ __export(localStore_exports, {
23
+ LocalStore: () => LocalStore,
24
+ LocalStoreConfig: () => LocalStoreConfig,
25
+ LocalStoreItem: () => LocalStoreItem,
26
+ configureLocalStore: () => configureLocalStore,
27
+ localStore: () => localStore,
28
+ localStoreItem: () => localStoreItem
29
+ });
30
+ module.exports = __toCommonJS(localStore_exports);
31
+
32
+ // src/timeConstants.ts
33
+ var MS_PER_SECOND = 1e3;
34
+ var MS_PER_MINUTE = 6e4;
35
+ var MS_PER_HOUR = 36e5;
36
+ var MS_PER_DAY = 864e5;
37
+
38
+ // src/duration.ts
39
+ function durationToMs(duration) {
40
+ const daysMs = (duration.days ?? 0) * MS_PER_DAY;
41
+ const hoursMs = (duration.hours ?? 0) * MS_PER_HOUR;
42
+ const minsMs = (duration.minutes ?? 0) * MS_PER_MINUTE;
43
+ const secsMs = (duration.seconds ?? 0) * MS_PER_SECOND;
44
+ const msMs = duration.milliseconds ?? 0;
45
+ return daysMs + hoursMs + minsMs + secsMs + msMs;
46
+ }
47
+ function durationOrMsToMs(duration) {
48
+ return typeof duration === "number" ? duration : durationToMs(duration);
49
+ }
50
+
51
+ // src/localStore.ts
52
+ var LocalStoreConfig = {
53
+ /** All items with the same store name will share the same storage space. */
54
+ storeName: "ts-utils",
55
+ /** 30 days in ms. */
56
+ expiryMs: MS_PER_DAY * 30,
57
+ /** Do GC once per day. */
58
+ gcIntervalMs: MS_PER_DAY
59
+ };
60
+ function configureLocalStore(config) {
61
+ Object.assign(LocalStoreConfig, config);
62
+ }
63
+ function validateStoredObject(obj) {
64
+ if (!obj || typeof obj !== "object" || obj.value === void 0 || typeof obj.storedMs !== "number" || typeof obj.expiryMs !== "number" || Date.now() >= obj.expiryMs) {
65
+ return void 0;
66
+ }
67
+ return obj;
68
+ }
69
+ var LocalStore = class {
70
+ constructor(storeName, options) {
71
+ this.storeName = storeName;
72
+ this.keyPrefix = storeName + ":";
73
+ this.defaultExpiryMs = options?.defaultExpiryMs ? durationOrMsToMs(options.defaultExpiryMs) : LocalStoreConfig.expiryMs;
74
+ this.gcIntervalMs = options?.gcIntervalMs ? durationOrMsToMs(options.gcIntervalMs) : LocalStoreConfig.gcIntervalMs;
75
+ this.gcMsStorageKey = `__localStore:lastGcMs:${storeName}`;
76
+ }
77
+ /**
78
+ * The prefix string for the local storage key which identifies items
79
+ * belonging to this namespace.
80
+ */
81
+ keyPrefix;
82
+ /** Local storage key name for the last GC completed timestamp. */
83
+ gcMsStorageKey;
84
+ defaultExpiryMs;
85
+ gcIntervalMs;
86
+ /** Set a value in the store. */
87
+ set(key, value, expiryDeltaMs = this.defaultExpiryMs) {
88
+ const nowMs = Date.now();
89
+ const obj = {
90
+ value,
91
+ storedMs: nowMs,
92
+ expiryMs: nowMs + durationOrMsToMs(expiryDeltaMs)
93
+ };
94
+ localStorage.setItem(this.keyPrefix + key, JSON.stringify(obj));
95
+ this.gc();
96
+ return value;
97
+ }
98
+ /** Delete one or multiple keys. */
99
+ delete(key) {
100
+ if (typeof key === "string") {
101
+ localStorage.removeItem(this.keyPrefix + key);
102
+ } else {
103
+ for (const k of key) {
104
+ localStorage.removeItem(this.keyPrefix + k);
105
+ }
106
+ }
107
+ }
108
+ /** Mainly used to get the expiration timestamp of an object. */
109
+ getStoredObject(key) {
110
+ const k = this.keyPrefix + key;
111
+ const stored = localStorage.getItem(k);
112
+ if (!stored) {
113
+ return void 0;
114
+ }
115
+ try {
116
+ const parsed = JSON.parse(stored);
117
+ const obj = validateStoredObject(parsed);
118
+ if (!obj) {
119
+ this.delete(k);
120
+ this.gc();
121
+ return void 0;
122
+ }
123
+ return obj;
124
+ } catch (e) {
125
+ console.error(`Invalid local value: ${k}=${stored}:`, e);
126
+ this.delete(k);
127
+ this.gc();
128
+ return void 0;
129
+ }
130
+ }
131
+ /** Get a value by key, or undefined if it does not exist. */
132
+ get(key) {
133
+ const obj = this.getStoredObject(key);
134
+ return obj?.value;
135
+ }
136
+ /** Generic way to iterate through all entries. */
137
+ forEach(callback) {
138
+ for (const k of Object.keys(localStorage)) {
139
+ if (!k.startsWith(this.keyPrefix)) continue;
140
+ const key = k.slice(this.keyPrefix.length);
141
+ const obj = this.getStoredObject(key);
142
+ if (!obj) continue;
143
+ callback(key, obj.value, obj.expiryMs, obj.storedMs);
144
+ }
145
+ }
146
+ /**
147
+ * Returns the number of items in the store. Note that getting the size
148
+ * requires iterating through the entire store because the items could expire
149
+ * at any time, and hence the size is a dynamic number.
150
+ */
151
+ size() {
152
+ let count = 0;
153
+ this.forEach(() => {
154
+ count++;
155
+ });
156
+ return count;
157
+ }
158
+ /** Remove all items from the store. */
159
+ clear() {
160
+ for (const key of Object.keys(localStorage)) {
161
+ if (key.startsWith(this.keyPrefix)) {
162
+ localStorage.removeItem(key);
163
+ }
164
+ }
165
+ }
166
+ /**
167
+ * Returns all items as map of key to value, mainly used for debugging dumps.
168
+ * The type T is applied to all values, even though they might not be of type
169
+ * T (in the case when you store different data types in the same store).
170
+ */
171
+ asMap() {
172
+ const map = /* @__PURE__ */ new Map();
173
+ this.forEach((key, value, expiryMs, storedMs) => {
174
+ map.set(key, { value, expiryMs, storedMs });
175
+ });
176
+ return map;
177
+ }
178
+ /** Returns the ms timestamp for the last GC (garbage collection). */
179
+ get lastGcMs() {
180
+ const lastGcMsStr = globalThis.localStorage.getItem(this.gcMsStorageKey);
181
+ if (!lastGcMsStr) return 0;
182
+ const ms = Number(lastGcMsStr);
183
+ return isNaN(ms) ? 0 : ms;
184
+ }
185
+ /** Set the ms timestamp for the last GC (garbage collection). */
186
+ set lastGcMs(ms) {
187
+ globalThis.localStorage.setItem(this.gcMsStorageKey, String(ms));
188
+ }
189
+ /** Perform garbage-collection if due, else do nothing. */
190
+ gc() {
191
+ const lastGcMs = this.lastGcMs;
192
+ if (!lastGcMs) {
193
+ this.lastGcMs = Date.now();
194
+ return;
195
+ }
196
+ if (Date.now() < lastGcMs + this.gcIntervalMs) {
197
+ return;
198
+ }
199
+ this.gcNow();
200
+ }
201
+ /**
202
+ * Perform garbage collection immediately without checking whether we are
203
+ * due for the next GC or not.
204
+ */
205
+ gcNow() {
206
+ console.log(`Starting localStore GC on ${this.storeName}`);
207
+ this.lastGcMs = Date.now();
208
+ let count = 0;
209
+ this.forEach((key, value, expiryMs) => {
210
+ if (Date.now() >= expiryMs) {
211
+ this.delete(key);
212
+ count++;
213
+ }
214
+ });
215
+ console.log(
216
+ `Finished localStore GC on ${this.storeName} - deleted ${count} keys`
217
+ );
218
+ this.lastGcMs = Date.now();
219
+ }
220
+ /** Returns `this` casted into a StorageAdapter<T>. */
221
+ asStorageAdapter() {
222
+ return this;
223
+ }
224
+ };
225
+ var localStore = new LocalStore(LocalStoreConfig.storeName);
226
+ var LocalStoreItem = class {
227
+ constructor(key, defaultExpiryMs = LocalStoreConfig.expiryMs, store = localStore) {
228
+ this.key = key;
229
+ this.store = store;
230
+ this.defaultExpiryMs = defaultExpiryMs && durationOrMsToMs(defaultExpiryMs);
231
+ }
232
+ defaultExpiryMs;
233
+ /** Set a value in the store. */
234
+ set(value, expiryDeltaMs = this.defaultExpiryMs) {
235
+ this.store.set(this.key, value, expiryDeltaMs);
236
+ }
237
+ /**
238
+ * Example usage:
239
+ *
240
+ * const { value, storedMs, expiryMs, storedMs } =
241
+ * await myLocalItem.getStoredObject();
242
+ */
243
+ getStoredObject() {
244
+ return this.store.getStoredObject(this.key);
245
+ }
246
+ /** Get a value by key, or undefined if it does not exist. */
247
+ get() {
248
+ return this.store.get(this.key);
249
+ }
250
+ /** Delete this key from the store. */
251
+ delete() {
252
+ this.store.delete(this.key);
253
+ }
254
+ };
255
+ function localStoreItem(key, expiryMs, store = localStore) {
256
+ expiryMs = expiryMs && durationOrMsToMs(expiryMs);
257
+ return new LocalStoreItem(key, expiryMs, store);
258
+ }
259
+ // Annotate the CommonJS export names for ESM import in node:
260
+ 0 && (module.exports = {
261
+ LocalStore,
262
+ LocalStoreConfig,
263
+ LocalStoreItem,
264
+ configureLocalStore,
265
+ localStore,
266
+ localStoreItem
267
+ });