-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathruntime.ts
More file actions
64 lines (54 loc) · 1.77 KB
/
runtime.ts
File metadata and controls
64 lines (54 loc) · 1.77 KB
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
import type { CryptoProvider, RuntimeEnvironment as RuntimeEnvironmentType } from '#types';
import { WebCryptoProvider } from '#crypto/crypto-provider';
/**
* Detects and provides runtime environment capabilities including `Web Crypto API`.
* Supports custom configuration for non-standard environments via {@link RuntimeEnvironment.configure}.
*/
export class RuntimeEnvironment {
private static instance: RuntimeEnvironmentType | null = null;
private static customInstance: RuntimeEnvironmentType | null = null;
/**
* Set a custom runtime environment
*/
static configure(runtime: RuntimeEnvironmentType): void {
this.customInstance = runtime;
}
/**
* Reset to auto-detected runtime environment
*/
static reset(): void {
this.customInstance = null;
this.instance = null;
}
/** Detects and returns the current runtime environment, using cached or custom instance if available. */
static detect(): RuntimeEnvironmentType {
if (this.customInstance) {
return this.customInstance;
}
if (this.instance) {
return this.instance;
}
const crypto = globalThis.crypto;
if (!crypto || typeof crypto.subtle === 'undefined') {
throw new Error(
'Web Crypto API is not available in this environment. Configure a custom runtime via RuntimeEnvironment.configure().'
);
}
const cryptoProvider: CryptoProvider = new WebCryptoProvider(crypto);
const env: RuntimeEnvironmentType = {
crypto: crypto,
cryptoProvider: cryptoProvider,
osName: 'unknown',
osVersion: 'unknown'
};
try {
const os = require('os');
env.osName = os.platform();
env.osVersion = os.release();
} catch {
// os module not available
}
this.instance = env;
return env;
}
}