summaryrefslogtreecommitdiffhomepage
path: root/packages/shared/src/util/identifier.ts
diff options
context:
space:
mode:
authorDax <[email protected]>2026-04-15 10:26:20 -0400
committerGitHub <[email protected]>2026-04-15 14:26:20 +0000
commitbe9432a893dd1662c10ff41c7ab552bcba8f3e1b (patch)
treef49000b3dd9c3bea5247d319e8fcbd4fb879b7b0 /packages/shared/src/util/identifier.ts
parentaf20191d1cd60a7f4a421ad81eca5053f7deace1 (diff)
downloadopencode-be9432a893dd1662c10ff41c7ab552bcba8f3e1b.tar.gz
opencode-be9432a893dd1662c10ff41c7ab552bcba8f3e1b.zip
shared package (#22626)
Diffstat (limited to 'packages/shared/src/util/identifier.ts')
-rw-r--r--packages/shared/src/util/identifier.ts48
1 files changed, 48 insertions, 0 deletions
diff --git a/packages/shared/src/util/identifier.ts b/packages/shared/src/util/identifier.ts
new file mode 100644
index 000000000..ba28a351b
--- /dev/null
+++ b/packages/shared/src/util/identifier.ts
@@ -0,0 +1,48 @@
+import { randomBytes } from "crypto"
+
+export namespace Identifier {
+ const LENGTH = 26
+
+ // State for monotonic ID generation
+ let lastTimestamp = 0
+ let counter = 0
+
+ export function ascending() {
+ return create(false)
+ }
+
+ export function descending() {
+ return create(true)
+ }
+
+ function randomBase62(length: number): string {
+ const chars = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz"
+ let result = ""
+ const bytes = randomBytes(length)
+ for (let i = 0; i < length; i++) {
+ result += chars[bytes[i] % 62]
+ }
+ return result
+ }
+
+ export function create(descending: boolean, timestamp?: number): string {
+ const currentTimestamp = timestamp ?? Date.now()
+
+ if (currentTimestamp !== lastTimestamp) {
+ lastTimestamp = currentTimestamp
+ counter = 0
+ }
+ counter++
+
+ let now = BigInt(currentTimestamp) * BigInt(0x1000) + BigInt(counter)
+
+ now = 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))
+ }
+
+ return timeBytes.toString("hex") + randomBase62(LENGTH - 12)
+ }
+}