id.ts 2.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293
  1. const prefixes = {
  2. session: "ses",
  3. message: "msg",
  4. permission: "per",
  5. user: "usr",
  6. part: "prt",
  7. pty: "pty",
  8. } as const
  9. const LENGTH = 26
  10. let lastTimestamp = 0
  11. let counter = 0
  12. type Prefix = keyof typeof prefixes
  13. export namespace Identifier {
  14. export function ascending(prefix: Prefix, given?: string) {
  15. return generateID(prefix, false, given)
  16. }
  17. export function descending(prefix: Prefix, given?: string) {
  18. return generateID(prefix, true, given)
  19. }
  20. }
  21. function generateID(prefix: Prefix, descending: boolean, given?: string): string {
  22. if (!given) {
  23. return create(prefix, descending)
  24. }
  25. if (!given.startsWith(prefixes[prefix])) {
  26. throw new Error(`ID ${given} does not start with ${prefixes[prefix]}`)
  27. }
  28. return given
  29. }
  30. function create(prefix: Prefix, descending: boolean, timestamp?: number): string {
  31. const currentTimestamp = timestamp ?? Date.now()
  32. if (currentTimestamp !== lastTimestamp) {
  33. lastTimestamp = currentTimestamp
  34. counter = 0
  35. }
  36. counter += 1
  37. let now = BigInt(currentTimestamp) * BigInt(0x1000) + BigInt(counter)
  38. if (descending) {
  39. now = ~now
  40. }
  41. const timeBytes = new Uint8Array(6)
  42. for (let i = 0; i < 6; i += 1) {
  43. timeBytes[i] = Number((now >> BigInt(40 - 8 * i)) & BigInt(0xff))
  44. }
  45. return prefixes[prefix] + "_" + bytesToHex(timeBytes) + randomBase62(LENGTH - 12)
  46. }
  47. function bytesToHex(bytes: Uint8Array): string {
  48. let hex = ""
  49. for (let i = 0; i < bytes.length; i += 1) {
  50. hex += bytes[i].toString(16).padStart(2, "0")
  51. }
  52. return hex
  53. }
  54. function randomBase62(length: number): string {
  55. const chars = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz"
  56. const bytes = getRandomBytes(length)
  57. let result = ""
  58. for (let i = 0; i < length; i += 1) {
  59. result += chars[bytes[i] % 62]
  60. }
  61. return result
  62. }
  63. function getRandomBytes(length: number): Uint8Array {
  64. const bytes = new Uint8Array(length)
  65. const cryptoObj = typeof globalThis !== "undefined" ? globalThis.crypto : undefined
  66. if (cryptoObj && typeof cryptoObj.getRandomValues === "function") {
  67. cryptoObj.getRandomValues(bytes)
  68. return bytes
  69. }
  70. for (let i = 0; i < length; i += 1) {
  71. bytes[i] = Math.floor(Math.random() * 256)
  72. }
  73. return bytes
  74. }