scroll/src/common/runtime.ts

67 lines
1.5 KiB
JavaScript
Raw Normal View History

2023-11-02 13:06:48 -04:00
import { getTermios } from './termios.ts';
2023-11-01 15:05:31 -04:00
export enum RunTime {
Bun = 'bun',
Deno = 'deno',
Unknown = 'common',
}
2023-11-02 13:06:48 -04:00
export function die(s: string): void {
getTermios().then((t) => t.disableRawMode());
console.error(s);
}
2023-11-01 15:05:31 -04:00
/**
* Determine which Typescript runtime we are operating under
*/
export const getRuntime = (): RunTime => {
let runtime = RunTime.Unknown;
if ('Deno' in globalThis) {
runtime = RunTime.Deno;
}
if ('Bun' in globalThis) {
runtime = RunTime.Bun;
}
return runtime;
};
/**
* Import a runtime-specific module
*
2023-11-03 11:59:58 -04:00
* eg. to load "src/bun/mod.ts", if the runtime is bun,
2023-11-01 15:05:31 -04:00
* you can use like so `await importForRuntime('index')`;
*
* @param path - the path within the runtime module
*/
export const importForRuntime = async (path: string) => {
const runtime = getRuntime();
2023-11-01 15:25:52 -04:00
const suffix = '.ts';
2023-11-01 15:05:31 -04:00
const base = `../${runtime}/`;
const pathParts = path.split('/')
.filter((part) => part !== '' && part !== '.' && part !== suffix)
.map((part) => part.replace(suffix, ''));
const cleanedPath = pathParts.join('/');
const importPath = base + cleanedPath + suffix;
return await import(importPath);
2023-11-01 15:27:31 -04:00
};
2023-11-03 11:59:58 -04:00
/**
* Import the default export for a runtime-specific module
* (this is just a simple wrapper of `importForRuntime`)
*
* @param path - the path within the runtime module
*/
export const importDefaultForRuntime = async (path: string) => {
const pkg = await importForRuntime(path);
if ('default' in pkg) {
return pkg.default;
}
return null;
};