-
Notifications
You must be signed in to change notification settings - Fork 4
/
Copy pathindex.ts
656 lines (608 loc) · 19.3 KB
/
index.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
/*!
* Copyright 2019 Google Inc. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
const FULL_ISO_REG = /\d{4}-[01]\d-[0-3]\dT[0-2]\d:[0-5]\d:[0-5]\d\.\d{4,9}Z/;
const NO_BIG_INT =
'BigInt only available in Node >= v10.7. Consider using getFullTimeString instead.';
export type DateTuple = [number, number];
export interface DateStruct {
seconds: number;
nanos: number;
}
// https://github.com/Microsoft/TypeScript/issues/27920
type DateFields = [number, number, number, number, number, number, number];
interface Long {
toNumber(): number;
}
interface ProtobufDate {
seconds?: number | string | Long;
nanos?: number | string;
}
enum Sign {
NEGATIVE = -1,
POSITIVE = 1,
ZERO = 0,
}
/**
* The native Date object.
* @external Date
* @see {@link https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date}
*/
/**
* @typedef {array} DateTuple
* @property {number} 0 Represents seconds of UTC time since Unix epoch
* 1970-01-01T00:00:00Z. Must be from 0001-01-01T00:00:00Z to
* 9999-12-31T23:59:59Z inclusive.
* @property {number} 1 Non-negative fractions of a second at nanosecond
* resolution. Negative second values with fractions must still have
* non-negative nanos values that count forward in time. Must be from 0 to
* 999,999,999 inclusive.
*/
/**
* @typedef {object} DateStruct
* @property {number} seconds Represents seconds of UTC time since Unix epoch
* 1970-01-01T00:00:00Z. Must be from 0001-01-01T00:00:00Z to
* 9999-12-31T23:59:59Z inclusive.
* @property {number} nanos Non-negative fractions of a second at nanosecond
* resolution. Negative second values with fractions must still have
* non-negative nanos values that count forward in time. Must be from 0 to
* 999,999,999 inclusive.
*/
/**
* Date object with nanosecond precision. Supports all standard Date arguments
* in addition to several custom types as noted below.
*
* @class
* @extends external:Date
*
* @param {number|string|bigint|Date|DateTuple|DateStruct} [time] The time
* value.
* @param {...number} [dateFields] Additional date fields (month, date, hours,
* minutes, seconds, milliseconds, microseconds, nanoseconds).
*
* @example <caption>With a RFC 3339 formatted string.</caption>
* const date = new PreciseDate('2019-02-08T10:34:29.481145231Z');
*
* @example <caption>With a nanosecond timestamp string.</caption>
* const date = new PreciseDate('1549622069481320032');
*
* @example <caption>With a BigInt (requires Node >= v10.7)</caption>
* const date = new PreciseDate(1549622069481320032n);
*
* @example <caption>With a tuple containing seconds and nanoseconds.</caption>
* const date = new PreciseDate([1549622069, 481320032]);
*
* @example <caption>With an object containing `seconds` and `nanos`</caption>
* const date = new PreciseDate({seconds: 1549622069, nanos: 481320032});
*
* @example <caption>Specifiying date fields</caption>
* const date = new PreciseDate(2018, 5, 14, 41, 11, 34, 123, 874, 321);
*/
export class PreciseDate extends Date {
private _micros = 0;
private _nanos = 0;
constructor(time?: number | Date);
constructor(preciseTime: string | bigint | DateTuple | ProtobufDate);
constructor(
year: number,
month?: number,
date?: number,
hours?: number,
minutes?: number,
seconds?: number,
milliseconds?: number,
microseconds?: number,
nanoseconds?: number
);
constructor(
time?: number | string | bigint | Date | DateTuple | ProtobufDate
) {
super();
if (time && typeof time !== 'number' && !(time instanceof Date)) {
this.setFullTime(PreciseDate.parseFull(time));
return;
}
// eslint-disable-next-line prefer-rest-params
const args: number[] = Array.from(arguments);
const dateFields = args.slice(0, 7) as DateFields;
const date = new Date(...dateFields);
const nanos = args.length === 9 ? args.pop()! : 0;
const micros = args.length === 8 ? args.pop()! : 0;
this.setTime(date.getTime());
this.setMicroseconds(micros);
this.setNanoseconds(nanos);
}
/**
* Returns the specified date represented in nanoseconds according to
* universal time.
*
* **NOTE:** Because this method returns a `BigInt` it requires Node >= v10.7.
* Use {@link PreciseDate#getFullTimeString} to get the time as a string.
*
* @see {@link https://github.com/tc39/proposal-bigint|BigInt}
*
* @throws {error} If `BigInt` is unavailable.
* @returns {bigint}
*
* @example
* const date = new PreciseDate('2019-02-08T10:34:29.481145231Z');
*
* console.log(date.getFullTime());
* // expected output: 1549622069481145231n
*/
getFullTime(): bigint {
if (typeof BigInt !== 'function') {
throw new Error(NO_BIG_INT);
}
return BigInt(this.getFullTimeString());
}
/**
* Returns a string of the specified date represented in nanoseconds according
* to universal time.
*
* @returns {string}
*
* @example
* const date = new PreciseDate('2019-02-08T10:34:29.481145231Z');
*
* console.log(date.getFullTimeString());
* // expected output: "1549622069481145231"
*/
getFullTimeString(): string {
const seconds = this._getSeconds();
let nanos = this._getNanos();
if (nanos && Math.sign(seconds) === Sign.NEGATIVE) {
nanos = 1e9 - nanos;
}
return `${seconds}${padLeft(nanos, 9)}`;
}
/**
* Returns the microseconds in the specified date according to universal time.
*
* @returns {number}
*
* @example
* const date = new PreciseDate('2019-02-08T10:34:29.481145Z');
*
* console.log(date.getMicroseconds());
* // expected output: 145
*/
getMicroseconds(): number {
return this._micros;
}
/**
* Returns the nanoseconds in the specified date according to universal time.
*
* @returns {number}
*
* @example
* const date = new PreciseDate('2019-02-08T10:34:29.481145231Z');
*
* console.log(date.getNanoseconds());
* // expected output: 231
*/
getNanoseconds(): number {
return this._nanos;
}
/**
* Sets the microseconds for a specified date according to universal time.
*
* @param {number} microseconds A number representing the microseconds.
* @returns {string} Returns a string representing the nanoseconds in the
* specified date according to universal time.
*
* @example
* const date = new PreciseDate();
*
* date.setMicroseconds(149);
*
* console.log(date.getMicroseconds());
* // expected output: 149
*/
setMicroseconds(micros: number): string {
const abs = Math.abs(micros);
let millis = this.getUTCMilliseconds();
if (abs >= 1000) {
millis += Math.floor(abs / 1000) * Math.sign(micros);
micros %= 1000;
}
if (Math.sign(micros) === Sign.NEGATIVE) {
millis -= 1;
micros += 1000;
}
this._micros = micros;
this.setUTCMilliseconds(millis);
return this.getFullTimeString();
}
/**
* Sets the nanoseconds for a specified date according to universal time.
*
* @param {number} nanoseconds A number representing the nanoseconds.
* @returns {string} Returns a string representing the nanoseconds in the
* specified date according to universal time.
*
* @example
* const date = new PreciseDate();
*
* date.setNanoseconds(231);
*
* console.log(date.getNanoseconds());
* // expected output: 231
*/
setNanoseconds(nanos: number): string {
const abs = Math.abs(nanos);
let micros = this._micros;
if (abs >= 1000) {
micros += Math.floor(abs / 1000) * Math.sign(nanos);
nanos %= 1000;
}
if (Math.sign(nanos) === Sign.NEGATIVE) {
micros -= 1;
nanos += 1000;
}
this._nanos = nanos;
return this.setMicroseconds(micros);
}
/**
* Sets the PreciseDate object to the time represented by a number of
* nanoseconds since January 1, 1970, 00:00:00 UTC.
*
* @param {bigint|number|string} time Value representing the number of
* nanoseconds since January 1, 1970, 00:00:00 UTC.
* @returns {string} Returns a string representing the nanoseconds in the
* specified date according to universal time (effectively, the value of
* the argument).
*
* @see {@link https://github.com/tc39/proposal-bigint|BigInt}
*
* @example <caption>With a nanosecond string.</caption>
* const date = new PreciseDate();
* date.setFullTime('1549622069481145231');
*
* @example <caption>With a BigInt</caption>
* date.setFullTime(1549622069481145231n);
*/
setFullTime(time: string | number | bigint): string {
if (typeof time !== 'string') {
time = time.toString();
}
const sign = Math.sign(Number(time));
time = time.replace(/^-/, '');
const seconds = Number(time.substr(0, time.length - 9)) * sign;
const nanos = Number(time.substr(-9)) * sign;
this.setTime(seconds * 1000);
return this.setNanoseconds(nanos);
}
/**
* Sets the PreciseDate object to the time represented by a number of
* milliseconds since January 1, 1970, 00:00:00 UTC. Calling this method will
* reset both the microseconds and nanoseconds to 0.
*
* @see {@link https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/setTime|Date#setTime}
*
* @param {number} time Value representing the number of milliseconds since
* January 1, 1970, 00:00:00 UTC.
* @returns {string} The number of milliseconds between January 1, 1970,
* 00:00:00 UTC and the updated date (effectively, the value of the
* argument).
*/
setTime(time: number): number {
this._micros = 0;
this._nanos = 0;
return super.setTime(time);
}
/**
* Returns a string in RFC 3339 format. Unlike the native `Date#toISOString`,
* this will return 9 digits to represent sub-second precision.
*
* @see {@link https://tools.ietf.org/html/rfc3339|RFC 3339}
*
* @returns {string}
*
* @example
* const date = new PreciseDate(1549622069481145231n);
*
* console.log(date.toISOString());
* // expected output: "2019-02-08T10:34:29.481145231Z"
*/
toISOString(): string {
const micros = padLeft(this._micros, 3);
const nanos = padLeft(this._nanos, 3);
return super.toISOString().replace(/z$/i, `${micros}${nanos}Z`);
}
/**
* Returns an object representing the specified date according to universal
* time.
*
* @see {@link https://developers.google.com/protocol-buffers/docs/reference/google.protobuf#timestamp|google.protobuf.Timestamp}
*
* @returns {DateStruct}
*
* @example
* const date = new PreciseDate('2019-02-08T10:34:29.481145231Z');
*
* console.log(date.toStruct());
* // expected output: {seconds: 1549622069, nanos: 481145231}
*/
toStruct(): DateStruct {
let seconds = this._getSeconds();
const nanos = this._getNanos();
const sign = Math.sign(seconds);
// These objects are essentially a mirror of protobuf timestamps.
// `nanos` must always count forward in time, even if the date is <= Unix
// epoch. To do this we just need to count backwards 1 second and return the
// nanoseconds as is.
if (sign === Sign.NEGATIVE && nanos) {
seconds -= 1;
}
return {seconds, nanos};
}
/**
* Returns a tuple representing the specified date according to universal
* time.
*
* @returns {DateTuple}
*
* @example
* const date = new PreciseDate('2019-02-08T10:34:29.481145231Z');
*
* console.log(date.toTuple());
* // expected output: [1549622069, 481145231]
*/
toTuple(): DateTuple {
const {seconds, nanos} = this.toStruct();
return [seconds, nanos];
}
/**
* Returns the total number of seconds in the specified date since Unix epoch.
* Numbers representing < epoch will be negative.
*
* @private
*
* @returns {number}
*/
private _getSeconds(): number {
const time = this.getTime();
const sign = Math.sign(time);
return Math.floor(Math.abs(time) / 1000) * sign;
}
/**
* Returns the sub-second precision of the specified date. This will always be
* a positive number.
*
* @private
*
* @returns {number}
*/
private _getNanos(): number {
const msInNanos = this.getUTCMilliseconds() * 1e6;
const microsInNanos = this._micros * 1000;
return this._nanos + msInNanos + microsInNanos;
}
/**
* Parses a precise time.
*
* @static
*
* @param {string|bigint|DateTuple|DateStruct} time The precise time value.
* @returns {string} Returns a string representing the nanoseconds in the
* specified date according to universal time.
*
* @example <caption>From a RFC 3339 formatted string.</caption>
* const time = PreciseDate.parseFull('2019-02-08T10:34:29.481145231Z');
* console.log(time); // expected output: "1549622069481145231"
*
* @example <caption>From a nanosecond timestamp string.</caption>
* const time = PreciseDate.parseFull('1549622069481145231');
* console.log(time); // expected output: "1549622069481145231"
*
* @example <caption>From a BigInt (requires Node >= v10.7)</caption>
* const time = PreciseDate.parseFull(1549622069481145231n);
* console.log(time); // expected output: "1549622069481145231"
*
* @example <caption>From a tuple.</caption>
* const time = PreciseDate.parseFull([1549622069, 481145231]);
* console.log(time); // expected output: "1549622069481145231"
*
* @example <caption>From an object.</caption>
* const struct = {seconds: 1549622069, nanos: 481145231};
* const time = PreciseDate.parseFull(struct);
* console.log(time); // expected output: "1549622069481145231"
*/
static parseFull(time: string | bigint | DateTuple | ProtobufDate): string {
const date = new PreciseDate();
if (Array.isArray(time)) {
const [seconds, nanos] = time as DateTuple;
time = {seconds, nanos} as DateStruct;
}
if (isFullTime(time)) {
date.setFullTime(time as string | bigint);
} else if (isStruct(time)) {
const {seconds, nanos} = parseProto(time as ProtobufDate);
date.setTime(seconds * 1000);
date.setNanoseconds(nanos);
} else if (isFullISOString(time)) {
date.setFullTime(parseFullISO(time as string));
} else {
date.setTime(new Date(time as string).getTime());
}
return date.getFullTimeString();
}
/**
* Accepts the same number parameters as the PreciseDate constructor, but
* treats them as UTC. It returns a string that represents the number of
* nanoseconds since January 1, 1970, 00:00:00 UTC.
*
* **NOTE:** Because this method returns a `BigInt` it requires Node >= v10.7.
*
* @see {@link https://github.com/tc39/proposal-bigint|BigInt}
*
* @static
*
* @throws {error} If `BigInt` is unavailable.
*
* @param {...number} [dateFields] The date fields.
* @returns {bigint}
*
* @example
* const time = PreciseDate.fullUTC(2019, 1, 8, 10, 34, 29, 481, 145, 231);
* console.log(time); // expected output: 1549622069481145231n
*/
static fullUTC(...args: number[]): bigint {
if (typeof BigInt !== 'function') {
throw new Error(NO_BIG_INT);
}
return BigInt(PreciseDate.fullUTCString(...args));
}
/**
* Accepts the same number parameters as the PreciseDate constructor, but
* treats them as UTC. It returns a string that represents the number of
* nanoseconds since January 1, 1970, 00:00:00 UTC.
*
* @static
*
* @param {...number} [dateFields] The date fields.
* @returns {string}
*
* @example
* const time = PreciseDate.fullUTCString(2019, 1, 8, 10, 34, 29, 481, 145,
* 231); console.log(time); // expected output: '1549622069481145231'
*/
static fullUTCString(...args: number[]): string {
const milliseconds = Date.UTC(...(args.slice(0, 7) as DateFields));
const date = new PreciseDate(milliseconds);
if (args.length === 9) {
date.setNanoseconds(args.pop()!);
}
if (args.length === 8) {
date.setMicroseconds(args.pop()!);
}
return date.getFullTimeString();
}
}
/**
* Parses a RFC 3339 formatted string representation of the date, and returns
* a string representing the nanoseconds since January 1, 1970, 00:00:00.
*
* @private
*
* @param {string} time The RFC 3339 formatted string.
* @returns {string}
*/
function parseFullISO(time: string): string {
let digits = '0';
time = time.replace(/\.(\d+)/, ($0, $1) => {
digits = $1;
return '.000';
});
const nanos = Number(padRight(digits, 9));
const date = new PreciseDate(time);
return date.setNanoseconds(nanos);
}
/**
* Normalizes a {@link google.protobuf.Timestamp} object.
*
* @private
*
* @param {google.protobuf.Timestamp} timestamp The timestamp object.
* @returns {DateStruct}
*/
function parseProto({seconds = 0, nanos = 0}: ProtobufDate): DateStruct {
if (typeof (seconds as Long).toNumber === 'function') {
seconds = (seconds as Long).toNumber();
}
seconds = Number(seconds);
nanos = Number(nanos);
return {seconds, nanos};
}
/**
* Checks to see if time value is specified in nanoseconds. We assume that all
* BigInt and string timestamps represent nanoseconds.
*
* @private
*
* @param {*} time The time to check.
* @returns {boolean}
*/
function isFullTime(time: unknown): boolean {
return (
typeof time === 'bigint' || (typeof time === 'string' && /^\d+$/.test(time))
);
}
/**
* Checks to see if time value is a {@link DateStruct}.
*
* @private
*
* @param {*} time The time to check.
* @returns {boolean}
*/
function isStruct(time: unknown): time is DateStruct {
return (
(typeof time === 'object' &&
typeof (time as DateStruct).seconds !== 'undefined') ||
typeof (time as DateStruct).nanos === 'number'
);
}
/**
* Checks to see if the time value is a RFC 3339 formatted string.
*
* @private
*
* @param {*} time The time to check.
* @returns {boolean}
*/
function isFullISOString(time: unknown): boolean {
return typeof time === 'string' && FULL_ISO_REG.test(time);
}
/**
* Pads a number/string with "0" to the left.
*
* @private
*
* @param {string|number} n The number/string to pad.
* @param {number} min The min size of the padded string.
* @returns {string}
*/
function padLeft(n: number | string, min: number): string {
const padding = getPadding(n, min);
return `${padding}${n}`;
}
/**
* Pads a number/string with "0" to the right.
*
* @private
*
* @param {string|number} n The number/string to pad.
* @param {number} min The min size of the padded string.
* @returns {string}
*/
function padRight(n: number | string, min: number): string {
const padding = getPadding(n, min);
return `${n}${padding}`;
}
/**
* Creates padding based on current size and min size needed.
*
* @private
*
* @param {string|number} n The number/string to pad.
* @param {number} [min=3] The min size of the padded string.
* @returns {string}
*/
function getPadding(n: number | string, min: number): string {
const size = Math.max(min - n.toString().length, 0);
return '0'.repeat(size);
}