summaryrefslogtreecommitdiffhomepage
path: root/js/src/id/id.ts
blob: 96ea870a13e613bc6d05d58183985acf15f38d1c (plain)
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
import { z } from "zod";
import { randomBytes } from "crypto";

export namespace Identifier {
  const prefixes = {
    session: "ses",
    message: "msg",
  } as const;

  export function schema(prefix: keyof typeof prefixes) {
    return z.string().startsWith(prefixes[prefix]);
  }

  const LENGTH = 26;

  export function ascending(prefix: keyof typeof prefixes, given?: string) {
    return generateID(prefix, false, given);
  }

  export function descending(prefix: keyof typeof prefixes, given?: string) {
    return generateID(prefix, true, given);
  }

  function generateID(
    prefix: keyof typeof prefixes,
    descending: boolean,
    given?: string,
  ): string {
    if (given) {
      if (given.startsWith(prefixes[prefix])) return given;
      throw new Error(`ID ${given} does not start with ${prefixes[prefix]}`);
    }

    let now = BigInt(Date.now());

    if (descending) {
      now = ~now;
    }

    const timeBytes = Buffer.alloc(6);
    for (let i = 0; i < 6; i++) {
      timeBytes[i] = Number((now >> BigInt(40 - 8 * i)) & BigInt(0xff));
    }

    const randLength = (LENGTH - 12) / 2;
    const random = randomBytes(randLength);

    return (
      prefixes[prefix] +
      "_" +
      timeBytes.toString("hex") +
      random.toString("hex")
    );
  }
}