@andrew_l/snowflake 0.3.22 → 0.4.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.
- package/dist/index.d.mts +197 -192
- package/dist/index.d.mts.map +1 -0
- package/dist/index.mjs +200 -293
- package/dist/index.mjs.map +1 -1
- package/package.json +9 -8
- package/dist/index.cjs +0 -303
- package/dist/index.cjs.map +0 -1
- package/dist/index.d.cts +0 -231
- package/dist/index.d.ts +0 -231
package/dist/index.mjs
CHANGED
|
@@ -1,298 +1,205 @@
|
|
|
1
|
-
import {
|
|
2
|
-
|
|
1
|
+
import { assert, bigIntFromBytes, bitPack, bitUnpack, isBigInt, isDate, isNumber, isString, timestampMs } from "@andrew_l/toolkit";
|
|
3
2
|
var MAX_WORKER_ID = 31;
|
|
4
3
|
var MAX_PROCESS_ID = 31;
|
|
5
4
|
var MAX_INCREMENT = 4095;
|
|
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
|
-
buffer[7] = low32;
|
|
204
|
-
return buffer;
|
|
205
|
-
}
|
|
206
|
-
/**
|
|
207
|
-
* Generates a snowflake given an epoch and optionally a timestamp
|
|
208
|
-
* @example
|
|
209
|
-
* ```typescript
|
|
210
|
-
* const epoch = new Date('2000-01-01T00:00:00.000Z');
|
|
211
|
-
* const snowflake = new Snowflake({ epoch }).generate();
|
|
212
|
-
* ```
|
|
213
|
-
* @returns A unique snowflake as Uint8Array
|
|
214
|
-
*/
|
|
215
|
-
generateBuffer(timestamp = Date.now()) {
|
|
216
|
-
this.generateBufferUnsafe(timestamp);
|
|
217
|
-
return new Uint8Array(this._buffer);
|
|
218
|
-
}
|
|
219
|
-
/**
|
|
220
|
-
* Deconstructs a snowflake given a snowflake ID
|
|
221
|
-
* @param id the snowflake to deconstruct
|
|
222
|
-
* @returns a deconstructed snowflake
|
|
223
|
-
* @example
|
|
224
|
-
* ```typescript
|
|
225
|
-
* const epoch = new Date('2000-01-01T00:00:00.000Z');
|
|
226
|
-
* const snowflake = new Snowflake(epoch).deconstruct('3971046231244935168');
|
|
227
|
-
* ```
|
|
228
|
-
*/
|
|
229
|
-
deconstruct(id) {
|
|
230
|
-
var high32, low32;
|
|
231
|
-
if (id instanceof Uint8Array) {
|
|
232
|
-
high32 = (id[0] << 24 | id[1] << 16 | id[2] << 8 | id[3]) >>> 0;
|
|
233
|
-
low32 = (id[4] << 24 | id[5] << 16 | id[6] << 8 | id[7]) >>> 0;
|
|
234
|
-
} else if (isBigInt(id)) {
|
|
235
|
-
return this.deconstruct(bigIntBytes(id));
|
|
236
|
-
} else {
|
|
237
|
-
return this.deconstruct(bigIntBytes(BigInt(id)));
|
|
238
|
-
}
|
|
239
|
-
return {
|
|
240
|
-
id: BigInt(high32) * 0x100000000n + BigInt(low32),
|
|
241
|
-
timestamp: high32 * 1024 + (low32 >>> 22) + this._epoch,
|
|
242
|
-
workerId: low32 >>> 17 & MAX_WORKER_ID,
|
|
243
|
-
processId: low32 >>> 12 & MAX_PROCESS_ID,
|
|
244
|
-
increment: low32 & MAX_INCREMENT,
|
|
245
|
-
epoch: this._epoch
|
|
246
|
-
};
|
|
247
|
-
}
|
|
248
|
-
/**
|
|
249
|
-
* Retrieves the timestamp field's value from a snowflake.
|
|
250
|
-
* @param id The snowflake to get the timestamp value from.
|
|
251
|
-
* @returns The UNIX timestamp that is stored in `id`.
|
|
252
|
-
*/
|
|
253
|
-
timestampFrom(id) {
|
|
254
|
-
if (isString(id) || isBigInt(id)) {
|
|
255
|
-
return this.timestampFrom(Snowflake.bufferFrom(id));
|
|
256
|
-
}
|
|
257
|
-
var high32 = (id[0] << 24 | id[1] << 16 | id[2] << 8 | id[3]) >>> 0;
|
|
258
|
-
var low32 = (id[4] << 24 | id[5] << 16 | id[6] << 8 | id[7]) >>> 0;
|
|
259
|
-
return high32 * 1024 + (low32 >>> 22) + this._epoch;
|
|
260
|
-
}
|
|
261
|
-
/**
|
|
262
|
-
* Returns a number indicating whether a reference snowflake comes before, or after, or is same as the given
|
|
263
|
-
* snowflake in sort order.
|
|
264
|
-
* @param a The first snowflake to compare.
|
|
265
|
-
* @param b The second snowflake to compare.
|
|
266
|
-
* @returns `-1` if `a` is older than `b`, `0` if `a` and `b` are equals, `1` if `a` is newer than `b`.
|
|
267
|
-
*/
|
|
268
|
-
static compare(a, b) {
|
|
269
|
-
if (isString(a)) {
|
|
270
|
-
a = BigInt(a);
|
|
271
|
-
} else if (a instanceof Uint8Array) {
|
|
272
|
-
a = bigIntFromBytes(a);
|
|
273
|
-
}
|
|
274
|
-
if (isString(b)) {
|
|
275
|
-
b = BigInt(b);
|
|
276
|
-
} else if (b instanceof Uint8Array) {
|
|
277
|
-
b = bigIntFromBytes(b);
|
|
278
|
-
}
|
|
279
|
-
return a === b ? 0 : a < b ? -1 : 1;
|
|
280
|
-
}
|
|
281
|
-
/**
|
|
282
|
-
* Parse value as Uint8Array buffer
|
|
283
|
-
*/
|
|
284
|
-
static bufferFrom(value) {
|
|
285
|
-
if (isString(value)) value = BigInt(value);
|
|
286
|
-
var buf = bigIntBytes(value);
|
|
287
|
-
var bufSize = buf.byteLength;
|
|
288
|
-
if (buf.byteLength < 8) {
|
|
289
|
-
var buf2 = new Uint8Array(8);
|
|
290
|
-
buf2.set(buf, 8 - bufSize);
|
|
291
|
-
buf = buf2;
|
|
292
|
-
}
|
|
293
|
-
return buf;
|
|
294
|
-
}
|
|
5
|
+
var ENCODE_BIGINT_BUFFER = /* @__PURE__ */ new Uint8Array(8);
|
|
6
|
+
var Snowflake = class {
|
|
7
|
+
decode = this.deconstruct;
|
|
8
|
+
_epoch;
|
|
9
|
+
_increment = 0;
|
|
10
|
+
_processId = 1;
|
|
11
|
+
_workerId = 0;
|
|
12
|
+
_timestamp = 0;
|
|
13
|
+
__buf;
|
|
14
|
+
_packBuffer;
|
|
15
|
+
_packBigInt;
|
|
16
|
+
_unpackBuffer;
|
|
17
|
+
_unpackBigInt;
|
|
18
|
+
constructor(opts) {
|
|
19
|
+
if (isDate(opts) || isNumber(opts)) this._epoch = timestampMs(opts);
|
|
20
|
+
else if (isBigInt(opts)) this._epoch = timestampMs(Number(opts));
|
|
21
|
+
else {
|
|
22
|
+
const { increment = 0, processId = 1, workerId = 0, epoch } = opts;
|
|
23
|
+
this._epoch = timestampMs(isBigInt(epoch) ? Number(epoch) : epoch);
|
|
24
|
+
this.workerId = workerId;
|
|
25
|
+
this.processId = processId;
|
|
26
|
+
this.increment = increment;
|
|
27
|
+
}
|
|
28
|
+
const packer = bitPack({
|
|
29
|
+
totalBits: 64,
|
|
30
|
+
fields: [
|
|
31
|
+
{
|
|
32
|
+
name: "_timestamp",
|
|
33
|
+
bits: 42,
|
|
34
|
+
take: "low"
|
|
35
|
+
},
|
|
36
|
+
{
|
|
37
|
+
name: "_workerId",
|
|
38
|
+
bits: 5,
|
|
39
|
+
take: "low"
|
|
40
|
+
},
|
|
41
|
+
{
|
|
42
|
+
name: "_processId",
|
|
43
|
+
bits: 5,
|
|
44
|
+
take: "low"
|
|
45
|
+
},
|
|
46
|
+
{
|
|
47
|
+
name: "_increment",
|
|
48
|
+
bits: 12,
|
|
49
|
+
take: "low"
|
|
50
|
+
}
|
|
51
|
+
],
|
|
52
|
+
optimize: true,
|
|
53
|
+
debug: true
|
|
54
|
+
});
|
|
55
|
+
const unpacker = bitUnpack({
|
|
56
|
+
totalBits: 64,
|
|
57
|
+
fields: [
|
|
58
|
+
{
|
|
59
|
+
name: "timestamp",
|
|
60
|
+
bits: 42,
|
|
61
|
+
take: "low"
|
|
62
|
+
},
|
|
63
|
+
{
|
|
64
|
+
name: "workerId",
|
|
65
|
+
bits: 5,
|
|
66
|
+
take: "low"
|
|
67
|
+
},
|
|
68
|
+
{
|
|
69
|
+
name: "processId",
|
|
70
|
+
bits: 5,
|
|
71
|
+
take: "low"
|
|
72
|
+
},
|
|
73
|
+
{
|
|
74
|
+
name: "increment",
|
|
75
|
+
bits: 12,
|
|
76
|
+
take: "low"
|
|
77
|
+
}
|
|
78
|
+
],
|
|
79
|
+
debug: true
|
|
80
|
+
});
|
|
81
|
+
this.__buf = /* @__PURE__ */ new Uint8Array(8);
|
|
82
|
+
this._packBigInt = packer.bigint;
|
|
83
|
+
this._packBuffer = packer.buffer;
|
|
84
|
+
this._unpackBigInt = unpacker.bigint;
|
|
85
|
+
this._unpackBuffer = unpacker.buffer;
|
|
86
|
+
}
|
|
87
|
+
get epoch() {
|
|
88
|
+
return this._epoch;
|
|
89
|
+
}
|
|
90
|
+
get processId() {
|
|
91
|
+
return this._processId;
|
|
92
|
+
}
|
|
93
|
+
set processId(value) {
|
|
94
|
+
this._processId = Number(value) & 31;
|
|
95
|
+
}
|
|
96
|
+
get workerId() {
|
|
97
|
+
return this._workerId;
|
|
98
|
+
}
|
|
99
|
+
set workerId(value) {
|
|
100
|
+
this._workerId = Number(value) & 31;
|
|
101
|
+
}
|
|
102
|
+
get increment() {
|
|
103
|
+
return this._increment;
|
|
104
|
+
}
|
|
105
|
+
set increment(value) {
|
|
106
|
+
this._increment = Number(value) & MAX_INCREMENT;
|
|
107
|
+
}
|
|
108
|
+
_createSavePoint() {
|
|
109
|
+
var increment = this._increment;
|
|
110
|
+
var workerId = this._workerId;
|
|
111
|
+
var processId = this._processId;
|
|
112
|
+
return () => {
|
|
113
|
+
this._increment = increment;
|
|
114
|
+
this._workerId = workerId;
|
|
115
|
+
this._processId = processId;
|
|
116
|
+
};
|
|
117
|
+
}
|
|
118
|
+
setLowest() {
|
|
119
|
+
this._increment = 0;
|
|
120
|
+
this._workerId = 0;
|
|
121
|
+
this._processId = 0;
|
|
122
|
+
}
|
|
123
|
+
setHighest() {
|
|
124
|
+
this._increment = MAX_INCREMENT;
|
|
125
|
+
this._workerId = 31;
|
|
126
|
+
this._processId = 31;
|
|
127
|
+
}
|
|
128
|
+
withLowest(fn) {
|
|
129
|
+
assert.fn(fn, "withLowest expected a function as first argument");
|
|
130
|
+
var reset = this._createSavePoint();
|
|
131
|
+
this.setLowest();
|
|
132
|
+
var result = fn(this);
|
|
133
|
+
reset();
|
|
134
|
+
return result;
|
|
135
|
+
}
|
|
136
|
+
withHighest(fn) {
|
|
137
|
+
assert.fn(fn, "withHighest expected a function as first argument");
|
|
138
|
+
var reset = this._createSavePoint();
|
|
139
|
+
this.setHighest();
|
|
140
|
+
var result = fn(this);
|
|
141
|
+
reset();
|
|
142
|
+
return result;
|
|
143
|
+
}
|
|
144
|
+
generate(timestamp = Date.now()) {
|
|
145
|
+
if (timestamp instanceof Date) timestamp = timestamp.getTime();
|
|
146
|
+
if (!isNumber(timestamp)) throw new Error(`"timestamp" argument must be a number or Date (received ${typeof timestamp})`);
|
|
147
|
+
this._timestamp = timestamp - this._epoch;
|
|
148
|
+
var res = this._packBigInt(this);
|
|
149
|
+
this._increment = this._increment + 1 & MAX_INCREMENT;
|
|
150
|
+
return res;
|
|
151
|
+
}
|
|
152
|
+
generateBufferUnsafe(timestamp = Date.now()) {
|
|
153
|
+
if (timestamp instanceof Date) timestamp = timestamp.getTime();
|
|
154
|
+
if (!isNumber(timestamp)) throw new Error(`"timestamp" argument must be a number or Date (received ${typeof timestamp})`);
|
|
155
|
+
this._timestamp = timestamp - this._epoch;
|
|
156
|
+
this._packBuffer(this);
|
|
157
|
+
this._increment = this._increment + 1 & MAX_INCREMENT;
|
|
158
|
+
return this.__buf;
|
|
159
|
+
}
|
|
160
|
+
generateBuffer(timestamp = Date.now()) {
|
|
161
|
+
if (timestamp instanceof Date) timestamp = timestamp.getTime();
|
|
162
|
+
if (!isNumber(timestamp)) throw new Error(`"timestamp" argument must be a number or Date (received ${typeof timestamp})`);
|
|
163
|
+
this.__buf = /* @__PURE__ */ new Uint8Array(8);
|
|
164
|
+
this._timestamp = timestamp - this._epoch;
|
|
165
|
+
this._packBuffer(this);
|
|
166
|
+
this._increment = this._increment + 1 & MAX_INCREMENT;
|
|
167
|
+
return this.__buf;
|
|
168
|
+
}
|
|
169
|
+
deconstruct(id) {
|
|
170
|
+
if (isString(id)) id = BigInt(id);
|
|
171
|
+
let result;
|
|
172
|
+
if (isBigInt(id)) {
|
|
173
|
+
result = this._unpackBigInt(id);
|
|
174
|
+
result.id = id;
|
|
175
|
+
} else {
|
|
176
|
+
result = this._unpackBuffer(id);
|
|
177
|
+
result.id = bigIntFromBytes(id);
|
|
178
|
+
}
|
|
179
|
+
result.timestamp += this._epoch;
|
|
180
|
+
result.epoch = this._epoch;
|
|
181
|
+
return result;
|
|
182
|
+
}
|
|
183
|
+
timestampFrom(id) {
|
|
184
|
+
return this.deconstruct(id).timestamp;
|
|
185
|
+
}
|
|
186
|
+
static compare(a, b) {
|
|
187
|
+
if (isString(a)) a = BigInt(a);
|
|
188
|
+
else if (a instanceof Uint8Array) a = bigIntFromBytes(a);
|
|
189
|
+
if (isString(b)) b = BigInt(b);
|
|
190
|
+
else if (b instanceof Uint8Array) b = bigIntFromBytes(b);
|
|
191
|
+
return a === b ? 0 : a < b ? -1 : 1;
|
|
192
|
+
}
|
|
193
|
+
static bufferFrom(value) {
|
|
194
|
+
if (isString(value)) value = BigInt(value);
|
|
195
|
+
return new Uint8Array(bigintToBuffer(value));
|
|
196
|
+
}
|
|
197
|
+
};
|
|
198
|
+
function bigintToBuffer(value) {
|
|
199
|
+
if (value < 0n) value = value * -1n;
|
|
200
|
+
for (var i = 0; i < 8; i++) ENCODE_BIGINT_BUFFER[i] = Number(value >> BigInt((8 - i - 1) * 8) & 255n);
|
|
201
|
+
return ENCODE_BIGINT_BUFFER;
|
|
295
202
|
}
|
|
296
|
-
|
|
297
203
|
export { MAX_INCREMENT, MAX_PROCESS_ID, MAX_WORKER_ID, Snowflake };
|
|
298
|
-
|
|
204
|
+
|
|
205
|
+
//# sourceMappingURL=index.mjs.map
|
package/dist/index.mjs.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.mjs","sources":["../src/Snowflake.ts"],"sourcesContent":["/**\n * Based on: https://github.com/sapphiredev/utilities/blob/main/packages/snowflake/src/lib/Snowflake.ts\n */\nimport {\n type AnyFunction,\n assert,\n bigIntBytes,\n bigIntFromBytes,\n isBigInt,\n isDate,\n isNumber,\n isString,\n timestampMs,\n} from '@andrew_l/toolkit';\n\n/**\n * Object returned by Snowflake#deconstruct\n */\nexport interface DeconstructedSnowflake {\n /**\n * The id as a number\n */\n id: bigint;\n\n /**\n * The timestamp stored in the snowflake\n */\n timestamp: number;\n\n /**\n * The worker id stored in the snowflake\n */\n workerId: number;\n\n /**\n * The process id stored in the snowflake\n */\n processId: number;\n\n /**\n * The increment stored in the snowflake\n */\n increment: number;\n\n /**\n * The epoch to use in the snowflake\n */\n epoch: number;\n}\n\n/**\n * Options for Snowflake\n */\nexport interface SnowflakeOptions {\n /**\n * Timestamp or date of the snowflake to generate\n */\n epoch: number | bigint | Date;\n\n /**\n * The increment to use\n * @default 0\n * @remark keep in mind that this number is auto-incremented between generate calls\n */\n increment?: number | bigint;\n\n /**\n * The worker ID to use, will be truncated to 5 bits (0-31)\n * @default 0\n */\n workerId?: number | bigint;\n\n /**\n * The process ID to use, will be truncated to 5 bits (0-31)\n * @default 1\n */\n processId?: number | bigint;\n}\n\n/**\n * The maximum value the `workerId` field accepts in snowflakes.\n */\nexport var MAX_WORKER_ID = 0x1f;\n\n/**\n * The maximum value the `processId` field accepts in snowflakes.\n */\nexport var MAX_PROCESS_ID = 0x1f;\n\n/**\n * The maximum value the `increment` field accepts in snowflakes.\n */\nexport var MAX_INCREMENT = 0xfff;\n\n/**\n * A class for generating and deconstructing Twitter snowflakes.\n *\n * A {@link https://developer.twitter.com/en/docs/twitter-ids Twitter snowflake}\n * is a 64-bit unsigned integer with 4 fields that have a fixed epoch value.\n *\n * If we have a snowflake `266241948824764416` we can represent it as binary:\n * ```\n * 64 22 17 12 0\n * 000000111011000111100001101001000101000000 00001 00000 000000000000\n * number of ms since epoch worker pid increment\n * ```\n *\n * @group Main\n */\nexport class Snowflake {\n /**\n * Alias for {@link deconstruct}\n */\n public decode = this.deconstruct;\n\n /**\n * Internal reference of the epoch passed in the constructor\n * @internal\n */\n private readonly _epoch: number;\n\n /**\n * Internal incrementor for generating snowflakes\n * @internal\n */\n private _increment = 0;\n\n /**\n * The process ID that will be used by default in the generate method\n * @internal\n */\n private _processId = 1;\n\n /**\n * The worker ID that will be used by default in the generate method\n * @internal\n */\n private _workerId = 0;\n\n /**\n * @internal\n */\n private _buffer: Uint8Array;\n\n /**\n * @param epoch the epoch to use\n */\n public constructor(opts: SnowflakeOptions | Date | number | bigint) {\n if (isDate(opts) || isNumber(opts)) {\n this._epoch = timestampMs(opts);\n } else if (isBigInt(opts)) {\n this._epoch = timestampMs(Number(opts));\n } else {\n const { increment = 0, processId = 1, workerId = 0, epoch } = opts;\n this._epoch = timestampMs(isBigInt(epoch) ? Number(epoch) : epoch);\n this.workerId = workerId;\n this.processId = processId;\n this.increment = increment;\n }\n\n this._buffer = new Uint8Array(8);\n }\n\n /**\n * The epoch for this snowflake, as a number\n */\n public get epoch(): number {\n return this._epoch;\n }\n\n /**\n * Gets the configured process ID\n */\n public get processId(): number {\n return this._processId;\n }\n\n /**\n * Sets the process ID that will be used by default for the {@link generate} method\n * @param value The new value, will be masked with `0b11111`\n */\n public set processId(value: number | bigint) {\n this._processId = Number(value) & MAX_PROCESS_ID;\n }\n\n /**\n * Gets the configured worker ID\n */\n public get workerId(): number {\n return this._workerId;\n }\n\n /**\n * Sets the worker ID that will be used by default for the {@link generate} method\n * @param value The new value, will be masked with `0b11111`\n */\n public set workerId(value: number | bigint) {\n this._workerId = Number(value) & MAX_WORKER_ID;\n }\n\n /**\n * Get incrementor for generating snowflakes\n */\n public get increment(): number {\n return this._increment;\n }\n\n /**\n * Sets the incrementor for generating snowflakes that will be used by default for the {@link generate} method\n * @param value The new value\n */\n public set increment(value: number | bigint) {\n this._increment = Number(value) & MAX_INCREMENT;\n }\n\n private _createSavePoint(): AnyFunction {\n var increment = this._increment;\n var workerId = this._workerId;\n var processId = this._processId;\n\n return () => {\n this._increment = increment;\n this._workerId = workerId;\n this._processId = processId;\n };\n }\n\n /**\n * Sets most lowest values for generating snowflakes that will be used by default for the {@link generate} method\n */\n setLowest(): void {\n this._increment = 0;\n this._workerId = 0;\n this._processId = 0;\n }\n\n /**\n * Sets most highest values for generating snowflakes that will be used by default for the {@link generate} method\n */\n setHighest(): void {\n this._increment = MAX_INCREMENT;\n this._workerId = MAX_WORKER_ID;\n this._processId = MAX_PROCESS_ID;\n }\n\n /**\n * Execute a function in context of most lowest values for generating snowflakes\n * @example\n * ```typescript\n * const epoch = new Date('2000-01-01T00:00:00.000Z');\n * const snowflake = new Snowflake();\n * const id = snowflake.withLowest((v) => v.generate(epoch)); // the lowest possible id for that epoch\n * ```\n */\n withLowest<Result = undefined>(fn: (instance: Snowflake) => Result): Result {\n assert.fn(fn, 'withLowest expected a function as first argument');\n\n var reset = this._createSavePoint();\n this.setLowest();\n\n var result = fn(this);\n reset();\n\n return result;\n }\n\n /**\n * Execute a function in context of most highest values for generating snowflakes\n * @example\n * ```typescript\n * const epoch = new Date('2000-01-01T00:00:00.000Z');\n * const snowflake = new Snowflake();\n * const id = snowflake.withLowest((v) => v.generate(epoch)); // the highest possible id for that epoch\n * ```\n */\n withHighest<Result = undefined>(fn: (instance: Snowflake) => Result): Result {\n assert.fn(fn, 'withHighest expected a function as first argument');\n\n var reset = this._createSavePoint();\n\n this.setHighest();\n\n var result = fn(this);\n reset();\n\n return result;\n }\n\n /**\n * Generates a Snowflake ID as bigint.\n */\n public generate(timestamp: Date | number = Date.now()): bigint {\n if (timestamp instanceof Date) timestamp = timestamp.getTime();\n if (!isNumber(timestamp)) {\n throw new Error(\n `\"timestamp\" argument must be a number or Date (received ${typeof timestamp})`,\n );\n }\n\n var increment = this._increment;\n this._increment = (this._increment + 1) & MAX_INCREMENT;\n\n return (\n (BigInt(timestamp - this._epoch) << 22n) |\n (BigInt(this._workerId & MAX_WORKER_ID) << 17n) |\n (BigInt(this._processId & MAX_PROCESS_ID) << 12n) |\n BigInt(increment & MAX_INCREMENT)\n );\n }\n\n /**\n * Generates a Snowflake ID as a `Uint8Array` buffer.\n *\n * ⚠️ Returns a reference to the **same** internal `Uint8Array` instance.\n * Its contents may be overwritten on the next ID generation call.\n *\n * This method is intended for high-performance scenarios where you\n * immediately transform the buffer (e.g., to base62) before calling again.\n * Avoid storing or mutating the returned buffer directly.\n */\n public generateBufferUnsafe(\n timestamp: Date | number = Date.now(),\n ): Uint8Array {\n if (timestamp instanceof Date) timestamp = timestamp.getTime();\n if (!isNumber(timestamp)) {\n throw new Error(\n `\"timestamp\" argument must be a number or Date (received ${typeof timestamp})`,\n );\n }\n\n var increment = this._increment;\n this._increment = (this._increment + 1) & MAX_INCREMENT;\n\n // Calculate the timestamp delta\n var timestampDelta = timestamp - this._epoch;\n\n // Split into 32-bit parts for bitwise operations\n var timestampHigh = Math.floor(timestampDelta / 0xffffffff);\n var timestampLow = timestampDelta >>> 0;\n\n var high32 = ((timestampHigh << 22) | (timestampLow >>> 10)) >>> 0;\n var low32 =\n ((timestampLow << 22) |\n (this._workerId << 17) |\n (this._processId << 12) |\n (increment & MAX_INCREMENT)) >>>\n 0;\n\n var buffer = this._buffer;\n\n buffer[0] = high32 >>> 24;\n buffer[1] = high32 >>> 16;\n buffer[2] = high32 >>> 8;\n buffer[3] = high32;\n buffer[4] = low32 >>> 24;\n buffer[5] = low32 >>> 16;\n buffer[6] = low32 >>> 8;\n buffer[7] = low32;\n\n return buffer;\n }\n\n /**\n * Generates a snowflake given an epoch and optionally a timestamp\n * @example\n * ```typescript\n * const epoch = new Date('2000-01-01T00:00:00.000Z');\n * const snowflake = new Snowflake({ epoch }).generate();\n * ```\n * @returns A unique snowflake as Uint8Array\n */\n public generateBuffer(timestamp: Date | number = Date.now()): Uint8Array {\n this.generateBufferUnsafe(timestamp);\n return new Uint8Array(this._buffer);\n }\n\n /**\n * Deconstructs a snowflake given a snowflake ID\n * @param id the snowflake to deconstruct\n * @returns a deconstructed snowflake\n * @example\n * ```typescript\n * const epoch = new Date('2000-01-01T00:00:00.000Z');\n * const snowflake = new Snowflake(epoch).deconstruct('3971046231244935168');\n * ```\n */\n public deconstruct(id: string | bigint | Uint8Array): DeconstructedSnowflake {\n var high32: number, low32: number;\n\n if (id instanceof Uint8Array) {\n // Convert from Uint8Array\n high32 = ((id[0] << 24) | (id[1] << 16) | (id[2] << 8) | id[3]) >>> 0;\n low32 = ((id[4] << 24) | (id[5] << 16) | (id[6] << 8) | id[7]) >>> 0;\n } else if (isBigInt(id)) {\n return this.deconstruct(bigIntBytes(id));\n } else {\n // Convert from string\n return this.deconstruct(bigIntBytes(BigInt(id)));\n }\n\n return {\n id: BigInt(high32) * 0x100000000n + BigInt(low32),\n timestamp: high32 * 0x400 + (low32 >>> 22) + this._epoch,\n workerId: (low32 >>> 17) & MAX_WORKER_ID,\n processId: (low32 >>> 12) & MAX_PROCESS_ID,\n increment: low32 & MAX_INCREMENT,\n epoch: this._epoch,\n };\n }\n\n /**\n * Retrieves the timestamp field's value from a snowflake.\n * @param id The snowflake to get the timestamp value from.\n * @returns The UNIX timestamp that is stored in `id`.\n */\n public timestampFrom(id: string | bigint | Uint8Array): number {\n if (isString(id) || isBigInt(id)) {\n return this.timestampFrom(Snowflake.bufferFrom(id));\n }\n\n var high32 = ((id[0] << 24) | (id[1] << 16) | (id[2] << 8) | id[3]) >>> 0;\n var low32 = ((id[4] << 24) | (id[5] << 16) | (id[6] << 8) | id[7]) >>> 0;\n\n return high32 * 0x400 + (low32 >>> 22) + this._epoch;\n }\n\n /**\n * Returns a number indicating whether a reference snowflake comes before, or after, or is same as the given\n * snowflake in sort order.\n * @param a The first snowflake to compare.\n * @param b The second snowflake to compare.\n * @returns `-1` if `a` is older than `b`, `0` if `a` and `b` are equals, `1` if `a` is newer than `b`.\n */\n public static compare(\n a: string | bigint | Uint8Array,\n b: string | bigint | Uint8Array,\n ): -1 | 0 | 1 {\n if (isString(a)) {\n a = BigInt(a);\n } else if (a instanceof Uint8Array) {\n a = bigIntFromBytes(a);\n }\n\n if (isString(b)) {\n b = BigInt(b);\n } else if (b instanceof Uint8Array) {\n b = bigIntFromBytes(b);\n }\n\n return a === b ? 0 : a < b ? -1 : 1;\n }\n\n /**\n * Parse value as Uint8Array buffer\n */\n public static bufferFrom(value: bigint | string): Uint8Array {\n if (isString(value)) value = BigInt(value);\n\n var buf = bigIntBytes(value);\n var bufSize = buf.byteLength;\n\n // Add padding\n if (buf.byteLength < 8) {\n var buf2 = new Uint8Array(8);\n buf2.set(buf, 8 - bufSize);\n buf = buf2;\n }\n\n return buf;\n }\n}\n"],"names":[],"mappings":";;AAkFO,IAAI,aAAA,GAAgB;AAKpB,IAAI,cAAA,GAAiB;AAKrB,IAAI,aAAA,GAAgB;AAiBpB,MAAM,SAAA,CAAU;AAAA;AAAA;AAAA;AAAA,EAId,SAAS,IAAA,CAAK,WAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EAMJ,MAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EAMT,UAAA,GAAa,CAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EAMb,UAAA,GAAa,CAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EAMb,SAAA,GAAY,CAAA;AAAA;AAAA;AAAA;AAAA,EAKZ,OAAA;AAAA;AAAA;AAAA;AAAA,EAKD,YAAY,IAAA,EAAiD;AAClE,IAAA,IAAI,MAAA,CAAO,IAAI,CAAA,IAAK,QAAA,CAAS,IAAI,CAAA,EAAG;AAClC,MAAA,IAAA,CAAK,MAAA,GAAS,YAAY,IAAI,CAAA;AAAA,IAChC,CAAA,MAAA,IAAW,QAAA,CAAS,IAAI,CAAA,EAAG;AACzB,MAAA,IAAA,CAAK,MAAA,GAAS,WAAA,CAAY,MAAA,CAAO,IAAI,CAAC,CAAA;AAAA,IACxC,CAAA,MAAO;AACL,MAAA,MAAM,EAAE,YAAY,CAAA,EAAG,SAAA,GAAY,GAAG,QAAA,GAAW,CAAA,EAAG,OAAM,GAAI,IAAA;AAC9D,MAAA,IAAA,CAAK,MAAA,GAAS,YAAY,QAAA,CAAS,KAAK,IAAI,MAAA,CAAO,KAAK,IAAI,KAAK,CAAA;AACjE,MAAA,IAAA,CAAK,QAAA,GAAW,QAAA;AAChB,MAAA,IAAA,CAAK,SAAA,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,GAAA,CAAI,aAAa,CAAA,EAAG;AACtB,MAAA,IAAI,IAAA,GAAO,IAAI,UAAA,CAAW,CAAC,CAAA;AAC3B,MAAA,IAAA,CAAK,GAAA,CAAI,GAAA,EAAK,CAAA,GAAI,OAAO,CAAA;AACzB,MAAA,GAAA,GAAM,IAAA;AAAA,IACR;AAEA,IAAA,OAAO,GAAA;AAAA,EACT;AACF;;;;"}
|
|
1
|
+
{"version":3,"file":"index.mjs","names":[],"sources":["../src/Snowflake.ts"],"sourcesContent":["/**\n * Based on: https://github.com/sapphiredev/utilities/blob/main/packages/snowflake/src/lib/Snowflake.ts\n */\nimport {\n type AnyFunction,\n type BitPack,\n type BitUnpack,\n assert,\n bigIntFromBytes,\n bitPack,\n bitUnpack,\n isBigInt,\n isDate,\n isNumber,\n isString,\n timestampMs,\n} from '@andrew_l/toolkit';\n\n/**\n * Object returned by Snowflake#deconstruct\n */\nexport interface DeconstructedSnowflake {\n /**\n * The id as a number\n */\n id: bigint;\n\n /**\n * The timestamp stored in the snowflake\n */\n timestamp: number;\n\n /**\n * The worker id stored in the snowflake\n */\n workerId: number;\n\n /**\n * The process id stored in the snowflake\n */\n processId: number;\n\n /**\n * The increment stored in the snowflake\n */\n increment: number;\n\n /**\n * The epoch to use in the snowflake\n */\n epoch: number;\n}\n\n/**\n * Options for Snowflake\n */\nexport interface SnowflakeOptions {\n /**\n * Timestamp or date of the snowflake to generate\n */\n epoch: number | bigint | Date;\n\n /**\n * The increment to use\n * @default 0\n * @remark keep in mind that this number is auto-incremented between generate calls\n */\n increment?: number | bigint;\n\n /**\n * The worker ID to use, will be truncated to 5 bits (0-31)\n * @default 0\n */\n workerId?: number | bigint;\n\n /**\n * The process ID to use, will be truncated to 5 bits (0-31)\n * @default 1\n */\n processId?: number | bigint;\n}\n\n/**\n * The maximum value the `workerId` field accepts in snowflakes.\n */\nexport var MAX_WORKER_ID = 0x1f;\n\n/**\n * The maximum value the `processId` field accepts in snowflakes.\n */\nexport var MAX_PROCESS_ID = 0x1f;\n\n/**\n * The maximum value the `increment` field accepts in snowflakes.\n */\nexport var MAX_INCREMENT = 0xfff;\n\nvar ENCODE_BIGINT_BUFFER = new Uint8Array(8);\n\n/**\n * A class for generating and deconstructing Twitter snowflakes.\n *\n * A {@link https://developer.twitter.com/en/docs/twitter-ids Twitter snowflake}\n * is a 64-bit unsigned integer with 4 fields that have a fixed epoch value.\n *\n * If we have a snowflake `266241948824764416` we can represent it as binary:\n * ```\n * 64 22 17 12 0\n * 000000111011000111100001101001000101000000 00001 00000 000000000000\n * number of ms since epoch worker pid increment\n * ```\n *\n * @group Main\n */\nexport class Snowflake {\n /**\n * Alias for {@link deconstruct}\n */\n public decode = this.deconstruct;\n\n /**\n * Internal reference of the epoch passed in the constructor\n * @internal\n */\n private readonly _epoch: number;\n\n /**\n * Internal incrementor for generating snowflakes\n * @internal\n */\n private _increment = 0;\n\n /**\n * The process ID that will be used by default in the generate method\n * @internal\n */\n private _processId = 1;\n\n /**\n * The worker ID that will be used by default in the generate method\n * @internal\n */\n private _workerId = 0;\n\n /**\n * @internal\n */\n private _timestamp = 0;\n\n private __buf: Uint8Array;\n\n private _packBuffer: BitPack.Fn.Buffer<\n '_timestamp' | '_workerId' | '_processId' | '_increment'\n >;\n\n private _packBigInt: BitPack.Fn.BigInt<\n '_timestamp' | '_workerId' | '_processId' | '_increment'\n >;\n\n private _unpackBuffer: BitUnpack.Fn.Buffer<\n 'timestamp' | 'workerId' | 'processId' | 'increment'\n >;\n\n private _unpackBigInt: BitUnpack.Fn.BigInt<\n 'timestamp' | 'workerId' | 'processId' | 'increment'\n >;\n\n /**\n * @param epoch the epoch to use\n */\n public constructor(opts: SnowflakeOptions | Date | number | bigint) {\n if (isDate(opts) || isNumber(opts)) {\n this._epoch = timestampMs(opts);\n } else if (isBigInt(opts)) {\n this._epoch = timestampMs(Number(opts));\n } else {\n const { increment = 0, processId = 1, workerId = 0, epoch } = opts;\n this._epoch = timestampMs(isBigInt(epoch) ? Number(epoch) : epoch);\n this.workerId = workerId;\n this.processId = processId;\n this.increment = increment;\n }\n\n const packer = bitPack({\n totalBits: 64,\n fields: [\n { name: '_timestamp', bits: 42, take: 'low' },\n { name: '_workerId', bits: 5, take: 'low' },\n { name: '_processId', bits: 5, take: 'low' },\n { name: '_increment', bits: 12, take: 'low' },\n ],\n optimize: true,\n debug: true,\n });\n\n const unpacker = bitUnpack({\n totalBits: 64,\n fields: [\n { name: 'timestamp', bits: 42, take: 'low' },\n { name: 'workerId', bits: 5, take: 'low' },\n { name: 'processId', bits: 5, take: 'low' },\n { name: 'increment', bits: 12, take: 'low' },\n ],\n debug: true,\n });\n\n this.__buf = new Uint8Array(8);\n this._packBigInt = packer.bigint;\n this._packBuffer = packer.buffer;\n this._unpackBigInt = unpacker.bigint;\n this._unpackBuffer = unpacker.buffer;\n }\n\n /**\n * The epoch for this snowflake, as a number\n */\n public get epoch(): number {\n return this._epoch;\n }\n\n /**\n * Gets the configured process ID\n */\n public get processId(): number {\n return this._processId;\n }\n\n /**\n * Sets the process ID that will be used by default for the {@link generate} method\n * @param value The new value, will be masked with `0b11111`\n */\n public set processId(value: number | bigint) {\n this._processId = Number(value) & MAX_PROCESS_ID;\n }\n\n /**\n * Gets the configured worker ID\n */\n public get workerId(): number {\n return this._workerId;\n }\n\n /**\n * Sets the worker ID that will be used by default for the {@link generate} method\n * @param value The new value, will be masked with `0b11111`\n */\n public set workerId(value: number | bigint) {\n this._workerId = Number(value) & MAX_WORKER_ID;\n }\n\n /**\n * Get incrementor for generating snowflakes\n */\n public get increment(): number {\n return this._increment;\n }\n\n /**\n * Sets the incrementor for generating snowflakes that will be used by default for the {@link generate} method\n * @param value The new value\n */\n public set increment(value: number | bigint) {\n this._increment = Number(value) & MAX_INCREMENT;\n }\n\n private _createSavePoint(): AnyFunction {\n var increment = this._increment;\n var workerId = this._workerId;\n var processId = this._processId;\n\n return () => {\n this._increment = increment;\n this._workerId = workerId;\n this._processId = processId;\n };\n }\n\n /**\n * Sets most lowest values for generating snowflakes that will be used by default for the {@link generate} method\n */\n setLowest(): void {\n this._increment = 0;\n this._workerId = 0;\n this._processId = 0;\n }\n\n /**\n * Sets most highest values for generating snowflakes that will be used by default for the {@link generate} method\n */\n setHighest(): void {\n this._increment = MAX_INCREMENT;\n this._workerId = MAX_WORKER_ID;\n this._processId = MAX_PROCESS_ID;\n }\n\n /**\n * Execute a function in context of most lowest values for generating snowflakes\n * @example\n * ```typescript\n * const epoch = new Date('2000-01-01T00:00:00.000Z');\n * const snowflake = new Snowflake();\n * const id = snowflake.withLowest((v) => v.generate(epoch)); // the lowest possible id for that epoch\n * ```\n */\n withLowest<Result = undefined>(fn: (instance: Snowflake) => Result): Result {\n assert.fn(fn, 'withLowest expected a function as first argument');\n\n var reset = this._createSavePoint();\n this.setLowest();\n\n var result = fn(this);\n reset();\n\n return result;\n }\n\n /**\n * Execute a function in context of most highest values for generating snowflakes\n * @example\n * ```typescript\n * const epoch = new Date('2000-01-01T00:00:00.000Z');\n * const snowflake = new Snowflake();\n * const id = snowflake.withLowest((v) => v.generate(epoch)); // the highest possible id for that epoch\n * ```\n */\n withHighest<Result = undefined>(fn: (instance: Snowflake) => Result): Result {\n assert.fn(fn, 'withHighest expected a function as first argument');\n\n var reset = this._createSavePoint();\n\n this.setHighest();\n\n var result = fn(this);\n reset();\n\n return result;\n }\n\n /**\n * Generates a Snowflake ID as bigint.\n */\n public generate(timestamp: Date | number = Date.now()): bigint {\n if (timestamp instanceof Date) timestamp = timestamp.getTime();\n if (!isNumber(timestamp)) {\n throw new Error(\n `\"timestamp\" argument must be a number or Date (received ${typeof timestamp})`,\n );\n }\n\n this._timestamp = timestamp - this._epoch;\n var res = this._packBigInt(this as any);\n this._increment = (this._increment + 1) & MAX_INCREMENT;\n\n return res;\n }\n\n /**\n * Generates a Snowflake ID as a `Uint8Array` buffer.\n *\n * ⚠️ Returns a reference to the **same** internal `Uint8Array` instance.\n * Its contents may be overwritten on the next ID generation call.\n *\n * This method is intended for high-performance scenarios where you\n * immediately transform the buffer (e.g., to base62) before calling again.\n * Avoid storing or mutating the returned buffer directly.\n */\n public generateBufferUnsafe(\n timestamp: Date | number = Date.now(),\n ): Uint8Array {\n if (timestamp instanceof Date) timestamp = timestamp.getTime();\n if (!isNumber(timestamp)) {\n throw new Error(\n `\"timestamp\" argument must be a number or Date (received ${typeof timestamp})`,\n );\n }\n\n this._timestamp = timestamp - this._epoch;\n this._packBuffer(this as any);\n this._increment = (this._increment + 1) & MAX_INCREMENT;\n\n return this.__buf;\n }\n\n /**\n * Generates a snowflake given an epoch and optionally a timestamp\n * @example\n * ```typescript\n * const epoch = new Date('2000-01-01T00:00:00.000Z');\n * const snowflake = new Snowflake({ epoch }).generate();\n * ```\n * @returns A unique snowflake as Uint8Array\n */\n public generateBuffer(timestamp: Date | number = Date.now()): Uint8Array {\n if (timestamp instanceof Date) timestamp = timestamp.getTime();\n if (!isNumber(timestamp)) {\n throw new Error(\n `\"timestamp\" argument must be a number or Date (received ${typeof timestamp})`,\n );\n }\n\n this.__buf = new Uint8Array(8);\n this._timestamp = timestamp - this._epoch;\n this._packBuffer(this as any);\n this._increment = (this._increment + 1) & MAX_INCREMENT;\n\n return this.__buf;\n }\n\n /**\n * Deconstructs a snowflake given a snowflake ID\n * @param id the snowflake to deconstruct\n * @returns a deconstructed snowflake\n * @example\n * ```typescript\n * const epoch = new Date('2000-01-01T00:00:00.000Z');\n * const snowflake = new Snowflake(epoch).deconstruct('3971046231244935168');\n * ```\n */\n public deconstruct(id: string | bigint | Uint8Array): DeconstructedSnowflake {\n if (isString(id)) {\n id = BigInt(id);\n }\n\n let result: DeconstructedSnowflake;\n\n if (isBigInt(id)) {\n result = this._unpackBigInt(id) as DeconstructedSnowflake;\n result.id = id;\n } else {\n result = this._unpackBuffer(id) as DeconstructedSnowflake;\n result.id = bigIntFromBytes(id);\n }\n\n result.timestamp += this._epoch;\n result.epoch = this._epoch;\n\n return result;\n }\n\n /**\n * Retrieves the timestamp field's value from a snowflake.\n * @param id The snowflake to get the timestamp value from.\n * @returns The UNIX timestamp that is stored in `id`.\n */\n public timestampFrom(id: string | bigint | Uint8Array): number {\n return this.deconstruct(id).timestamp;\n }\n\n /**\n * Returns a number indicating whether a reference snowflake comes before, or after, or is same as the given\n * snowflake in sort order.\n * @param a The first snowflake to compare.\n * @param b The second snowflake to compare.\n * @returns `-1` if `a` is older than `b`, `0` if `a` and `b` are equals, `1` if `a` is newer than `b`.\n */\n public static compare(\n a: string | bigint | Uint8Array,\n b: string | bigint | Uint8Array,\n ): -1 | 0 | 1 {\n if (isString(a)) {\n a = BigInt(a);\n } else if (a instanceof Uint8Array) {\n a = bigIntFromBytes(a);\n }\n\n if (isString(b)) {\n b = BigInt(b);\n } else if (b instanceof Uint8Array) {\n b = bigIntFromBytes(b);\n }\n\n return a === b ? 0 : a < b ? -1 : 1;\n }\n\n /**\n * Parse value as Uint8Array buffer\n */\n public static bufferFrom(value: bigint | string): Uint8Array {\n if (isString(value)) value = BigInt(value);\n\n return new Uint8Array(bigintToBuffer(value));\n }\n}\n\nfunction bigintToBuffer(value: bigint): Uint8Array {\n if (value < 0n) {\n value = value * -1n;\n }\n for (var i = 0; i < 8; i++) {\n ENCODE_BIGINT_BUFFER[i] = Number(\n (value >> BigInt((8 - i - 1) * 8)) & 0xffn,\n );\n }\n return ENCODE_BIGINT_BUFFER;\n}\n"],"mappings":";;;AAqFA,IAAW,gBAAgB;;;;;CAY3B,aAAI;;;;;;;;;;;;OAiBS;;;;GAIJ,KAAA,YAAc;;;;;GAMJ,QAAA;;;;;IAMT;;;;;IAMA;;;;;IAMA;;;;KAKA,MAAA;IAEA;GAEA;GAIA,UAAA;GAIA,OAAA;EAIA,CAAA;;;;IAOD;KACL,MAAI;WAEO;WAEJ;IACL;IACA;KACA,MAAK;KACL,MAAK;KACL,MAAK;IACP;IAEA;KACE,MAAA;KACA,MAAQ;KACN,MAAA;;;KAAgC,MAAM;KAAM,MAAA;KAC5C,MAAA;;;UAA8B;;OAC9B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AAkB,EAAA,GAAA,KAAA,OAAA,EAAA;EAChB,IAAA;EACA,IAAA,SAAK,EAAA,GAAY;GACjB,SAAK,KAAA,cAAa,EAAA;GACpB,OAAA,KAAA;;;;EAKA;EACE,OAAK,aAAa,KAAA;EAClB,OAAK,QAAA,KAAA;EACL,OAAK;CACP;;;;;;;;OAWA,IAAA,aAA4E,YAAA,IAAA,gBAAA,CAAA;EAC1E,OAAO,MAAG,IAAI,IAAA,IAAA,IAAA,KAAA;;QAKV,WAAY,OAAI;EACpB,IAAA,SAAM,KAAA,GAAA,QAAA,OAAA,KAAA;EAEN,OAAO,IAAA,WAAA,eAAA,KAAA,CAAA;CACT"}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@andrew_l/snowflake",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "0.4.1",
|
|
4
4
|
"description": "Another implementation of snowflake id generator.",
|
|
5
5
|
"license": "MIT",
|
|
6
6
|
"type": "module",
|
|
@@ -19,27 +19,28 @@
|
|
|
19
19
|
"exports": {
|
|
20
20
|
".": {
|
|
21
21
|
"import": "./dist/index.mjs",
|
|
22
|
-
"require": "./dist/index.
|
|
22
|
+
"require": "./dist/index.mjs",
|
|
23
|
+
"types": "./dist/index.d.mts"
|
|
23
24
|
}
|
|
24
25
|
},
|
|
25
|
-
"main": "./dist/index.
|
|
26
|
-
"types": "./dist/index.d.
|
|
26
|
+
"main": "./dist/index.mjs",
|
|
27
|
+
"types": "./dist/index.d.mts",
|
|
27
28
|
"files": [
|
|
28
29
|
"dist"
|
|
29
30
|
],
|
|
30
31
|
"dependencies": {
|
|
31
|
-
"@andrew_l/toolkit": "0.
|
|
32
|
+
"@andrew_l/toolkit": "0.4.1"
|
|
32
33
|
},
|
|
33
34
|
"devDependencies": {
|
|
34
35
|
"@sapphire/snowflake": "^3.5.5",
|
|
35
36
|
"@types/node": "22.10.5",
|
|
36
|
-
"
|
|
37
|
-
"
|
|
37
|
+
"obuild": "^0.4.37",
|
|
38
|
+
"typescript": "6.0.3",
|
|
38
39
|
"vitest": "^3.2.4"
|
|
39
40
|
},
|
|
40
41
|
"scripts": {
|
|
41
42
|
"check-types": "tsc --noEmit",
|
|
42
|
-
"build": "
|
|
43
|
+
"build": "obuild",
|
|
43
44
|
"test": "vitest run --typecheck",
|
|
44
45
|
"test:watch": "vitest watch --typecheck",
|
|
45
46
|
"benchmark": "vitest bench watch ./benchmark",
|