@choksheak/ts-utils 0.3.0 → 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/arrayBuffer.d.ts +4 -2
- package/assert.d.ts +3 -1
- package/average.d.ts +3 -1
- package/base64Url.d.ts +4 -2
- package/dateTimeStr.d.ts +15 -13
- package/duration.d.ts +15 -13
- package/isEmpty.d.ts +3 -1
- 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 +103 -71
- package/kvStore.d.mts +91 -49
- package/kvStore.d.ts +95 -50
- package/kvStore.min.cjs +1 -1
- package/kvStore.min.cjs.map +1 -1
- package/kvStore.min.mjs +1 -1
- package/kvStore.min.mjs.map +1 -1
- package/kvStore.mjs +99 -66
- 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.d.ts +4 -2
- package/nonEmpty.d.ts +3 -1
- package/nonNil.d.ts +3 -1
- package/package.json +48 -15
- package/round.d.ts +4 -2
- package/safeBtoa.d.ts +3 -1
- package/safeParseFloat.d.ts +3 -1
- package/safeParseInt.d.ts +3 -1
- package/sha256.d.ts +3 -1
- package/sleep.d.ts +3 -1
- 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.d.ts +3 -1
- package/timeConstants.d.ts +16 -14
- package/timer.d.ts +4 -2
- package/localStorageCache.cjs +0 -119
- package/localStorageCache.d.mts +0 -57
- package/localStorageCache.d.ts +0 -55
- package/localStorageCache.min.cjs +0 -2
- package/localStorageCache.min.cjs.map +0 -1
- package/localStorageCache.min.mjs +0 -2
- package/localStorageCache.min.mjs.map +0 -1
- package/localStorageCache.mjs +0 -92
package/localStorageCache.cjs
DELETED
|
@@ -1,119 +0,0 @@
|
|
|
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/localStorageCache.ts
|
|
21
|
-
var localStorageCache_exports = {};
|
|
22
|
-
__export(localStorageCache_exports, {
|
|
23
|
-
storeItem: () => storeItem
|
|
24
|
-
});
|
|
25
|
-
module.exports = __toCommonJS(localStorageCache_exports);
|
|
26
|
-
|
|
27
|
-
// src/timeConstants.ts
|
|
28
|
-
var MS_PER_SECOND = 1e3;
|
|
29
|
-
var MS_PER_MINUTE = 6e4;
|
|
30
|
-
var MS_PER_HOUR = 36e5;
|
|
31
|
-
var MS_PER_DAY = 864e5;
|
|
32
|
-
|
|
33
|
-
// src/duration.ts
|
|
34
|
-
function durationToMs(duration) {
|
|
35
|
-
const daysMs = (duration.days ?? 0) * MS_PER_DAY;
|
|
36
|
-
const hoursMs = (duration.hours ?? 0) * MS_PER_HOUR;
|
|
37
|
-
const minsMs = (duration.minutes ?? 0) * MS_PER_MINUTE;
|
|
38
|
-
const secsMs = (duration.seconds ?? 0) * MS_PER_SECOND;
|
|
39
|
-
const msMs = duration.milliseconds ?? 0;
|
|
40
|
-
return daysMs + hoursMs + minsMs + secsMs + msMs;
|
|
41
|
-
}
|
|
42
|
-
function durationOrMsToMs(duration) {
|
|
43
|
-
return typeof duration === "number" ? duration : durationToMs(duration);
|
|
44
|
-
}
|
|
45
|
-
|
|
46
|
-
// src/localStorageCache.ts
|
|
47
|
-
function storeItem(key, expires, logError = true, defaultValue) {
|
|
48
|
-
const expireDeltaMs = durationOrMsToMs(expires);
|
|
49
|
-
return new CacheItem(key, expireDeltaMs, logError, defaultValue);
|
|
50
|
-
}
|
|
51
|
-
var CacheItem = class {
|
|
52
|
-
/**
|
|
53
|
-
* Create a cache item accessor object with auto-expiration.
|
|
54
|
-
*/
|
|
55
|
-
constructor(key, expireDeltaMs, logError, defaultValue) {
|
|
56
|
-
this.key = key;
|
|
57
|
-
this.expireDeltaMs = expireDeltaMs;
|
|
58
|
-
this.logError = logError;
|
|
59
|
-
this.defaultValue = defaultValue;
|
|
60
|
-
}
|
|
61
|
-
/**
|
|
62
|
-
* Set the value of this item with auto-expiration.
|
|
63
|
-
*/
|
|
64
|
-
set(value, expiryDelta = this.expireDeltaMs) {
|
|
65
|
-
const nowMs = Date.now();
|
|
66
|
-
const toStore = {
|
|
67
|
-
value,
|
|
68
|
-
storedMs: nowMs,
|
|
69
|
-
expiryMs: nowMs + durationOrMsToMs(expiryDelta)
|
|
70
|
-
};
|
|
71
|
-
const valueStr = JSON.stringify(toStore);
|
|
72
|
-
globalThis.localStorage.setItem(this.key, valueStr);
|
|
73
|
-
}
|
|
74
|
-
/**
|
|
75
|
-
* Example usage:
|
|
76
|
-
*
|
|
77
|
-
* const { value, storedMs, expiryMs } = await myItem.getStoredItem();
|
|
78
|
-
*/
|
|
79
|
-
getStoredItem() {
|
|
80
|
-
const jsonStr = globalThis.localStorage.getItem(this.key);
|
|
81
|
-
if (!jsonStr) {
|
|
82
|
-
return void 0;
|
|
83
|
-
}
|
|
84
|
-
try {
|
|
85
|
-
const obj = JSON.parse(jsonStr);
|
|
86
|
-
if (!obj || typeof obj !== "object" || !("value" in obj) || !("storedMs" in obj) || typeof obj.storedMs !== "number" || !("expiryMs" in obj) || typeof obj.expiryMs !== "number" || Date.now() >= obj.expiryMs) {
|
|
87
|
-
this.remove();
|
|
88
|
-
return void 0;
|
|
89
|
-
}
|
|
90
|
-
return obj;
|
|
91
|
-
} catch (e) {
|
|
92
|
-
if (this.logError) {
|
|
93
|
-
console.error(
|
|
94
|
-
`Found invalid storage value: ${this.key}=${jsonStr}:`,
|
|
95
|
-
e
|
|
96
|
-
);
|
|
97
|
-
}
|
|
98
|
-
this.remove();
|
|
99
|
-
return void 0;
|
|
100
|
-
}
|
|
101
|
-
}
|
|
102
|
-
/**
|
|
103
|
-
* Get the value of this item, or undefined if value is not set or expired.
|
|
104
|
-
*/
|
|
105
|
-
get() {
|
|
106
|
-
const stored = this.getStoredItem();
|
|
107
|
-
return stored !== void 0 ? stored.value : this.defaultValue;
|
|
108
|
-
}
|
|
109
|
-
/**
|
|
110
|
-
* Remove the value of this item.
|
|
111
|
-
*/
|
|
112
|
-
remove() {
|
|
113
|
-
globalThis.localStorage.removeItem(this.key);
|
|
114
|
-
}
|
|
115
|
-
};
|
|
116
|
-
// Annotate the CommonJS export names for ESM import in node:
|
|
117
|
-
0 && (module.exports = {
|
|
118
|
-
storeItem
|
|
119
|
-
});
|
package/localStorageCache.d.mts
DELETED
|
@@ -1,57 +0,0 @@
|
|
|
1
|
-
import { Duration } from './duration.mjs';
|
|
2
|
-
|
|
3
|
-
type StoredItem<T> = {
|
|
4
|
-
value: T;
|
|
5
|
-
storedMs: number;
|
|
6
|
-
expiryMs: number;
|
|
7
|
-
};
|
|
8
|
-
/**
|
|
9
|
-
* Simple local storage cache with support for auto-expiration.
|
|
10
|
-
* Note that this works in the browser context only because nodejs does not
|
|
11
|
-
* have local storage.
|
|
12
|
-
*
|
|
13
|
-
* Create a cache item accessor object with auto-expiration. The value will
|
|
14
|
-
* always be stored as a string by applying JSON.stringify(), and will be
|
|
15
|
-
* returned in the same object type by applying JSON.parse().
|
|
16
|
-
*
|
|
17
|
-
* In order to provide proper type-checking, please always specify the T
|
|
18
|
-
* type parameter. E.g. const item = storeItem<string>("name", 10_000);
|
|
19
|
-
*
|
|
20
|
-
* @param key The store key in local storage.
|
|
21
|
-
* @param expires Either a number in milliseconds, or a Duration object
|
|
22
|
-
* @param logError Log an error if we found an invalid object in the store.
|
|
23
|
-
* The invalid object is usually a string that cannot be parsed as JSON.
|
|
24
|
-
* @param defaultValue Specify a default value to use for the object. Defaults
|
|
25
|
-
* to undefined.
|
|
26
|
-
*/
|
|
27
|
-
declare function storeItem<T>(key: string, expires: number | Duration, logError?: boolean, defaultValue?: T): CacheItem<T>;
|
|
28
|
-
declare class CacheItem<T> {
|
|
29
|
-
readonly key: string;
|
|
30
|
-
readonly expireDeltaMs: number;
|
|
31
|
-
readonly logError: boolean;
|
|
32
|
-
readonly defaultValue: T | undefined;
|
|
33
|
-
/**
|
|
34
|
-
* Create a cache item accessor object with auto-expiration.
|
|
35
|
-
*/
|
|
36
|
-
constructor(key: string, expireDeltaMs: number, logError: boolean, defaultValue: T | undefined);
|
|
37
|
-
/**
|
|
38
|
-
* Set the value of this item with auto-expiration.
|
|
39
|
-
*/
|
|
40
|
-
set(value: T, expiryDelta?: number | Duration): void;
|
|
41
|
-
/**
|
|
42
|
-
* Example usage:
|
|
43
|
-
*
|
|
44
|
-
* const { value, storedMs, expiryMs } = await myItem.getStoredItem();
|
|
45
|
-
*/
|
|
46
|
-
getStoredItem(): StoredItem<T> | undefined;
|
|
47
|
-
/**
|
|
48
|
-
* Get the value of this item, or undefined if value is not set or expired.
|
|
49
|
-
*/
|
|
50
|
-
get(): T | undefined;
|
|
51
|
-
/**
|
|
52
|
-
* Remove the value of this item.
|
|
53
|
-
*/
|
|
54
|
-
remove(): void;
|
|
55
|
-
}
|
|
56
|
-
|
|
57
|
-
export { type StoredItem, storeItem };
|
package/localStorageCache.d.ts
DELETED
|
@@ -1,55 +0,0 @@
|
|
|
1
|
-
import { Duration } from "./duration";
|
|
2
|
-
export type StoredItem<T> = {
|
|
3
|
-
value: T;
|
|
4
|
-
storedMs: number;
|
|
5
|
-
expiryMs: number;
|
|
6
|
-
};
|
|
7
|
-
/**
|
|
8
|
-
* Simple local storage cache with support for auto-expiration.
|
|
9
|
-
* Note that this works in the browser context only because nodejs does not
|
|
10
|
-
* have local storage.
|
|
11
|
-
*
|
|
12
|
-
* Create a cache item accessor object with auto-expiration. The value will
|
|
13
|
-
* always be stored as a string by applying JSON.stringify(), and will be
|
|
14
|
-
* returned in the same object type by applying JSON.parse().
|
|
15
|
-
*
|
|
16
|
-
* In order to provide proper type-checking, please always specify the T
|
|
17
|
-
* type parameter. E.g. const item = storeItem<string>("name", 10_000);
|
|
18
|
-
*
|
|
19
|
-
* @param key The store key in local storage.
|
|
20
|
-
* @param expires Either a number in milliseconds, or a Duration object
|
|
21
|
-
* @param logError Log an error if we found an invalid object in the store.
|
|
22
|
-
* The invalid object is usually a string that cannot be parsed as JSON.
|
|
23
|
-
* @param defaultValue Specify a default value to use for the object. Defaults
|
|
24
|
-
* to undefined.
|
|
25
|
-
*/
|
|
26
|
-
export declare function storeItem<T>(key: string, expires: number | Duration, logError?: boolean, defaultValue?: T): CacheItem<T>;
|
|
27
|
-
declare class CacheItem<T> {
|
|
28
|
-
readonly key: string;
|
|
29
|
-
readonly expireDeltaMs: number;
|
|
30
|
-
readonly logError: boolean;
|
|
31
|
-
readonly defaultValue: T | undefined;
|
|
32
|
-
/**
|
|
33
|
-
* Create a cache item accessor object with auto-expiration.
|
|
34
|
-
*/
|
|
35
|
-
constructor(key: string, expireDeltaMs: number, logError: boolean, defaultValue: T | undefined);
|
|
36
|
-
/**
|
|
37
|
-
* Set the value of this item with auto-expiration.
|
|
38
|
-
*/
|
|
39
|
-
set(value: T, expiryDelta?: number | Duration): void;
|
|
40
|
-
/**
|
|
41
|
-
* Example usage:
|
|
42
|
-
*
|
|
43
|
-
* const { value, storedMs, expiryMs } = await myItem.getStoredItem();
|
|
44
|
-
*/
|
|
45
|
-
getStoredItem(): StoredItem<T> | undefined;
|
|
46
|
-
/**
|
|
47
|
-
* Get the value of this item, or undefined if value is not set or expired.
|
|
48
|
-
*/
|
|
49
|
-
get(): T | undefined;
|
|
50
|
-
/**
|
|
51
|
-
* Remove the value of this item.
|
|
52
|
-
*/
|
|
53
|
-
remove(): void;
|
|
54
|
-
}
|
|
55
|
-
export {};
|
|
@@ -1,2 +0,0 @@
|
|
|
1
|
-
"use strict";var i=Object.defineProperty;var l=Object.getOwnPropertyDescriptor;var c=Object.getOwnPropertyNames;var p=Object.prototype.hasOwnProperty;var d=(r,o)=>{for(var t in o)i(r,t,{get:o[t],enumerable:!0})},f=(r,o,t,n)=>{if(o&&typeof o=="object"||typeof o=="function")for(let e of c(o))!p.call(r,e)&&e!==t&&i(r,e,{get:()=>o[e],enumerable:!(n=l(o,e))||n.enumerable});return r};var S=r=>f(i({},"__esModule",{value:!0}),r);var h={};d(h,{storeItem:()=>M});module.exports=S(h);function y(r){let o=(r.days??0)*864e5,t=(r.hours??0)*36e5,n=(r.minutes??0)*6e4,e=(r.seconds??0)*1e3,s=r.milliseconds??0;return o+t+n+e+s}function u(r){return typeof r=="number"?r:y(r)}function M(r,o,t=!0,n){let e=u(o);return new a(r,e,t,n)}var a=class{constructor(o,t,n,e){this.key=o;this.expireDeltaMs=t;this.logError=n;this.defaultValue=e}set(o,t=this.expireDeltaMs){let n=Date.now(),e={value:o,storedMs:n,expiryMs:n+u(t)},s=JSON.stringify(e);globalThis.localStorage.setItem(this.key,s)}getStoredItem(){let o=globalThis.localStorage.getItem(this.key);if(o)try{let t=JSON.parse(o);if(!t||typeof t!="object"||!("value"in t)||!("storedMs"in t)||typeof t.storedMs!="number"||!("expiryMs"in t)||typeof t.expiryMs!="number"||Date.now()>=t.expiryMs){this.remove();return}return t}catch(t){this.logError&&console.error(`Found invalid storage value: ${this.key}=${o}:`,t),this.remove();return}}get(){let o=this.getStoredItem();return o!==void 0?o.value:this.defaultValue}remove(){globalThis.localStorage.removeItem(this.key)}};0&&(module.exports={storeItem});
|
|
2
|
-
//# sourceMappingURL=localStorageCache.min.cjs.map
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/localStorageCache.ts","../src/duration.ts"],"sourcesContent":["import { Duration, durationOrMsToMs } from \"./duration\";\n\nexport type StoredItem<T> = { value: T; storedMs: number; expiryMs: number };\n\n/**\n * Simple local storage cache with support for auto-expiration.\n * Note that this works in the browser context only because nodejs does not\n * have local storage.\n *\n * Create a cache item accessor object with auto-expiration. The value will\n * always be stored as a string by applying JSON.stringify(), and will be\n * returned in the same object type by applying JSON.parse().\n *\n * In order to provide proper type-checking, please always specify the T\n * type parameter. E.g. const item = storeItem<string>(\"name\", 10_000);\n *\n * @param key The store key in local storage.\n * @param expires Either a number in milliseconds, or a Duration object\n * @param logError Log an error if we found an invalid object in the store.\n * The invalid object is usually a string that cannot be parsed as JSON.\n * @param defaultValue Specify a default value to use for the object. Defaults\n * to undefined.\n */\nexport function storeItem<T>(\n key: string,\n expires: number | Duration,\n logError = true,\n defaultValue?: T,\n) {\n const expireDeltaMs = durationOrMsToMs(expires);\n\n return new CacheItem<T>(key, expireDeltaMs, logError, defaultValue);\n}\n\nclass CacheItem<T> {\n /**\n * Create a cache item accessor object with auto-expiration.\n */\n public constructor(\n public readonly key: string,\n public readonly expireDeltaMs: number,\n public readonly logError: boolean,\n public readonly defaultValue: T | undefined,\n ) {}\n\n /**\n * Set the value of this item with auto-expiration.\n */\n public set(\n value: T,\n expiryDelta: number | Duration = this.expireDeltaMs,\n ): void {\n const nowMs = Date.now();\n const toStore: StoredItem<T> = {\n value,\n storedMs: nowMs,\n expiryMs: nowMs + durationOrMsToMs(expiryDelta),\n };\n const valueStr = JSON.stringify(toStore);\n\n globalThis.localStorage.setItem(this.key, valueStr);\n }\n\n /**\n * Example usage:\n *\n * const { value, storedMs, expiryMs } = await myItem.getStoredItem();\n */\n public getStoredItem(): StoredItem<T> | undefined {\n const jsonStr = globalThis.localStorage.getItem(this.key);\n\n if (!jsonStr) {\n return undefined;\n }\n\n try {\n const obj: StoredItem<T> | undefined = JSON.parse(jsonStr);\n\n if (\n !obj ||\n typeof obj !== \"object\" ||\n !(\"value\" in obj) ||\n !(\"storedMs\" in obj) ||\n typeof obj.storedMs !== \"number\" ||\n !(\"expiryMs\" in obj) ||\n typeof obj.expiryMs !== \"number\" ||\n Date.now() >= obj.expiryMs\n ) {\n this.remove();\n return undefined;\n }\n\n return obj;\n } catch (e) {\n if (this.logError) {\n console.error(\n `Found invalid storage value: ${this.key}=${jsonStr}:`,\n e,\n );\n }\n this.remove();\n return undefined;\n }\n }\n\n /**\n * Get the value of this item, or undefined if value is not set or expired.\n */\n public get(): T | undefined {\n const stored = this.getStoredItem();\n\n return stored !== undefined ? stored.value : this.defaultValue;\n }\n\n /**\n * Remove the value of this item.\n */\n public remove(): void {\n globalThis.localStorage.removeItem(this.key);\n }\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,eAAAE,IAAA,eAAAC,EAAAH,GC0LO,SAASI,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,CDlLO,SAASO,EACdC,EACAC,EACAC,EAAW,GACXC,EACA,CACA,IAAMC,EAAgBC,EAAiBJ,CAAO,EAE9C,OAAO,IAAIK,EAAaN,EAAKI,EAAeF,EAAUC,CAAY,CACpE,CAEA,IAAMG,EAAN,KAAmB,CAIV,YACWN,EACAI,EACAF,EACAC,EAChB,CAJgB,SAAAH,EACA,mBAAAI,EACA,cAAAF,EACA,kBAAAC,CACf,CAKI,IACLI,EACAC,EAAiC,KAAK,cAChC,CACN,IAAMC,EAAQ,KAAK,IAAI,EACjBC,EAAyB,CAC7B,MAAAH,EACA,SAAUE,EACV,SAAUA,EAAQJ,EAAiBG,CAAW,CAChD,EACMG,EAAW,KAAK,UAAUD,CAAO,EAEvC,WAAW,aAAa,QAAQ,KAAK,IAAKC,CAAQ,CACpD,CAOO,eAA2C,CAChD,IAAMC,EAAU,WAAW,aAAa,QAAQ,KAAK,GAAG,EAExD,GAAKA,EAIL,GAAI,CACF,IAAMC,EAAiC,KAAK,MAAMD,CAAO,EAEzD,GACE,CAACC,GACD,OAAOA,GAAQ,UACf,EAAE,UAAWA,IACb,EAAE,aAAcA,IAChB,OAAOA,EAAI,UAAa,UACxB,EAAE,aAAcA,IAChB,OAAOA,EAAI,UAAa,UACxB,KAAK,IAAI,GAAKA,EAAI,SAClB,CACA,KAAK,OAAO,EACZ,MACF,CAEA,OAAOA,CACT,OAASC,EAAG,CACN,KAAK,UACP,QAAQ,MACN,gCAAgC,KAAK,GAAG,IAAIF,CAAO,IACnDE,CACF,EAEF,KAAK,OAAO,EACZ,MACF,CACF,CAKO,KAAqB,CAC1B,IAAMC,EAAS,KAAK,cAAc,EAElC,OAAOA,IAAW,OAAYA,EAAO,MAAQ,KAAK,YACpD,CAKO,QAAe,CACpB,WAAW,aAAa,WAAW,KAAK,GAAG,CAC7C,CACF","names":["localStorageCache_exports","__export","storeItem","__toCommonJS","durationToMs","duration","daysMs","hoursMs","minsMs","secsMs","msMs","durationOrMsToMs","storeItem","key","expires","logError","defaultValue","expireDeltaMs","durationOrMsToMs","CacheItem","value","expiryDelta","nowMs","toStore","valueStr","jsonStr","obj","e","stored"]}
|
|
@@ -1,2 +0,0 @@
|
|
|
1
|
-
function d(r){let t=(r.days??0)*864e5,o=(r.hours??0)*36e5,e=(r.minutes??0)*6e4,n=(r.seconds??0)*1e3,s=r.milliseconds??0;return t+o+e+n+s}function i(r){return typeof r=="number"?r:d(r)}function h(r,t,o=!0,e){let n=i(t);return new u(r,n,o,e)}var u=class{constructor(t,o,e,n){this.key=t;this.expireDeltaMs=o;this.logError=e;this.defaultValue=n}set(t,o=this.expireDeltaMs){let e=Date.now(),n={value:t,storedMs:e,expiryMs:e+i(o)},s=JSON.stringify(n);globalThis.localStorage.setItem(this.key,s)}getStoredItem(){let t=globalThis.localStorage.getItem(this.key);if(t)try{let o=JSON.parse(t);if(!o||typeof o!="object"||!("value"in o)||!("storedMs"in o)||typeof o.storedMs!="number"||!("expiryMs"in o)||typeof o.expiryMs!="number"||Date.now()>=o.expiryMs){this.remove();return}return o}catch(o){this.logError&&console.error(`Found invalid storage value: ${this.key}=${t}:`,o),this.remove();return}}get(){let t=this.getStoredItem();return t!==void 0?t.value:this.defaultValue}remove(){globalThis.localStorage.removeItem(this.key)}};export{h as storeItem};
|
|
2
|
-
//# sourceMappingURL=localStorageCache.min.mjs.map
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/duration.ts","../src/localStorageCache.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","import { Duration, durationOrMsToMs } from \"./duration\";\n\nexport type StoredItem<T> = { value: T; storedMs: number; expiryMs: number };\n\n/**\n * Simple local storage cache with support for auto-expiration.\n * Note that this works in the browser context only because nodejs does not\n * have local storage.\n *\n * Create a cache item accessor object with auto-expiration. The value will\n * always be stored as a string by applying JSON.stringify(), and will be\n * returned in the same object type by applying JSON.parse().\n *\n * In order to provide proper type-checking, please always specify the T\n * type parameter. E.g. const item = storeItem<string>(\"name\", 10_000);\n *\n * @param key The store key in local storage.\n * @param expires Either a number in milliseconds, or a Duration object\n * @param logError Log an error if we found an invalid object in the store.\n * The invalid object is usually a string that cannot be parsed as JSON.\n * @param defaultValue Specify a default value to use for the object. Defaults\n * to undefined.\n */\nexport function storeItem<T>(\n key: string,\n expires: number | Duration,\n logError = true,\n defaultValue?: T,\n) {\n const expireDeltaMs = durationOrMsToMs(expires);\n\n return new CacheItem<T>(key, expireDeltaMs, logError, defaultValue);\n}\n\nclass CacheItem<T> {\n /**\n * Create a cache item accessor object with auto-expiration.\n */\n public constructor(\n public readonly key: string,\n public readonly expireDeltaMs: number,\n public readonly logError: boolean,\n public readonly defaultValue: T | undefined,\n ) {}\n\n /**\n * Set the value of this item with auto-expiration.\n */\n public set(\n value: T,\n expiryDelta: number | Duration = this.expireDeltaMs,\n ): void {\n const nowMs = Date.now();\n const toStore: StoredItem<T> = {\n value,\n storedMs: nowMs,\n expiryMs: nowMs + durationOrMsToMs(expiryDelta),\n };\n const valueStr = JSON.stringify(toStore);\n\n globalThis.localStorage.setItem(this.key, valueStr);\n }\n\n /**\n * Example usage:\n *\n * const { value, storedMs, expiryMs } = await myItem.getStoredItem();\n */\n public getStoredItem(): StoredItem<T> | undefined {\n const jsonStr = globalThis.localStorage.getItem(this.key);\n\n if (!jsonStr) {\n return undefined;\n }\n\n try {\n const obj: StoredItem<T> | undefined = JSON.parse(jsonStr);\n\n if (\n !obj ||\n typeof obj !== \"object\" ||\n !(\"value\" in obj) ||\n !(\"storedMs\" in obj) ||\n typeof obj.storedMs !== \"number\" ||\n !(\"expiryMs\" in obj) ||\n typeof obj.expiryMs !== \"number\" ||\n Date.now() >= obj.expiryMs\n ) {\n this.remove();\n return undefined;\n }\n\n return obj;\n } catch (e) {\n if (this.logError) {\n console.error(\n `Found invalid storage value: ${this.key}=${jsonStr}:`,\n e,\n );\n }\n this.remove();\n return undefined;\n }\n }\n\n /**\n * Get the value of this item, or undefined if value is not set or expired.\n */\n public get(): T | undefined {\n const stored = this.getStoredItem();\n\n return stored !== undefined ? stored.value : this.defaultValue;\n }\n\n /**\n * Remove the value of this item.\n */\n public remove(): void {\n globalThis.localStorage.removeItem(this.key);\n }\n}\n"],"mappings":"AA0LO,SAASA,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,CClLO,SAASO,EACdC,EACAC,EACAC,EAAW,GACXC,EACA,CACA,IAAMC,EAAgBC,EAAiBJ,CAAO,EAE9C,OAAO,IAAIK,EAAaN,EAAKI,EAAeF,EAAUC,CAAY,CACpE,CAEA,IAAMG,EAAN,KAAmB,CAIV,YACWN,EACAI,EACAF,EACAC,EAChB,CAJgB,SAAAH,EACA,mBAAAI,EACA,cAAAF,EACA,kBAAAC,CACf,CAKI,IACLI,EACAC,EAAiC,KAAK,cAChC,CACN,IAAMC,EAAQ,KAAK,IAAI,EACjBC,EAAyB,CAC7B,MAAAH,EACA,SAAUE,EACV,SAAUA,EAAQJ,EAAiBG,CAAW,CAChD,EACMG,EAAW,KAAK,UAAUD,CAAO,EAEvC,WAAW,aAAa,QAAQ,KAAK,IAAKC,CAAQ,CACpD,CAOO,eAA2C,CAChD,IAAMC,EAAU,WAAW,aAAa,QAAQ,KAAK,GAAG,EAExD,GAAKA,EAIL,GAAI,CACF,IAAMC,EAAiC,KAAK,MAAMD,CAAO,EAEzD,GACE,CAACC,GACD,OAAOA,GAAQ,UACf,EAAE,UAAWA,IACb,EAAE,aAAcA,IAChB,OAAOA,EAAI,UAAa,UACxB,EAAE,aAAcA,IAChB,OAAOA,EAAI,UAAa,UACxB,KAAK,IAAI,GAAKA,EAAI,SAClB,CACA,KAAK,OAAO,EACZ,MACF,CAEA,OAAOA,CACT,OAASC,EAAG,CACN,KAAK,UACP,QAAQ,MACN,gCAAgC,KAAK,GAAG,IAAIF,CAAO,IACnDE,CACF,EAEF,KAAK,OAAO,EACZ,MACF,CACF,CAKO,KAAqB,CAC1B,IAAMC,EAAS,KAAK,cAAc,EAElC,OAAOA,IAAW,OAAYA,EAAO,MAAQ,KAAK,YACpD,CAKO,QAAe,CACpB,WAAW,aAAa,WAAW,KAAK,GAAG,CAC7C,CACF","names":["durationToMs","duration","daysMs","hoursMs","minsMs","secsMs","msMs","durationOrMsToMs","storeItem","key","expires","logError","defaultValue","expireDeltaMs","durationOrMsToMs","CacheItem","value","expiryDelta","nowMs","toStore","valueStr","jsonStr","obj","e","stored"]}
|
package/localStorageCache.mjs
DELETED
|
@@ -1,92 +0,0 @@
|
|
|
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/localStorageCache.ts
|
|
21
|
-
function storeItem(key, expires, logError = true, defaultValue) {
|
|
22
|
-
const expireDeltaMs = durationOrMsToMs(expires);
|
|
23
|
-
return new CacheItem(key, expireDeltaMs, logError, defaultValue);
|
|
24
|
-
}
|
|
25
|
-
var CacheItem = class {
|
|
26
|
-
/**
|
|
27
|
-
* Create a cache item accessor object with auto-expiration.
|
|
28
|
-
*/
|
|
29
|
-
constructor(key, expireDeltaMs, logError, defaultValue) {
|
|
30
|
-
this.key = key;
|
|
31
|
-
this.expireDeltaMs = expireDeltaMs;
|
|
32
|
-
this.logError = logError;
|
|
33
|
-
this.defaultValue = defaultValue;
|
|
34
|
-
}
|
|
35
|
-
/**
|
|
36
|
-
* Set the value of this item with auto-expiration.
|
|
37
|
-
*/
|
|
38
|
-
set(value, expiryDelta = this.expireDeltaMs) {
|
|
39
|
-
const nowMs = Date.now();
|
|
40
|
-
const toStore = {
|
|
41
|
-
value,
|
|
42
|
-
storedMs: nowMs,
|
|
43
|
-
expiryMs: nowMs + durationOrMsToMs(expiryDelta)
|
|
44
|
-
};
|
|
45
|
-
const valueStr = JSON.stringify(toStore);
|
|
46
|
-
globalThis.localStorage.setItem(this.key, valueStr);
|
|
47
|
-
}
|
|
48
|
-
/**
|
|
49
|
-
* Example usage:
|
|
50
|
-
*
|
|
51
|
-
* const { value, storedMs, expiryMs } = await myItem.getStoredItem();
|
|
52
|
-
*/
|
|
53
|
-
getStoredItem() {
|
|
54
|
-
const jsonStr = globalThis.localStorage.getItem(this.key);
|
|
55
|
-
if (!jsonStr) {
|
|
56
|
-
return void 0;
|
|
57
|
-
}
|
|
58
|
-
try {
|
|
59
|
-
const obj = JSON.parse(jsonStr);
|
|
60
|
-
if (!obj || typeof obj !== "object" || !("value" in obj) || !("storedMs" in obj) || typeof obj.storedMs !== "number" || !("expiryMs" in obj) || typeof obj.expiryMs !== "number" || Date.now() >= obj.expiryMs) {
|
|
61
|
-
this.remove();
|
|
62
|
-
return void 0;
|
|
63
|
-
}
|
|
64
|
-
return obj;
|
|
65
|
-
} catch (e) {
|
|
66
|
-
if (this.logError) {
|
|
67
|
-
console.error(
|
|
68
|
-
`Found invalid storage value: ${this.key}=${jsonStr}:`,
|
|
69
|
-
e
|
|
70
|
-
);
|
|
71
|
-
}
|
|
72
|
-
this.remove();
|
|
73
|
-
return void 0;
|
|
74
|
-
}
|
|
75
|
-
}
|
|
76
|
-
/**
|
|
77
|
-
* Get the value of this item, or undefined if value is not set or expired.
|
|
78
|
-
*/
|
|
79
|
-
get() {
|
|
80
|
-
const stored = this.getStoredItem();
|
|
81
|
-
return stored !== void 0 ? stored.value : this.defaultValue;
|
|
82
|
-
}
|
|
83
|
-
/**
|
|
84
|
-
* Remove the value of this item.
|
|
85
|
-
*/
|
|
86
|
-
remove() {
|
|
87
|
-
globalThis.localStorage.removeItem(this.key);
|
|
88
|
-
}
|
|
89
|
-
};
|
|
90
|
-
export {
|
|
91
|
-
storeItem
|
|
92
|
-
};
|