Skip to content

Commit 34b3edf

Browse files
committed
fix(web): browser-safe ere computation
- Add byteLength helper (Buffer.byteLength or TextEncoder fallback)\n- Use in puid.ts and puid.web.ts to avoid Buffer dependency in browsers\n- All tests passing
1 parent 7f23418 commit 34b3edf

File tree

3 files changed

+11
-2
lines changed

3 files changed

+11
-2
lines changed

src/lib/byteLength.ts

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,7 @@
1+
export const byteLength = (s: string): number => {
2+
const B: any = (globalThis as any)?.Buffer
3+
if (B && typeof B.byteLength === 'function') return B.byteLength(s)
4+
if (typeof TextEncoder !== 'undefined') return new TextEncoder().encode(s).length
5+
// Fallback: UTF-16 code units length; acceptable as a last resort for ere
6+
return s.length
7+
}

src/lib/puid.ts

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -5,6 +5,7 @@ import { EntropyByBytes, EntropyByValues, EntropyFunction, Puid, PuidConfig, Pui
55
import muncher from './bits'
66
import { Chars, charsName, validChars } from './chars'
77
import { entropyBits, entropyBitsPerChar } from './entropy'
8+
import { byteLength } from './byteLength'
89

910
const round2 = (f: number): number => round(f * 100) / 100
1011

@@ -99,7 +100,7 @@ export default (puidConfig: PuidConfig = {}): PuidResult => {
99100
: puidConfig.bits || DEFAULT_ENTROPY
100101
const puidBitsPerChar = entropyBitsPerChar(puidChars)
101102
const puidLen = round(ceil(puidEntropyBits / puidBitsPerChar))
102-
const ere = (puidBitsPerChar * puidChars.length) / (8 * Buffer.byteLength(puidChars))
103+
const ere = (puidBitsPerChar * puidChars.length) / (8 * byteLength(puidChars))
103104

104105
const bitsMuncher = muncher(puidLen, puidChars, selectEntropyFunction(puidConfig))
105106

src/lib/puid.web.ts

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -3,6 +3,7 @@ import { EntropyByBytes, EntropyByValues, EntropyFunction, Puid, PuidConfig, Pui
33
import muncher from './bits'
44
import { Chars, charsName, validChars } from './chars'
55
import { entropyBits, entropyBitsPerChar } from './entropy'
6+
import { byteLength } from './byteLength'
67

78
const round2 = (f: number): number => round(f * 100) / 100
89

@@ -50,7 +51,7 @@ export default (puidConfig: PuidConfig = {}): PuidResult => {
5051
: puidConfig.bits || DEFAULT_ENTROPY
5152
const puidBitsPerChar = entropyBitsPerChar(puidChars)
5253
const puidLen = round(ceil(puidEntropyBits / puidBitsPerChar))
53-
const ere = (puidBitsPerChar * puidChars.length) / (8 * Buffer.byteLength(puidChars))
54+
const ere = (puidBitsPerChar * puidChars.length) / (8 * byteLength(puidChars))
5455

5556
const bitsMuncher = muncher(puidLen, puidChars, selectEntropyFunction(puidConfig))
5657

0 commit comments

Comments
 (0)