File size: 22,993 Bytes
96c8713 | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 | import {
API_VERSION_HEADER_NAME,
BASE64URL_REGEX,
PKCE_FLOW_ID_PARAM,
PKCE_MAX_CONCURRENT_FLOWS,
} from './constants'
import { AuthInvalidJwtError } from './errors'
import { base64UrlToUint8Array, stringFromBase64URL } from './base64url'
import { JwtHeader, JwtPayload, SupportedStorage, User } from './types'
import { Uint8Array_ } from './webauthn.dom'
export function expiresAt(expiresIn: number) {
const timeNow = Math.round(Date.now() / 1000)
return timeNow + expiresIn
}
/**
* Generates a unique identifier for internal callback subscriptions.
*
* This function uses JavaScript Symbols to create guaranteed-unique identifiers
* for auth state change callbacks. Symbols are ideal for this use case because:
* - They are guaranteed unique by the JavaScript runtime
* - They work in all environments (browser, SSR, Node.js)
* - They avoid issues with Next.js 16 deterministic rendering requirements
* - They are perfect for internal, non-serializable identifiers
*
* Note: This function is only used for internal subscription management,
* not for security-critical operations like session tokens.
*/
export function generateCallbackId(): symbol {
return Symbol('auth-callback')
}
export const isBrowser = () => typeof window !== 'undefined' && typeof document !== 'undefined'
const localStorageWriteTests = {
tested: false,
writable: false,
}
/**
* Checks whether localStorage is supported on this browser.
*/
export const supportsLocalStorage = () => {
if (!isBrowser()) {
return false
}
try {
if (typeof globalThis.localStorage !== 'object') {
return false
}
} catch (e) {
// DOM exception when accessing `localStorage`
return false
}
if (localStorageWriteTests.tested) {
return localStorageWriteTests.writable
}
const randomKey = `lswt-${Math.random()}${Math.random()}`
try {
globalThis.localStorage.setItem(randomKey, randomKey)
globalThis.localStorage.removeItem(randomKey)
localStorageWriteTests.tested = true
localStorageWriteTests.writable = true
} catch (e) {
// localStorage can't be written to
// https://www.chromium.org/for-testers/bug-reporting-guidelines/uncaught-securityerror-failed-to-read-the-localstorage-property-from-window-access-is-denied-for-this-document
localStorageWriteTests.tested = true
localStorageWriteTests.writable = false
}
return localStorageWriteTests.writable
}
/**
* Extracts parameters encoded in the URL both in the query and fragment.
*/
export function parseParametersFromURL(href: string) {
const result: { [parameter: string]: string } = {}
const url = new URL(href)
if (url.hash && url.hash[0] === '#') {
try {
const hashSearchParams = new URLSearchParams(url.hash.substring(1))
hashSearchParams.forEach((value, key) => {
result[key] = value
})
} catch (_e) {
// hash is not a query string
}
}
// search parameters take precedence over hash parameters
url.searchParams.forEach((value, key) => {
result[key] = value
})
return result
}
type Fetch = typeof fetch
export const resolveFetch = (customFetch?: Fetch): Fetch => {
if (customFetch) {
return (...args) => customFetch(...args)
}
return (...args) => fetch(...args)
}
export const looksLikeFetchResponse = (maybeResponse: unknown): maybeResponse is Response => {
return (
typeof maybeResponse === 'object' &&
maybeResponse !== null &&
'status' in maybeResponse &&
'ok' in maybeResponse &&
'json' in maybeResponse &&
typeof (maybeResponse as any).json === 'function'
)
}
// Storage helpers
export const setItemAsync = async (
storage: SupportedStorage,
key: string,
data: any
): Promise<void> => {
await storage.setItem(key, JSON.stringify(data))
}
export const getItemAsync = async (storage: SupportedStorage, key: string): Promise<unknown> => {
const value = await storage.getItem(key)
if (!value) {
return null
}
try {
return JSON.parse(value)
} catch {
// Storage values are always written as JSON via setItemAsync. A non-JSON
// value means the entry is corrupted (e.g. mismatched chunked cookies in
// SSR contexts). Treat as absent so callers do not mutate or re-save the
// garbage, which would otherwise trigger a TypeError downstream and
// leak the raw value into error logs.
return null
}
}
export const removeItemAsync = async (storage: SupportedStorage, key: string): Promise<void> => {
await storage.removeItem(key)
}
/**
* A deferred represents some asynchronous work that is not yet finished, which
* may or may not culminate in a value.
* Taken from: https://github.com/mike-north/types/blob/master/src/async.ts
*/
export class Deferred<T = any> {
public static promiseConstructor: PromiseConstructor = Promise
public readonly promise!: PromiseLike<T>
public readonly resolve!: (value?: T | PromiseLike<T>) => void
public readonly reject!: (reason?: any) => any
public constructor() {
// eslint-disable-next-line @typescript-eslint/no-extra-semi
;(this as any).promise = new Deferred.promiseConstructor((res, rej) => {
// eslint-disable-next-line @typescript-eslint/no-extra-semi
;(this as any).resolve = res
// eslint-disable-next-line @typescript-eslint/no-extra-semi
;(this as any).reject = rej
})
}
}
export function decodeJWT(token: string): {
header: JwtHeader
payload: JwtPayload
signature: Uint8Array_
raw: {
header: string
payload: string
}
} {
const parts = token.split('.')
if (parts.length !== 3) {
throw new AuthInvalidJwtError('Invalid JWT structure')
}
// Regex checks for base64url format
for (let i = 0; i < parts.length; i++) {
if (!BASE64URL_REGEX.test(parts[i] as string)) {
throw new AuthInvalidJwtError('JWT not in base64url format')
}
}
const data = {
// using base64url lib
header: JSON.parse(stringFromBase64URL(parts[0])),
payload: JSON.parse(stringFromBase64URL(parts[1])),
signature: base64UrlToUint8Array(parts[2]),
raw: {
header: parts[0],
payload: parts[1],
},
}
return data
}
/**
* Creates a promise that resolves to null after some time.
*/
export async function sleep(time: number): Promise<null> {
return await new Promise((accept) => {
setTimeout(() => accept(null), time)
})
}
/**
* Converts the provided async function into a retryable function. Each result
* or thrown error is sent to the isRetryable function which should return true
* if the function should run again.
*/
export function retryable<T>(
fn: (attempt: number) => Promise<T>,
isRetryable: (attempt: number, error: any | null, result?: T) => boolean
): Promise<T> {
const promise = new Promise<T>((accept, reject) => {
// eslint-disable-next-line @typescript-eslint/no-extra-semi
;(async () => {
for (let attempt = 0; attempt < Infinity; attempt++) {
try {
const result = await fn(attempt)
if (!isRetryable(attempt, null, result)) {
accept(result)
return
}
} catch (e) {
if (!isRetryable(attempt, e)) {
reject(e)
return
}
}
}
})()
})
return promise
}
function dec2hex(dec: number) {
return ('0' + dec.toString(16)).substr(-2)
}
// Functions below taken from: https://stackoverflow.com/questions/63309409/creating-a-code-verifier-and-challenge-for-pkce-auth-on-spotify-api-in-reactjs
export function generatePKCEVerifier() {
const verifierLength = 56
const array = new Uint32Array(verifierLength)
if (typeof crypto === 'undefined') {
const charSet = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-._~'
const charSetLen = charSet.length
let verifier = ''
for (let i = 0; i < verifierLength; i++) {
verifier += charSet.charAt(Math.floor(Math.random() * charSetLen))
}
return verifier
}
crypto.getRandomValues(array)
return Array.from(array, dec2hex).join('')
}
async function sha256(randomString: string) {
const encoder = new TextEncoder()
const encodedData = encoder.encode(randomString)
const hash = await crypto.subtle.digest('SHA-256', encodedData)
const bytes = new Uint8Array(hash)
return Array.from(bytes)
.map((c) => String.fromCharCode(c))
.join('')
}
export async function generatePKCEChallenge(verifier: string) {
const hasCryptoSupport =
typeof crypto !== 'undefined' &&
typeof crypto.subtle !== 'undefined' &&
typeof TextEncoder !== 'undefined'
if (!hasCryptoSupport) {
console.warn(
'WebCrypto API is not supported. Code challenge method will default to use plain instead of sha256.'
)
return verifier
}
const hashed = await sha256(verifier)
return btoa(hashed).replace(/\+/g, '-').replace(/\//g, '_').replace(/=+$/, '')
}
const PKCE_FLOW_ID_PATTERN = /^[a-zA-Z0-9_-]{8,64}$/
/**
* Returns the flow id if it is a plausible flow id, `null` otherwise. Flow
* ids can arrive via URL parameters, so anything outside the expected shape
* is discarded before it is used to build a storage key.
*/
export function validatePKCEFlowId(flowId: unknown): string | null {
return typeof flowId === 'string' && PKCE_FLOW_ID_PATTERN.test(flowId) ? flowId : null
}
export function generatePKCEFlowId(): string {
if (typeof crypto !== 'undefined' && typeof crypto.getRandomValues === 'function') {
const bytes = new Uint8Array(16)
crypto.getRandomValues(bytes)
return Array.from(bytes, dec2hex).join('')
}
let flowId = ''
for (let i = 0; i < 32; i++) {
flowId += Math.floor(Math.random() * 16).toString(16)
}
return flowId
}
// Slot keys deliberately end in `-code-verifier`: @supabase/ssr's server
// cookie adapter only persists writes immediately for keys with that suffix
// (no auth event fires when a verifier is stored). They also contain no dot,
// because @supabase/ssr chunks oversized cookies as `<key>.<number>` and a
// dot-delimited key could be mistaken for a chunk of the fixed
// `-code-verifier` cookie and clobbered by its chunk management.
export const pkceVerifierSlotKey = (storageKey: string, flowId: string) =>
`${storageKey}-flow-${flowId}-code-verifier`
const pkceFlowIndexKey = (storageKey: string) => `${storageKey}-flows-code-verifier`
/**
* Storage adapters cannot enumerate keys, so the ids of pending verifier
* slots are tracked in an index entry, oldest first. Index entries pass
* through the same validation as URL-provided flow ids: with cookie-based
* storage the index contents are no more trustworthy than a URL parameter.
*/
async function getPKCEFlowIndex(storage: SupportedStorage, storageKey: string): Promise<string[]> {
const index = await getItemAsync(storage, pkceFlowIndexKey(storageKey))
return Array.isArray(index)
? index.filter((id): id is string => validatePKCEFlowId(id) !== null)
: []
}
/**
* The index is read-modify-write without a lock: two concurrent starts (e.g.
* two tabs) can lose one index update. The losing flow still works — its slot
* is addressed directly by key — but its entry is missing from the index, so
* it escapes both ring eviction and removeAllPKCEVerifiers: the orphaned slot
* persists for the storage medium's lifetime (up to the cookie max age in
* cookie storage) and repeated races accumulate one orphan each. Accepted
* trade-off: locking every flow start is far more intrusive than the leak.
*/
export async function storePKCEVerifier(
storage: SupportedStorage,
storageKey: string,
flowId: string,
verifier: string,
onEvictFlow?: (evictedFlowId: string) => void
): Promise<void> {
await setItemAsync(storage, pkceVerifierSlotKey(storageKey, flowId), verifier)
const index = (await getPKCEFlowIndex(storage, storageKey)).filter((id) => id !== flowId)
index.push(flowId)
while (index.length > PKCE_MAX_CONCURRENT_FLOWS) {
const evicted = index.shift()!
await removeItemAsync(storage, pkceVerifierSlotKey(storageKey, evicted))
onEvictFlow?.(evicted)
}
await setItemAsync(storage, pkceFlowIndexKey(storageKey), index)
// Deprecation-window dual write: exchanges that cannot identify their flow
// (older SDK versions, redirects without the flow id parameter) read the
// fixed key, which mirrors the most recently started flow.
await setItemAsync(storage, `${storageKey}-code-verifier`, verifier)
}
/**
* Looks up the verifier for `flowId`. When a flow id is given, only that slot
* is consulted — deliberately no fallback to the fixed legacy key: submitting
* another flow's verifier would burn the single-use auth code, and the
* subsequent cleanup would delete a pending flow's only fallback. The legacy
* key is read only when no flow id is available at all.
*/
export async function retrievePKCEVerifier(
storage: SupportedStorage,
storageKey: string,
flowId: string | null
): Promise<{ verifier: string | null; flowId: string | null }> {
if (flowId) {
const verifier = await getItemAsync(storage, pkceVerifierSlotKey(storageKey, flowId))
return { verifier: typeof verifier === 'string' ? verifier : null, flowId }
}
const verifier = await getItemAsync(storage, `${storageKey}-code-verifier`)
return { verifier: typeof verifier === 'string' ? verifier : null, flowId: null }
}
/**
* Removes a single flow's verifier. Never clears other flows' slots: with a
* `flowId` only that slot is deleted (plus the legacy fixed key when it holds
* the same verifier); without one, only the legacy fixed key is deleted.
*/
export async function removePKCEVerifier(
storage: SupportedStorage,
storageKey: string,
flowId: string | null
): Promise<void> {
const legacyKey = `${storageKey}-code-verifier`
if (!flowId) {
await removeItemAsync(storage, legacyKey)
return
}
const slotKey = pkceVerifierSlotKey(storageKey, flowId)
const slotValue = await getItemAsync(storage, slotKey)
await removeItemAsync(storage, slotKey)
// Skip the index rewrite when the flow was never indexed (e.g. a failed
// exchange for an absent slot): on cookie storage every write is a full
// Set-Cookie cycle.
const index = await getPKCEFlowIndex(storage, storageKey)
const remaining = index.filter((id) => id !== flowId)
if (remaining.length !== index.length) {
if (remaining.length > 0) {
await setItemAsync(storage, pkceFlowIndexKey(storageKey), remaining)
} else {
await removeItemAsync(storage, pkceFlowIndexKey(storageKey))
}
}
if (slotValue != null && slotValue === (await getItemAsync(storage, legacyKey))) {
await removeItemAsync(storage, legacyKey)
}
}
/**
* Removes every pending verifier: all slots in the index, the index itself
* and the fixed legacy key. Used on session teardown (sign-out, invalid
* session) — matches the pre-slot behavior where tearing down the session
* deleted the only verifier, and prevents long-lived stale verifier cookies.
*/
export async function removeAllPKCEVerifiers(
storage: SupportedStorage,
storageKey: string
): Promise<void> {
const index = await getPKCEFlowIndex(storage, storageKey)
for (const flowId of index) {
await removeItemAsync(storage, pkceVerifierSlotKey(storageKey, flowId))
}
await removeItemAsync(storage, pkceFlowIndexKey(storageKey))
await removeItemAsync(storage, `${storageKey}-code-verifier`)
}
/**
* Appends the reserved flow id parameter to a `redirectTo` URL, replacing any
* existing occurrence. String-based (no URL round-trip) so custom schemes
* (native deep links) and the exact encoding of the app's own parameters
* survive untouched; an existing fragment stays at the end of the URL.
*/
export function appendFlowIdToRedirectTo(redirectTo: string, flowId: string): string {
const hashIndex = redirectTo.indexOf('#')
let base = hashIndex === -1 ? redirectTo : redirectTo.slice(0, hashIndex)
const fragment = hashIndex === -1 ? '' : redirectTo.slice(hashIndex)
const queryIndex = base.indexOf('?')
if (queryIndex !== -1) {
const path = base.slice(0, queryIndex)
const remaining = base
.slice(queryIndex + 1)
.split('&')
.filter(
(pair) =>
pair !== '' && pair !== PKCE_FLOW_ID_PARAM && !pair.startsWith(`${PKCE_FLOW_ID_PARAM}=`)
)
base = remaining.length > 0 ? `${path}?${remaining.join('&')}` : path
}
const separator = base.includes('?') ? '&' : '?'
return `${base}${separator}${PKCE_FLOW_ID_PARAM}=${encodeURIComponent(flowId)}${fragment}`
}
export async function getCodeChallengeAndMethod(
storage: SupportedStorage,
storageKey: string,
isPasswordRecovery = false,
onEvictFlow?: (evictedFlowId: string) => void
): Promise<[string, string, string]> {
const codeVerifier = generatePKCEVerifier()
let storedCodeVerifier = codeVerifier
if (isPasswordRecovery) {
storedCodeVerifier += '/recovery'
}
const flowId = generatePKCEFlowId()
await storePKCEVerifier(storage, storageKey, flowId, storedCodeVerifier, onEvictFlow)
const codeChallenge = await generatePKCEChallenge(codeVerifier)
const codeChallengeMethod = codeVerifier === codeChallenge ? 'plain' : 's256'
return [codeChallenge, codeChallengeMethod, flowId]
}
/** Parses the API version which is 2YYY-MM-DD. */
const API_VERSION_REGEX = /^2[0-9]{3}-(0[1-9]|1[0-2])-(0[1-9]|1[0-9]|2[0-9]|3[0-1])$/i
export function parseResponseAPIVersion(response: Response) {
const apiVersion = response.headers.get(API_VERSION_HEADER_NAME)
if (!apiVersion) {
return null
}
if (!apiVersion.match(API_VERSION_REGEX)) {
return null
}
try {
const date = new Date(`${apiVersion}T00:00:00.0Z`)
return date
} catch (_e) {
return null
}
}
export function validateExp(exp: number) {
if (!exp) {
throw new Error('Missing exp claim')
}
const timeNow = Math.floor(Date.now() / 1000)
if (exp <= timeNow) {
throw new Error('JWT has expired')
}
}
export function getAlgorithm(
alg: 'HS256' | 'RS256' | 'ES256' | (string & {})
): RsaHashedImportParams | EcKeyImportParams {
switch (alg) {
case 'RS256':
return {
name: 'RSASSA-PKCS1-v1_5',
hash: { name: 'SHA-256' },
}
case 'ES256':
return {
name: 'ECDSA',
namedCurve: 'P-256',
hash: { name: 'SHA-256' },
}
default:
throw new Error('Invalid alg claim')
}
}
const UUID_REGEX = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i
export function validateUUID(str: string) {
if (!UUID_REGEX.test(str)) {
throw new Error('@supabase/auth-js: Expected parameter to be UUID but is not')
}
}
export function assertPasskeyExperimentalEnabled(experimental: { passkey?: boolean }): void {
if (!experimental.passkey) {
throw new Error(
'@supabase/auth-js: the passkey API is experimental and disabled by default. Enable it by passing `auth: { experimental: { passkey: true } }` to createClient (or to the GoTrueClient constructor).'
)
}
}
export function userNotAvailableProxy(): User {
const proxyTarget = {} as User
return new Proxy(proxyTarget, {
get: (target: any, prop: string) => {
if (prop === '__isUserNotAvailableProxy') {
return true
}
// Preventative check for common problematic symbols during cloning/inspection
// These symbols might be accessed by structuredClone or other internal mechanisms.
if (typeof prop === 'symbol') {
const sProp = (prop as symbol).toString()
if (
sProp === 'Symbol(Symbol.toPrimitive)' ||
sProp === 'Symbol(Symbol.toStringTag)' ||
sProp === 'Symbol(util.inspect.custom)'
) {
// Node.js util.inspect
return undefined
}
}
throw new Error(
`@supabase/auth-js: client was created with userStorage option and there was no user stored in the user storage. Accessing the "${prop}" property of the session object is not supported. Please use getUser() instead.`
)
},
set: (_target: any, prop: string) => {
throw new Error(
`@supabase/auth-js: client was created with userStorage option and there was no user stored in the user storage. Setting the "${prop}" property of the session object is not supported. Please use getUser() to fetch a user object you can manipulate.`
)
},
deleteProperty: (_target: any, prop: string) => {
throw new Error(
`@supabase/auth-js: client was created with userStorage option and there was no user stored in the user storage. Deleting the "${prop}" property of the session object is not supported. Please use getUser() to fetch a user object you can manipulate.`
)
},
})
}
/**
* Creates a proxy around a user object that warns when properties are accessed on the server.
* This is used to alert developers that using user data from getSession() on the server is insecure.
*
* @param user The actual user object to wrap
* @param suppressWarningRef An object with a 'value' property that controls warning suppression
* @returns A proxied user object that warns on property access
*/
export function insecureUserWarningProxy(user: User, suppressWarningRef: { value: boolean }): User {
return new Proxy(user, {
get: (target: any, prop: string | symbol, receiver: any) => {
// Allow internal checks without warning
if (prop === '__isInsecureUserWarningProxy') {
return true
}
// Preventative check for common problematic symbols during cloning/inspection
// These symbols might be accessed by structuredClone or other internal mechanisms
if (typeof prop === 'symbol') {
const sProp = prop.toString()
if (
sProp === 'Symbol(Symbol.toPrimitive)' ||
sProp === 'Symbol(Symbol.toStringTag)' ||
sProp === 'Symbol(util.inspect.custom)' ||
sProp === 'Symbol(nodejs.util.inspect.custom)'
) {
// Return the actual value for these symbols to allow proper inspection
return Reflect.get(target, prop, receiver)
}
}
// Emit warning on first property access
if (!suppressWarningRef.value && typeof prop === 'string') {
console.warn(
'Using the user object as returned from supabase.auth.getSession() or from some supabase.auth.onAuthStateChange() events could be insecure! This value comes directly from the storage medium (usually cookies on the server) and may not be authentic. Use supabase.auth.getUser() instead which authenticates the data by contacting the Supabase Auth server.'
)
suppressWarningRef.value = true
}
return Reflect.get(target, prop, receiver)
},
})
}
/**
* Deep clones a JSON-serializable object using JSON.parse(JSON.stringify(obj)).
* Note: Only works for JSON-safe data.
*/
export function deepClone<T>(obj: T): T {
return JSON.parse(JSON.stringify(obj))
}
|