@picovoice/cobra-web-factory
Advanced tools
Comparing version 1.0.5 to 1.0.7
@@ -13,8 +13,3 @@ export declare type CobraWorkerRequestInit = { | ||
}; | ||
export declare type CobraWorkerRequestFileOperation = { | ||
command: 'file-save-succeeded' | 'file-save-failed' | 'file-load-succeeded' | 'file-load-failed' | 'file-exists-succeeded' | 'file-exists-failed' | 'file-delete-succeeded' | 'file-delete-failed'; | ||
message: string; | ||
content?: string; | ||
}; | ||
export declare type CobraWorkerRequest = CobraWorkerRequestInit | CobraWorkerRequestProcess | CobraWorkerRequestVoid | CobraWorkerRequestFileOperation; | ||
export declare type CobraWorkerRequest = CobraWorkerRequestInit | CobraWorkerRequestProcess | CobraWorkerRequestVoid; | ||
export declare type CobraWorkerResponseReady = { | ||
@@ -31,8 +26,3 @@ command: 'cobra-ready'; | ||
}; | ||
export declare type CobraWorkerResponseFileOperation = { | ||
command: 'file-save' | 'file-load' | 'file-exists' | 'file-delete'; | ||
path: string; | ||
content?: string; | ||
}; | ||
export declare type CobraWorkerResponse = CobraWorkerResponseReady | CobraWorkerResponseFailed | CobraWorkerResponseVoiceProbability | CobraWorkerResponseFileOperation; | ||
export declare type CobraWorkerResponse = CobraWorkerResponseReady | CobraWorkerResponseFailed | CobraWorkerResponseVoiceProbability; | ||
export interface CobraEngine { | ||
@@ -39,0 +29,0 @@ /** Release all resources acquired by Cobra */ |
@@ -16,4 +16,2 @@ import { CobraEngine } from './cobra_types'; | ||
private static _version; | ||
private static _resolvePromise; | ||
private static _rejectPromise; | ||
private static _cobraMutex; | ||
@@ -48,5 +46,2 @@ private constructor(); | ||
static create(accessKey: string): Promise<Cobra>; | ||
static clearFilePromises(): void; | ||
static resolveFilePromise(args: any): void; | ||
static rejectFilePromise(args: any): void; | ||
private static initWasm; | ||
@@ -53,0 +48,0 @@ } |
/** | ||
* Storage Interface. | ||
*/ | ||
interface PvStorage { | ||
setItem: (key: string, value: string) => void | Promise<void>; | ||
getItem: (key: string) => string | Promise<string>; | ||
removeItem: (key: string) => void | Promise<void>; | ||
} | ||
/** | ||
* Gets the storage to use. Either tries to use IndexedDB or localStorage. | ||
* | ||
* @returns PvStorage instance to use as storage. | ||
*/ | ||
export declare function getPvStorage(): PvStorage; | ||
/** | ||
* Convert a null terminated phrase stored inside an array buffer to a string | ||
@@ -42,8 +56,2 @@ * | ||
/** | ||
* Environment identifier | ||
* | ||
* @return a string containing the envirorment name | ||
*/ | ||
export declare function getRuntimeEnvironment(): string; | ||
/** | ||
* Checking whether the given AccessKey is valid | ||
@@ -54,2 +62,3 @@ * | ||
export declare function isAccessKeyValid(accessKey: string): boolean; | ||
export {}; | ||
//# sourceMappingURL=utils.d.ts.map |
{ | ||
"name": "@picovoice/cobra-web-factory", | ||
"version": "1.0.5", | ||
"version": "1.0.7", | ||
"description": "Cobra library for web browsers (via WebAssembly)", | ||
@@ -5,0 +5,0 @@ "author": "Picovoice Inc", |
/* | ||
Copyright 2018-2021 Picovoice Inc. | ||
Copyright 2018-2021 Picovoice Inc. | ||
You may not use this file except in compliance with the license. A copy of the license is located in the "LICENSE" | ||
file accompanying this source. | ||
You may not use this file except in compliance with the license. A copy of the license is located in the "LICENSE" | ||
file accompanying this source. | ||
Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on | ||
an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the | ||
specific language governing permissions and limitations under the License. | ||
Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on | ||
an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the | ||
specific language governing permissions and limitations under the License. | ||
*/ | ||
@@ -27,21 +27,6 @@ | ||
export type CobraWorkerRequestFileOperation = { | ||
command: | ||
| 'file-save-succeeded' | ||
| 'file-save-failed' | ||
| 'file-load-succeeded' | ||
| 'file-load-failed' | ||
| 'file-exists-succeeded' | ||
| 'file-exists-failed' | ||
| 'file-delete-succeeded' | ||
| 'file-delete-failed'; | ||
message: string; | ||
content?: string; | ||
}; | ||
export type CobraWorkerRequest = | ||
| CobraWorkerRequestInit | ||
| CobraWorkerRequestProcess | ||
| CobraWorkerRequestVoid | ||
| CobraWorkerRequestFileOperation; | ||
| CobraWorkerRequestVoid; | ||
@@ -62,13 +47,6 @@ export type CobraWorkerResponseReady = { | ||
export type CobraWorkerResponseFileOperation = { | ||
command: 'file-save' | 'file-load' | 'file-exists' | 'file-delete'; | ||
path: string; | ||
content?: string; | ||
}; | ||
export type CobraWorkerResponse = | ||
| CobraWorkerResponseReady | ||
| CobraWorkerResponseFailed | ||
| CobraWorkerResponseVoiceProbability | ||
| CobraWorkerResponseFileOperation; | ||
| CobraWorkerResponseVoiceProbability; | ||
@@ -75,0 +53,0 @@ export interface CobraEngine { |
/* | ||
Copyright 2018-2021 Picovoice Inc. | ||
You may not use this file except in compliance with the license. A copy of the license is located in the "LICENSE" | ||
file accompanying this source. | ||
Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on | ||
an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the | ||
specific language governing permissions and limitations under the License. | ||
Copyright 2018-2021 Picovoice Inc. | ||
You may not use this file except in compliance with the license. A copy of the license is located in the "LICENSE" | ||
file accompanying this source. | ||
Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on | ||
an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the | ||
specific language governing permissions and limitations under the License. | ||
*/ | ||
@@ -14,3 +14,3 @@ | ||
export default class CobraWorkerFactory { | ||
private constructor() { } | ||
private constructor() {} | ||
@@ -60,61 +60,2 @@ /** | ||
break; | ||
case 'file-save': | ||
try { | ||
localStorage.setItem(event.data.path, event.data.content || ''); | ||
cobraWorker.postMessage({ | ||
command: 'file-save-succeeded', | ||
message: `Saved ${event.data.path} successfully`, | ||
}); | ||
} catch (error) { | ||
cobraWorker.postMessage({ | ||
command: 'file-save-failed', | ||
message: `${error}`, | ||
}); | ||
} | ||
break; | ||
case 'file-load': | ||
try { | ||
const content = localStorage.getItem(event.data.path); | ||
if (content === null) { | ||
throw new Error('file does not exist.'); | ||
} | ||
cobraWorker.postMessage({ | ||
command: 'file-load-succeeded', | ||
content: content, | ||
}); | ||
} catch (error) { | ||
cobraWorker.postMessage({ | ||
command: 'file-load-failed', | ||
message: `${error}`, | ||
}); | ||
} | ||
break; | ||
case 'file-exists': | ||
try { | ||
const content = localStorage.getItem(event.data.path); | ||
cobraWorker.postMessage({ | ||
command: 'file-exists-succeeded', | ||
content: content, | ||
}); | ||
} catch (error) { | ||
cobraWorker.postMessage({ | ||
command: 'file-exists-failed', | ||
message: `${error}`, | ||
}); | ||
} | ||
break; | ||
case 'file-delete': | ||
try { | ||
localStorage.removeItem(event.data.path); | ||
cobraWorker.postMessage({ | ||
command: 'file-delete-succeeded', | ||
message: `Deleted ${event.data.path} successfully`, | ||
}); | ||
} catch (error) { | ||
cobraWorker.postMessage({ | ||
command: 'file-delete-failed', | ||
message: `${error}`, | ||
}); | ||
} | ||
break; | ||
default: | ||
@@ -121,0 +62,0 @@ // eslint-disable-next-line no-console |
/* | ||
Copyright 2018-2021 Picovoice Inc. | ||
You may not use this file except in compliance with the license. A copy of the license is located in the "LICENSE" | ||
file accompanying this source. | ||
Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on | ||
an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the | ||
specific language governing permissions and limitations under the License. | ||
Copyright 2018-2021 Picovoice Inc. | ||
You may not use this file except in compliance with the license. A copy of the license is located in the "LICENSE" | ||
file accompanying this source. | ||
Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on | ||
an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the | ||
specific language governing permissions and limitations under the License. | ||
*/ | ||
@@ -63,5 +63,3 @@ | ||
onmessage = function ( | ||
event: MessageEvent<CobraWorkerRequest> | ||
): void { | ||
onmessage = function (event: MessageEvent<CobraWorkerRequest>): void { | ||
switch (event.data.command) { | ||
@@ -83,34 +81,2 @@ case 'init': | ||
break; | ||
case 'file-save-succeeded': | ||
Cobra.resolveFilePromise(event.data.message); | ||
Cobra.clearFilePromises(); | ||
break; | ||
case 'file-save-failed': | ||
Cobra.rejectFilePromise(event.data.message); | ||
Cobra.clearFilePromises(); | ||
break; | ||
case 'file-load-succeeded': | ||
Cobra.resolveFilePromise(event.data.content); | ||
Cobra.clearFilePromises(); | ||
break; | ||
case 'file-load-failed': | ||
Cobra.rejectFilePromise(event.data.message); | ||
Cobra.clearFilePromises(); | ||
break; | ||
case 'file-exists-succeeded': | ||
Cobra.resolveFilePromise(event.data.content); | ||
Cobra.clearFilePromises(); | ||
break; | ||
case 'file-exists-failed': | ||
Cobra.rejectFilePromise(event.data.message); | ||
Cobra.clearFilePromises(); | ||
break; | ||
case 'file-delete-succeeded': | ||
Cobra.resolveFilePromise(event.data.message); | ||
Cobra.clearFilePromises(); | ||
break; | ||
case 'file-delete-failed': | ||
Cobra.rejectFilePromise(event.data.message); | ||
Cobra.clearFilePromises(); | ||
break; | ||
default: | ||
@@ -117,0 +83,0 @@ // eslint-disable-next-line no-console |
280
src/cobra.ts
/* | ||
Copyright 2018-2021 Picovoice Inc. | ||
Copyright 2018-2021 Picovoice Inc. | ||
You may not use this file except in compliance with the license. A copy of the license is located in the "LICENSE" | ||
file accompanying this source. | ||
You may not use this file except in compliance with the license. A copy of the license is located in the "LICENSE" | ||
file accompanying this source. | ||
Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on | ||
an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the | ||
specific language governing permissions and limitations under the License. | ||
Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on | ||
an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the | ||
specific language governing permissions and limitations under the License. | ||
*/ | ||
@@ -14,3 +14,2 @@ | ||
import * as Asyncify from 'asyncify-wasm'; | ||
@@ -28,3 +27,3 @@ import { Mutex } from 'async-mutex'; | ||
fetchWithTimeout, | ||
getRuntimeEnvironment, | ||
getPvStorage, | ||
isAccessKeyValid, | ||
@@ -34,4 +33,2 @@ stringHeaderToObject, | ||
type EmptyPromise = (value: any) => void; | ||
/** | ||
@@ -80,5 +77,3 @@ * JavaScript/WebAssembly Binding for the Picovoice Cobra voice activity detection (VAD) engine. | ||
private static _resolvePromise: EmptyPromise | null; | ||
private static _rejectPromise: EmptyPromise | null; | ||
private static _cobraMutex = new Mutex; | ||
private static _cobraMutex = new Mutex(); | ||
@@ -124,33 +119,36 @@ private constructor(handleWasm: CobraWasmOutput) { | ||
const returnPromise = new Promise<number>((resolve, reject) => { | ||
this._processMutex.runExclusive(async () => { | ||
this._memoryBuffer.set( | ||
pcm, | ||
this._inputBufferAddress / Int16Array.BYTES_PER_ELEMENT | ||
); | ||
this._processMutex | ||
.runExclusive(async () => { | ||
this._memoryBuffer.set( | ||
pcm, | ||
this._inputBufferAddress / Int16Array.BYTES_PER_ELEMENT | ||
); | ||
const status = await this._pvCobraProcess( | ||
this._objectAddress, | ||
this._inputBufferAddress, | ||
this._voiceProbabilityAddress | ||
); | ||
if (status !== PV_STATUS_SUCCESS) { | ||
const memoryBuffer = new Uint8Array(this._wasmMemory.buffer); | ||
throw new Error( | ||
`process failed with status ${arrayBufferToStringAtIndex( | ||
memoryBuffer, | ||
await this._pvStatusToString(status) | ||
)}` | ||
const status = await this._pvCobraProcess( | ||
this._objectAddress, | ||
this._inputBufferAddress, | ||
this._voiceProbabilityAddress | ||
); | ||
} | ||
const voiceProbability = this._memoryBufferView.getFloat32( | ||
this._voiceProbabilityAddress, | ||
true | ||
); | ||
if (status !== PV_STATUS_SUCCESS) { | ||
const memoryBuffer = new Uint8Array(this._wasmMemory.buffer); | ||
throw new Error( | ||
`process failed with status ${arrayBufferToStringAtIndex( | ||
memoryBuffer, | ||
await this._pvStatusToString(status) | ||
)}` | ||
); | ||
} | ||
const voiceProbability = this._memoryBufferView.getFloat32( | ||
this._voiceProbabilityAddress, | ||
true | ||
); | ||
return voiceProbability; | ||
}).then((result: number) => { | ||
resolve(result); | ||
}).catch((error: any) => { | ||
reject(error); | ||
}); | ||
return voiceProbability; | ||
}) | ||
.then((result: number) => { | ||
resolve(result); | ||
}) | ||
.catch((error: any) => { | ||
reject(error); | ||
}); | ||
}); | ||
@@ -187,10 +185,13 @@ return returnPromise; | ||
const returnPromise = new Promise<Cobra>((resolve, reject) => { | ||
Cobra._cobraMutex.runExclusive(async () => { | ||
const wasmOutput = await Cobra.initWasm(accessKey.trim()); | ||
return new Cobra(wasmOutput); | ||
}).then((result: Cobra) => { | ||
resolve(result); | ||
}).catch((error: any) => { | ||
reject(error); | ||
}); | ||
Cobra._cobraMutex | ||
.runExclusive(async () => { | ||
const wasmOutput = await Cobra.initWasm(accessKey.trim()); | ||
return new Cobra(wasmOutput); | ||
}) | ||
.then((result: Cobra) => { | ||
resolve(result); | ||
}) | ||
.catch((error: any) => { | ||
reject(error); | ||
}); | ||
}); | ||
@@ -200,19 +201,2 @@ return returnPromise; | ||
public static clearFilePromises(): void { | ||
Cobra._rejectPromise = null; | ||
Cobra._resolvePromise = null; | ||
} | ||
// eslint-disable-next-line | ||
public static resolveFilePromise(args: any): void { | ||
// @ts-ignore | ||
Cobra._resolvePromise(args); | ||
} | ||
// eslint-disable-next-line | ||
public static rejectFilePromise(args: any): void { | ||
// @ts-ignore | ||
Cobra._rejectPromise(args); | ||
} | ||
private static async initWasm(accessKey: string): Promise<any> { | ||
@@ -224,2 +208,4 @@ const memory = new WebAssembly.Memory({ initial: 100, maximum: 200 }); | ||
const storage = getPvStorage(); | ||
const pvConsoleLogWasm = function (index: number): void { | ||
@@ -230,64 +216,2 @@ // eslint-disable-next-line no-console | ||
const pvFileOperationHelper = function (args: any): Promise<any> { | ||
let promise: any; | ||
const runtimeEnvironment = getRuntimeEnvironment(); | ||
if (runtimeEnvironment === 'worker') { | ||
promise = new Promise((resolve, reject) => { | ||
Cobra._resolvePromise = resolve; | ||
Cobra._rejectPromise = reject; | ||
}); | ||
self.postMessage( | ||
{ | ||
command: args.command, | ||
path: args.path, | ||
content: args.content, | ||
}, | ||
// @ts-ignore | ||
undefined | ||
); | ||
} else if (runtimeEnvironment === 'browser') { | ||
promise = new Promise<string>((resolve, reject) => { | ||
try { | ||
switch (args.command) { | ||
case 'file-save': | ||
localStorage.setItem(args.path, args.content); | ||
resolve('saved'); | ||
break; | ||
case 'file-exists': | ||
{ | ||
const content = localStorage.getItem(args.path); | ||
resolve(content as string); | ||
} | ||
break; | ||
case 'file-load': | ||
{ | ||
const content = localStorage.getItem(args.path); | ||
if (content === null) { | ||
reject(`${args.path} does not exist`); | ||
} else { | ||
resolve(content as string); | ||
} | ||
} | ||
break; | ||
case 'file-delete': | ||
localStorage.removeItem(args.path); | ||
resolve('deleted'); | ||
break; | ||
default: | ||
// eslint-disable-next-line no-console | ||
console.warn(`Unexpected command: ${args.command}`); | ||
reject(); | ||
} | ||
} catch (error) { | ||
reject(); | ||
} | ||
}); | ||
} else { | ||
// eslint-disable-next-line no-console | ||
console.error(`Unexpected environment: ${runtimeEnvironment}`); | ||
return Promise.reject(); | ||
} | ||
return promise; | ||
}; | ||
const pvAssertWasm = function ( | ||
@@ -377,6 +301,5 @@ expr: number, | ||
memoryBufferInt32[responseSizeAddress / Int32Array.BYTES_PER_ELEMENT] = | ||
responseText.length + 1; | ||
memoryBufferInt32[ | ||
responseSizeAddress / Int32Array.BYTES_PER_ELEMENT | ||
] = responseText.length + 1; | ||
memoryBufferInt32[ | ||
responseAddressAddress / Int32Array.BYTES_PER_ELEMENT | ||
@@ -391,5 +314,4 @@ ] = responseAddress; | ||
memoryBufferInt32[ | ||
responseCodeAddress / Int32Array.BYTES_PER_ELEMENT | ||
] = statusCode; | ||
memoryBufferInt32[responseCodeAddress / Int32Array.BYTES_PER_ELEMENT] = | ||
statusCode; | ||
}; | ||
@@ -405,6 +327,3 @@ | ||
try { | ||
const contentBase64 = await pvFileOperationHelper({ | ||
command: 'file-load', | ||
path: path, | ||
}); | ||
const contentBase64 = await storage.getItem(path); | ||
const contentBuffer = base64ToUint8Array(contentBase64); | ||
@@ -428,9 +347,5 @@ // eslint-disable-next-line | ||
memoryBufferUint8.set(contentBuffer, contentAddress); | ||
memoryBufferInt32[ | ||
succeededAddress / Int32Array.BYTES_PER_ELEMENT | ||
] = 1; | ||
memoryBufferInt32[succeededAddress / Int32Array.BYTES_PER_ELEMENT] = 1; | ||
} catch (error) { | ||
memoryBufferInt32[ | ||
succeededAddress / Int32Array.BYTES_PER_ELEMENT | ||
] = 0; | ||
memoryBufferInt32[succeededAddress / Int32Array.BYTES_PER_ELEMENT] = 0; | ||
} | ||
@@ -452,14 +367,6 @@ }; | ||
try { | ||
await pvFileOperationHelper({ | ||
command: 'file-save', | ||
path: path, | ||
content: content, | ||
}); | ||
memoryBufferInt32[ | ||
succeededAddress / Int32Array.BYTES_PER_ELEMENT | ||
] = 1; | ||
await storage.setItem(path, content); | ||
memoryBufferInt32[succeededAddress / Int32Array.BYTES_PER_ELEMENT] = 1; | ||
} catch (error) { | ||
memoryBufferInt32[ | ||
succeededAddress / Int32Array.BYTES_PER_ELEMENT | ||
] = 0; | ||
memoryBufferInt32[succeededAddress / Int32Array.BYTES_PER_ELEMENT] = 0; | ||
} | ||
@@ -476,14 +383,8 @@ }; | ||
try { | ||
const isExists = await pvFileOperationHelper({ | ||
command: 'file-exists', | ||
path: path, | ||
}); | ||
memoryBufferUint8[isExistsAddress] = isExists === null ? 0 : 1; | ||
memoryBufferInt32[ | ||
succeededAddress / Int32Array.BYTES_PER_ELEMENT | ||
] = 1; | ||
const isExists = await storage.getItem(path); | ||
memoryBufferUint8[isExistsAddress] = | ||
isExists === undefined || isExists === null ? 0 : 1; | ||
memoryBufferInt32[succeededAddress / Int32Array.BYTES_PER_ELEMENT] = 1; | ||
} catch (error) { | ||
memoryBufferInt32[ | ||
succeededAddress / Int32Array.BYTES_PER_ELEMENT | ||
] = 0; | ||
memoryBufferInt32[succeededAddress / Int32Array.BYTES_PER_ELEMENT] = 0; | ||
} | ||
@@ -498,17 +399,12 @@ }; | ||
try { | ||
await pvFileOperationHelper({ | ||
command: 'file-delete', | ||
path: path, | ||
}); | ||
memoryBufferInt32[ | ||
succeededAddress / Int32Array.BYTES_PER_ELEMENT | ||
] = 1; | ||
await storage.removeItem(path); | ||
memoryBufferInt32[succeededAddress / Int32Array.BYTES_PER_ELEMENT] = 1; | ||
} catch (error) { | ||
memoryBufferInt32[ | ||
succeededAddress / Int32Array.BYTES_PER_ELEMENT | ||
] = 0; | ||
memoryBufferInt32[succeededAddress / Int32Array.BYTES_PER_ELEMENT] = 0; | ||
} | ||
}; | ||
const pvGetBrowserInfo = async function (browserInfoAddressAddress: number): Promise<void> { | ||
const pvGetBrowserInfo = async function ( | ||
browserInfoAddressAddress: number | ||
): Promise<void> { | ||
const userAgent = | ||
@@ -535,2 +431,25 @@ navigator.userAgent !== undefined ? navigator.userAgent : 'unknown'; | ||
const pvGetOriginInfo = async function ( | ||
originInfoAddressAddress: number | ||
): Promise<void> { | ||
const origin = self.origin ?? self.location.origin; | ||
// eslint-disable-next-line | ||
const originInfoAddress = await aligned_alloc( | ||
Uint8Array.BYTES_PER_ELEMENT, | ||
(origin.length + 1) * Uint8Array.BYTES_PER_ELEMENT | ||
); | ||
if (originInfoAddress === 0) { | ||
throw new Error('malloc failed: Cannot allocate memory'); | ||
} | ||
memoryBufferInt32[ | ||
originInfoAddressAddress / Int32Array.BYTES_PER_ELEMENT | ||
] = originInfoAddress; | ||
for (let i = 0; i < origin.length; i++) { | ||
memoryBufferUint8[originInfoAddress + i] = origin.charCodeAt(i); | ||
} | ||
memoryBufferUint8[originInfoAddress + origin.length] = 0; | ||
}; | ||
const importObject = { | ||
@@ -559,2 +478,4 @@ // eslint-disable-next-line camelcase | ||
pv_get_browser_info: pvGetBrowserInfo, | ||
// eslint-disable-next-line camelcase | ||
pv_get_origin_info: pvGetOriginInfo, | ||
}, | ||
@@ -624,6 +545,3 @@ }; | ||
const memoryBufferView = new DataView(memory.buffer); | ||
const objectAddress = memoryBufferView.getInt32( | ||
objectAddressAddress, | ||
true | ||
); | ||
const objectAddress = memoryBufferView.getInt32(objectAddressAddress, true); | ||
@@ -630,0 +548,0 @@ const sampleRate = await pv_sample_rate(); |
136
src/utils.ts
/* | ||
Copyright 2021 Picovoice Inc. | ||
Copyright 2021 Picovoice Inc. | ||
You may not use this file except in compliance with the license. A copy of the license is located in the "LICENSE" | ||
file accompanying this source. | ||
You may not use this file except in compliance with the license. A copy of the license is located in the "LICENSE" | ||
file accompanying this source. | ||
Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on | ||
an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the | ||
specific language governing permissions and limitations under the License. | ||
Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on | ||
an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the | ||
specific language governing permissions and limitations under the License. | ||
*/ | ||
/** | ||
* Indexed DB configurations | ||
*/ | ||
const DB_NAME = 'pv_db'; | ||
const STORE_NAME = 'pv_store'; | ||
const V = 1; | ||
/** | ||
* Storage Interface. | ||
*/ | ||
interface PvStorage { | ||
setItem: (key: string, value: string) => void | Promise<void>; | ||
getItem: (key: string) => string | Promise<string>; | ||
removeItem: (key: string) => void | Promise<void>; | ||
} | ||
/** | ||
* Opens indexedDB connection, handles version changes and gets the db instance. | ||
* | ||
* @returns The instance of indexedDB connection. | ||
*/ | ||
function getDB(): Promise<IDBDatabase> { | ||
return new Promise((resolve, reject) => { | ||
const request = self.indexedDB.open(DB_NAME, V); | ||
request.onerror = (): void => { | ||
reject(request.error); | ||
}; | ||
request.onsuccess = (): void => { | ||
resolve(request.result); | ||
}; | ||
request.onupgradeneeded = (): void => { | ||
request.result.createObjectStore(STORE_NAME); | ||
}; | ||
}); | ||
} | ||
/** | ||
* Gets the storage to use. Either tries to use IndexedDB or localStorage. | ||
* | ||
* @returns PvStorage instance to use as storage. | ||
*/ | ||
export function getPvStorage(): PvStorage { | ||
if (self.indexedDB) { | ||
const requestHelper = (request: IDBRequest): Promise<any> => new Promise((resolve, reject) => { | ||
request.onerror = (): void => { | ||
reject(request.error); | ||
}; | ||
request.onsuccess = (): void => { | ||
resolve(request.result); | ||
}; | ||
}); | ||
return { | ||
setItem: async (key: string, value: string): Promise<void> => { | ||
const db = await getDB(); | ||
const request = db | ||
.transaction(STORE_NAME, 'readwrite') | ||
.objectStore(STORE_NAME) | ||
.put(value, key); | ||
await requestHelper(request); | ||
db.close(); | ||
}, | ||
getItem: async (key: string): Promise<string> => { | ||
const db = await getDB(); | ||
const request = db | ||
.transaction(STORE_NAME, 'readonly') | ||
.objectStore(STORE_NAME) | ||
.get(key); | ||
const res = await requestHelper(request); | ||
db.close(); | ||
return res; | ||
}, | ||
removeItem: async (key: string): Promise<void> => { | ||
const db = await getDB(); | ||
const request = db | ||
.transaction(STORE_NAME, 'readwrite') | ||
.objectStore(STORE_NAME) | ||
.delete(key); | ||
await requestHelper(request); | ||
db.close(); | ||
}, | ||
}; | ||
} else if (self.localStorage) { | ||
return self.localStorage as PvStorage; | ||
} | ||
throw new Error('Cannot get a presistent storage object.'); | ||
} | ||
/** | ||
* Convert a null terminated phrase stored inside an array buffer to a string | ||
@@ -22,3 +111,3 @@ * | ||
arrayBuffer: Uint8Array, | ||
index: number, | ||
index: number | ||
): string { | ||
@@ -58,3 +147,7 @@ let stringBuffer = ''; | ||
export function arrayBufferToBase64AtIndex(arrayBuffer: ArrayBuffer, size: number, index: number): string { | ||
export function arrayBufferToBase64AtIndex( | ||
arrayBuffer: ArrayBuffer, | ||
size: number, | ||
index: number | ||
): string { | ||
let binary = ''; | ||
@@ -97,3 +190,7 @@ for (let i = 0; i < size; i++) { | ||
export async function fetchWithTimeout(uri: string, options = {}, time = 5000): Promise<Response> { | ||
export async function fetchWithTimeout( | ||
uri: string, | ||
options = {}, | ||
time = 5000 | ||
): Promise<Response> { | ||
const controller = new AbortController(); | ||
@@ -110,15 +207,2 @@ const config = { ...options, signal: controller.signal }; | ||
/** | ||
* Environment identifier | ||
* | ||
* @return a string containing the envirorment name | ||
*/ | ||
export function getRuntimeEnvironment(): string { | ||
if (typeof window === 'object' && typeof document === 'object') { | ||
return 'browser'; | ||
} | ||
return 'worker'; | ||
} | ||
/** | ||
* Checking whether the given AccessKey is valid | ||
@@ -129,5 +213,7 @@ * | ||
export function isAccessKeyValid(accessKey: string): boolean { | ||
export function isAccessKeyValid(accessKey: string): boolean { | ||
const accessKeyCleaned = accessKey.trim(); | ||
if (accessKeyCleaned === '') { return false; } | ||
if (accessKeyCleaned === '') { | ||
return false; | ||
} | ||
try { | ||
@@ -138,2 +224,2 @@ return btoa(atob(accessKeyCleaned)) === accessKeyCleaned; | ||
} | ||
} | ||
} |
Sorry, the diff of this file is too big to display
Sorry, the diff of this file is too big to display
Sorry, the diff of this file is too big to display
Sorry, the diff of this file is too big to display
Sorry, the diff of this file is not supported yet
Sorry, the diff of this file is not supported yet
Sorry, the diff of this file is not supported yet
Sorry, the diff of this file is not supported yet
New author
Supply chain riskA new npm collaborator published a version of the package for the first time. New collaborators are usually benign additions to a project, but do indicate a change to the security surface area of a package.
Found 1 instance in 1 package
1669322
11246
5