Handle browsers without Web Locks
This commit is contained in:
@@ -0,0 +1,42 @@
|
||||
import {afterEach, describe, expect, it, jest} from '@jest/globals'
|
||||
|
||||
import {runWithSessionCredentialLock} from '../session-lock.web'
|
||||
|
||||
const originalNavigatorDescriptor = Object.getOwnPropertyDescriptor(
|
||||
globalThis,
|
||||
'navigator',
|
||||
)
|
||||
|
||||
function setNavigator(value: unknown) {
|
||||
Object.defineProperty(globalThis, 'navigator', {
|
||||
configurable: true,
|
||||
value,
|
||||
})
|
||||
}
|
||||
|
||||
afterEach(() => {
|
||||
if (originalNavigatorDescriptor) {
|
||||
Object.defineProperty(globalThis, 'navigator', originalNavigatorDescriptor)
|
||||
} else {
|
||||
Reflect.deleteProperty(globalThis, 'navigator')
|
||||
}
|
||||
})
|
||||
|
||||
describe('session credential locks on unsupported browsers', () => {
|
||||
it.each([
|
||||
['navigator is unavailable', undefined],
|
||||
['navigator.locks is unavailable', {}],
|
||||
['navigator.locks.request is unavailable', {locks: {}}],
|
||||
])('runs without a lock when %s', async (_, navigatorValue) => {
|
||||
setNavigator(navigatorValue)
|
||||
const operation = jest.fn(() => 'result')
|
||||
|
||||
await expect(
|
||||
runWithSessionCredentialLock({
|
||||
accountDids: ['did:plc:example'],
|
||||
operation,
|
||||
}),
|
||||
).resolves.toBe('result')
|
||||
expect(operation).toHaveBeenCalledTimes(1)
|
||||
})
|
||||
})
|
||||
@@ -8,7 +8,7 @@ export function runWithSessionCredentialLock<T>({
|
||||
accountDids: string[]
|
||||
operation: () => T | Promise<T>
|
||||
}): Promise<T> {
|
||||
const lockManager = navigator.locks
|
||||
const lockManager = getLockManager()
|
||||
if (!lockManager) {
|
||||
try {
|
||||
return Promise.resolve(operation())
|
||||
@@ -35,3 +35,11 @@ export function runWithSessionCredentialLock<T>({
|
||||
|
||||
return run(0)
|
||||
}
|
||||
|
||||
function getLockManager(): LockManager | undefined {
|
||||
if (typeof navigator === 'undefined' || !('locks' in navigator)) {
|
||||
return undefined
|
||||
}
|
||||
const lockManager = navigator.locks
|
||||
return typeof lockManager?.request === 'function' ? lockManager : undefined
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user