cloudaxe-opencode/packages/util/src/identifier.ts

49 lines
1.1 KiB
TypeScript
Raw Permalink Normal View History

2025-12-18 21:47:16 +00:00
import { randomBytes } from "crypto"
export namespace Identifier {
2025-12-18 21:47:16 +00:00
const LENGTH = 26
2025-12-18 21:47:16 +00:00
// State for monotonic ID generation
let lastTimestamp = 0
let counter = 0
2025-12-18 21:47:16 +00:00
export function ascending() {
return create(false)
}
2025-12-18 21:47:16 +00:00
export function descending() {
return create(true)
}
function randomBase62(length: number): string {
const chars = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz"
let result = ""
2025-12-18 21:47:16 +00:00
const bytes = randomBytes(length)
for (let i = 0; i < length; i++) {
2025-12-18 21:47:16 +00:00
result += chars[bytes[i] % 62]
}
return result
}
2025-12-18 21:47:16 +00:00
export function create(descending: boolean, timestamp?: number): string {
const currentTimestamp = timestamp ?? Date.now()
2025-12-18 21:47:16 +00:00
if (currentTimestamp !== lastTimestamp) {
lastTimestamp = currentTimestamp
counter = 0
}
2025-12-18 21:47:16 +00:00
counter++
2025-12-18 21:47:16 +00:00
let now = BigInt(currentTimestamp) * BigInt(0x1000) + BigInt(counter)
2025-12-18 21:47:16 +00:00
now = descending ? ~now : now
2025-12-18 21:47:16 +00:00
const timeBytes = Buffer.alloc(6)
for (let i = 0; i < 6; i++) {
timeBytes[i] = Number((now >> BigInt(40 - 8 * i)) & BigInt(0xff))
}
2025-12-18 21:47:16 +00:00
return timeBytes.toString("hex") + randomBase62(LENGTH - 12)
}
}