1 | "use strict";
|
---|
2 | Object.defineProperty(exports, "__esModule", { value: true });
|
---|
3 | exports.updateV7State = updateV7State;
|
---|
4 | const rng_js_1 = require("./rng.js");
|
---|
5 | const stringify_js_1 = require("./stringify.js");
|
---|
6 | const _state = {};
|
---|
7 | function v7(options, buf, offset) {
|
---|
8 | let bytes;
|
---|
9 | if (options) {
|
---|
10 | bytes = v7Bytes(options.random ?? options.rng?.() ?? (0, rng_js_1.default)(), options.msecs, options.seq, buf, offset);
|
---|
11 | }
|
---|
12 | else {
|
---|
13 | const now = Date.now();
|
---|
14 | const rnds = (0, rng_js_1.default)();
|
---|
15 | updateV7State(_state, now, rnds);
|
---|
16 | bytes = v7Bytes(rnds, _state.msecs, _state.seq, buf, offset);
|
---|
17 | }
|
---|
18 | return buf ? bytes : (0, stringify_js_1.unsafeStringify)(bytes);
|
---|
19 | }
|
---|
20 | function updateV7State(state, now, rnds) {
|
---|
21 | state.msecs ??= -Infinity;
|
---|
22 | state.seq ??= 0;
|
---|
23 | if (now > state.msecs) {
|
---|
24 | state.seq = (rnds[6] << 23) | (rnds[7] << 16) | (rnds[8] << 8) | rnds[9];
|
---|
25 | state.msecs = now;
|
---|
26 | }
|
---|
27 | else {
|
---|
28 | state.seq = (state.seq + 1) | 0;
|
---|
29 | if (state.seq === 0) {
|
---|
30 | state.msecs++;
|
---|
31 | }
|
---|
32 | }
|
---|
33 | return state;
|
---|
34 | }
|
---|
35 | function v7Bytes(rnds, msecs, seq, buf, offset = 0) {
|
---|
36 | if (!buf) {
|
---|
37 | buf = new Uint8Array(16);
|
---|
38 | offset = 0;
|
---|
39 | }
|
---|
40 | msecs ??= Date.now();
|
---|
41 | seq ??= ((rnds[6] * 0x7f) << 24) | (rnds[7] << 16) | (rnds[8] << 8) | rnds[9];
|
---|
42 | buf[offset++] = (msecs / 0x10000000000) & 0xff;
|
---|
43 | buf[offset++] = (msecs / 0x100000000) & 0xff;
|
---|
44 | buf[offset++] = (msecs / 0x1000000) & 0xff;
|
---|
45 | buf[offset++] = (msecs / 0x10000) & 0xff;
|
---|
46 | buf[offset++] = (msecs / 0x100) & 0xff;
|
---|
47 | buf[offset++] = msecs & 0xff;
|
---|
48 | buf[offset++] = 0x70 | ((seq >>> 28) & 0x0f);
|
---|
49 | buf[offset++] = (seq >>> 20) & 0xff;
|
---|
50 | buf[offset++] = 0x80 | ((seq >>> 14) & 0x3f);
|
---|
51 | buf[offset++] = (seq >>> 6) & 0xff;
|
---|
52 | buf[offset++] = ((seq << 2) & 0xff) | (rnds[10] & 0x03);
|
---|
53 | buf[offset++] = rnds[11];
|
---|
54 | buf[offset++] = rnds[12];
|
---|
55 | buf[offset++] = rnds[13];
|
---|
56 | buf[offset++] = rnds[14];
|
---|
57 | buf[offset++] = rnds[15];
|
---|
58 | return buf;
|
---|
59 | }
|
---|
60 | exports.default = v7;
|
---|