@naturalcycles/js-lib 14.244.0 → 14.245.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (40) hide show
  1. package/dist/datetime/dateInterval.d.ts +1 -1
  2. package/dist/datetime/localDate.d.ts +62 -43
  3. package/dist/datetime/localDate.js +153 -123
  4. package/dist/datetime/localTime.d.ts +57 -28
  5. package/dist/datetime/localTime.js +205 -138
  6. package/dist/datetime/timeInterval.d.ts +2 -2
  7. package/dist/datetime/timeInterval.js +2 -2
  8. package/dist/error/error.util.d.ts +1 -1
  9. package/dist/index.d.ts +37 -37
  10. package/dist/index.js +37 -37
  11. package/dist/json-schema/from-data/generateJsonSchemaFromData.d.ts +1 -1
  12. package/dist/json-schema/jsonSchemaBuilder.d.ts +1 -1
  13. package/dist/log/commonLogger.js +10 -9
  14. package/dist/object/object.util.d.ts +1 -1
  15. package/dist/time/time.util.js +4 -2
  16. package/dist/zod/zod.util.d.ts +1 -1
  17. package/dist-esm/datetime/localDate.js +153 -122
  18. package/dist-esm/datetime/localTime.js +205 -137
  19. package/dist-esm/datetime/timeInterval.js +2 -2
  20. package/dist-esm/decorators/logMethod.decorator.js +1 -1
  21. package/dist-esm/index.js +37 -37
  22. package/dist-esm/json-schema/jsonSchemaBuilder.js +1 -1
  23. package/dist-esm/log/commonLogger.js +2 -1
  24. package/dist-esm/time/time.util.js +4 -2
  25. package/package.json +1 -1
  26. package/src/datetime/dateInterval.ts +1 -1
  27. package/src/datetime/localDate.ts +157 -133
  28. package/src/datetime/localTime.ts +204 -149
  29. package/src/datetime/timeInterval.ts +4 -4
  30. package/src/decorators/logMethod.decorator.ts +1 -1
  31. package/src/define.ts +1 -1
  32. package/src/error/error.util.ts +3 -3
  33. package/src/http/fetcher.ts +1 -1
  34. package/src/index.ts +37 -37
  35. package/src/json-schema/from-data/generateJsonSchemaFromData.ts +1 -1
  36. package/src/json-schema/jsonSchemaBuilder.ts +2 -2
  37. package/src/log/commonLogger.ts +2 -1
  38. package/src/object/object.util.ts +1 -1
  39. package/src/time/time.util.ts +4 -1
  40. package/src/zod/zod.util.ts +1 -1
@@ -217,26 +217,71 @@ export declare class LocalTime {
217
217
  }
