@choksheak/ts-utils 0.2.0 → 0.2.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/dateTimeStr.d.ts CHANGED
@@ -4,6 +4,13 @@ export type AnyDateTime = number | Date | string;
4
4
  * Date object (no conversion) into a Date object.
5
5
  */
6
6
  export declare function toDate(ts: AnyDateTime): Date;
7
+ /**
8
+ * Returns a date in yyyy-MM format. E.g. '2000-01'.
9
+ *
10
+ * @param dt Specify a date object or default to the current date.
11
+ * @param separator Defaults to '-'.
12
+ */
13
+ export declare function yyyyMm(dt?: Date, separator?: string): string;
7
14
  /**
8
15
  * Returns a date in yyyy-MM-dd format. E.g. '2000-01-02'.
9
16
  *
@@ -11,6 +18,13 @@ export declare function toDate(ts: AnyDateTime): Date;
11
18
  * @param separator Defaults to '-'.
12
19
  */
13
20
  export declare function yyyyMmDd(dt?: Date, separator?: string): string;
21
+ /**
22
+ * Returns a date in hh:mm format. E.g. '01:02'.
23
+ *
24
+ * @param dt Specify a date object or default to the current date/time.
25
+ * @param separator Defaults to ':'.
26
+ */
27
+ export declare function hhMm(dt?: Date, separator?: string): string;
14
28
  /**
15
29
  * Returns a date in hh:mm:ss format. E.g. '01:02:03'.
16
30
  *
package/dateTimeStr.js CHANGED
@@ -25,10 +25,12 @@ __export(dateTimeStr_exports, {
25
25
  getLongMonthNameZeroIndexed: () => getLongMonthNameZeroIndexed,
26
26
  getShortMonthNameOneIndexed: () => getShortMonthNameOneIndexed,
27
27
  getShortMonthNameZeroIndexed: () => getShortMonthNameZeroIndexed,
28
+ hhMm: () => hhMm,
28
29
  hhMmSs: () => hhMmSs,
29
30
  hhMmSsMs: () => hhMmSsMs,
30
31
  toDate: () => toDate,
31
32
  tzShort: () => tzShort,
33
+ yyyyMm: () => yyyyMm,
32
34
  yyyyMmDd: () => yyyyMmDd
33
35
  });
34
36
  module.exports = __toCommonJS(dateTimeStr_exports);
@@ -38,17 +40,23 @@ function toDate(ts) {
38
40
  }
39
41
  return ts;
40
42
  }
41
- function yyyyMmDd(dt = /* @__PURE__ */ new Date(), separator = "-") {
43
+ function yyyyMm(dt = /* @__PURE__ */ new Date(), separator = "-") {
42
44
  const yr = dt.getFullYear();
43
45
  const mth = dt.getMonth() + 1;
46
+ return yr + separator + (mth < 10 ? "0" + mth : mth);
47
+ }
48
+ function yyyyMmDd(dt = /* @__PURE__ */ new Date(), separator = "-") {
44
49
  const day = dt.getDate();
45
- return yr + separator + (mth < 10 ? "0" + mth : mth) + separator + (day < 10 ? "0" + day : day);
50
+ return yyyyMm(dt, separator) + separator + (day < 10 ? "0" + day : day);
46
51
  }
47
- function hhMmSs(dt = /* @__PURE__ */ new Date(), separator = ":") {
52
+ function hhMm(dt = /* @__PURE__ */ new Date(), separator = ":") {
48
53
  const hr = dt.getHours();
49
54
  const min = dt.getMinutes();
55
+ return (hr < 10 ? "0" + hr : hr) + separator + (min < 10 ? "0" + min : min);
56
+ }
57
+ function hhMmSs(dt = /* @__PURE__ */ new Date(), separator = ":") {
50
58
  const sec = dt.getSeconds();
51
- return (hr < 10 ? "0" + hr : hr) + separator + (min < 10 ? "0" + min : min) + separator + (sec < 10 ? "0" + sec : sec);
59
+ return hhMm(dt, separator) + separator + (sec < 10 ? "0" + sec : sec);
52
60
  }
53
61
  function hhMmSsMs(dt = /* @__PURE__ */ new Date(), timeSeparator = ":", msSeparator = ".") {
54
62
  const ms = dt.getMilliseconds();
@@ -89,10 +97,12 @@ function getDisplayDateTime(ts) {
89
97
  getLongMonthNameZeroIndexed,
90
98
  getShortMonthNameOneIndexed,
91
99
  getShortMonthNameZeroIndexed,
100
+ hhMm,
92
101
  hhMmSs,
93
102
  hhMmSsMs,
94
103
  toDate,
95
104
  tzShort,
105
+ yyyyMm,
96
106
  yyyyMmDd
97
107
  });
98
108
  //# sourceMappingURL=dateTimeStr.js.map
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/dateTimeStr.ts"],"sourcesContent":["export type AnyDateTime = number | Date | string;\n\n/**\n * Convert a number (epoch milliseconds), string (parseable date/time), or\n * Date object (no conversion) into a Date object.\n */\nexport function toDate(ts: AnyDateTime): Date {\n if (typeof ts === \"number\" || typeof ts === \"string\") {\n return new Date(ts);\n }\n\n return ts;\n}\n\n/**\n * Returns a date in yyyy-MM-dd format. E.g. '2000-01-02'.\n *\n * @param dt Specify a date object or default to the current date.\n * @param separator Defaults to '-'.\n */\nexport function yyyyMmDd(dt = new Date(), separator = \"-\"): string {\n const yr = dt.getFullYear();\n const mth = dt.getMonth() + 1;\n const day = dt.getDate();\n\n return (\n yr +\n separator +\n (mth < 10 ? \"0\" + mth : mth) +\n separator +\n (day < 10 ? \"0\" + day : day)\n );\n}\n\n/**\n * Returns a date in hh:mm:ss format. E.g. '01:02:03'.\n *\n * @param dt Specify a date object or default to the current date/time.\n * @param separator Defaults to ':'.\n */\nexport function hhMmSs(dt = new Date(), separator = \":\"): string {\n const hr = dt.getHours();\n const min = dt.getMinutes();\n const sec = dt.getSeconds();\n\n return (\n (hr < 10 ? \"0\" + hr : hr) +\n separator +\n (min < 10 ? \"0\" + min : min) +\n separator +\n (sec < 10 ? \"0\" + sec : sec)\n );\n}\n\n/**\n * Returns a date in hh:mm:ss.SSS format. E.g. '01:02:03.004'.\n *\n * @param dt Specify a date object or default to the current date/time.\n * @param timeSeparator Separator for hh/mm/ss. Defaults to ':'.\n * @param msSeparator Separator before SSS. Defaults to '.'.\n */\nexport function hhMmSsMs(\n dt = new Date(),\n timeSeparator = \":\",\n msSeparator = \".\",\n): string {\n const ms = dt.getMilliseconds();\n\n return (\n hhMmSs(dt, timeSeparator) +\n msSeparator +\n (ms < 10 ? \"00\" + ms : ms < 100 ? \"0\" + ms : ms)\n );\n}\n\n/**\n * Returns the timezone string for the given date. E.g. '+8', '-3.5'.\n * Returns 'Z' for UTC.\n *\n * @param dt Specify a date object or default to the current date/time.\n */\nexport function tzShort(dt = new Date()): string {\n if (dt.getTimezoneOffset() === 0) {\n return \"Z\";\n }\n\n const tzHours = dt.getTimezoneOffset() / 60;\n return tzHours >= 0 ? \"+\" + tzHours : String(tzHours);\n}\n\n/**\n * Returns the long month name, zero-indexed. E.g. 0 for 'January'.\n *\n * @param month Zero-indexed month.\n * @param locales Specify the locale, e.g. 'en-US', new Intl.Locale(\"en-US\").\n */\nexport function getLongMonthNameZeroIndexed(\n month: number,\n locales: Intl.LocalesArgument = \"default\",\n): string {\n return new Date(2024, month, 15).toLocaleString(locales, {\n month: \"long\",\n });\n}\n\n/**\n * Returns the long month name, one-indexed. E.g. 1 for 'January'.\n *\n * @param month One-indexed month.\n * @param locales Specify the locale, e.g. 'en-US', new Intl.Locale(\"en-US\").\n */\nexport function getLongMonthNameOneIndexed(\n month: number,\n locales: Intl.LocalesArgument = \"default\",\n): string {\n return getLongMonthNameZeroIndexed(month - 1, locales);\n}\n\n/**\n * Returns the short month name, zero-indexed. E.g. 0 for 'Jan'.\n *\n * @param month Zero-indexed month.\n * @param locales Specify the locale, e.g. 'en-US', new Intl.Locale(\"en-US\").\n */\nexport function getShortMonthNameZeroIndexed(\n month: number,\n locales: Intl.LocalesArgument = \"default\",\n): string {\n return new Date(2000, month, 15).toLocaleString(locales, {\n month: \"short\",\n });\n}\n\n/**\n * Returns the short month name, one-indexed. E.g. 1 for 'Jan'.\n *\n * @param month One-indexed month.\n * @param locales Specify the locale, e.g. 'en-US', new Intl.Locale(\"en-US\").\n */\nexport function getShortMonthNameOneIndexed(\n month: number,\n locales: Intl.LocalesArgument = \"default\",\n): string {\n return getShortMonthNameZeroIndexed(month - 1, locales);\n}\n\n/**\n * Returns a human-readable string date/time like '2025-01-01 22:31:16Z'.\n * Excludes the milliseconds assuming it is not necessary for display.\n */\nexport function getDisplayDateTime(ts: AnyDateTime) {\n const iso = toDate(ts).toISOString();\n const noMs = iso.slice(0, 19) + \"Z\";\n return noMs.replace(\"T\", \" \");\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAA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,2BACd,OACA,UAAgC,WACxB;AACR,SAAO,4BAA4B,QAAQ,GAAG,OAAO;AACvD;AAQO,SAAS,6BACd,OACA,UAAgC,WACxB;AACR,SAAO,IAAI,KAAK,KAAM,OAAO,EAAE,EAAE,eAAe,SAAS;AAAA,IACvD,OAAO;AAAA,EACT,CAAC;AACH;AAQO,SAAS,4BACd,OACA,UAAgC,WACxB;AACR,SAAO,6BAA6B,QAAQ,GAAG,OAAO;AACxD;AAMO,SAAS,mBAAmB,IAAiB;AAClD,QAAM,MAAM,OAAO,EAAE,EAAE,YAAY;AACnC,QAAM,OAAO,IAAI,MAAM,GAAG,EAAE,IAAI;AAChC,SAAO,KAAK,QAAQ,KAAK,GAAG;AAC9B;","names":[]}
1
+ {"version":3,"sources":["../src/dateTimeStr.ts"],"sourcesContent":["export type AnyDateTime = number | Date | string;\n\n/**\n * Convert a number (epoch milliseconds), string (parseable date/time), or\n * Date object (no conversion) into a Date object.\n */\nexport function toDate(ts: AnyDateTime): Date {\n if (typeof ts === \"number\" || typeof ts === \"string\") {\n return new Date(ts);\n }\n\n return ts;\n}\n\n/**\n * Returns a date in yyyy-MM format. E.g. '2000-01'.\n *\n * @param dt Specify a date object or default to the current date.\n * @param separator Defaults to '-'.\n */\nexport function yyyyMm(dt = new Date(), separator = \"-\"): string {\n const yr = dt.getFullYear();\n const mth = dt.getMonth() + 1;\n\n return yr + separator + (mth < 10 ? \"0\" + mth : mth);\n}\n\n/**\n * Returns a date in yyyy-MM-dd format. E.g. '2000-01-02'.\n *\n * @param dt Specify a date object or default to the current date.\n * @param separator Defaults to '-'.\n */\nexport function yyyyMmDd(dt = new Date(), separator = \"-\"): string {\n const day = dt.getDate();\n\n return yyyyMm(dt, separator) + separator + (day < 10 ? \"0\" + day : day);\n}\n\n/**\n * Returns a date in hh:mm format. E.g. '01:02'.\n *\n * @param dt Specify a date object or default to the current date/time.\n * @param separator Defaults to ':'.\n */\nexport function hhMm(dt = new Date(), separator = \":\"): string {\n const hr = dt.getHours();\n const min = dt.getMinutes();\n\n return (hr < 10 ? \"0\" + hr : hr) + separator + (min < 10 ? \"0\" + min : min);\n}\n\n/**\n * Returns a date in hh:mm:ss format. E.g. '01:02:03'.\n *\n * @param dt Specify a date object or default to the current date/time.\n * @param separator Defaults to ':'.\n */\nexport function hhMmSs(dt = new Date(), separator = \":\"): string {\n const sec = dt.getSeconds();\n\n return hhMm(dt, separator) + separator + (sec < 10 ? \"0\" + sec : sec);\n}\n\n/**\n * Returns a date in hh:mm:ss.SSS format. E.g. '01:02:03.004'.\n *\n * @param dt Specify a date object or default to the current date/time.\n * @param timeSeparator Separator for hh/mm/ss. Defaults to ':'.\n * @param msSeparator Separator before SSS. Defaults to '.'.\n */\nexport function hhMmSsMs(\n dt = new Date(),\n timeSeparator = \":\",\n msSeparator = \".\",\n): string {\n const ms = dt.getMilliseconds();\n\n return (\n hhMmSs(dt, timeSeparator) +\n msSeparator +\n (ms < 10 ? \"00\" + ms : ms < 100 ? \"0\" + ms : ms)\n );\n}\n\n/**\n * Returns the timezone string for the given date. E.g. '+8', '-3.5'.\n * Returns 'Z' for UTC.\n *\n * @param dt Specify a date object or default to the current date/time.\n */\nexport function tzShort(dt = new Date()): string {\n if (dt.getTimezoneOffset() === 0) {\n return \"Z\";\n }\n\n const tzHours = dt.getTimezoneOffset() / 60;\n return tzHours >= 0 ? \"+\" + tzHours : String(tzHours);\n}\n\n/**\n * Returns the long month name, zero-indexed. E.g. 0 for 'January'.\n *\n * @param month Zero-indexed month.\n * @param locales Specify the locale, e.g. 'en-US', new Intl.Locale(\"en-US\").\n */\nexport function getLongMonthNameZeroIndexed(\n month: number,\n locales: Intl.LocalesArgument = \"default\",\n): string {\n return new Date(2024, month, 15).toLocaleString(locales, {\n month: \"long\",\n });\n}\n\n/**\n * Returns the long month name, one-indexed. E.g. 1 for 'January'.\n *\n * @param month One-indexed month.\n * @param locales Specify the locale, e.g. 'en-US', new Intl.Locale(\"en-US\").\n */\nexport function getLongMonthNameOneIndexed(\n month: number,\n locales: Intl.LocalesArgument = \"default\",\n): string {\n return getLongMonthNameZeroIndexed(month - 1, locales);\n}\n\n/**\n * Returns the short month name, zero-indexed. E.g. 0 for 'Jan'.\n *\n * @param month Zero-indexed month.\n * @param locales Specify the locale, e.g. 'en-US', new Intl.Locale(\"en-US\").\n */\nexport function getShortMonthNameZeroIndexed(\n month: number,\n locales: Intl.LocalesArgument = \"default\",\n): string {\n return new Date(2000, month, 15).toLocaleString(locales, {\n month: \"short\",\n });\n}\n\n/**\n * Returns the short month name, one-indexed. E.g. 1 for 'Jan'.\n *\n * @param month One-indexed month.\n * @param locales Specify the locale, e.g. 'en-US', new Intl.Locale(\"en-US\").\n */\nexport function getShortMonthNameOneIndexed(\n month: number,\n locales: Intl.LocalesArgument = \"default\",\n): string {\n return getShortMonthNameZeroIndexed(month - 1, locales);\n}\n\n/**\n * Returns a human-readable string date/time like '2025-01-01 22:31:16Z'.\n * Excludes the milliseconds assuming it is not necessary for display.\n */\nexport function getDisplayDateTime(ts: AnyDateTime) {\n const iso = toDate(ts).toISOString();\n const noMs = iso.slice(0, 19) + \"Z\";\n return noMs.replace(\"T\", \" \");\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAMO,SAAS,OAAO,IAAuB;AAC5C,MAAI,OAAO,OAAO,YAAY,OAAO,OAAO,UAAU;AACpD,WAAO,IAAI,KAAK,EAAE;AAAA,EACpB;AAEA,SAAO;AACT;AAQO,SAAS,OAAO,KAAK,oBAAI,KAAK,GAAG,YAAY,KAAa;AAC/D,QAAM,KAAK,GAAG,YAAY;AAC1B,QAAM,MAAM,GAAG,SAAS,IAAI;AAE5B,SAAO,KAAK,aAAa,MAAM,KAAK,MAAM,MAAM;AAClD;AAQO,SAAS,SAAS,KAAK,oBAAI,KAAK,GAAG,YAAY,KAAa;AACjE,QAAM,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,SAAO,6BAA6B,QAAQ,GAAG,OAAO;AACxD;AAMO,SAAS,mBAAmB,IAAiB;AAClD,QAAM,MAAM,OAAO,EAAE,EAAE,YAAY;AACnC,QAAM,OAAO,IAAI,MAAM,GAAG,EAAE,IAAI;AAChC,SAAO,KAAK,QAAQ,KAAK,GAAG;AAC9B;","names":[]}
package/duration.d.ts CHANGED
@@ -51,6 +51,10 @@ export declare function msToDuration(ms: number, durationTypeForZero?: DurationT
51
51
  * Returns the number of milliseconds for the given duration.
52
52
  */
53
53
  export declare function durationToMs(duration: Duration): number;
54
+ /**
55
+ * Convenience function to return a duration given an ms or Duration.
56
+ */
57
+ export declare function durationOrMsToMs(duration: number | Duration): number;
54
58
  /**
55
59
  * Format a given Duration object into a string. If the object has no fields,
56
60
  * then returns an empty string.
package/duration.js CHANGED
@@ -22,6 +22,7 @@ var duration_exports = {};
22
22
  __export(duration_exports, {
23
23
  DURATION_STYLE_SUFFIX_MAP: () => DURATION_STYLE_SUFFIX_MAP,
24
24
  DURATION_TYPE_SEQUENCE: () => DURATION_TYPE_SEQUENCE,
25
+ durationOrMsToMs: () => durationOrMsToMs,
25
26
  durationToMs: () => durationToMs,
26
27
  formatDuration: () => formatDuration,
27
28
  msToDuration: () => msToDuration,
@@ -143,6 +144,9 @@ function durationToMs(duration) {
143
144
  const msMs = (_e = duration.milliseconds) != null ? _e : 0;
144
145
  return daysMs + hoursMs + minsMs + secsMs + msMs;
145
146
  }
147
+ function durationOrMsToMs(duration) {
148
+ return typeof duration === "number" ? duration : durationToMs(duration);
149
+ }
146
150
  function formatDuration(duration, style) {
147
151
  style = style != null ? style : "short";
148
152
  const stylePlural = getDurationStyleForPlural(style);
@@ -166,6 +170,7 @@ function readableDuration(ms, options) {
166
170
  0 && (module.exports = {
167
171
  DURATION_STYLE_SUFFIX_MAP,
168
172
  DURATION_TYPE_SEQUENCE,
173
+ durationOrMsToMs,
169
174
  durationToMs,
170
175
  formatDuration,
171
176
  msToDuration,
package/duration.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/duration.ts","../src/timeConstants.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 MS_PER_SECOND,\n SECONDS_PER_MINUTE,\n MINUTES_PER_HOUR,\n HOURS_PER_DAY,\n MS_PER_DAY,\n MS_PER_MINUTE,\n MS_PER_HOUR,\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 * 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 * Note that month and year do not have fixed durations, and hence are excluded\n * from this file.\n */\n\nexport const MS_PER_SECOND = 1000;\nexport const MS_PER_MINUTE = 60_000;\nexport const MS_PER_HOUR = 3_600_000;\nexport const MS_PER_DAY = 86_400_000;\nexport const MS_PER_WEEK = 604_800_000;\n\nexport const SECONDS_PER_MINUTE = 60;\nexport const SECONDS_PER_HOUR = 3_600;\nexport const SECONDS_PER_DAY = 86_400;\nexport const SECONDS_PER_WEEK = 604_800;\n\nexport const MINUTES_PER_HOUR = 60;\nexport const MINUTES_PER_DAY = 1440;\nexport const MINUTES_PER_WEEK = 10_080;\n\nexport const HOURS_PER_DAY = 24;\nexport const HOURS_PER_WEEK = 168;\n"],"mappings":";;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;;;ACKO,IAAM,gBAAgB;AACtB,IAAM,gBAAgB;AACtB,IAAM,cAAc;AACpB,IAAM,aAAa;AAGnB,IAAM,qBAAqB;AAK3B,IAAM,mBAAmB;AAIzB,IAAM,gBAAgB;;;ADetB,IAAM,yBAAyC;AAAA,EACpD;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AACF;AAsBO,IAAM,4BAGT;AAAA,EACF,MAAM;AAAA,IACJ,OAAO;AAAA,IACP,QAAQ;AAAA,IACR,MAAM;AAAA,IACN,OAAO;AAAA,IACP,QAAQ;AAAA,EACV;AAAA,EACA,OAAO;AAAA,IACL,OAAO;AAAA,IACP,QAAQ;AAAA,IACR,MAAM;AAAA,IACN,OAAO;AAAA,IACP,QAAQ;AAAA,EACV;AAAA,EACA,SAAS;AAAA,IACP,OAAO;AAAA,IACP,QAAQ;AAAA,IACR,MAAM;AAAA,IACN,OAAO;AAAA,IACP,QAAQ;AAAA,EACV;AAAA,EACA,SAAS;AAAA,IACP,OAAO;AAAA,IACP,QAAQ;AAAA,IACR,MAAM;AAAA,IACN,OAAO;AAAA,IACP,QAAQ;AAAA,EACV;AAAA,EACA,cAAc;AAAA,IACZ,OAAO;AAAA,IACP,QAAQ;AAAA,IACR,MAAM;AAAA,IACN,OAAO;AAAA,IACP,QAAQ;AAAA,EACV;AACF;AAEA,SAAS,0BAA0B,OAA0C;AAC3E,SAAO,SAAS,UAAU,WAAW,UAAU,SAAS,UAAU;AACpE;AAEA,SAAS,yBAAyB,OAA8B;AAC9D,SAAO,UAAU,WA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T,YAAyB;AAEtC,SAAO,SAAS,UAAU,SAAS,SAAS;AAC9C;AAQO,SAAS,eAAe,UAAoB,OAAuB;AACxE,UAAQ,wBAAS;AACjB,QAAM,cAAc,0BAA0B,KAAK;AAEnD,QAAM,QAAQ,yBAAyB,KAAK;AAE5C,QAAM,IAAc,CAAC;AAErB,aAAW,QAAQ,wBAAwB;AACzC,UAAM,QAAQ,SAAS,IAAI;AAC3B,QAAI,UAAU,OAAW;AAEzB,UAAM,YAAY,0BAA0B,IAAI;AAChD,UAAM,SAAS,UAAU,IAAI,UAAU,KAAK,IAAI,UAAU,WAAW;AACrE,MAAE,KAAK,QAAQ,QAAQ,MAAM;AAAA,EAC/B;AAEA,QAAM,YAAY,yBAAyB,KAAK;AAChD,SAAO,EAAE,KAAK,SAAS;AACzB;AAQO,SAAS,iBACd,IACA,SACQ;AACR,QAAM,WAAW,aAAa,IAAI,mCAAS,mBAAmB;AAE9D,SAAO,eAAe,UAAU,mCAAS,KAAK;AAChD;","names":[]}
1
+ {"version":3,"sources":["../src/duration.ts","../src/timeConstants.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 MS_PER_SECOND,\n SECONDS_PER_MINUTE,\n MINUTES_PER_HOUR,\n HOURS_PER_DAY,\n MS_PER_DAY,\n MS_PER_MINUTE,\n MS_PER_HOUR,\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 * Note that month and year do not have fixed durations, and hence are excluded\n * from this file.\n */\n\nexport const MS_PER_SECOND = 1000;\nexport const MS_PER_MINUTE = 60_000;\nexport const MS_PER_HOUR = 3_600_000;\nexport const MS_PER_DAY = 86_400_000;\nexport const MS_PER_WEEK = 604_800_000;\n\nexport const SECONDS_PER_MINUTE = 60;\nexport const SECONDS_PER_HOUR = 3_600;\nexport const SECONDS_PER_DAY = 86_400;\nexport const SECONDS_PER_WEEK = 604_800;\n\nexport const MINUTES_PER_HOUR = 60;\nexport const MINUTES_PER_DAY = 1440;\nexport const MINUTES_PER_WEEK = 10_080;\n\nexport const HOURS_PER_DAY = 24;\nexport const HOURS_PER_WEEK = 168;\n"],"mappings":";;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;;;ACKO,IAAM,gBAAgB;AACtB,IAAM,gBAAgB;AACtB,IAAM,cAAc;AACpB,IAAM,aAAa;AAGnB,IAAM,qBAAqB;AAK3B,IAAM,mBAAmB;AAIzB,IAAM,gBAAgB;;;ADetB,IAAM,yBAAyC;AAAA,EACpD;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AACF;AAsBO,IAAM,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AEA,QAAM,YAAY,yBAAyB,KAAK;AAChD,SAAO,EAAE,KAAK,SAAS;AACzB;AAQO,SAAS,iBACd,IACA,SACQ;AACR,QAAM,WAAW,aAAa,IAAI,mCAAS,mBAAmB;AAE9D,SAAO,eAAe,UAAU,mCAAS,KAAK;AAChD;","names":[]}
package/kvStore.d.ts CHANGED
@@ -10,12 +10,19 @@
10
10
  * How to use?
11
11
  * Just use the `kvStore` global constant like the local storage.
12
12
  */
13
+ import { Duration } from "./duration";
13
14
  /** One day in milliseconds. */
14
15
  export declare const MILLIS_PER_DAY = 86400000;
15
16
  /** 30 days in ms. */
16
17
  export declare const DEFAULT_EXPIRY_DELTA_MS: number;
17
18
  /** Do GC once per day. */
18
19
  export declare const GC_INTERVAL_MS = 86400000;
20
+ type StoredObject<T> = {
21
+ key: string;
22
+ value: T;
23
+ storedMs: number;
24
+ expiryMs: number;
25
+ };
19
26
  export declare class KVStoreField<T> {
20
27
  readonly store: KVStore;
21
28
  readonly key: string;
@@ -37,11 +44,12 @@ export declare class KVStore {
37
44
  constructor(dbName: string, dbVersion: number, defaultExpiryDeltaMs: number);
38
45
  private getOrCreateDb;
39
46
  private transact;
40
- set<T>(key: string, value: T, expiryDeltaMs?: number): Promise<T>;
47
+ set<T>(key: string, value: T, expiryDeltaMs?: number | Duration): Promise<T>;
41
48
  /** Delete one or multiple keys. */
42
49
  delete(key: string | string[]): Promise<void>;
50
+ getStoredObject<T>(key: string): Promise<StoredObject<T> | undefined>;
43
51
  get<T>(key: string): Promise<T | undefined>;
44
- forEach(callback: (key: string, value: unknown, expireMs: number) => void | Promise<void>): Promise<void>;
52
+ forEach(callback: (key: string, value: unknown, expiryMs: number) => void | Promise<void>): Promise<void>;
45
53
  /** Cannot be a getter because this needs to be async. */
46
54
  size(): Promise<number>;
47
55
  clear(): Promise<void>;
@@ -69,12 +77,18 @@ declare class KvStoreItem<T> {
69
77
  readonly defaultExpiryDeltaMs: number;
70
78
  readonly store: KVStore;
71
79
  constructor(key: string, defaultExpiryDeltaMs: number, store?: KVStore);
72
- get(): Promise<Awaited<T> | undefined>;
80
+ /**
81
+ * Example usage:
82
+ *
83
+ * const { value, storedMs, expiryMs } = await myKvItem.getStoredObject();
84
+ */
85
+ getStoredObject(): Promise<StoredObject<T> | undefined>;
86
+ get(): Promise<T | undefined>;
73
87
  set(value: T, expiryDeltaMs?: number): Promise<void>;
74
88
  delete(): Promise<void>;
75
89
  }
76
90
  /**
77
91
  * Create a KV store item with a key and a default expiration.
78
92
  */
79
- export declare function kvStoreItem<T>(key: string, defaultExpiryDeltaMs: number): KvStoreItem<T>;
93
+ export declare function kvStoreItem<T>(key: string, defaultExpiration: number | Duration): KvStoreItem<T>;
80
94
  export {};
package/kvStore.js CHANGED
@@ -49,6 +49,28 @@ __export(kvStore_exports, {
49
49
  kvStoreItem: () => kvStoreItem
50
50
  });
51
51
  module.exports = __toCommonJS(kvStore_exports);
52
+
53
+ // src/timeConstants.ts
54
+ var MS_PER_SECOND = 1e3;
55
+ var MS_PER_MINUTE = 6e4;
56
+ var MS_PER_HOUR = 36e5;
57
+ var MS_PER_DAY = 864e5;
58
+
59
+ // src/duration.ts
60
+ function durationToMs(duration) {
61
+ var _a, _b, _c, _d, _e;
62
+ const daysMs = ((_a = duration.days) != null ? _a : 0) * MS_PER_DAY;
63
+ const hoursMs = ((_b = duration.hours) != null ? _b : 0) * MS_PER_HOUR;
64
+ const minsMs = ((_c = duration.minutes) != null ? _c : 0) * MS_PER_MINUTE;
65
+ const secsMs = ((_d = duration.seconds) != null ? _d : 0) * MS_PER_SECOND;
66
+ const msMs = (_e = duration.milliseconds) != null ? _e : 0;
67
+ return daysMs + hoursMs + minsMs + secsMs + msMs;
68
+ }
69
+ function durationOrMsToMs(duration) {
70
+ return typeof duration === "number" ? duration : durationToMs(duration);
71
+ }
72
+
73
+ // src/kvStore.ts
52
74
  var DEFAULT_DB_NAME = "KVStore";
53
75
  var DEFAULT_DB_VERSION = 1;
54
76
  var STORE_NAME = "kvStore";
@@ -56,7 +78,7 @@ var MILLIS_PER_DAY = 864e5;
56
78
  var DEFAULT_EXPIRY_DELTA_MS = MILLIS_PER_DAY * 30;
57
79
  var GC_INTERVAL_MS = MILLIS_PER_DAY;
58
80
  function validateStoredObject(obj) {
59
- if (!obj || typeof obj !== "object" || !("key" in obj) || typeof obj.key !== "string" || !("value" in obj) || obj.value === void 0 || !("expireMs" in obj) || typeof obj.expireMs !== "number" || Date.now() >= obj.expireMs) {
81
+ if (!obj || typeof obj !== "object" || !("key" in obj) || typeof obj.key !== "string" || !("value" in obj) || !("storedMs" in obj) || typeof obj.storedMs !== "number" || obj.value === void 0 || !("expiryMs" in obj) || typeof obj.expiryMs !== "number" || Date.now() >= obj.expiryMs) {
60
82
  return void 0;
61
83
  }
62
84
  return obj;
@@ -130,10 +152,12 @@ var KVStore = class {
130
152
  }
131
153
  set(_0, _1) {
132
154
  return __async(this, arguments, function* (key, value, expiryDeltaMs = this.defaultExpiryDeltaMs) {
155
+ const nowMs = Date.now();
133
156
  const obj = {
134
157
  key,
135
158
  value,
136
- expireMs: Date.now() + expiryDeltaMs
159
+ storedMs: nowMs,
160
+ expiryMs: nowMs + durationOrMsToMs(expiryDeltaMs)
137
161
  };
138
162
  return yield this.transact(
139
163
  "readwrite",
@@ -167,7 +191,7 @@ var KVStore = class {
167
191
  );
168
192
  });
169
193
  }
170
- get(key) {
194
+ getStoredObject(key) {
171
195
  return __async(this, null, function* () {
172
196
  const stored = yield this.transact(
173
197
  "readonly",
@@ -188,7 +212,7 @@ var KVStore = class {
188
212
  this.gc();
189
213
  return void 0;
190
214
  }
191
- return obj.value;
215
+ return obj;
192
216
  } catch (e) {
193
217
  console.error(`Invalid kv value: ${key}=${JSON.stringify(stored)}:`, e);
194
218
  yield this.delete(key);
@@ -197,6 +221,12 @@ var KVStore = class {
197
221
  }
198
222
  });
199
223
  }
224
+ get(key) {
225
+ return __async(this, null, function* () {
226
+ const obj = yield this.getStoredObject(key);
227
+ return obj == null ? void 0 : obj.value;
228
+ });
229
+ }
200
230
  forEach(callback) {
201
231
  return __async(this, null, function* () {
202
232
  yield this.transact("readonly", (objectStore, resolve, reject) => {
@@ -207,7 +237,7 @@ var KVStore = class {
207
237
  if (cursor.key) {
208
238
  const obj = validateStoredObject(cursor.value);
209
239
  if (obj) {
210
- yield callback(String(cursor.key), obj.value, obj.expireMs);
240
+ yield callback(String(cursor.key), obj.value, obj.expiryMs);
211
241
  } else {
212
242
  yield callback(String(cursor.key), void 0, 0);
213
243
  }
@@ -243,8 +273,8 @@ var KVStore = class {
243
273
  asMap() {
244
274
  return __async(this, null, function* () {
245
275
  const map = /* @__PURE__ */ new Map();
246
- yield this.forEach((key, value, expireMs) => {
247
- map.set(key, { value, expireMs });
276
+ yield this.forEach((key, value, expiryMs) => {
277
+ map.set(key, { value, expiryMs });
248
278
  });
249
279
  return map;
250
280
  });
@@ -279,8 +309,8 @@ var KVStore = class {
279
309
  this.lastGcMs = Date.now();
280
310
  const keysToDelete = [];
281
311
  yield this.forEach(
282
- (key, value, expireMs) => __async(this, null, function* () {
283
- if (value === void 0 || Date.now() >= expireMs) {
312
+ (key, value, expiryMs) => __async(this, null, function* () {
313
+ if (value === void 0 || Date.now() >= expiryMs) {
284
314
  keysToDelete.push(key);
285
315
  }
286
316
  })
@@ -310,6 +340,16 @@ var KvStoreItem = class {
310
340
  this.defaultExpiryDeltaMs = defaultExpiryDeltaMs;
311
341
  this.store = store;
312
342
  }
343
+ /**
344
+ * Example usage:
345
+ *
346
+ * const { value, storedMs, expiryMs } = await myKvItem.getStoredObject();
347
+ */
348
+ getStoredObject() {
349
+ return __async(this, null, function* () {
350
+ return yield this.store.getStoredObject(this.key);
351
+ });
352
+ }
313
353
  get() {
314
354
  return __async(this, null, function* () {
315
355
  return yield this.store.get(this.key);
@@ -326,7 +366,8 @@ var KvStoreItem = class {
326
366
  });
327
367
  }
328
368
  };
329
- function kvStoreItem(key, defaultExpiryDeltaMs) {
369
+ function kvStoreItem(key, defaultExpiration) {
370
+ const defaultExpiryDeltaMs = durationOrMsToMs(defaultExpiration);
330
371
  return new KvStoreItem(key, defaultExpiryDeltaMs);
331
372
  }
332
373
  // Annotate the CommonJS export names for ESM import in node:
package/kvStore.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/kvStore.ts"],"sourcesContent":["/**\n * Indexed DB key-value store with support for auto-expirations.\n *\n * Why use this?\n * 1. No need to worry about running out of storage.\n * 2. Extremely simple interface to use indexed DBs.\n * 3. Auto-expirations frees you from worrying about data clean-up.\n * 4. Any serializable data type can be stored (except undefined).\n *\n * How to use?\n * Just use the `kvStore` global constant like the local storage.\n */\n\n// Updating the DB name will cause all old entries to be gone.\nconst DEFAULT_DB_NAME = \"KVStore\";\n\n// Updating the version will cause all old entries to be gone.\nconst DEFAULT_DB_VERSION = 1;\n\n// Use a constant store name to keep things simple.\nconst STORE_NAME = \"kvStore\";\n\n/** One day in milliseconds. */\nexport const MILLIS_PER_DAY = 86_400_000;\n\n/** 30 days in ms. */\nexport const DEFAULT_EXPIRY_DELTA_MS = MILLIS_PER_DAY * 30;\n\n/** Do GC once per day. */\nexport const GC_INTERVAL_MS = MILLIS_PER_DAY;\n\ntype StoredObject<T> = {\n key: string;\n value: T;\n expireMs: number;\n};\n\n/**\n * Parse a stored value string. Returns undefined if invalid or expired.\n * Throws an error if the string cannot be parsed as JSON.\n */\nfunction validateStoredObject<T>(\n obj: StoredObject<T>,\n): StoredObject<T> | undefined {\n if (\n !obj ||\n typeof obj !== \"object\" ||\n !(\"key\" in obj) ||\n typeof obj.key !== \"string\" ||\n !(\"value\" in obj) ||\n obj.value === undefined ||\n !(\"expireMs\" in obj) ||\n typeof obj.expireMs !== \"number\" ||\n Date.now() >= obj.expireMs\n ) {\n return undefined;\n }\n\n return obj;\n}\n\n/** Add an `onerror` handler to the request. */\nfunction withOnError<T extends IDBRequest | IDBTransaction>(\n request: T,\n reject: (reason?: unknown) => void,\n): T {\n request.onerror = (event) => {\n reject(event);\n };\n\n return request;\n}\n\nexport class KVStoreField<T> {\n public constructor(\n public readonly store: KVStore,\n public readonly key: string,\n ) {}\n\n public get(): Promise<T | undefined> {\n return this.store.get(this.key);\n }\n\n public set(t: T): Promise<T> {\n return this.store.set(this.key, t);\n }\n\n public delete(): Promise<void> {\n return this.store.delete(this.key);\n }\n}\n\n/**\n * You can create multiple KVStores if you want, but most likely you will only\n * need to use the default `kvStore` instance.\n */\nexport class KVStore {\n // We'll init the DB only on first use.\n private db: IDBDatabase | undefined;\n\n // Local storage key name for the last GC completed timestamp.\n public readonly gcMsStorageKey: string;\n\n public constructor(\n public readonly dbName: string,\n public readonly dbVersion: number,\n public readonly defaultExpiryDeltaMs: number,\n ) {\n this.gcMsStorageKey = `__kvStore:lastGcMs:${dbName}:v${dbVersion}:${STORE_NAME}`;\n }\n\n private async getOrCreateDb() {\n if (!this.db) {\n this.db = await new Promise<IDBDatabase>((resolve, reject) => {\n const request = withOnError(\n globalThis.indexedDB.open(this.dbName, this.dbVersion),\n reject,\n );\n\n request.onupgradeneeded = (event) => {\n const db = (event.target as unknown as { result: IDBDatabase })\n .result;\n\n // Create the store on DB init.\n const objectStore = db.createObjectStore(STORE_NAME, {\n keyPath: \"key\",\n });\n\n objectStore.createIndex(\"key\", \"key\", {\n unique: true,\n });\n };\n\n request.onsuccess = (event) => {\n const db = (event.target as unknown as { result: IDBDatabase })\n .result;\n resolve(db);\n };\n });\n }\n\n return this.db;\n }\n\n private async transact<T>(\n mode: IDBTransactionMode,\n callback: (\n objectStore: IDBObjectStore,\n resolve: (t: T) => void,\n reject: (reason?: unknown) => void,\n ) => void,\n ): Promise<T> {\n const db = await this.getOrCreateDb();\n\n return await new Promise<T>((resolve, reject) => {\n const transaction = withOnError(db.transaction(STORE_NAME, mode), reject);\n\n transaction.onabort = (event) => {\n reject(event);\n };\n\n const objectStore = transaction.objectStore(STORE_NAME);\n\n callback(objectStore, resolve, reject);\n });\n }\n\n public async set<T>(\n key: string,\n value: T,\n expiryDeltaMs: number = this.defaultExpiryDeltaMs,\n ): Promise<T> {\n const obj = {\n key,\n value,\n expireMs: Date.now() + expiryDeltaMs,\n };\n\n return await this.transact<T>(\n \"readwrite\",\n (objectStore, resolve, reject) => {\n const request = withOnError(objectStore.put(obj), reject);\n\n request.onsuccess = () => {\n resolve(value);\n\n this.gc(); // check GC on every write\n };\n },\n );\n }\n\n /** Delete one or multiple keys. */\n public async delete(key: string | string[]): Promise<void> {\n return await this.transact<void>(\n \"readwrite\",\n (objectStore, resolve, reject) => {\n objectStore.transaction.oncomplete = () => {\n resolve();\n };\n\n if (typeof key === \"string\") {\n withOnError(objectStore.delete(key), reject);\n } else {\n for (const k of key) {\n withOnError(objectStore.delete(k), reject);\n }\n }\n },\n );\n }\n\n public async get<T>(key: string): Promise<T | undefined> {\n const stored = await this.transact<StoredObject<T> | undefined>(\n \"readonly\",\n (objectStore, resolve, reject) => {\n const request = withOnError(objectStore.get(key), reject);\n\n request.onsuccess = () => {\n resolve(request.result);\n };\n },\n );\n\n if (!stored) {\n return undefined;\n }\n\n try {\n const obj = validateStoredObject(stored);\n if (!obj) {\n await this.delete(key);\n\n this.gc(); // check GC on every read of an expired key\n\n return undefined;\n }\n\n return obj.value;\n } catch (e) {\n console.error(`Invalid kv value: ${key}=${JSON.stringify(stored)}:`, e);\n await this.delete(key);\n\n this.gc(); // check GC on every read of an invalid key\n\n return undefined;\n }\n }\n\n public async forEach(\n callback: (\n key: string,\n value: unknown,\n expireMs: number,\n ) => void | Promise<void>,\n ): Promise<void> {\n await this.transact<void>(\"readonly\", (objectStore, resolve, reject) => {\n const request = withOnError(objectStore.openCursor(), reject);\n\n request.onsuccess = async (event) => {\n const cursor = (\n event.target as unknown as { result: IDBCursorWithValue }\n ).result;\n\n if (cursor) {\n if (cursor.key) {\n const obj = validateStoredObject(cursor.value);\n if (obj) {\n await callback(String(cursor.key), obj.value, obj.expireMs);\n } else {\n await callback(String(cursor.key), undefined, 0);\n }\n }\n cursor.continue();\n } else {\n resolve();\n }\n };\n });\n }\n\n /** Cannot be a getter because this needs to be async. */\n public async size() {\n let count = 0;\n await this.forEach(() => {\n count++;\n });\n return count;\n }\n\n public async clear() {\n const keys: string[] = [];\n await this.forEach((key) => {\n keys.push(key);\n });\n\n await this.delete(keys);\n }\n\n /** Mainly for debugging dumps. */\n public async asMap(): Promise<Map<string, unknown>> {\n const map = new Map<string, unknown>();\n await this.forEach((key, value, expireMs) => {\n map.set(key, { value, expireMs });\n });\n return map;\n }\n\n public get lastGcMs(): number {\n const lastGcMsStr = globalThis.localStorage.getItem(this.gcMsStorageKey);\n if (!lastGcMsStr) return 0;\n\n const ms = Number(lastGcMsStr);\n return isNaN(ms) ? 0 : ms;\n }\n\n public set lastGcMs(ms: number) {\n globalThis.localStorage.setItem(this.gcMsStorageKey, String(ms));\n }\n\n /** Perform garbage-collection if due. */\n public async gc() {\n const lastGcMs = this.lastGcMs;\n\n // Set initial timestamp - no need GC now.\n if (!lastGcMs) {\n this.lastGcMs = Date.now();\n return;\n }\n\n if (Date.now() < lastGcMs + GC_INTERVAL_MS) {\n return; // not due for next GC yet\n }\n\n // GC is due now, so run it.\n await this.gcNow();\n }\n\n /** Perform garbage-collection immediately without checking. */\n public async gcNow() {\n console.log(`Starting kvStore GC on ${this.dbName} v${this.dbVersion}...`);\n\n // Prevent concurrent GC runs.\n this.lastGcMs = Date.now();\n\n const keysToDelete: string[] = [];\n await this.forEach(\n async (key: string, value: unknown, expireMs: number) => {\n if (value === undefined || Date.now() >= expireMs) {\n keysToDelete.push(key);\n }\n },\n );\n\n if (keysToDelete.length) {\n await this.delete(keysToDelete);\n }\n\n console.log(\n `Finished kvStore GC on ${this.dbName} v${this.dbVersion} ` +\n `- deleted ${keysToDelete.length} keys`,\n );\n\n // Mark the end time as last GC time.\n this.lastGcMs = Date.now();\n }\n\n /** Get an independent store item with a locked key and value type. */\n public field<T>(key: string) {\n return new KVStoreField<T>(this, key);\n }\n}\n\n/**\n * Default KV store ready for immediate use. You can create new instances if\n * you want, but most likely you will only need one store instance.\n */\nexport const kvStore = new KVStore(\n DEFAULT_DB_NAME,\n DEFAULT_DB_VERSION,\n DEFAULT_EXPIRY_DELTA_MS,\n);\n\n/**\n * Class to represent one key in the store with a default expiration.\n */\nclass KvStoreItem<T> {\n public constructor(\n public readonly key: string,\n public readonly defaultExpiryDeltaMs: number,\n public readonly store = kvStore,\n ) {}\n\n public async get(): Promise<Awaited<T> | undefined> {\n return await this.store.get(this.key);\n }\n\n public async set(\n value: T,\n expiryDeltaMs: number = this.defaultExpiryDeltaMs,\n ): Promise<void> {\n await this.store.set(this.key, value, expiryDeltaMs);\n }\n\n public async delete(): Promise<void> {\n await this.store.delete(this.key);\n }\n}\n\n/**\n * Create a KV store item with a key and a default expiration.\n */\nexport function kvStoreItem<T>(\n key: string,\n defaultExpiryDeltaMs: number,\n): KvStoreItem<T> {\n return new KvStoreItem<T>(key, defaultExpiryDeltaMs);\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAcA,IAAM,kBAAkB;AAGxB,IAAM,qBAAqB;AAG3B,IAAM,aAAa;AAGZ,IAAM,iBAAiB;AAGvB,IAAM,0BAA0B,iBAAiB;AAGjD,IAAM,iBAAiB;AAY9B,SAAS,qBACP,KAC6B;AAC7B,MACE,CAAC,OACD,OAAO,QAAQ,YACf,EAAE,SAAS,QACX,OAAO,IAAI,QAAQ,YACnB,EAAE,WAAW,QACb,IAAI,UAAU,UACd,EAAE,cAAc,QAChB,OAAO,IAAI,aAAa,YACxB,KAAK,IAAI,KAAK,IAAI,UAClB;AACA,WAAO;AAAA,EACT;AAEA,SAAO;AACT;AAGA,SAAS,YACP,SACA,QACG;AACH,UAAQ,UAAU,CAAC,UAAU;AAC3B,WAAO,KAAK;AAAA,EACd;AAEA,SAAO;AACT;AAEO,IAAM,eAAN,MAAsB;AAAA,EACp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EAGO,MAAS,KAAa;AAC3B,WAAO,IAAI,aAAgB,MAAM,GAAG;AAAA,EACtC;AACF;AAMO,IAAM,UAAU,IAAI;AAAA,EACzB;AAAA,EACA;AAAA,EACA;AACF;AAKA,IAAM,cAAN,MAAqB;AAAA,EACZ,YACW,KACA,sBACA,QAAQ,SACxB;AAHgB;AACA;AACA;AAAA,EACf;AAAA,EAEU,MAAuC;AAAA;AAClD,aAAO,MAAM,KAAK,MAAM,IAAI,KAAK,GAAG;AAAA,IACtC;AAAA;AAAA,EAEa,IACX,IAEe;AAAA,+CAFf,OACA,gBAAwB,KAAK,sBACd;AACf,YAAM,KAAK,MAAM,IAAI,KAAK,KAAK,OAAO,aAAa;AAAA,IACrD;AAAA;AAAA,EAEa,SAAwB;AAAA;AACnC,YAAM,KAAK,MAAM,OAAO,KAAK,GAAG;AAAA,IAClC;AAAA;AACF;AAKO,SAAS,YACd,KACA,sBACgB;AAChB,SAAO,IAAI,YAAe,KAAK,oBAAoB;AACrD;","names":[]}
1
+ {"version":3,"sources":["../src/kvStore.ts","../src/timeConstants.ts","../src/duration.ts"],"sourcesContent":["/**\n * Indexed DB key-value store with support for auto-expirations.\n *\n * Why use this?\n * 1. No need to worry about running out of storage.\n * 2. Extremely simple interface to use indexed DBs.\n * 3. Auto-expirations frees you from worrying about data clean-up.\n * 4. Any serializable data type can be stored (except undefined).\n *\n * How to use?\n * Just use the `kvStore` global constant like the local storage.\n */\n\nimport { Duration, durationOrMsToMs } from \"./duration\";\n\n// Updating the DB name will cause all old entries to be gone.\nconst DEFAULT_DB_NAME = \"KVStore\";\n\n// Updating the version will cause all old entries to be gone.\nconst DEFAULT_DB_VERSION = 1;\n\n// Use a constant store name to keep things simple.\nconst STORE_NAME = \"kvStore\";\n\n/** One day in milliseconds. */\nexport const MILLIS_PER_DAY = 86_400_000;\n\n/** 30 days in ms. */\nexport const DEFAULT_EXPIRY_DELTA_MS = MILLIS_PER_DAY * 30;\n\n/** Do GC once per day. */\nexport const GC_INTERVAL_MS = MILLIS_PER_DAY;\n\ntype StoredObject<T> = {\n key: string;\n value: T;\n storedMs: number;\n expiryMs: number;\n};\n\n/**\n * Parse a stored value string. Returns undefined if invalid or expired.\n * Throws an error if the string cannot be parsed as JSON.\n */\nfunction validateStoredObject<T>(\n obj: StoredObject<T>,\n): StoredObject<T> | undefined {\n if (\n !obj ||\n typeof obj !== \"object\" ||\n !(\"key\" in obj) ||\n typeof obj.key !== \"string\" ||\n !(\"value\" in obj) ||\n !(\"storedMs\" in obj) ||\n typeof obj.storedMs !== \"number\" ||\n obj.value === undefined ||\n !(\"expiryMs\" in obj) ||\n typeof obj.expiryMs !== \"number\" ||\n Date.now() >= obj.expiryMs\n ) {\n return undefined;\n }\n\n return obj;\n}\n\n/** Add an `onerror` handler to the request. */\nfunction withOnError<T extends IDBRequest | IDBTransaction>(\n request: T,\n reject: (reason?: unknown) => void,\n): T {\n request.onerror = (event) => {\n reject(event);\n };\n\n return request;\n}\n\nexport class KVStoreField<T> {\n public constructor(\n public readonly store: KVStore,\n public readonly key: string,\n ) {}\n\n public get(): Promise<T | undefined> {\n return this.store.get(this.key);\n }\n\n public set(t: T): Promise<T> {\n return this.store.set(this.key, t);\n }\n\n public delete(): Promise<void> {\n return this.store.delete(this.key);\n }\n}\n\n/**\n * You can create multiple KVStores if you want, but most likely you will only\n * need to use the default `kvStore` instance.\n */\nexport class KVStore {\n // We'll init the DB only on first use.\n private db: IDBDatabase | undefined;\n\n // Local storage key name for the last GC completed timestamp.\n public readonly gcMsStorageKey: string;\n\n public constructor(\n public readonly dbName: string,\n public readonly dbVersion: number,\n public readonly defaultExpiryDeltaMs: number,\n ) {\n this.gcMsStorageKey = `__kvStore:lastGcMs:${dbName}:v${dbVersion}:${STORE_NAME}`;\n }\n\n private async getOrCreateDb() {\n if (!this.db) {\n this.db = await new Promise<IDBDatabase>((resolve, reject) => {\n const request = withOnError(\n globalThis.indexedDB.open(this.dbName, this.dbVersion),\n reject,\n );\n\n request.onupgradeneeded = (event) => {\n const db = (event.target as unknown as { result: IDBDatabase })\n .result;\n\n // Create the store on DB init.\n const objectStore = db.createObjectStore(STORE_NAME, {\n keyPath: \"key\",\n });\n\n objectStore.createIndex(\"key\", \"key\", {\n unique: true,\n });\n };\n\n request.onsuccess = (event) => {\n const db = (event.target as unknown as { result: IDBDatabase })\n .result;\n resolve(db);\n };\n });\n }\n\n return this.db;\n }\n\n private async transact<T>(\n mode: IDBTransactionMode,\n callback: (\n objectStore: IDBObjectStore,\n resolve: (t: T) => void,\n reject: (reason?: unknown) => void,\n ) => void,\n ): Promise<T> {\n const db = await this.getOrCreateDb();\n\n return await new Promise<T>((resolve, reject) => {\n const transaction = withOnError(db.transaction(STORE_NAME, mode), reject);\n\n transaction.onabort = (event) => {\n reject(event);\n };\n\n const objectStore = transaction.objectStore(STORE_NAME);\n\n callback(objectStore, resolve, reject);\n });\n }\n\n public async set<T>(\n key: string,\n value: T,\n expiryDeltaMs: number | Duration = this.defaultExpiryDeltaMs,\n ): Promise<T> {\n const nowMs = Date.now();\n const obj: StoredObject<T> = {\n key,\n value,\n storedMs: nowMs,\n expiryMs: nowMs + durationOrMsToMs(expiryDeltaMs),\n };\n\n return await this.transact<T>(\n \"readwrite\",\n (objectStore, resolve, reject) => {\n const request = withOnError(objectStore.put(obj), reject);\n\n request.onsuccess = () => {\n resolve(value);\n\n this.gc(); // check GC on every write\n };\n },\n );\n }\n\n /** Delete one or multiple keys. */\n public async delete(key: string | string[]): Promise<void> {\n return await this.transact<void>(\n \"readwrite\",\n (objectStore, resolve, reject) => {\n objectStore.transaction.oncomplete = () => {\n resolve();\n };\n\n if (typeof key === \"string\") {\n withOnError(objectStore.delete(key), reject);\n } else {\n for (const k of key) {\n withOnError(objectStore.delete(k), reject);\n }\n }\n },\n );\n }\n\n public async getStoredObject<T>(\n key: string,\n ): Promise<StoredObject<T> | undefined> {\n const stored = await this.transact<StoredObject<T> | undefined>(\n \"readonly\",\n (objectStore, resolve, reject) => {\n const request = withOnError(objectStore.get(key), reject);\n\n request.onsuccess = () => {\n resolve(request.result);\n };\n },\n );\n\n if (!stored) {\n return undefined;\n }\n\n try {\n const obj = validateStoredObject(stored);\n if (!obj) {\n await this.delete(key);\n\n this.gc(); // check GC on every read of an expired key\n\n return undefined;\n }\n\n return obj;\n } catch (e) {\n console.error(`Invalid kv value: ${key}=${JSON.stringify(stored)}:`, e);\n await this.delete(key);\n\n this.gc(); // check GC on every read of an invalid key\n\n return undefined;\n }\n }\n\n public async get<T>(key: string): Promise<T | undefined> {\n const obj = await this.getStoredObject<T>(key);\n\n return obj?.value;\n }\n\n public async forEach(\n callback: (\n key: string,\n value: unknown,\n expiryMs: number,\n ) => void | Promise<void>,\n ): Promise<void> {\n await this.transact<void>(\"readonly\", (objectStore, resolve, reject) => {\n const request = withOnError(objectStore.openCursor(), reject);\n\n request.onsuccess = async (event) => {\n const cursor = (\n event.target as unknown as { result: IDBCursorWithValue }\n ).result;\n\n if (cursor) {\n if (cursor.key) {\n const obj = validateStoredObject(cursor.value);\n if (obj) {\n await callback(String(cursor.key), obj.value, obj.expiryMs);\n } else {\n await callback(String(cursor.key), undefined, 0);\n }\n }\n cursor.continue();\n } else {\n resolve();\n }\n };\n });\n }\n\n /** Cannot be a getter because this needs to be async. */\n public async size() {\n let count = 0;\n await this.forEach(() => {\n count++;\n });\n return count;\n }\n\n public async clear() {\n const keys: string[] = [];\n await this.forEach((key) => {\n keys.push(key);\n });\n\n await this.delete(keys);\n }\n\n /** Mainly for debugging dumps. */\n public async asMap(): Promise<Map<string, unknown>> {\n const map = new Map<string, unknown>();\n await this.forEach((key, value, expiryMs) => {\n map.set(key, { value, expiryMs });\n });\n return map;\n }\n\n public get lastGcMs(): number {\n const lastGcMsStr = globalThis.localStorage.getItem(this.gcMsStorageKey);\n if (!lastGcMsStr) return 0;\n\n const ms = Number(lastGcMsStr);\n return isNaN(ms) ? 0 : ms;\n }\n\n public set lastGcMs(ms: number) {\n globalThis.localStorage.setItem(this.gcMsStorageKey, String(ms));\n }\n\n /** Perform garbage-collection if due. */\n public async gc() {\n const lastGcMs = this.lastGcMs;\n\n // Set initial timestamp - no need GC now.\n if (!lastGcMs) {\n this.lastGcMs = Date.now();\n return;\n }\n\n if (Date.now() < lastGcMs + GC_INTERVAL_MS) {\n return; // not due for next GC yet\n }\n\n // GC is due now, so run it.\n await this.gcNow();\n }\n\n /** Perform garbage-collection immediately without checking. */\n public async gcNow() {\n console.log(`Starting kvStore GC on ${this.dbName} v${this.dbVersion}...`);\n\n // Prevent concurrent GC runs.\n this.lastGcMs = Date.now();\n\n const keysToDelete: string[] = [];\n await this.forEach(\n async (key: string, value: unknown, expiryMs: number) => {\n if (value === undefined || Date.now() >= expiryMs) {\n keysToDelete.push(key);\n }\n },\n );\n\n if (keysToDelete.length) {\n await this.delete(keysToDelete);\n }\n\n console.log(\n `Finished kvStore GC on ${this.dbName} v${this.dbVersion} ` +\n `- deleted ${keysToDelete.length} keys`,\n );\n\n // Mark the end time as last GC time.\n this.lastGcMs = Date.now();\n }\n\n /** Get an independent store item with a locked key and value type. */\n public field<T>(key: string) {\n return new KVStoreField<T>(this, key);\n }\n}\n\n/**\n * Default KV store ready for immediate use. You can create new instances if\n * you want, but most likely you will only need one store instance.\n */\nexport const kvStore = new KVStore(\n DEFAULT_DB_NAME,\n DEFAULT_DB_VERSION,\n DEFAULT_EXPIRY_DELTA_MS,\n);\n\n/**\n * Class to represent one key in the store with a default expiration.\n */\nclass KvStoreItem<T> {\n public constructor(\n public readonly key: string,\n public readonly defaultExpiryDeltaMs: number,\n public readonly store = kvStore,\n ) {}\n\n /**\n * Example usage:\n *\n * const { value, storedMs, expiryMs } = await myKvItem.getStoredObject();\n */\n public async getStoredObject(): Promise<StoredObject<T> | undefined> {\n return await this.store.getStoredObject(this.key);\n }\n\n public async get(): Promise<T | undefined> {\n return await this.store.get(this.key);\n }\n\n public async set(\n value: T,\n expiryDeltaMs: number = this.defaultExpiryDeltaMs,\n ): Promise<void> {\n await this.store.set(this.key, value, expiryDeltaMs);\n }\n\n public async delete(): Promise<void> {\n await this.store.delete(this.key);\n }\n}\n\n/**\n * Create a KV store item with a key and a default expiration.\n */\nexport function kvStoreItem<T>(\n key: string,\n defaultExpiration: number | Duration,\n): KvStoreItem<T> {\n const defaultExpiryDeltaMs = durationOrMsToMs(defaultExpiration);\n\n return new KvStoreItem<T>(key, defaultExpiryDeltaMs);\n}\n","/**\n * Note that month and year do not have fixed durations, and hence are excluded\n * from this file.\n */\n\nexport const MS_PER_SECOND = 1000;\nexport const MS_PER_MINUTE = 60_000;\nexport const MS_PER_HOUR = 3_600_000;\nexport const MS_PER_DAY = 86_400_000;\nexport const MS_PER_WEEK = 604_800_000;\n\nexport const SECONDS_PER_MINUTE = 60;\nexport const SECONDS_PER_HOUR = 3_600;\nexport const SECONDS_PER_DAY = 86_400;\nexport const SECONDS_PER_WEEK = 604_800;\n\nexport const MINUTES_PER_HOUR = 60;\nexport const MINUTES_PER_DAY = 1440;\nexport const MINUTES_PER_WEEK = 10_080;\n\nexport const HOURS_PER_DAY = 24;\nexport const HOURS_PER_WEEK = 168;\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 MS_PER_SECOND,\n SECONDS_PER_MINUTE,\n MINUTES_PER_HOUR,\n HOURS_PER_DAY,\n MS_PER_DAY,\n MS_PER_MINUTE,\n MS_PER_HOUR,\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"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;;;ACKO,IAAM,gBAAgB;AACtB,IAAM,gBAAgB;AACtB,IAAM,cAAc;AACpB,IAAM,aAAa;;;ACkLnB,SAAS,aAAa,UAA4B;AA1LzD;AA2LE,QAAM,WAAU,cAAS,SAAT,YAAiB,KAAK;AACtC,QAAM,YAAW,cAAS,UAAT,YAAkB,KAAK;AACxC,QAAM,WAAU,cAAS,YAAT,YAAoB,KAAK;AACzC,QAAM,WAAU,cAAS,YAAT,YAAoB,KAAK;AACzC,QAAM,QAAO,cAAS,iBAAT,YAAyB;AAEtC,SAAO,SAAS,UAAU,SAAS,SAAS;AAC9C;AAKO,SAAS,iBAAiB,UAAqC;AACpE,SAAO,OAAO,aAAa,WAAW,WAAW,aAAa,QAAQ;AACxE;;;AFzLA,IAAM,kBAAkB;AAGxB,IAAM,qBAAqB;AAG3B,IAAM,aAAa;AAGZ,IAAM,iBAAiB;AAGvB,IAAM,0BAA0B,iBAAiB;AAGjD,IAAM,iBAAiB;AAa9B,SAAS,qBACP,KAC6B;AAC7B,MACE,CAAC,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,YACd,KACA,mBACgB;AAChB,QAAM,uBAAuB,iBAAiB,iBAAiB;AAE/D,SAAO,IAAI,YAAe,KAAK,oBAAoB;AACrD;","names":[]}
@@ -1,7 +1,8 @@
1
1
  import { Duration } from "./duration";
2
2
  export type StoredItem<T> = {
3
3
  value: T;
4
- expireMs: number;
4
+ storedMs: number;
5
+ expiryMs: number;
5
6
  };
6
7
  /**
7
8
  * Simple local storage cache with support for auto-expiration.
@@ -35,7 +36,13 @@ declare class CacheItem<T> {
35
36
  /**
36
37
  * Set the value of this item with auto-expiration.
37
38
  */
38
- set(value: T): void;
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;
39
46
  /**
40
47
  * Get the value of this item, or undefined if value is not set or expired.
41
48
  */
@@ -40,10 +40,13 @@ function durationToMs(duration) {
40
40
  const msMs = (_e = duration.milliseconds) != null ? _e : 0;
41
41
  return daysMs + hoursMs + minsMs + secsMs + msMs;
42
42
  }
43
+ function durationOrMsToMs(duration) {
44
+ return typeof duration === "number" ? duration : durationToMs(duration);
45
+ }
43
46
 
44
47
  // src/localStorageCache.ts
45
48
  function storeItem(key, expires, logError = true, defaultValue) {
46
- const expireDeltaMs = typeof expires === "number" ? expires : durationToMs(expires);
49
+ const expireDeltaMs = durationOrMsToMs(expires);
47
50
  return new CacheItem(key, expireDeltaMs, logError, defaultValue);
48
51
  }
49
52
  var CacheItem = class {
@@ -59,27 +62,33 @@ var CacheItem = class {
59
62
  /**
60
63
  * Set the value of this item with auto-expiration.
61
64
  */
62
- set(value) {
63
- const expireMs = Date.now() + this.expireDeltaMs;
64
- const toStore = { value, expireMs };
65
+ set(value, expiryDelta = this.expireDeltaMs) {
66
+ const nowMs = Date.now();
67
+ const toStore = {
68
+ value,
69
+ storedMs: nowMs,
70
+ expiryMs: nowMs + durationOrMsToMs(expiryDelta)
71
+ };
65
72
  const valueStr = JSON.stringify(toStore);
66
73
  globalThis.localStorage.setItem(this.key, valueStr);
67
74
  }
68
75
  /**
69
- * Get the value of this item, or undefined if value is not set or expired.
76
+ * Example usage:
77
+ *
78
+ * const { value, storedMs, expiryMs } = await myItem.getStoredItem();
70
79
  */
71
- get() {
80
+ getStoredItem() {
72
81
  const jsonStr = globalThis.localStorage.getItem(this.key);
73
82
  if (!jsonStr) {
74
- return this.defaultValue;
83
+ return void 0;
75
84
  }
76
85
  try {
77
86
  const obj = JSON.parse(jsonStr);
78
- if (!obj || typeof obj !== "object" || !("value" in obj) || !("expireMs" in obj) || typeof obj.expireMs !== "number" || Date.now() >= obj.expireMs) {
87
+ 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) {
79
88
  this.remove();
80
- return this.defaultValue;
89
+ return void 0;
81
90
  }
82
- return obj.value;
91
+ return obj;
83
92
  } catch (e) {
84
93
  if (this.logError) {
85
94
  console.error(
@@ -88,9 +97,16 @@ var CacheItem = class {
88
97
  );
89
98
  }
90
99
  this.remove();
91
- return this.defaultValue;
100
+ return void 0;
92
101
  }
93
102
  }
103
+ /**
104
+ * Get the value of this item, or undefined if value is not set or expired.
105
+ */
106
+ get() {
107
+ const stored = this.getStoredItem();
108
+ return stored !== void 0 ? stored.value : this.defaultValue;
109
+ }
94
110
  /**
95
111
  * Remove the value of this item.
96
112
  */
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/localStorageCache.ts","../src/timeConstants.ts","../src/duration.ts"],"sourcesContent":["import { Duration, durationToMs } from \"./duration\";\n\nexport type StoredItem<T> = { value: T; expireMs: 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 =\n typeof expires === \"number\" ? expires : durationToMs(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(value: T): void {\n const expireMs = Date.now() + this.expireDeltaMs;\n const toStore: StoredItem<T> = { value, expireMs };\n const valueStr = JSON.stringify(toStore);\n\n globalThis.localStorage.setItem(this.key, valueStr);\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 jsonStr = globalThis.localStorage.getItem(this.key);\n\n if (!jsonStr) {\n return this.defaultValue;\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 !(\"expireMs\" in obj) ||\n typeof obj.expireMs !== \"number\" ||\n Date.now() >= obj.expireMs\n ) {\n this.remove();\n return this.defaultValue;\n }\n\n return obj.value;\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 this.defaultValue;\n }\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 * Note that month and year do not have fixed durations, and hence are excluded\n * from this file.\n */\n\nexport const MS_PER_SECOND = 1000;\nexport const MS_PER_MINUTE = 60_000;\nexport const MS_PER_HOUR = 3_600_000;\nexport const MS_PER_DAY = 86_400_000;\nexport const MS_PER_WEEK = 604_800_000;\n\nexport const SECONDS_PER_MINUTE = 60;\nexport const SECONDS_PER_HOUR = 3_600;\nexport const SECONDS_PER_DAY = 86_400;\nexport const SECONDS_PER_WEEK = 604_800;\n\nexport const MINUTES_PER_HOUR = 60;\nexport const MINUTES_PER_DAY = 1440;\nexport const MINUTES_PER_WEEK = 10_080;\n\nexport const HOURS_PER_DAY = 24;\nexport const HOURS_PER_WEEK = 168;\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 MS_PER_SECOND,\n SECONDS_PER_MINUTE,\n MINUTES_PER_HOUR,\n HOURS_PER_DAY,\n MS_PER_DAY,\n MS_PER_MINUTE,\n MS_PER_HOUR,\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 * 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"],"mappings":";;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;;;ACKO,IAAM,gBAAgB;AACtB,IAAM,gBAAgB;AACtB,IAAM,cAAc;AACpB,IAAM,aAAa;;;ACkLnB,SAAS,aAAa,UAA4B;AA1LzD;AA2LE,QAAM,WAAU,cAAS,SAAT,YAAiB,KAAK;AACtC,QAAM,YAAW,cAAS,UAAT,YAAkB,KAAK;AACxC,QAAM,WAAU,cAAS,YAAT,YAAoB,KAAK;AACzC,QAAM,WAAU,cAAS,YAAT,YAAoB,KAAK;AACzC,QAAM,QAAO,cAAS,iBAAT,YAAyB;AAEtC,SAAO,SAAS,UAAU,SAAS,SAAS;AAC9C;;;AF3KO,SAAS,UACd,KACA,SACA,WAAW,MACX,cACA;AACA,QAAM,gBACJ,OAAO,YAAY,WAAW,UAAU,aAAa,OAAO;AAE9D,SAAO,IAAI,UAAa,KAAK,eAAe,UAAU,YAAY;AACpE;AAEA,IAAM,YAAN,MAAmB;AAAA;AAAA;AAAA;AAAA,EAIV,YACW,KACA,eACA,UACA,cAChB;AAJgB;AACA;AACA;AACA;AAAA,EACf;AAAA;AAAA;AAAA;AAAA,EAKI,IAAI,OAAgB;AACzB,UAAM,WAAW,KAAK,IAAI,IAAI,KAAK;AACnC,UAAM,UAAyB,EAAE,OAAO,SAAS;AACjD,UAAM,WAAW,KAAK,UAAU,OAAO;AAEvC,eAAW,aAAa,QAAQ,KAAK,KAAK,QAAQ;AAAA,EACpD;AAAA;AAAA;AAAA;AAAA,EAKO,MAAqB;AAC1B,UAAM,UAAU,WAAW,aAAa,QAAQ,KAAK,GAAG;AAExD,QAAI,CAAC,SAAS;AACZ,aAAO,KAAK;AAAA,IACd;AAEA,QAAI;AACF,YAAM,MAAiC,KAAK,MAAM,OAAO;AAEzD,UACE,CAAC,OACD,OAAO,QAAQ,YACf,EAAE,WAAW,QACb,EAAE,cAAc,QAChB,OAAO,IAAI,aAAa,YACxB,KAAK,IAAI,KAAK,IAAI,UAClB;AACA,aAAK,OAAO;AACZ,eAAO,KAAK;AAAA,MACd;AAEA,aAAO,IAAI;AAAA,IACb,SAAS,GAAG;AACV,UAAI,KAAK,UAAU;AACjB,gBAAQ;AAAA,UACN,gCAAgC,KAAK,GAAG,IAAI,OAAO;AAAA,UACnD;AAAA,QACF;AAAA,MACF;AACA,WAAK,OAAO;AACZ,aAAO,KAAK;AAAA,IACd;AAAA,EACF;AAAA;AAAA;AAAA;AAAA,EAKO,SAAe;AACpB,eAAW,aAAa,WAAW,KAAK,GAAG;AAAA,EAC7C;AACF;","names":[]}
1
+ {"version":3,"sources":["../src/localStorageCache.ts","../src/timeConstants.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 * Note that month and year do not have fixed durations, and hence are excluded\n * from this file.\n */\n\nexport const MS_PER_SECOND = 1000;\nexport const MS_PER_MINUTE = 60_000;\nexport const MS_PER_HOUR = 3_600_000;\nexport const MS_PER_DAY = 86_400_000;\nexport const MS_PER_WEEK = 604_800_000;\n\nexport const SECONDS_PER_MINUTE = 60;\nexport const SECONDS_PER_HOUR = 3_600;\nexport const SECONDS_PER_DAY = 86_400;\nexport const SECONDS_PER_WEEK = 604_800;\n\nexport const MINUTES_PER_HOUR = 60;\nexport const MINUTES_PER_DAY = 1440;\nexport const MINUTES_PER_WEEK = 10_080;\n\nexport const HOURS_PER_DAY = 24;\nexport const HOURS_PER_WEEK = 168;\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 MS_PER_SECOND,\n SECONDS_PER_MINUTE,\n MINUTES_PER_HOUR,\n HOURS_PER_DAY,\n MS_PER_DAY,\n MS_PER_MINUTE,\n MS_PER_HOUR,\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"],"mappings":";;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;;;ACKO,IAAM,gBAAgB;AACtB,IAAM,gBAA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AAa,YACxB,EAAE,cAAc,QAChB,OAAO,IAAI,aAAa,YACxB,KAAK,IAAI,KAAK,IAAI,UAClB;AACA,aAAK,OAAO;AACZ,eAAO;AAAA,MACT;AAEA,aAAO;AAAA,IACT,SAAS,GAAG;AACV,UAAI,KAAK,UAAU;AACjB,gBAAQ;AAAA,UACN,gCAAgC,KAAK,GAAG,IAAI,OAAO;AAAA,UACnD;AAAA,QACF;AAAA,MACF;AACA,WAAK,OAAO;AACZ,aAAO;AAAA,IACT;AAAA,EACF;AAAA;AAAA;AAAA;AAAA,EAKO,MAAqB;AAC1B,UAAM,SAAS,KAAK,cAAc;AAElC,WAAO,WAAW,SAAY,OAAO,QAAQ,KAAK;AAAA,EACpD;AAAA;AAAA;AAAA;AAAA,EAKO,SAAe;AACpB,eAAW,aAAa,WAAW,KAAK,GAAG;AAAA,EAC7C;AACF;","names":[]}
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "@choksheak/ts-utils",
3
3
  "license": "The Unlicense",
4
- "version": "0.2.0",
4
+ "version": "0.2.1",
5
5
  "description": "Random Typescript utilities with support for full tree-shaking",
6
6
  "private": false,
7
7
  "scripts": {
@@ -13,43 +13,53 @@ export function toDate(ts: AnyDateTime): Date {
13
13
  }
14
14
 
15
15
  /**
16
- * Returns a date in yyyy-MM-dd format. E.g. '2000-01-02'.
16
+ * Returns a date in yyyy-MM format. E.g. '2000-01'.
17
17
  *
18
18
  * @param dt Specify a date object or default to the current date.
19
19
  * @param separator Defaults to '-'.
20
20
  */
21
- export function yyyyMmDd(dt = new Date(), separator = "-"): string {
21
+ export function yyyyMm(dt = new Date(), separator = "-"): string {
22
22
  const yr = dt.getFullYear();
23
23
  const mth = dt.getMonth() + 1;
24
+
25
+ return yr + separator + (mth < 10 ? "0" + mth : mth);
26
+ }
27
+
28
+ /**
29
+ * Returns a date in yyyy-MM-dd format. E.g. '2000-01-02'.
30
+ *
31
+ * @param dt Specify a date object or default to the current date.
32
+ * @param separator Defaults to '-'.
33
+ */
34
+ export function yyyyMmDd(dt = new Date(), separator = "-"): string {
24
35
  const day = dt.getDate();
25
36
 
26
- return (
27
- yr +
28
- separator +
29
- (mth < 10 ? "0" + mth : mth) +
30
- separator +
31
- (day < 10 ? "0" + day : day)
32
- );
37
+ return yyyyMm(dt, separator) + separator + (day < 10 ? "0" + day : day);
33
38
  }
34
39
 
35
40
  /**
36
- * Returns a date in hh:mm:ss format. E.g. '01:02:03'.
41
+ * Returns a date in hh:mm format. E.g. '01:02'.
37
42
  *
38
43
  * @param dt Specify a date object or default to the current date/time.
39
44
  * @param separator Defaults to ':'.
40
45
  */
41
- export function hhMmSs(dt = new Date(), separator = ":"): string {
46
+ export function hhMm(dt = new Date(), separator = ":"): string {
42
47
  const hr = dt.getHours();
43
48
  const min = dt.getMinutes();
49
+
50
+ return (hr < 10 ? "0" + hr : hr) + separator + (min < 10 ? "0" + min : min);
51
+ }
52
+
53
+ /**
54
+ * Returns a date in hh:mm:ss format. E.g. '01:02:03'.
55
+ *
56
+ * @param dt Specify a date object or default to the current date/time.
57
+ * @param separator Defaults to ':'.
58
+ */
59
+ export function hhMmSs(dt = new Date(), separator = ":"): string {
44
60
  const sec = dt.getSeconds();
45
61
 
46
- return (
47
- (hr < 10 ? "0" + hr : hr) +
48
- separator +
49
- (min < 10 ? "0" + min : min) +
50
- separator +
51
- (sec < 10 ? "0" + sec : sec)
52
- );
62
+ return hhMm(dt, separator) + separator + (sec < 10 ? "0" + sec : sec);
53
63
  }
54
64
 
55
65
  /**
package/src/duration.ts CHANGED
@@ -194,6 +194,13 @@ export function durationToMs(duration: Duration): number {
194
194
  return daysMs + hoursMs + minsMs + secsMs + msMs;
195
195
  }
196
196
 
197
+ /**
198
+ * Convenience function to return a duration given an ms or Duration.
199
+ */
200
+ export function durationOrMsToMs(duration: number | Duration): number {
201
+ return typeof duration === "number" ? duration : durationToMs(duration);
202
+ }
203
+
197
204
  /**
198
205
  * Format a given Duration object into a string. If the object has no fields,
199
206
  * then returns an empty string.
package/src/kvStore.ts CHANGED
@@ -11,6 +11,8 @@
11
11
  * Just use the `kvStore` global constant like the local storage.
12
12
  */
13
13
 
14
+ import { Duration, durationOrMsToMs } from "./duration";
15
+
14
16
  // Updating the DB name will cause all old entries to be gone.
15
17
  const DEFAULT_DB_NAME = "KVStore";
16
18
 
@@ -32,7 +34,8 @@ export const GC_INTERVAL_MS = MILLIS_PER_DAY;
32
34
  type StoredObject<T> = {
33
35
  key: string;
34
36
  value: T;
35
- expireMs: number;
37
+ storedMs: number;
38
+ expiryMs: number;
36
39
  };
37
40
 
38
41
  /**
@@ -48,10 +51,12 @@ function validateStoredObject<T>(
48
51
  !("key" in obj) ||
49
52
  typeof obj.key !== "string" ||
50
53
  !("value" in obj) ||
54
+ !("storedMs" in obj) ||
55
+ typeof obj.storedMs !== "number" ||
51
56
  obj.value === undefined ||
52
- !("expireMs" in obj) ||
53
- typeof obj.expireMs !== "number" ||
54
- Date.now() >= obj.expireMs
57
+ !("expiryMs" in obj) ||
58
+ typeof obj.expiryMs !== "number" ||
59
+ Date.now() >= obj.expiryMs
55
60
  ) {
56
61
  return undefined;
57
62
  }
@@ -168,12 +173,14 @@ export class KVStore {
168
173
  public async set<T>(
169
174
  key: string,
170
175
  value: T,
171
- expiryDeltaMs: number = this.defaultExpiryDeltaMs,
176
+ expiryDeltaMs: number | Duration = this.defaultExpiryDeltaMs,
172
177
  ): Promise<T> {
173
- const obj = {
178
+ const nowMs = Date.now();
179
+ const obj: StoredObject<T> = {
174
180
  key,
175
181
  value,
176
- expireMs: Date.now() + expiryDeltaMs,
182
+ storedMs: nowMs,
183
+ expiryMs: nowMs + durationOrMsToMs(expiryDeltaMs),
177
184
  };
178
185
 
179
186
  return await this.transact<T>(
@@ -210,7 +217,9 @@ export class KVStore {
210
217
  );
211
218
  }
212
219
 
213
- public async get<T>(key: string): Promise<T | undefined> {
220
+ public async getStoredObject<T>(
221
+ key: string,
222
+ ): Promise<StoredObject<T> | undefined> {
214
223
  const stored = await this.transact<StoredObject<T> | undefined>(
215
224
  "readonly",
216
225
  (objectStore, resolve, reject) => {
@@ -236,7 +245,7 @@ export class KVStore {
236
245
  return undefined;
237
246
  }
238
247
 
239
- return obj.value;
248
+ return obj;
240
249
  } catch (e) {
241
250
  console.error(`Invalid kv value: ${key}=${JSON.stringify(stored)}:`, e);
242
251
  await this.delete(key);
@@ -247,11 +256,17 @@ export class KVStore {
247
256
  }
248
257
  }
249
258
 
259
+ public async get<T>(key: string): Promise<T | undefined> {
260
+ const obj = await this.getStoredObject<T>(key);
261
+
262
+ return obj?.value;
263
+ }
264
+
250
265
  public async forEach(
251
266
  callback: (
252
267
  key: string,
253
268
  value: unknown,
254
- expireMs: number,
269
+ expiryMs: number,
255
270
  ) => void | Promise<void>,
256
271
  ): Promise<void> {
257
272
  await this.transact<void>("readonly", (objectStore, resolve, reject) => {
@@ -266,7 +281,7 @@ export class KVStore {
266
281
  if (cursor.key) {
267
282
  const obj = validateStoredObject(cursor.value);
268
283
  if (obj) {
269
- await callback(String(cursor.key), obj.value, obj.expireMs);
284
+ await callback(String(cursor.key), obj.value, obj.expiryMs);
270
285
  } else {
271
286
  await callback(String(cursor.key), undefined, 0);
272
287
  }
@@ -300,8 +315,8 @@ export class KVStore {
300
315
  /** Mainly for debugging dumps. */
301
316
  public async asMap(): Promise<Map<string, unknown>> {
302
317
  const map = new Map<string, unknown>();
303
- await this.forEach((key, value, expireMs) => {
304
- map.set(key, { value, expireMs });
318
+ await this.forEach((key, value, expiryMs) => {
319
+ map.set(key, { value, expiryMs });
305
320
  });
306
321
  return map;
307
322
  }
@@ -345,8 +360,8 @@ export class KVStore {
345
360
 
346
361
  const keysToDelete: string[] = [];
347
362
  await this.forEach(
348
- async (key: string, value: unknown, expireMs: number) => {
349
- if (value === undefined || Date.now() >= expireMs) {
363
+ async (key: string, value: unknown, expiryMs: number) => {
364
+ if (value === undefined || Date.now() >= expiryMs) {
350
365
  keysToDelete.push(key);
351
366
  }
352
367
  },
@@ -391,7 +406,16 @@ class KvStoreItem<T> {
391
406
  public readonly store = kvStore,
392
407
  ) {}
393
408
 
394
- public async get(): Promise<Awaited<T> | undefined> {
409
+ /**
410
+ * Example usage:
411
+ *
412
+ * const { value, storedMs, expiryMs } = await myKvItem.getStoredObject();
413
+ */
414
+ public async getStoredObject(): Promise<StoredObject<T> | undefined> {
415
+ return await this.store.getStoredObject(this.key);
416
+ }
417
+
418
+ public async get(): Promise<T | undefined> {
395
419
  return await this.store.get(this.key);
396
420
  }
397
421
 
@@ -412,7 +436,9 @@ class KvStoreItem<T> {
412
436
  */
413
437
  export function kvStoreItem<T>(
414
438
  key: string,
415
- defaultExpiryDeltaMs: number,
439
+ defaultExpiration: number | Duration,
416
440
  ): KvStoreItem<T> {
441
+ const defaultExpiryDeltaMs = durationOrMsToMs(defaultExpiration);
442
+
417
443
  return new KvStoreItem<T>(key, defaultExpiryDeltaMs);
418
444
  }
@@ -1,6 +1,6 @@
1
- import { Duration, durationToMs } from "./duration";
1
+ import { Duration, durationOrMsToMs } from "./duration";
2
2
 
3
- export type StoredItem<T> = { value: T; expireMs: number };
3
+ export type StoredItem<T> = { value: T; storedMs: number; expiryMs: number };
4
4
 
5
5
  /**
6
6
  * Simple local storage cache with support for auto-expiration.
@@ -27,8 +27,7 @@ export function storeItem<T>(
27
27
  logError = true,
28
28
  defaultValue?: T,
29
29
  ) {
30
- const expireDeltaMs =
31
- typeof expires === "number" ? expires : durationToMs(expires);
30
+ const expireDeltaMs = durationOrMsToMs(expires);
32
31
 
33
32
  return new CacheItem<T>(key, expireDeltaMs, logError, defaultValue);
34
33
  }
@@ -47,22 +46,31 @@ class CacheItem<T> {
47
46
  /**
48
47
  * Set the value of this item with auto-expiration.
49
48
  */
50
- public set(value: T): void {
51
- const expireMs = Date.now() + this.expireDeltaMs;
52
- const toStore: StoredItem<T> = { value, expireMs };
49
+ public set(
50
+ value: T,
51
+ expiryDelta: number | Duration = this.expireDeltaMs,
52
+ ): void {
53
+ const nowMs = Date.now();
54
+ const toStore: StoredItem<T> = {
55
+ value,
56
+ storedMs: nowMs,
57
+ expiryMs: nowMs + durationOrMsToMs(expiryDelta),
58
+ };
53
59
  const valueStr = JSON.stringify(toStore);
54
60
 
55
61
  globalThis.localStorage.setItem(this.key, valueStr);
56
62
  }
57
63
 
58
64
  /**
59
- * Get the value of this item, or undefined if value is not set or expired.
65
+ * Example usage:
66
+ *
67
+ * const { value, storedMs, expiryMs } = await myItem.getStoredItem();
60
68
  */
61
- public get(): T | undefined {
69
+ public getStoredItem(): StoredItem<T> | undefined {
62
70
  const jsonStr = globalThis.localStorage.getItem(this.key);
63
71
 
64
72
  if (!jsonStr) {
65
- return this.defaultValue;
73
+ return undefined;
66
74
  }
67
75
 
68
76
  try {
@@ -72,15 +80,17 @@ class CacheItem<T> {
72
80
  !obj ||
73
81
  typeof obj !== "object" ||
74
82
  !("value" in obj) ||
75
- !("expireMs" in obj) ||
76
- typeof obj.expireMs !== "number" ||
77
- Date.now() >= obj.expireMs
83
+ !("storedMs" in obj) ||
84
+ typeof obj.storedMs !== "number" ||
85
+ !("expiryMs" in obj) ||
86
+ typeof obj.expiryMs !== "number" ||
87
+ Date.now() >= obj.expiryMs
78
88
  ) {
79
89
  this.remove();
80
- return this.defaultValue;
90
+ return undefined;
81
91
  }
82
92
 
83
- return obj.value;
93
+ return obj;
84
94
  } catch (e) {
85
95
  if (this.logError) {
86
96
  console.error(
@@ -89,10 +99,19 @@ class CacheItem<T> {
89
99
  );
90
100
  }
91
101
  this.remove();
92
- return this.defaultValue;
102
+ return undefined;
93
103
  }
94
104
  }
95
105
 
106
+ /**
107
+ * Get the value of this item, or undefined if value is not set or expired.
108
+ */
109
+ public get(): T | undefined {
110
+ const stored = this.getStoredItem();
111
+
112
+ return stored !== undefined ? stored.value : this.defaultValue;
113
+ }
114
+
96
115
  /**
97
116
  * Remove the value of this item.
98
117
  */