@file:OptIn(kotlin.js.ExperimentalWasmJsInterop::class) package eu.friedcutlet.yokan.app.profiles import kotlinx.coroutines.NonCancellable import kotlinx.coroutines.await import kotlinx.coroutines.withContext import kotlin.js.JsAny import kotlin.js.Promise import eu.friedcutlet.yokan.domain.ProfileId internal actual suspend fun acquireProfileStorageLease(id: ProfileId): ProfileStorageLease { if (id == ProfileId.Default) return ProfileStorageLease {} var acquired: JsAny? = null try { withContext(NonCancellable) { acquired = reserveProfile(id.value).await() } val handle = checkNotNull(acquired) return ProfileStorageLease { withContext(NonCancellable) { releaseProfile(handle).await() } } } catch (error: Throwable) { acquired?.let { handle -> withContext(NonCancellable) { releaseProfile(handle).await() } } throw error } } private fun reserveProfile(id: String): Promise = js( """new Promise((resolve, reject) => { if (!navigator.locks || !navigator.locks.request) { reject(new Error('Profile storage requires Web Locks')); return; } const handle = { release: null, done: null }; handle.done = navigator.locks.request('yokan-profile-storage:' + id, {ifAvailable: true}, lock => { if (!lock) throw new Error('Profile is open in another tab'); return new Promise(release => { handle.release = release; resolve(handle); }); }); handle.done.catch(reject); })""", ) private fun releaseProfile(handle: JsAny): Promise = js("(handle.release(), handle.done)")