@naturalcycles/js-lib 14.235.0 → 14.237.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (43) hide show
  1. package/dist/datetime/localDate.d.ts +2 -1
  2. package/dist/datetime/localDate.js +7 -0
  3. package/dist/datetime/localTime.d.ts +67 -26
  4. package/dist/datetime/localTime.js +99 -33
  5. package/dist/datetime/wallTime.d.ts +33 -0
  6. package/dist/datetime/wallTime.js +48 -0
  7. package/dist/index.d.ts +1 -5
  8. package/dist/index.js +1 -5
  9. package/dist-esm/array/range.js +4 -7
  10. package/dist-esm/datetime/localDate.js +7 -0
  11. package/dist-esm/datetime/localTime.js +105 -35
  12. package/dist-esm/datetime/wallTime.js +44 -0
  13. package/dist-esm/decorators/asyncMemo.decorator.js +1 -1
  14. package/dist-esm/decorators/createPromiseDecorator.js +10 -5
  15. package/dist-esm/decorators/debounce.js +6 -1
  16. package/dist-esm/decorators/memo.decorator.js +1 -1
  17. package/dist-esm/define.js +14 -2
  18. package/dist-esm/enum.util.js +1 -2
  19. package/dist-esm/error/assert.js +12 -3
  20. package/dist-esm/error/error.util.js +13 -8
  21. package/dist-esm/error/tryCatch.js +1 -1
  22. package/dist-esm/http/fetcher.js +74 -41
  23. package/dist-esm/index.js +1 -5
  24. package/dist-esm/iter/asyncIterable2.js +37 -122
  25. package/dist-esm/json-schema/jsonSchema.util.js +2 -3
  26. package/dist-esm/json-schema/jsonSchemaBuilder.js +1 -2
  27. package/dist-esm/math/math.util.js +1 -1
  28. package/dist-esm/object/object.util.js +4 -5
  29. package/dist-esm/polyfill.js +2 -3
  30. package/dist-esm/promise/abortable.js +1 -2
  31. package/dist-esm/promise/pMap.js +3 -3
  32. package/dist-esm/promise/pQueue.js +7 -2
  33. package/dist-esm/string/json.util.js +3 -3
  34. package/dist-esm/string/readingTime.js +4 -1
  35. package/dist-esm/string/safeJsonStringify.js +2 -2
  36. package/dist-esm/string/stringify.js +1 -1
  37. package/dist-esm/web.js +2 -4
  38. package/dist-esm/zod/zod.util.js +1 -2
  39. package/package.json +1 -1
  40. package/src/datetime/localDate.ts +9 -1
  41. package/src/datetime/localTime.ts +110 -37
  42. package/src/datetime/wallTime.ts +56 -0
  43. package/src/index.ts +1 -5
@@ -8,7 +8,7 @@ export function _safeJsonStringify(obj, replacer, spaces, cycleReplacer) {
8
8
  // Try native first (as it's ~3 times faster)
9
9
  return JSON.stringify(obj, replacer, spaces);
10
10
  }
