@sapphire/time-utilities 1.7.6-next.fca7a80.0 → 1.7.6

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/CHANGELOG.md CHANGED
@@ -2,6 +2,19 @@
2
2
 
3
3
  All notable changes to this project will be documented in this file.
4
4
 
5
+ # [@sapphire/time-utilities@1.7.6](https://github.com/sapphiredev/utilities/compare/@sapphire/time-utilities@1.7.5...@sapphire/time-utilities@1.7.6) - (2022-08-20)
6
+
7
+ ## 🐛 Bug Fixes
8
+
9
+ - **deps:** Update all non-major dependencies ([2308bd7](https://github.com/sapphiredev/utilities/commit/2308bd74356b6b2e0c12995b25f4d8ade4803fe9))
10
+
11
+ ## 📝 Documentation
12
+
13
+ - Fixed typos (#427) ([e840a97](https://github.com/sapphiredev/utilities/commit/e840a9795583b59ee3da9ffe0d325e0a3cfa0c14))
14
+ - Add @muchnameless as a contributor ([a1221fe](https://github.com/sapphiredev/utilities/commit/a1221fea68506e99591d5d00ec552a07c26833f9))
15
+ - Add @enxg as a contributor ([d2382f0](https://github.com/sapphiredev/utilities/commit/d2382f04e3909cb4ad11798a0a10e683f6cf5383))
16
+ - Add @EvolutionX-10 as a contributor ([efc3a32](https://github.com/sapphiredev/utilities/commit/efc3a320a72ae258996dd62866d206c33f8d4961))
17
+
5
18
  # [@sapphire/time-utilities@1.7.5](https://github.com/sapphiredev/utilities/compare/@sapphire/time-utilities@1.7.4...@sapphire/time-utilities@1.7.5) - (2022-07-13)
6
19
 
7
20
  ## 🏠 Refactor
package/dist/index.d.ts CHANGED
@@ -1,7 +1,261 @@
1
- export { Time, TimeTypes } from './lib/constants';
2
- export * from './lib/Cron';
3
- export * from './lib/Duration';
4
- export * from './lib/DurationFormatter';
5
- export * from './lib/TimerManager';
6
- export * from './lib/Timestamp';
7
- //# sourceMappingURL=index.d.ts.map
1
+ /**
2
+ * Display the duration
3
+ * @param duration The duration in milliseconds to parse and display
4
+ * @param assets The language assets
5
+ */
6
+ declare class DurationFormatter {
7
+ units: DurationFormatAssetsTime;
8
+ constructor(units?: DurationFormatAssetsTime);
9
+ format(duration: number, precision?: number, { left: leftSeparator, right: rightSeparator }?: DurationFormatSeparators): string;
10
+ }
11
+ interface DurationFormatSeparators {
12
+ left?: string;
13
+ right?: string;
14
+ }
15
+ interface DurationFormatAssetsUnit extends Record<number, string> {
16
+ DEFAULT: string;
17
+ }
18
+ interface DurationFormatAssetsTime {
19
+ [TimeTypes.Second]: DurationFormatAssetsUnit;
20
+ [TimeTypes.Minute]: DurationFormatAssetsUnit;
21
+ [TimeTypes.Hour]: DurationFormatAssetsUnit;
22
+ [TimeTypes.Day]: DurationFormatAssetsUnit;
23
+ [TimeTypes.Week]: DurationFormatAssetsUnit;
24
+ [TimeTypes.Month]: DurationFormatAssetsUnit;
25
+ [TimeTypes.Year]: DurationFormatAssetsUnit;
26
+ }
27
+
28
+ /**
29
+ * The supported time types
30
+ */
31
+ declare enum TimeTypes {
32
+ Second = "second",
33
+ Minute = "minute",
34
+ Hour = "hour",
35
+ Day = "day",
36
+ Week = "week",
37
+ Month = "month",
38
+ Year = "year"
39
+ }
40
+ declare enum Time {
41
+ Millisecond = 1,
42
+ Second = 1000,
43
+ Minute = 60000,
44
+ Hour = 3600000,
45
+ Day = 86400000,
46
+ Month = 2628000000,
47
+ Year = 31536000000
48
+ }
49
+
50
+ /**
51
+ * Handles Cron strings and generates dates based on the cron string provided.
52
+ * @see https://en.wikipedia.org/wiki/Cron
53
+ */
54
+ declare class Cron {
55
+ cron: string;
56
+ normalized: string;
57
+ minutes: number[];
58
+ hours: number[];
59
+ days: number[];
60
+ months: number[];
61
+ dows: number[];
62
+ /**
63
+ * @param cron The cron pattern to use
64
+ */
65
+ constructor(cron: string);
66
+ /**
67
+ * Get the next date that matches with the current pattern
68
+ * @param outset The Date instance to compare with
69
+ * @param origin Whether this next call is origin
70
+ */
71
+ next(outset?: Date, origin?: boolean): Date;
72
+ /**
73
+ * Normalize the pattern
74
+ * @param cron The pattern to normalize
75
+ */
76
+ private static normalize;
77
+ /**
78
+ * Parse the pattern
79
+ * @param cron The pattern to parse
80
+ */
81
+ private static parseString;
82
+ /**
83
+ * Parse the current part
84
+ * @param cronPart The part of the pattern to parse
85
+ * @param id The id that identifies the current part
86
+ */
87
+ private static parsePart;
88
+ }
89
+
90
+ /**
91
+ * Converts duration strings into ms and future dates
92
+ */
93
+ declare class Duration {
94
+ /**
95
+ * The offset
96
+ */
97
+ offset: number;
98
+ /**
99
+ * Create a new Duration instance
100
+ * @param pattern The string to parse
101
+ */
102
+ constructor(pattern: string);
103
+ /**
104
+ * Get the date from now
105
+ */
106
+ get fromNow(): Date;
107
+ /**
108
+ * Get the date from
109
+ * @param date The Date instance to get the date from
110
+ */
111
+ dateFrom(date: Date): Date;
112
+ /**
113
+ * The RegExp used for the pattern parsing
114
+ */
115
+ private static readonly kPatternRegex;
116
+ /**
117
+ * The RegExp used for removing commas
118
+ */
119
+ private static readonly kCommaRegex;
120
+ /**
121
+ * The RegExp used for replacing a/an with 1
122
+ */
123
+ private static readonly kAanRegex;
124
+ /**
125
+ * Parse the pattern
126
+ * @param pattern The pattern to parse
127
+ */
128
+ private static parse;
129
+ }
130
+
131
+ /**
132
+ * Manages timers so that this application can be cleanly exited
133
+ */
134
+ declare class TimerManager extends null {
135
+ /**
136
+ * A set of timeouts to clear on destroy
137
+ */
138
+ private static storedTimeouts;
139
+ /**
140
+ * A set of intervals to clear on destroy
141
+ */
142
+ private static storedIntervals;
143
+ /**
144
+ * Creates a timeout gets cleared when destroyed
145
+ * @param fn callback function
146
+ * @param delay amount of time before running the callback
147
+ * @param args additional arguments to pass back to the callback
148
+ */
149
+ static setTimeout<A = unknown>(fn: (...args: A[]) => void, delay: number, ...args: A[]): NodeJS.Timeout;
150
+ /**
151
+ * Clears a timeout created through this class
152
+ * @param timeout The timeout to clear
153
+ */
154
+ static clearTimeout(timeout: NodeJS.Timeout): void;
155
+ /**
156
+ * Creates an interval gets cleared when destroyed
157
+ * @param fn callback function
158
+ * @param delay amount of time before running the callback
159
+ * @param args additional arguments to pass back to the callback
160
+ */
161
+ static setInterval<A = unknown>(fn: (...args: A[]) => void, delay: number, ...args: A[]): NodeJS.Timeout;
162
+ /**
163
+ * Clears an internal created through this class
164
+ * @param interval The interval to clear
165
+ */
166
+ static clearInterval(interval: NodeJS.Timeout): void;
167
+ /**
168
+ * Clears running timeouts and intervals created through this class so NodeJS can gracefully exit
169
+ */
170
+ static destroy(): void;
171
+ }
172
+
173
+ declare type TimeResolvable = Date | number | string;
174
+ interface TimestampTemplateEntry {
175
+ type: string;
176
+ content: string | null;
177
+ }
178
+ /**
179
+ * Timestamp class, parses the pattern once, displays the desired Date or UNIX timestamp with the selected pattern.
180
+ */
181
+ declare class Timestamp {
182
+ /**
183
+ * The raw pattern
184
+ * @since 1.0.0
185
+ */
186
+ pattern: string;
187
+ /**
188
+ * @since 1.0.0
189
+ */
190
+ private template;
191
+ /**
192
+ * Starts a new Timestamp and parses the pattern.
193
+ * @since 1.0.0
194
+ * @param pattern The pattern to parse
195
+ */
196
+ constructor(pattern: string);
197
+ /**
198
+ * Display the current date with the current pattern.
199
+ * @since 1.0.0
200
+ * @param time The time to display
201
+ */
202
+ display(time?: TimeResolvable): string;
203
+ /**
204
+ * Display the current date utc with the current pattern.
205
+ * @since 1.0.0
206
+ * @param time The time to display in utc
207
+ */
208
+ displayUTC(time?: TimeResolvable): string;
209
+ /**
210
+ * Edits the current pattern.
211
+ * @since 1.0.0
212
+ * @param pattern The new pattern for this instance
213
+ * @chainable
214
+ */
215
+ edit(pattern: string): this;
216
+ /**
217
+ * Defines the toString behavior of Timestamp.
218
+ */
219
+ toString(): string;
220
+ /**
221
+ * Display the current date with the current pattern.
222
+ * @since 1.0.0
223
+ * @param pattern The pattern to parse
224
+ * @param time The time to display
225
+ */
226
+ static displayArbitrary(pattern: string, time?: TimeResolvable): string;
227
+ /**
228
+ * Display the current date utc with the current pattern.
229
+ * @since 1.0.0
230
+ * @param pattern The pattern to parse
231
+ * @param time The time to display
232
+ */
233
+ static displayUTCArbitrary(pattern: string, time?: TimeResolvable): string;
234
+ /**
235
+ * Creates a UTC Date object to work with.
236
+ * @since 1.0.0
237
+ * @param time The date to convert to utc
238
+ */
239
+ static utc(time?: Date | number | string): Date;
240
+ /**
241
+ * Display the current date with the current pattern.
242
+ * @since 1.0.0
243
+ * @param template The pattern to parse
244
+ * @param time The time to display
245
+ */
246
+ private static display;
247
+ /**
248
+ * Parses the pattern.
249
+ * @since 1.0.0
250
+ * @param pattern The pattern to parse
251
+ */
252
+ private static parse;
253
+ /**
254
+ * Resolves a date.
255
+ * @since 1.0.0
256
+ * @param time The time to parse
257
+ */
258
+ private static resolveDate;
259
+ }
260
+
261
+ export { Cron, Duration, DurationFormatAssetsTime, DurationFormatAssetsUnit, DurationFormatSeparators, DurationFormatter, Time, TimeResolvable, TimeTypes, TimerManager, Timestamp, TimestampTemplateEntry };
@@ -411,40 +411,55 @@ ${expression || zws}\`\`\``;
411
411
  }
412
412
  __name(filterNullAndUndefinedAndZero, "filterNullAndUndefinedAndZero");
413
413
  __name2(filterNullAndUndefinedAndZero, "filterNullAndUndefinedAndZero");
414
- function isObject(input, constructorType) {
415
- return typeof input === "object" && input ? input.constructor === (constructorType != null ? constructorType : Object) : false;
414
+ function getDeepObjectKeys(obj, options) {
415
+ return [...getDeepObjectKeysGenerator(obj, options)];
416
416
  }
417
- __name(isObject, "isObject");
418
- __name2(isObject, "isObject");
419
- function getDeepObjectKeys(obj, { arrayKeysIndexStyle = "dotted" } = { arrayKeysIndexStyle: "dotted" }) {
420
- const keys = [];
421
- for (const [key, value] of Object.entries(obj)) {
422
- if (Array.isArray(value)) {
423
- for (const [index, innerValue] of value.entries()) {
424
- const arraySubKeys = getDeepObjectKeys(innerValue);
425
- keys.push(...arraySubKeys.map((arraySubKey) => {
426
- switch (arrayKeysIndexStyle) {
427
- case "braces-with-dot":
428
- return `${key}[${index}].${arraySubKey}`;
429
- case "braces":
430
- return `${key}[${index}]${arraySubKey}`;
431
- case "dotted":
432
- default:
433
- return `${key}.${index}.${arraySubKey}`;
434
- }
435
- }));
436
- }
437
- } else if (isObject(value)) {
438
- const objectSubKeys = getDeepObjectKeys(value);
439
- keys.push(...objectSubKeys.map((subKey) => `${key}.${subKey}`));
417
+ __name(getDeepObjectKeys, "getDeepObjectKeys");
418
+ __name2(getDeepObjectKeys, "getDeepObjectKeys");
419
+ function* getDeepObjectKeysGenerator(obj, { arrayKeysIndexStyle = "dotted" } = { arrayKeysIndexStyle: "dotted" }) {
420
+ if (Array.isArray(obj)) {
421
+ for (const [index, value] of obj.entries()) {
422
+ yield* getDeepArrayKeysRecursive(value, index, { arrayKeysIndexStyle });
423
+ }
424
+ } else {
425
+ for (const [key, value] of Object.entries(obj)) {
426
+ yield* getDeepObjectKeysRecursive(value, `${key}`, { arrayKeysIndexStyle });
427
+ }
428
+ }
429
+ }
430
+ __name(getDeepObjectKeysGenerator, "getDeepObjectKeysGenerator");
431
+ __name2(getDeepObjectKeysGenerator, "getDeepObjectKeysGenerator");
432
+ function* getDeepArrayKeysRecursive(value, index, { arrayKeysIndexStyle }) {
433
+ const resolvedIndex = arrayKeysIndexStyle === "dotted" ? `${index}` : arrayKeysIndexStyle === "braces" ? `[${index}]` : `[${index}].`;
434
+ yield* getDeepObjectKeysRecursive(value, resolvedIndex, { arrayKeysIndexStyle });
435
+ }
436
+ __name(getDeepArrayKeysRecursive, "getDeepArrayKeysRecursive");
437
+ __name2(getDeepArrayKeysRecursive, "getDeepArrayKeysRecursive");
438
+ function* getDeepObjectKeysRecursive(obj, prefix, { arrayKeysIndexStyle }) {
439
+ if (typeof obj !== "object" || obj === null) {
440
+ yield prefix;
441
+ return;
442
+ }
443
+ if (Array.isArray(obj)) {
444
+ for (const [index, value] of obj.entries()) {
445
+ const resolvedPrefixedIndex = arrayKeysIndexStyle === "dotted" ? `${prefix}.${index}` : `${prefix}[${index}]`;
446
+ yield* getDeepObjectKeysRecursive(value, resolvedPrefixedIndex, { arrayKeysIndexStyle });
447
+ }
448
+ } else {
449
+ const objectEntries = Object.entries(obj);
450
+ if (isNullOrUndefinedOrEmpty(objectEntries) && prefix) {
451
+ yield prefix;
440
452
  } else {
441
- keys.push(key);
453
+ for (const [key, value] of objectEntries) {
454
+ yield* getDeepObjectKeysRecursive(value, arrayKeysIndexStyle === "braces" ? `${prefix}${key}` : `${prefix}.${key}`, {
455
+ arrayKeysIndexStyle
456
+ });
457
+ }
442
458
  }
443
459
  }
444
- return keys;
445
460
  }
446
- __name(getDeepObjectKeys, "getDeepObjectKeys");
447
- __name2(getDeepObjectKeys, "getDeepObjectKeys");
461
+ __name(getDeepObjectKeysRecursive, "getDeepObjectKeysRecursive");
462
+ __name2(getDeepObjectKeysRecursive, "getDeepObjectKeysRecursive");
448
463
  function hasAtLeastOneKeyInMap(map, keys) {
449
464
  return keys.some((key) => map.has(key));
450
465
  }
@@ -471,6 +486,11 @@ ${expression || zws}\`\`\``;
471
486
  }
472
487
  __name(isNumber, "isNumber");
473
488
  __name2(isNumber, "isNumber");
489
+ function isObject(input, constructorType) {
490
+ return typeof input === "object" && input ? input.constructor === (constructorType != null ? constructorType : Object) : false;
491
+ }
492
+ __name(isObject, "isObject");
493
+ __name2(isObject, "isObject");
474
494
  function hasThen(input) {
475
495
  return Reflect.has(input, "then") && isFunction(input.then);
476
496
  }
@@ -619,12 +639,18 @@ ${expression || zws}\`\`\``;
619
639
  const { additionalVariants = {}, caseSensitive } = options;
620
640
  const titleCaseVariants = {
621
641
  ...baseVariants,
622
- ...caseSensitive ? additionalVariants : Object.entries(additionalVariants).reduce((variants, [key, variant]) => ({ ...variants, [key.toLowerCase()]: variant }), {})
642
+ ...caseSensitive ? additionalVariants : Object.entries(additionalVariants).reduce(
643
+ (variants, [key, variant]) => ({ ...variants, [key.toLowerCase()]: variant }),
644
+ {}
645
+ )
623
646
  };
624
- return str.replace(TO_TITLE_CASE, (txt) => {
625
- var _a;
626
- return (_a = titleCaseVariants[caseSensitive ? txt : txt.toLowerCase()]) != null ? _a : txt.charAt(0).toUpperCase() + txt.substring(1).toLowerCase();
627
- });
647
+ return str.replace(
648
+ TO_TITLE_CASE,
649
+ (txt) => {
650
+ var _a;
651
+ return (_a = titleCaseVariants[caseSensitive ? txt : txt.toLowerCase()]) != null ? _a : txt.charAt(0).toUpperCase() + txt.substring(1).toLowerCase();
652
+ }
653
+ );
628
654
  }
629
655
  __name(toTitleCase, "toTitleCase");
630
656
  __name2(toTitleCase, "toTitleCase");
@@ -674,25 +700,27 @@ ${expression || zws}\`\`\``;
674
700
  if (Reflect.has(predefined, cron))
675
701
  return Reflect.get(predefined, cron);
676
702
  const now = new Date();
677
- cron = cron.split(" ").map((val, i) => val.replace(wildcardRegex, (match) => {
678
- if (match === "h")
679
- return (Math.floor(Math.random() * allowedNum[i][1]) + allowedNum[i][0]).toString();
680
- if (match === "?") {
681
- switch (i) {
682
- case 0:
683
- return now.getUTCMinutes().toString();
684
- case 1:
685
- return now.getUTCHours().toString();
686
- case 2:
687
- return now.getUTCDate().toString();
688
- case 3:
689
- return now.getUTCMonth().toString();
690
- case 4:
691
- return now.getUTCDay().toString();
703
+ cron = cron.split(" ").map(
704
+ (val, i) => val.replace(wildcardRegex, (match) => {
705
+ if (match === "h")
706
+ return (Math.floor(Math.random() * allowedNum[i][1]) + allowedNum[i][0]).toString();
707
+ if (match === "?") {
708
+ switch (i) {
709
+ case 0:
710
+ return now.getUTCMinutes().toString();
711
+ case 1:
712
+ return now.getUTCHours().toString();
713
+ case 2:
714
+ return now.getUTCDate().toString();
715
+ case 3:
716
+ return now.getUTCMonth().toString();
717
+ case 4:
718
+ return now.getUTCDay().toString();
719
+ }
692
720
  }
693
- }
694
- return match;
695
- })).join(" ");
721
+ return match;
722
+ })
723
+ ).join(" ");
696
724
  return cron.replace(tokensRegex, (match) => String(Reflect.get(cronTokens, match)));
697
725
  }
698
726
  static parseString(cron) {
@@ -815,10 +843,10 @@ ${expression || zws}\`\`\``;
815
843
  if (negative)
816
844
  duration *= -1;
817
845
  for (const [type, timeDuration] of kTimeDurations) {
818
- const substraction = duration / timeDuration;
819
- if (substraction < 1)
846
+ const division = duration / timeDuration;
847
+ if (division < 1)
820
848
  continue;
821
- const floored = Math.floor(substraction);
849
+ const floored = Math.floor(division);
822
850
  duration -= floored * timeDuration;
823
851
  output.push(addUnit(floored, this.units[type], leftSeparator));
824
852
  if (output.length >= precision)
@@ -928,19 +956,27 @@ ${expression || zws}\`\`\``;
928
956
  ["ll", (time) => `${months[time.getMonth()].slice(0, 3)} ${String(time.getDate()).padStart(2, "0")}, ${String(time.getFullYear())}`],
929
957
  [
930
958
  "LLL",
931
- (time) => `${months[time.getMonth()]} ${String(time.getDate()).padStart(2, "0")}, ${String(time.getFullYear())} ${String(time.getHours() % 12 || 12)}:${String(time.getMinutes()).padStart(2, "0")} ${time.getHours() < 12 ? "AM" : "PM"}`
959
+ (time) => `${months[time.getMonth()]} ${String(time.getDate()).padStart(2, "0")}, ${String(time.getFullYear())} ${String(
960
+ time.getHours() % 12 || 12
961
+ )}:${String(time.getMinutes()).padStart(2, "0")} ${time.getHours() < 12 ? "AM" : "PM"}`
932
962
  ],
933
963
  [
934
964
  "lll",
935
- (time) => `${months[time.getMonth()].slice(0, 3)} ${String(time.getDate()).padStart(2, "0")}, ${String(time.getFullYear())} ${String(time.getHours() % 12 || 12)}:${String(time.getMinutes()).padStart(2, "0")} ${time.getHours() < 12 ? "AM" : "PM"}`
965
+ (time) => `${months[time.getMonth()].slice(0, 3)} ${String(time.getDate()).padStart(2, "0")}, ${String(time.getFullYear())} ${String(
966
+ time.getHours() % 12 || 12
967
+ )}:${String(time.getMinutes()).padStart(2, "0")} ${time.getHours() < 12 ? "AM" : "PM"}`
936
968
  ],
937
969
  [
938
970
  "LLLL",
939
- (time) => `${days[time.getDay()]}, ${months[time.getMonth()]} ${String(time.getDate()).padStart(2, "0")}, ${String(time.getFullYear())} ${String(time.getHours() % 12 || 12)}:${String(time.getMinutes()).padStart(2, "0")} ${time.getHours() < 12 ? "AM" : "PM"}`
971
+ (time) => `${days[time.getDay()]}, ${months[time.getMonth()]} ${String(time.getDate()).padStart(2, "0")}, ${String(time.getFullYear())} ${String(
972
+ time.getHours() % 12 || 12
973
+ )}:${String(time.getMinutes()).padStart(2, "0")} ${time.getHours() < 12 ? "AM" : "PM"}`
940
974
  ],
941
975
  [
942
976
  "llll",
943
- (time) => `${days[time.getDay()].slice(0, 3)} ${months[time.getMonth()].slice(0, 3)} ${String(time.getDate()).padStart(2, "0")}, ${String(time.getFullYear())} ${String(time.getHours() % 12 || 12)}:${String(time.getMinutes()).padStart(2, "0")} ${time.getHours() < 12 ? "AM" : "PM"}`
977
+ (time) => `${days[time.getDay()].slice(0, 3)} ${months[time.getMonth()].slice(0, 3)} ${String(time.getDate()).padStart(2, "0")}, ${String(
978
+ time.getFullYear()
979
+ )} ${String(time.getHours() % 12 || 12)}:${String(time.getMinutes()).padStart(2, "0")} ${time.getHours() < 12 ? "AM" : "PM"}`
944
980
  ],
945
981
  [
946
982
  "Z",