218
218
  declare class LocalTimeFactory {
219
219
  /**
220
- * Parses input String into LocalTime.
220
+ * Creates a LocalTime from the input, unless it's falsy - then returns undefined.
221
+ *
222
+ * `localTime` function will instead return LocalTime of `now` for falsy input.
223
+ */
224
+ orUndefined(input: LocalTimeInputNullable): LocalTime | undefined;
225
+ /**
226
+ * Creates a LocalTime from the input, unless it's falsy - then returns LocalTime.now
227
+ */
228
+ orNow(input: LocalTimeInputNullable): LocalTime;
229
+ now(): LocalTime;
230
+ /**
231
+ Convenience function to return current Unix timestamp in seconds.
232
+ Like Date.now(), but in seconds.
233
+ */
234
+ nowUnix(): UnixTimestampNumber;
235
+ /**
236
+ * Create LocalTime from LocalTimeInput.
221
237
  * Input can already be a LocalTime - it is returned as-is in that case.
238
+ * Date - will be used as-is.
239
+ * String - will be parsed as strict `yyyy-mm-ddThh:mm:ss`.
240
+ * Number - will be treated as unix timestamp in seconds.
241
+ */
242
+ fromInput(input: LocalTimeInput): LocalTime;
243
+ /**
244
+ * Returns true if input is valid to create LocalTime.
245
+ */
246
+ isValid(input: LocalTimeInputNullable): boolean;
247
+ /**
248
+ * Returns true if isoString is a valid iso8601 string like `yyyy-mm-ddThh:mm:dd`.
249
+ */
250
+ isValidString(isoString: string | undefined | null): boolean;
251
+ /**
252
+ * Tries to convert/parse the input into LocalTime.
253
+ * Uses LOOSE parsing.
254
+ * If invalid - doesn't throw, but returns undefined instead.
222
255
  */
223
- from(input: LocalTimeInput): LocalTime;
256
+ try(input: LocalTimeInputNullable): LocalTime | undefined;
257
+ /**
258
+ * Performs STRICT parsing.
259
+ * Only allows IsoDateTimeString or IsoDateString input, nothing else.
260
+ */
261
+ fromIsoDateTimeString(s: IsoDateTimeString | IsoDateString): LocalTime;
262
+ /**
263
+ * Performs LOOSE parsing.
264
+ * Tries to coerce imprefect/incorrect string input into IsoDateTimeString.
265
+ * Use with caution.
266
+ * Allows to input IsoDateString, will set h:m:s to zeros.
267
+ */
268
+ parse(s: string): LocalTime;
269
+ private parseStrictlyOrUndefined;
270
+ private parseLooselyOrUndefined;
271
+ /**
272
+ * Throws on invalid value.
273
+ */
274
+ private validateDateTimeObject;
275
+ isDateTimeObjectValid(o: DateTimeObject): boolean;
276
+ isTimeObjectValid({ hour, minute, second }: TimeObject): boolean;
224
277
  fromDate(date: Date): LocalTime;
225
278
  fromUnix(ts: UnixTimestampNumber): LocalTime;
226
279
  /**
227
280
  * Create LocalTime from unixTimestamp in milliseconds (not in seconds).
228
281
  */
229
282
  fromMillis(millis: UnixTimestampMillisNumber): LocalTime;
230
- /**
231
- * Returns null if invalid
232
- */
233
- fromOrNull(d: LocalTimeInputNullable): LocalTime | null;
234
- fromStringOrNull(s: string | undefined | null): LocalTime | null;
235
- fromDateTimeObject(input: DateTimeObjectInput): LocalTime;
236
- private parseStringToDateOrNull;
237
- isValid(input: LocalTimeInputNullable): boolean;
238
- isValidString(isoString: string | undefined | null): boolean;
239
- private assertNotNull;
283
+ fromDateTimeObject(o: DateTimeObjectInput): LocalTime;
284
+ private createDateFromDateTimeObject;
240
285
  /**
241
286
  * Returns the IANA timezone e.g `Europe/Stockholm`.
242
287
  * https://en.wikipedia.org/wiki/List_of_tz_database_time_zones
@@ -250,17 +295,6 @@ declare class LocalTimeFactory {
250
295
  * consider caching the Intl.supportedValuesOf values as Set and reuse that.
251
296
  */
252
297
  isTimezoneValid(tz: string): boolean;
253
- now(): LocalTime;
254
- /**
255
- * Creates a LocalTime from the input, unless it's falsy - then returns undefined.
256
- *
257
- * `localTime` function will instead return LocalTime of `now` for falsy input.
258
- */
259
- orUndefined(input: LocalTimeInputNullable): LocalTime | undefined;
260
- /**
261
- * Creates a LocalTime from the input, unless it's falsy - then returns LocalTime.now
262
- */
263
- orNow(input: LocalTimeInputNullable): LocalTime;
264
298
  sort(items: LocalTime[], dir?: SortDirection, mutate?: boolean): LocalTime[];
265
299
  minOrUndefined(items: LocalTimeInputNullable[]): LocalTime | undefined;
266
300
  min(items: LocalTimeInputNullable[]): LocalTime;
@@ -271,9 +305,4 @@ interface LocalTimeFn extends LocalTimeFactory {
271
305
  (d: LocalTimeInput): LocalTime;
272
306
  }
273
307
  export declare const localTime: LocalTimeFn;
274
- /**
275
- Convenience function to return current Unix timestamp in seconds.
276
- Like Date.now(), but in seconds.
277
- */
278
- export declare function nowUnix(): UnixTimestampNumber;
279
308
  export {};
@@ -1,7 +1,6 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
3
  exports.localTime = exports.LocalTime = exports.ISODayOfWeek = void 0;
4
- exports.nowUnix = nowUnix;
5
4
  const assert_1 = require("../error/assert");
6
5
  const is_util_1 = require("../is.util");
7
6
  const time_util_1 = require("../time/time.util");
@@ -23,10 +22,22 @@ const SECONDS_IN_DAY = 86400;
23
22
  // const MILLISECONDS_IN_DAY = 86400000
24
23
  // const MILLISECONDS_IN_MINUTE = 60000
25
24
  const VALID_DAYS_OF_WEEK = new Set([1, 2, 3, 4, 5, 6, 7]);
26
- // It supports 2 forms:
27
- // 1. 2023-03-03
28
- // 2. 2023-03-03T05:10:02
29
- const DATE_TIME_REGEX = /^(\d{4})-(\d{2})-(\d{2})([T\s](\d{2}):(\d{2}):(\d{2}))?/;
25
+ /**
26
+ * It supports 2 forms:
27
+ * 1. 2023-03-03
28
+ * 2. 2023-03-03T05:10:02
29
+ * // todo: make it even looser, like Day.js
30
+ */
31
+ const DATE_TIME_REGEX_LOOSE = /^(\d{4})-(\d{2})-(\d{2})([Tt\s](\d{2}):?(\d{2})?:?(\d{2})?)?/;
32
+ /**
33
+ * Supports 2 forms:
34
+ * 1. 2023-03-03
35
+ * 2. 2023-03-03T05:10:02
36
+ * Ok, now it allows arbitrary stuff after `:ss`, to allow millis/timezone info,
37
+ * but it will not take it into account.
38
+ */
39
+ const DATE_TIME_REGEX_STRICT = /^(\d{4})-(\d{2})-(\d{2})T(\d{2}):(\d{2}):(\d{2})/;
40
+ const DATE_REGEX_STRICT = /^(\d\d\d\d)-(\d\d)-(\d\d)$/;
30
41
  class LocalTime {
31
42
  constructor($date) {
32
43
  this.$date = $date;
@@ -283,7 +294,7 @@ class LocalTime {
283
294
  }
284
295
  if (unit === 'year' || unit === 'month') {
285
296
  const d = addMonths(this.$date, unit === 'month' ? num : num * 12, mutate);
286
- return mutate ? this : exports.localTime.from(d);
297
+ return mutate ? this : exports.localTime.fromInput(d);
287
298
  }
288
299
  return this.set(unit, this.get(unit) + num, mutate);
289
300
  }
@@ -294,7 +305,7 @@ class LocalTime {
294
305
  return Math.abs(this.diff(other, unit));
295
306
  }
296
307
  diff(other, unit) {
297
- const date2 = exports.localTime.from(other).$date;
308
+ const date2 = exports.localTime.fromInput(other).$date;
298
309
  const secDiff = (this.$date.valueOf() - date2.valueOf()) / 1000;
299
310
  if (!secDiff)
300
311
  return 0;
@@ -422,13 +433,13 @@ class LocalTime {
422
433
  * Third argument allows to override "now".
423
434
  */
424
435
  isOlderThan(n, unit, now) {
425
- return this.isBefore(exports.localTime.from(now ?? new Date()).plus(-n, unit));
436
+ return this.isBefore(exports.localTime.fromInput(now ?? new Date()).plus(-n, unit));
426
437
  }
427
438
  /**
428
439
  * Checks if this localTime is same or older (<=) than "now" by X units.
429
440
  */
430
441
  isSameOrOlderThan(n, unit, now) {
431
- return this.isSameOrBefore(exports.localTime.from(now ?? new Date()).plus(-n, unit));
442
+ return this.isSameOrBefore(exports.localTime.fromInput(now ?? new Date()).plus(-n, unit));
432
443
  }
433
444
  /**
434
445
  * Checks if this localTime is younger (>) than "now" by X units.
@@ -440,13 +451,13 @@ class LocalTime {
440
451
  * Third argument allows to override "now".
441
452
  */
442
453
  isYoungerThan(n, unit, now) {
443
- return this.isAfter(exports.localTime.from(now ?? new Date()).plus(-n, unit));
454
+ return this.isAfter(exports.localTime.fromInput(now ?? new Date()).plus(-n, unit));
444
455
  }
445
456
  /**
446
457
  * Checks if this localTime is same or younger (>=) than "now" by X units.
447
458
  */
448
459
  isSameOrYoungerThan(n, unit, now) {
449
- return this.isSameOrAfter(exports.localTime.from(now ?? new Date()).plus(-n, unit));
460
+ return this.isSameOrAfter(exports.localTime.fromInput(now ?? new Date()).plus(-n, unit));
450
461
  }
451
462
  getAgeInYears(now) {
452
463
  return this.getAgeIn('year', now);
@@ -467,7 +478,7 @@ class LocalTime {
467
478
  return this.getAgeIn('second', now);
468
479
  }
469
480
  getAgeIn(unit, now) {
470
- return exports.localTime.from(now ?? new Date()).diff(this, unit);
481
+ return exports.localTime.fromInput(now ?? new Date()).diff(this, unit);
471
482
  }
472
483
  /**
473
484
  * Returns 1 if this > d
@@ -476,7 +487,7 @@ class LocalTime {
476
487
  */
477
488
  compare(d) {
478
489
  const t1 = this.$date.valueOf();
479
- const t2 = exports.localTime.from(d).$date.valueOf();
490
+ const t2 = exports.localTime.fromInput(d).$date.valueOf();
480
491
  if (t1 === t2)
481
492
  return 0;
482
493
  return t1 < t2 ? -1 : 1;
@@ -502,7 +513,7 @@ class LocalTime {
502
513
  };
503
514
  }
504
515
  toFromNowString(now = new Date()) {
505
- const msDiff = exports.localTime.from(now).$date.valueOf() - this.$date.valueOf();
516
+ const msDiff = exports.localTime.fromInput(now).$date.valueOf() - this.$date.valueOf();
506
517
  if (msDiff === 0)
507
518
  return 'now';
508
519
  if (msDiff >= 0) {
@@ -609,118 +620,198 @@ class LocalTime {
609
620
  exports.LocalTime = LocalTime;
610
621
  class LocalTimeFactory {
611
622
  /**
612
- * Parses input String into LocalTime.
613
- * Input can already be a LocalTime - it is returned as-is in that case.
623
+ * Creates a LocalTime from the input, unless it's falsy - then returns undefined.
624
+ *
625
+ * `localTime` function will instead return LocalTime of `now` for falsy input.
614
626
  */
615
- from(input) {
616
- const lt = this.fromOrNull(input);
617
- this.assertNotNull(lt, input);
618
- return lt;
627
+ orUndefined(input) {
628
+ return input || input === 0 ? this.fromInput(input) : undefined;
619
629
  }
620
- fromDate(date) {
621
- return new LocalTime(date);
630
+ /**
631
+ * Creates a LocalTime from the input, unless it's falsy - then returns LocalTime.now
632
+ */
633
+ orNow(input) {
634
+ return input || input === 0 ? this.fromInput(input) : this.now();
622
635
  }
623
- fromUnix(ts) {
624
- return new LocalTime(new Date(ts * 1000));
636
+ now() {
637
+ return new LocalTime(new Date());
625
638
  }
626
639
  /**
627
- * Create LocalTime from unixTimestamp in milliseconds (not in seconds).
640
+ Convenience function to return current Unix timestamp in seconds.
641
+ Like Date.now(), but in seconds.
628
642
  */
629
- fromMillis(millis) {
630
- return new LocalTime(new Date(millis));
643
+ nowUnix() {
644
+ return Math.floor(Date.now() / 1000);
631
645
  }
632
646
  /**
633
- * Returns null if invalid
647
+ * Create LocalTime from LocalTimeInput.
648
+ * Input can already be a LocalTime - it is returned as-is in that case.
649
+ * Date - will be used as-is.
650
+ * String - will be parsed as strict `yyyy-mm-ddThh:mm:ss`.
651
+ * Number - will be treated as unix timestamp in seconds.
634
652
  */
635
- fromOrNull(d) {
636
- if (d instanceof LocalTime)
637
- return d;
638
- if (d instanceof Date) {
639
- return new LocalTime(d);
640
- }
641
- if (typeof d === 'number') {
642
- return new LocalTime(new Date(d * 1000));
643
- }
644
- if (typeof d === 'string') {
645
- return this.fromStringOrNull(d);
646
- }
647
- // This check is after checking the number, to support `0`
648
- // unexpected type, e.g Function or something
649
- return null;
650
- }
651
- fromStringOrNull(s) {
652
- const date = this.parseStringToDateOrNull(s);
653
- return date ? new LocalTime(date) : null;
654
- }
655
- fromDateTimeObject(input) {
656
- const { year, month, day = 1, hour = 0, minute = 0, second = 0 } = input;
657
- return new LocalTime(new Date(year, month - 1, day, hour, minute, second));
658
- }
659
- parseStringToDateOrNull(s) {
660
- if (!s)
661
- return null;
662
- // Slicing removes the "timezone component", and makes the date "local"
663
- // e.g 2022-04-06T23:15:00+09:00
664
- // becomes 2022-04-06T23:15:00
665
- // date = new Date(d.slice(0, 19))
666
- // Parsing is inspired by how Day.js does it
667
- // Specifically, it ensures that `localTime('2023-03-03')` returns the expected Date, and not a day before
668
- // Because `new Date('2023-03-03')` in NewYork gives you '2023-03-02 19:00:00 GMT-0500'
669
- const m = s.match(DATE_TIME_REGEX);
670
- // Validate in 3 ways:
671
- // 1. Should match Regex.
672
- // In some ways it's stricter than Date constructor, e.g it doesn't allow 2023/05/05
673
- // In other ways it's looser, e.g it allows `2023-05-05T`, while Date constructor doesn't.
674
- // 2. Date constructor (of Node/v8 implementation, which we know is different from e.g WebKit/Safari)
675
- // should not return `Invalid Date`.
676
- // 3. Year, month and day should be valid, e.g 2023-01-32 should not be allowed.
677
- // UPD: Actually, 3 can be skipped, because 2 is catching it already
678
- // UPD: 2 is skipped, 1 and 3 are kept
679
- // if (!m || isNaN(new Date(s).getDate())) return null
680
- if (!m)
681
- return null;
682
- const year = Number(m[1]);
683
- const month = Number(m[2]);
684
- const day = Number(m[3]);
685
- const hour = Number(m[5]);
686
- const minute = Number(m[6]);
687
- const second = Number(m[7]);
688
- // Validation for just the Date part
689
- if (!year ||
690
- !month ||
691
- month < 1 ||
692
- month > 12 ||
693
- !day ||
694
- day < 1 ||
695
- day > localDate_1.localDate.getMonthLength(year, month)) {
696
- return null;
697
- }
698
- // Validation for Date+Time string, since the string is longer than YYYY-MM-DD
699
- if (s.length > 10 &&
700
- (isNaN(hour) ||
701
- isNaN(minute) ||
702
- isNaN(second) ||
703
- hour < 0 ||
704
- hour > 23 ||
705
- minute < 0 ||
706
- minute > 59 ||
707
- second < 0 ||
708
- second > 59)) {
709
- return null;
710
- }
711
- return new Date(year, month - 1, day, hour || 0, minute || 0, second || 0, 0);
653
+ fromInput(input) {
654
+ if (input instanceof LocalTime)
655
+ return input;
656
+ if (input instanceof Date) {
657
+ return this.fromDate(input);
658
+ }
659
+ if (typeof input === 'number') {
660
+ return this.fromUnix(input);
661
+ }
662
+ // It means it's a string
663
+ // Will parse it STRICTLY
664
+ return this.fromIsoDateTimeString(input);
712
665
  }
666
+ /**
667
+ * Returns true if input is valid to create LocalTime.
668
+ */
713
669
  isValid(input) {
714
- return this.fromOrNull(input) !== null;
670
+ if (!input)
671
+ return false;
672
+ if (input instanceof LocalTime)
673
+ return true;
674
+ if (input instanceof Date)
675
+ return !isNaN(input.getDate());
676
+ // We currently don't validate Unixtimestamp input, treat it as always valid
677
+ if (typeof input === 'number')
678
+ return true;
679
+ return this.isValidString(input);
715
680
  }
681
+ /**
682
+ * Returns true if isoString is a valid iso8601 string like `yyyy-mm-ddThh:mm:dd`.
683
+ */
716
684
  isValidString(isoString) {
717
- return this.fromStringOrNull(isoString) !== null;
685
+ return !!this.parseStrictlyOrUndefined(isoString);
718
686
  }
719
- assertNotNull(lt, input) {
720
- (0, assert_1._assert)(lt !== null, `Cannot parse "${input}" into LocalTime`, {
721
- input,
722
- });
687
+ /**
688
+ * Tries to convert/parse the input into LocalTime.
689
+ * Uses LOOSE parsing.
690
+ * If invalid - doesn't throw, but returns undefined instead.
691
+ */
692
+ try(input) {
693
+ if (input instanceof LocalTime)
694
+ return input;
695
+ if (input instanceof Date) {
696
+ if (isNaN(input.getDate()))
697
+ return;
698
+ return new LocalTime(input);
699
+ }
700
+ if (typeof input === 'number') {
701
+ return this.fromUnix(input);
702
+ }
703
+ if (!input)
704
+ return;
705
+ const date = this.parseLooselyOrUndefined(input);
706
+ return date ? new LocalTime(date) : undefined;
707
+ }
708
+ /**
709
+ * Performs STRICT parsing.
710
+ * Only allows IsoDateTimeString or IsoDateString input, nothing else.
711
+ */
712
+ // eslint-disable-next-line @typescript-eslint/no-duplicate-type-constituents
713
+ fromIsoDateTimeString(s) {
714
+ const d = this.parseStrictlyOrUndefined(s);
715
+ (0, assert_1._assert)(d, `Cannot parse "${s}" into LocalTime`);
716
+ return new LocalTime(d);
717
+ }
718
+ /**
719
+ * Performs LOOSE parsing.
720
+ * Tries to coerce imprefect/incorrect string input into IsoDateTimeString.
721
+ * Use with caution.
722
+ * Allows to input IsoDateString, will set h:m:s to zeros.
723
+ */
724
+ parse(s) {
725
+ const d = this.parseLooselyOrUndefined(String(s));
726
+ (0, assert_1._assert)(d, `Cannot parse "${s}" into LocalTime`);
727
+ return new LocalTime(d);
728
+ }
729
+ parseStrictlyOrUndefined(s) {
730
+ if (!s || typeof s !== 'string')
731
+ return;
732
+ let m = DATE_TIME_REGEX_STRICT.exec(s);
733
+ if (!m) {
734
+ // DateTime regex didn't match, try just-Date regex
735
+ m = DATE_REGEX_STRICT.exec(s);
736
+ if (!m)
737
+ return;
738
+ }
739
+ const o = {
740
+ year: Number(m[1]),
741
+ month: Number(m[2]),
742
+ day: Number(m[3]),
743
+ hour: Number(m[4]) || 0,
744
+ minute: Number(m[5]) || 0,
745
+ second: Number(m[6]) || 0,
746
+ };
747
+ if (!this.isDateTimeObjectValid(o))
748
+ return;
749
+ return this.createDateFromDateTimeObject(o);
750
+ }
751
+ parseLooselyOrUndefined(s) {
752
+ if (!s || typeof s !== 'string')
753
+ return;
754
+ const m = DATE_TIME_REGEX_LOOSE.exec(s);
755
+ if (!m) {
756
+ if (s.length < 8)
757
+ return;
758
+ // Attempt to parse with Date constructor
759
+ const d = new Date(s);
760
+ return isNaN(d.getDate()) ? undefined : d;
761
+ }
762
+ const o = {
763
+ year: Number(m[1]),
764
+ month: Number(m[2]),
765
+ day: Number(m[3]) || 1,
766
+ // [4] is skipped due to extra regex parentheses group
767
+ hour: Number(m[5]) || 0,
768
+ minute: Number(m[6]) || 0,
769
+ second: Number(m[7]) || 0,
770
+ };
771
+ if (!this.isDateTimeObjectValid(o))
772
+ return;
773
+ return this.createDateFromDateTimeObject(o);
774
+ }
775
+ /**
776
+ * Throws on invalid value.
777
+ */
778
+ validateDateTimeObject(o) {
779
+ (0, assert_1._assert)(this.isDateTimeObjectValid(o), `Cannot construct LocalTime from: ${o.year}-${o.month}-${o.day} ${o.hour}:${o.minute}:${o.second}`);
780
+ }
781
+ isDateTimeObjectValid(o) {
782
+ return localDate_1.localDate.isDateObjectValid(o) && this.isTimeObjectValid(o);
783
+ }
784
+ isTimeObjectValid({ hour, minute, second }) {
785
+ return hour >= 0 && hour <= 23 && minute >= 0 && minute <= 59 && second >= 0 && second <= 59;
786
+ }
787
+ fromDate(date) {
788
+ (0, assert_1._assert)(!isNaN(date.getDate()), `localTime.fromDate is called on Date object that is invalid`);
789
+ return new LocalTime(date);
790
+ }
791
+ fromUnix(ts) {
792
+ return new LocalTime(new Date(ts * 1000));
793
+ }
794
+ /**
795
+ * Create LocalTime from unixTimestamp in milliseconds (not in seconds).
796
+ */
797
+ fromMillis(millis) {
798
+ return new LocalTime(new Date(millis));
723
799
  }
800
+ fromDateTimeObject(o) {
801
+ // todo: validate?
802
+ return new LocalTime(this.createDateFromDateTimeObject(o));
803
+ }
804
+ createDateFromDateTimeObject(o) {
805
+ return new Date(o.year, o.month - 1, o.day || 1, o.hour || 0, o.minute || 0, o.second || 0);
806
+ }
807
+ // private assertNotNull(
808
+ // lt: LocalTime | null,
809
+ // input: LocalTimeInputNullable,
810
+ // ): asserts lt is LocalTime {
811
+ // _assert(lt !== null, `Cannot parse "${input}" into LocalTime`, {
812
+ // input,
813
+ // })
814
+ // }
724
815
  /**
725
816
  * Returns the IANA timezone e.g `Europe/Stockholm`.
726
817
  * https://en.wikipedia.org/wiki/List_of_tz_database_time_zones
@@ -738,23 +829,6 @@ class LocalTimeFactory {
738
829
  isTimezoneValid(tz) {
739
830
  return Intl.supportedValuesOf('timeZone').includes(tz);
740
831
  }
741
- now() {
742
- return new LocalTime(new Date());
743
- }
744
- /**
745
- * Creates a LocalTime from the input, unless it's falsy - then returns undefined.
746
- *
747
- * `localTime` function will instead return LocalTime of `now` for falsy input.
748
- */
749
- orUndefined(input) {
750
- return input || input === 0 ? this.from(input) : undefined;
751
- }
752
- /**
753
- * Creates a LocalTime from the input, unless it's falsy - then returns LocalTime.now
754
- */
755
- orNow(input) {
756
- return input || input === 0 ? this.from(input) : this.now();
757
- }
758
832
  sort(items, dir = 'asc', mutate = false) {
759
833
  const mod = dir === 'desc' ? -1 : 1;
760
834
  return (mutate ? items : [...items]).sort((a, b) => {
@@ -772,7 +846,7 @@ class LocalTimeFactory {
772
846
  const items2 = items.filter(is_util_1._isTruthy);
773
847
  (0, assert_1._assert)(items2.length, 'localTime.min called on empty array');
774
848
  return items2
775
- .map(i => this.from(i))
849
+ .map(i => this.fromInput(i))
776
850
  .reduce((min, item) => (min.$date.valueOf() <= item.$date.valueOf() ? min : item));
777
851
  }
778
852
  maxOrUndefined(items) {
@@ -782,7 +856,7 @@ class LocalTimeFactory {
782
856
  const items2 = items.filter(is_util_1._isTruthy);
783
857
  (0, assert_1._assert)(items2.length, 'localTime.max called on empty array');
784
858
  return items2
785
- .map(i => this.from(i))
859
+ .map(i => this.fromInput(i))
786
860
  .reduce((max, item) => (max.$date.valueOf() >= item.$date.valueOf() ? max : item));
787
861
  }
788
862
  }
@@ -875,14 +949,7 @@ function differenceInMonths(a, b) {
875
949
  return -(wholeMonthDiff + ((b.getTime() - anchor) / (anchor2 - anchor)) * sign);
876
950
  }
877
951
  const localTimeFactory = new LocalTimeFactory();
878
- exports.localTime = localTimeFactory.from.bind(localTimeFactory);
952
+ exports.localTime = localTimeFactory.fromInput.bind(localTimeFactory);
879
953
  // The line below is the blackest of black magic I have ever written in 2024.
880
954
  // And probably 2023 as well.
881
955
  Object.setPrototypeOf(exports.localTime, localTimeFactory);
882
- /**
883
- Convenience function to return current Unix timestamp in seconds.
884
- Like Date.now(), but in seconds.
885
- */
886
- function nowUnix() {
887
- return Math.floor(Date.now() / 1000);
888
- }
@@ -1,5 +1,5 @@
1
- import type { UnixTimestampNumber, Inclusiveness } from '../types';
2
- import { LocalTimeInput, LocalTime } from './localTime';
1
+ import type { Inclusiveness, UnixTimestampNumber } from '../types';
2
+ import { LocalTime, LocalTimeInput } from './localTime';
3
3
  export type TimeIntervalConfig = TimeInterval | TimeIntervalString;
4
4
  export type TimeIntervalString = string;
5
5
  /**
@@ -14,7 +14,7 @@ class TimeInterval {
14
14
  this.$end = $end;
15
15
  }
16
16
  static of(start, end) {
17
- return new TimeInterval(localTime_1.localTime.from(start).unix, localTime_1.localTime.from(end).unix);
17
+ return new TimeInterval(localTime_1.localTime.fromInput(start).unix, localTime_1.localTime.fromInput(end).unix);
18
18
  }
19
19
  get start() {
20
20
  return this.$start;
@@ -58,7 +58,7 @@ class TimeInterval {
58
58
  return this.cmp(d) >= 0;
59
59
  }
60
60
  includes(d, incl = '[)') {
61
- d = localTime_1.localTime.from(d).unix;
61
+ d = localTime_1.localTime.fromInput(d).unix;
62
62
  // eslint-disable-next-line @typescript-eslint/prefer-string-starts-ends-with
63
63
  if (d < this.$start || (d === this.$start && incl[0] === '('))
64
64
  return false;
@@ -1,4 +1,4 @@
1
- import type { ErrorData, ErrorObject, BackendErrorResponseObject, Class, HttpRequestErrorData, ErrorLike } from '..';
1
+ import type { BackendErrorResponseObject, Class, ErrorData, ErrorLike, ErrorObject, HttpRequestErrorData } from '..';
2
2
  /**
3
3
  * Useful to ensure that error in `catch (err) { ... }`
4
4
  * is indeed an Error (and not e.g `string` or `undefined`).