11
- catch (_a) {
11
+ catch {
12
12
  // Native failed - resort to the "safe" serializer
13
13
  return JSON.stringify(obj, serializer(replacer, cycleReplacer), spaces);
14
14
  }
@@ -17,7 +17,7 @@ export function _safeJsonStringify(obj, replacer, spaces, cycleReplacer) {
17
17
  function serializer(replacer, cycleReplacer) {
18
18
  const stack = [];
19
19
  const keys = [];
20
- cycleReplacer !== null && cycleReplacer !== void 0 ? cycleReplacer : (cycleReplacer = function (key, value) {
20
+ cycleReplacer ?? (cycleReplacer = function (key, value) {
21
21
  if (stack[0] === value)
22
22
  return '[Circular ~]';
23
23
  return '[Circular ~.' + keys.slice(0, stack.indexOf(value)).join('.') + ']';
@@ -117,7 +117,7 @@ export function _stringify(obj, opt = {}) {
117
117
  const { stringifyFn = globalStringifyFunction } = opt;
118
118
  s = stringifyFn(obj, undefined, 2);
119
119
  }
120
- catch (_a) {
120
+ catch {
121
121
  s = String(obj); // fallback
122
122
  }
123
123
  }
package/dist-esm/web.js CHANGED
@@ -14,8 +14,7 @@ export class InMemoryWebStorage {
14
14
  // but can be implemented with Proxy
15
15
  // [ name: string ]: any
16
16
  getItem(key) {
17
- var _a;
18
- return (_a = this.data[key]) !== null && _a !== void 0 ? _a : null;
17
+ return this.data[key] ?? null;
19
18
  }
20
19
  setItem(key, value) {
21
20
  this.data[key] = String(value);
@@ -24,8 +23,7 @@ export class InMemoryWebStorage {
24
23
  delete this.data[key];
25
24
  }
26
25
  key(index) {
27
- var _a;
28
- return (_a = Object.keys(this.data)[index]) !== null && _a !== void 0 ? _a : null;
26
+ return Object.keys(this.data)[index] ?? null;
29
27
  }
30
28
  clear() {
31
29
  this.data = {};
@@ -31,10 +31,9 @@ export class ZodValidationError extends ZodError {
31
31
  return this.annotate();
32
32
  }
33
33
  annotate() {
34
- var _a;
35
34
  let objectTitle = this.schema.description;
36
35
  if (typeof this.value === 'object' && this.value) {
37
- const objectName = this.schema.description || ((_a = this.value.constructor) === null || _a === void 0 ? void 0 : _a.name);
36
+ const objectName = this.schema.description || this.value.constructor?.name;
38
37
  const objectId = this.value['id'];
39
38
  objectTitle = [objectName, objectId].filter(Boolean).join('.');
40
39
  }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@naturalcycles/js-lib",
3
- "version": "14.235.0",
3
+ "version": "14.237.0",
4
4
  "scripts": {
5
5
  "prepare": "husky",
6
6
  "build-prod": "build-prod-esm-cjs",
@@ -9,7 +9,7 @@ import type {
9
9
  UnixTimestampMillisNumber,
10
10
  UnixTimestampNumber,
11
11
  } from '../types'
12
- import { ISODayOfWeek, localTime, LocalTime } from './localTime'
12
+ import { DateObject, ISODayOfWeek, localTime, LocalTime } from './localTime'
13
13
 
14
14
  export type LocalDateUnit = LocalDateUnitStrict | 'week'
15
15
  export type LocalDateUnitStrict = 'year' | 'month' | 'day'
@@ -381,6 +381,14 @@ export class LocalDate {
381
381
  return new Date(this.toISODateTimeInUTC())
382
382
  }
383
383
 
384
+ toDateObject(): DateObject {
385
+ return {
386
+ year: this.$year,
387
+ month: this.$month,
388
+ day: this.$day,
389
+ }
390
+ }
391
+
384
392
  /**
385
393
  * Converts LocalDate to LocalTime with 0 hours, 0 minutes, 0 seconds.
386
394
  * LocalTime's Date will be in local timezone.
@@ -12,6 +12,7 @@ import type {
12
12
  UnixTimestampNumber,
13
13
  } from '../types'
14
14
  import { localDate, LocalDate } from './localDate'
15
+ import { WallTime } from './wallTime'
15
16
 
16
17
  export type LocalTimeUnit = 'year' | 'month' | 'week' | 'day' | 'hour' | 'minute' | 'second'
17
18
 
@@ -28,15 +29,15 @@ export enum ISODayOfWeek {
28
29
  export type LocalTimeInput = LocalTime | Date | IsoDateTimeString | UnixTimestampNumber
29
30
  export type LocalTimeFormatter = (ld: LocalTime) => string
30
31
 
31
- export type LocalTimeComponents = DateComponents & TimeComponents
32
+ export type DateTimeObject = DateObject & TimeObject
32
33
 
33
- interface DateComponents {
34
+ export interface DateObject {
34
35
  year: number
35
36
  month: number
36
37
  day: number
37
38
  }
38
39
 
39
- interface TimeComponents {
40
+ export interface TimeObject {
40
41
  hour: number
41
42
  minute: number
42
43
  second: number
@@ -68,6 +69,83 @@ export class LocalTime {
68
69
  return new LocalTime(new Date(this.$date.getTime()))
69
70
  }
70
71
 
72
+ /**
73
+ * Returns [cloned] fake LocalTime that has yyyy-mm-dd hh:mm:ss in the provided timezone.
74
+ * It is a fake LocalTime in a sense that it's timezone is not real.
75
+ * See this ("common errors"): https://stackoverflow.com/a/15171030/4919972
76
+ * Fake also means that unixTimestamp of that new LocalDate is not the same.
77
+ * For that reason we return WallTime, and not a LocalTime.
78
+ * WallTime can be pretty-printed as Date-only, Time-only or DateAndTime.
79
+ *
80
+ * E.g `inTimezone('America/New_York').toISOTime()`
81
+ *
82
+ * https://en.wikipedia.org/wiki/List_of_tz_database_time_zones
83
+ *
84
+ * @experimental
85
+ */
86
+ inTimezone(tz: string): WallTime {
87
+ const d = new Date(this.$date.toLocaleString('en-US', { timeZone: tz }))
88
+ return new WallTime({
89
+ year: d.getFullYear(),
90
+ month: d.getMonth() + 1,
91
+ day: d.getDate(),
92
+ hour: d.getHours(),
93
+ minute: d.getMinutes(),
94
+ second: d.getSeconds(),
95
+ })
96
+ }
97
+
98
+ /**
99
+ * UTC offset is the opposite of "timezone offset" - it's the number of minutes to add
100
+ * to the local time to get UTC time.
101
+ *
102
+ * E.g utcOffset for CEST is -120,
103
+ * which means that you need to add -120 minutes to the local time to get UTC time.
104
+ *
105
+ * Instead of -0 it returns 0, for the peace of mind and less weird test/snapshot differences.
106
+ *
107
+ * If timezone (tz) is specified, e.g `America/New_York`,
108
+ * it will return the UTC offset for that timezone.
109
+ *
110
+ * https://en.wikipedia.org/wiki/List_of_tz_database_time_zones
111
+ */
112
+ getUTCOffsetMinutes(tz?: string): NumberOfMinutes {
113
+ if (tz) {
114
+ // based on: https://stackoverflow.com/a/53652131/4919972
115
+ const nowTime = this.$date.getTime()
116
+ const tzTime = new Date(this.$date.toLocaleString('en-US', { timeZone: tz })).getTime()
117
+ return Math.round((tzTime - nowTime) / 60000) || 0
118
+ }
119
+
120
+ return -this.$date.getTimezoneOffset() || 0
121
+ }
122
+
123
+ /**
124
+ * Same as getUTCOffsetMinutes, but rounded to hours.
125
+ *
126
+ * E.g for CEST it is -2.
127
+ *
128
+ * Instead of -0 it returns 0, for the peace of mind and less weird test/snapshot differences.
129
+ *
130
+ * If timezone (tz) is specified, e.g `America/New_York`,
131
+ * it will return the UTC offset for that timezone.
132
+ */
133
+ getUTCOffsetHours(tz?: string): NumberOfHours {
134
+ return Math.round(this.getUTCOffsetMinutes(tz) / 60)
135
+ }
136
+
137
+ /**
138
+ * Returns e.g `-05:00` for New_York winter time.
139
+ */
140
+ getUTCOffsetString(tz: string): string {
141
+ const minutes = this.getUTCOffsetMinutes(tz)
142
+ const hours = Math.trunc(minutes / 60)
143
+ const sign = hours < 0 ? '-' : '+'
144
+ const h = String(Math.abs(hours)).padStart(2, '0')
145
+ const m = String(minutes % 60).padStart(2, '0')
146
+ return `${sign}${h}:${m}`
147
+ }
148
+
71
149
  get(unit: LocalTimeUnit): number {
72
150
  if (unit === 'year') {
73
151
  return this.$date.getFullYear()
@@ -166,7 +244,7 @@ export class LocalTime {
166
244
  return v === undefined ? this.get('second') : this.set('second', v)
167
245
  }
168
246
 
169
- setComponents(c: Partial<LocalTimeComponents>, mutate = false): LocalTime {
247
+ setComponents(c: Partial<DateTimeObject>, mutate = false): LocalTime {
170
248
  const d = mutate ? this.$date : new Date(this.$date)
171
249
 
172
250
  // Year, month and day set all-at-once, to avoid 30/31 (and 28/29) mishap
@@ -434,14 +512,14 @@ export class LocalTime {
434
512
  return t1 < t2 ? -1 : 1
435
513
  }
436
514
 
437
- components(): LocalTimeComponents {
515
+ getDateTimeObject(): DateTimeObject {
438
516
  return {
439
- ...this.dateComponents(),
440
- ...this.timeComponents(),
517
+ ...this.getDateObject(),
518
+ ...this.getTimeObject(),
441
519
  }
442
520
  }
443
521
 
444
- private dateComponents(): DateComponents {
522
+ getDateObject(): DateObject {
445
523
  return {
446
524
  year: this.$date.getFullYear(),
447
525
  month: this.$date.getMonth() + 1,
@@ -449,7 +527,7 @@ export class LocalTime {
449
527
  }
450
528
  }
451
529
 
452
- private timeComponents(): TimeComponents {
530
+ getTimeObject(): TimeObject {
453
531
  return {
454
532
  hour: this.$date.getHours(),
455
533
  minute: this.$date.getMinutes(),
@@ -518,7 +596,7 @@ export class LocalTime {
518
596
  * Returns e.g: `1984-06-21`, only the date part of DateTime
519
597
  */
520
598
  toISODate(): IsoDateString {
521
- const { year, month, day } = this.dateComponents()
599
+ const { year, month, day } = this.getDateObject()
522
600
 
523
601
  return [
524
602
  String(year).padStart(4, '0'),
@@ -534,7 +612,7 @@ export class LocalTime {
534
612
  * Returns e.g: `17:03:15` (or `17:03` with seconds=false)
535
613
  */
536
614
  toISOTime(seconds = true): string {
537
- const { hour, minute, second } = this.timeComponents()
615
+ const { hour, minute, second } = this.getTimeObject()
538
616
 
539
617
  return [
540
618
  String(hour).padStart(2, '0'),
@@ -552,7 +630,7 @@ export class LocalTime {
552
630
  * Returns e.g: `19840621_1705`
553
631
  */
554
632
  toStringCompact(seconds = false): string {
555
- const { year, month, day, hour, minute, second } = this.components()
633
+ const { year, month, day, hour, minute, second } = this.getDateTimeObject()
556
634
 
557
635
  return [
558
636
  String(year).padStart(4, '0'),
@@ -672,6 +750,25 @@ class LocalTimeFactory {
672
750
  return this.parseOrNull(d) !== null
673
751
  }
674
752
 
753
+ /**
754
+ * Returns the IANA timezone e.g `Europe/Stockholm`.
755
+ * https://en.wikipedia.org/wiki/List_of_tz_database_time_zones
756
+ */
757
+ getTimezone(): string {
758
+ return Intl.DateTimeFormat().resolvedOptions().timeZone
759
+ }
760
+
761
+ /**
762
+ * Returns true if passed IANA timezone is valid/supported.
763
+ * E.g `Europe/Stockholm` is valid, but `Europe/Stockholm2` is not.
764
+ *
765
+ * This implementation is not optimized for performance. If you need frequent validation -
766
+ * consider caching the Intl.supportedValuesOf values as Set and reuse that.
767
+ */
768
+ isTimezoneValid(tz: string): boolean {
769
+ return Intl.supportedValuesOf('timeZone').includes(tz)
770
+ }
771
+
675
772
  now(): LocalTime {
676
773
  return new LocalTime(new Date())
677
774
  }
@@ -692,7 +789,7 @@ class LocalTimeFactory {
692
789
  return d ? this.of(d) : this.now()
693
790
  }
694
791
 
695
- fromComponents(c: { year: number; month: number } & Partial<LocalTimeComponents>): LocalTime {
792
+ fromComponents(c: { year: number; month: number } & Partial<DateTimeObject>): LocalTime {
696
793
  return new LocalTime(
697
794
  new Date(c.year, c.month - 1, c.day || 1, c.hour || 0, c.minute || 0, c.second || 0),
698
795
  )
@@ -857,27 +954,3 @@ Object.setPrototypeOf(localTime, localTimeFactory)
857
954
  export function nowUnix(): UnixTimestampNumber {
858
955
  return Math.floor(Date.now() / 1000)
859
956
  }
860
-
861
- /**
862
- * UTC offset is the opposite of "timezone offset" - it's the number of minutes to add
863
- * to the local time to get UTC time.
864
- *
865
- * E.g utcOffset for CEST is -120,
866
- * which means that you need to add -120 minutes to the local time to get UTC time.
867
- *
868
- * Instead of -0 it returns 0, for the peace of mind and less weird test/snapshot differences.
869
- */
870
- export function getUTCOffsetMinutes(): NumberOfMinutes {
871
- return -new Date().getTimezoneOffset() || 0
872
- }
873
-
874
- /**
875
- * Same as getUTCOffsetMinutes, but rounded to hours.
876
- *
877
- * E.g for CEST it is -2.
878
- *
879
- * Instead of -0 it returns 0, for the peace of mind and less weird test/snapshot differences.
880
- */
881
- export function getUTCOffsetHours(): NumberOfHours {
882
- return Math.round(getUTCOffsetMinutes() / 60)
883
- }
@@ -0,0 +1,56 @@
1
+ import { DateTimeObject } from './localTime'
2
+
3
+ /**
4
+ * Representation of a "time on the wall clock",
5
+ * which means "local time, regardless of timezone".
6
+ *
7
+ * Experimental simplified container object to hold
8
+ * date and time components as numbers.
9
+ * No math or manipulation is possible here.
10
+ * Can be pretty-printed as Date, Time or DateAndTime.
11
+ */
12
+ export class WallTime implements DateTimeObject {
13
+ year!: number
14
+ month!: number
15
+ day!: number
16
+ hour!: number
17
+ minute!: number
18
+ second!: number
19
+
20
+ constructor(obj: DateTimeObject) {
21
+ Object.assign(this, obj)
22
+ }
23
+
24
+ /**
25
+ * Returns e.g: `1984-06-21 17:56:21`
26
+ * or (if seconds=false):
27
+ * `1984-06-21 17:56`
28
+ */
29
+ toPretty(seconds = true): string {
30
+ return this.toISODate() + ' ' + this.toISOTime(seconds)
31
+ }
32
+
33
+ /**
34
+ * Returns e.g: `1984-06-21`, only the date part of DateTime
35
+ */
36
+ toISODate(): string {
37
+ return [
38
+ String(this.year).padStart(4, '0'),
39
+ String(this.month).padStart(2, '0'),
40
+ String(this.day).padStart(2, '0'),
41
+ ].join('-')
42
+ }
43
+
44
+ /**
45
+ * Returns e.g: `17:03:15` (or `17:03` with seconds=false)
46
+ */
47
+ toISOTime(seconds = true): string {
48
+ return [
49
+ String(this.hour).padStart(2, '0'),
50
+ String(this.minute).padStart(2, '0'),
51
+ seconds && String(this.second).padStart(2, '0'),
52
+ ]
53
+ .filter(Boolean)
54
+ .join(':')
55
+ }
56
+ }
package/src/index.ts CHANGED
@@ -26,7 +26,6 @@ export * from './json-schema/jsonSchema.cnst'
26
26
  export * from './json-schema/jsonSchema.model'
27
27
  export * from './json-schema/jsonSchema.util'
28
28
  export * from './json-schema/jsonSchemaBuilder'
29
- export * from './json-schema/jsonSchemaBuilder'
30
29
  export * from './math/math.util'
31
30
  export * from './math/sma'
32
31
  export * from './number/createDeterministicRandom'
@@ -68,10 +67,7 @@ export * from './math/stack.util'
68
67
  export * from './string/leven'
69
68
  export * from './datetime/localDate'
70
69
  export * from './datetime/localTime'
71
- export * from './datetime/dateInterval'
72
- export * from './datetime/timeInterval'
73
- export * from './datetime/localDate'
74
- export * from './datetime/localTime'
70
+ export * from './datetime/wallTime'
75
71
  export * from './datetime/dateInterval'
76
72
  export * from './datetime/timeInterval'
77
73
  export * from './env'