36 lines
1.3 KiB
TypeScript
36 lines
1.3 KiB
TypeScript
/**
|
||
* Генерация UUID v4.
|
||
*
|
||
* `crypto.randomUUID()` доступен только в secure context (https или localhost),
|
||
* поэтому при открытии фронта по сетевому адресу (http://<ip>:5174) он отсутствует
|
||
* и падает с «crypto.randomUUID is not a function». `crypto.getRandomValues`, наоборот,
|
||
* доступен и в insecure context — используем его как фолбэк (RFC 4122 v4).
|
||
*/
|
||
export function generateUuid(): string {
|
||
if (typeof crypto !== "undefined" && typeof crypto.randomUUID === "function") {
|
||
return crypto.randomUUID();
|
||
}
|
||
return uuidV4Fallback();
|
||
}
|
||
|
||
/** RFC 4122 v4 на основе crypto.getRandomValues (работает в insecure context). */
|
||
export function uuidV4Fallback(): string {
|
||
const bytes = new Uint8Array(16);
|
||
crypto.getRandomValues(bytes);
|
||
bytes[6] = (bytes[6] & 0x0f) | 0x40; // версия 4
|
||
bytes[8] = (bytes[8] & 0x3f) | 0x80; // variant 10xx
|
||
|
||
const hex = Array.from(bytes, (b) => b.toString(16).padStart(2, "0"));
|
||
return (
|
||
hex.slice(0, 4).join("") +
|
||
"-" +
|
||
hex.slice(4, 6).join("") +
|
||
"-" +
|
||
hex.slice(6, 8).join("") +
|
||
"-" +
|
||
hex.slice(8, 10).join("") +
|
||
"-" +
|
||
hex.slice(10, 16).join("")
|
||
);
|
||
}
|