snippets.browser.ts 1.5 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647
  1. import { IS_PLATFORM } from 'common'
  2. import { compact } from 'lodash'
  3. import { v4 as uuidv4 } from 'uuid'
  4. /**
  5. * Generates a UUID v4. If the platform is self-hosted, it will generate a deterministic UUID v4 from the inputs.
  6. */
  7. export const generateUuid = (inputs: (string | undefined | null)[] = []) => {
  8. const cleaned = compact(inputs)
  9. if (!IS_PLATFORM && cleaned.length === 0) return uuidv4()
  10. return IS_PLATFORM ? uuidv4() : generateDeterministicUuid(cleaned)
  11. }
  12. /**
  13. * Generates a deterministic UUID v4 from a string input
  14. * @param inputs - The array of strings to generate a UUID from
  15. * @returns A deterministic UUID v4 string
  16. */
  17. export function generateDeterministicUuid(inputs: (string | undefined | null)[]): string {
  18. const simpleHash = (str: string): number => {
  19. let hash = 0
  20. if (str.length === 0) return hash
  21. for (let i = 0; i < str.length; i++) {
  22. const char = str.charCodeAt(i)
  23. hash = (hash << 5) - hash + char
  24. hash = hash & hash // Convert to 32-bit integer
  25. }
  26. return Math.abs(hash)
  27. }
  28. const input = compact(inputs).join('_')
  29. // Create a deterministic random number generator using the hash as seed
  30. let seed = simpleHash(input)
  31. const rng = () => {
  32. const bytes = new Uint8Array(16)
  33. for (let i = 0; i < 16; i++) {
  34. // Simple LCG (Linear Congruential Generator) for deterministic randomness
  35. seed = (seed * 1103515245 + 12345) & 0x7fffffff
  36. bytes[i] = (seed >>> 16) & 0xff
  37. }
  38. return bytes
  39. }
  40. // Generate UUID v4 using the deterministic RNG
  41. return uuidv4({ rng })
  42. }