fantomid 1.0.2 → 1.0.4
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/package.json +4 -1
- package/src/fantomid.js +37 -0
- package/src/index.js +2 -0
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "fantomid",
|
|
3
|
-
"version": "1.0.
|
|
3
|
+
"version": "1.0.4",
|
|
4
4
|
"type": "module",
|
|
5
5
|
"description": "A tiny, universal ID generator compatible with JavaScript integers",
|
|
6
6
|
"repository": "th3rius/fantomid",
|
|
@@ -16,6 +16,9 @@
|
|
|
16
16
|
"build": "rimraf dist && pkgroll --sourcemap",
|
|
17
17
|
"test": "node --test --experimental-test-module-mocks **/*.spec.js"
|
|
18
18
|
},
|
|
19
|
+
"main": "./dist/index.js",
|
|
20
|
+
"module": "./dist/index.mjs",
|
|
21
|
+
"types": "./dist/index.d.cts",
|
|
19
22
|
"exports": {
|
|
20
23
|
"require": {
|
|
21
24
|
"types": "./dist/index.d.ts",
|
package/src/fantomid.js
ADDED
|
@@ -0,0 +1,37 @@
|
|
|
1
|
+
import { random } from "@lukeed/csprng";
|
|
2
|
+
|
|
3
|
+
const EPOCH = new Date("2024-09-08");
|
|
4
|
+
|
|
5
|
+
export function fantomid() {
|
|
6
|
+
const TIMESTAMP_LENGTH = 36;
|
|
7
|
+
const RANDOM_BITS_LENGTH = 17;
|
|
8
|
+
const TIMESTAMP_PRECISION_DIVIDER = 100;
|
|
9
|
+
|
|
10
|
+
const bits = new Array(TIMESTAMP_LENGTH + RANDOM_BITS_LENGTH);
|
|
11
|
+
|
|
12
|
+
// Generates a timestamp to be part of the key. This is
|
|
13
|
+
// inspired by how UUID v7 works: the idea is that this
|
|
14
|
+
// will guarantee keys are generated evenly across time.
|
|
15
|
+
const timestamp = Math.round(
|
|
16
|
+
// Use a more recent base date instead of the Unix Epoch to
|
|
17
|
+
// increase the amount of time we can represent in the timestamp.
|
|
18
|
+
(new Date() - EPOCH) /
|
|
19
|
+
// Decrease the precision of the timestamp to
|
|
20
|
+
// increase the amount of bits we can fit in a key.
|
|
21
|
+
TIMESTAMP_PRECISION_DIVIDER,
|
|
22
|
+
);
|
|
23
|
+
for (let i = 0; i < TIMESTAMP_LENGTH; i++) {
|
|
24
|
+
bits[TIMESTAMP_LENGTH + RANDOM_BITS_LENGTH - 1 - i] = (timestamp >> i) & 1;
|
|
25
|
+
}
|
|
26
|
+
|
|
27
|
+
// Generates a randomized part of the key. If multiple machines generate a
|
|
28
|
+
// key at the exact same time (limited by the precision of the timestamp),
|
|
29
|
+
// we are ensured to have a chance of collision of `1` in `2 ** RANDOM_BITS_LENGTH`.
|
|
30
|
+
const randomBytes = random(Math.ceil(RANDOM_BITS_LENGTH / 8));
|
|
31
|
+
for (let i = 0; i < RANDOM_BITS_LENGTH; i++) {
|
|
32
|
+
bits[RANDOM_BITS_LENGTH - 1 - i] =
|
|
33
|
+
(randomBytes[Math.floor(i / 8)] >> i % 8) & 1;
|
|
34
|
+
}
|
|
35
|
+
|
|
36
|
+
return Number("0b" + bits.reduce((id, bit) => id + bit, String()));
|
|
37
|
+
}
|
package/src/index.js
ADDED