brainy/src/utils/environment.ts

81 lines
2 KiB
TypeScript
Raw Normal View History

2025-06-24 11:41:30 -07:00
/**
* Utility functions for environment detection
*/
/**
* Check if code is running in a browser environment
*/
export function isBrowser(): boolean {
return typeof window !== 'undefined' && typeof document !== 'undefined'
2025-06-24 11:41:30 -07:00
}
/**
* Check if code is running in a Node.js environment
*/
export function isNode(): boolean {
return (
typeof process !== 'undefined' &&
process.versions != null &&
process.versions.node != null
)
2025-06-24 11:41:30 -07:00
}
/**
* Check if code is running in a Web Worker environment
*/
export function isWebWorker(): boolean {
return (
typeof self === 'object' &&
self.constructor &&
self.constructor.name === 'DedicatedWorkerGlobalScope'
)
2025-06-24 11:41:30 -07:00
}
/**
* Check if Web Workers are available in the current environment
*/
export function areWebWorkersAvailable(): boolean {
return isBrowser() && typeof Worker !== 'undefined'
2025-06-24 11:41:30 -07:00
}
/**
* Check if Worker Threads are available in the current environment (Node.js)
*/
export async function areWorkerThreadsAvailable(): Promise<boolean> {
if (!isNode()) return false
2025-06-24 11:41:30 -07:00
try {
// Use dynamic import to avoid errors in browser environments
await import('worker_threads')
return true
2025-06-24 11:41:30 -07:00
} catch (e) {
return false
2025-06-24 11:41:30 -07:00
}
}
/**
* Synchronous version that doesn't actually try to load the module
* This is safer in ES module environments
*/
export function areWorkerThreadsAvailableSync(): boolean {
if (!isNode()) return false
// In Node.js 12+, worker_threads is available without requiring a flag
return parseInt(process.versions.node.split('.')[0]) >= 12
}
2025-06-24 11:41:30 -07:00
/**
* Determine if threading is available in the current environment
* Returns true if either Web Workers (browser) or Worker Threads (Node.js) are available
2025-06-24 11:41:30 -07:00
*/
export function isThreadingAvailable(): boolean {
return areWebWorkersAvailable() || areWorkerThreadsAvailableSync()
}
/**
* Async version of isThreadingAvailable
*/
export async function isThreadingAvailableAsync(): Promise<boolean> {
return areWebWorkersAvailable() || (await areWorkerThreadsAvailable())
2025-06-24 11:41:30 -07:00
}