mihawk
Version:
A tiny & simple mock server tool, support json,js,cjs,ts(typescript).
79 lines (78 loc) • 2.85 kB
JavaScript
;
import { join, basename, relative, resolve, isAbsolute, normalize } from 'path';
import { existsSync } from 'fs-extra';
import { CWD } from '../consts';
export function relPathToCWD(targetPath) {
return relative(CWD, targetPath);
}
export function absifyPath(targetPath, rootPath = CWD) {
rootPath = rootPath || CWD;
targetPath = targetPath ? targetPath.trim() : rootPath;
const absPath = isAbsolute(targetPath) ? targetPath : resolve(rootPath, targetPath);
return absPath.replace(/[/\\]+$/, '');
}
export function unixifyPath(targetPath) {
return process.platform === 'win32' ? targetPath.replace(/\\+/g, '/') : targetPath;
}
export function isExistedSync(targetPath, rootPath = CWD) {
if (!targetPath) {
return false;
}
targetPath = absifyPath(targetPath.trim(), rootPath);
return existsSync(targetPath);
}
let _pkgRootAbsPath = '';
export function getRootAbsPath() {
if (!_pkgRootAbsPath) {
const curDirPath = join(__dirname, '../');
const curParentDirPath = join(curDirPath, '../');
const curParentDirName = basename(curParentDirPath);
const isInDist = ['cjs', 'esm', 'types'].some(distSubDir => curParentDirName == distSubDir);
const rootPath = isInDist ? join(curParentDirPath, '../../') : curParentDirPath;
_pkgRootAbsPath = resolve(rootPath);
}
return _pkgRootAbsPath;
}
export function getLogicFileExt(fileType) {
switch (fileType) {
case 'js':
case 'javascript':
return 'js';
case 'cjs':
return 'cjs';
case 'ts':
case 'typescript':
return 'ts';
case 'none':
default:
return '';
}
}
export function getRoutesFileExt(fileType) {
return (getLogicFileExt(fileType) || 'json');
}
export function removeSpecialExt(filePath) {
return filePath.replace(/\.(js|cjs|ts|json|json5)$/g, '');
}
export function formatPath(targetPath) {
return unixifyPath(normalize(targetPath));
}
export function formatMockPath(mockPath) {
let newPath = formatPath(removeSpecialExt(mockPath));
newPath = newPath.endsWith('/') ? `${newPath}index` : newPath;
return newPath;
}
export function getRouteByJsonPath(jsonRelPath, jsonExt = 'json') {
const ext = (jsonExt || 'json').replace(/^\.+/g, '');
const routePath = unixifyPath(jsonRelPath.replace(/^\/+/, '').replace(new RegExp(`\\.${ext}$`), ''));
const [first, ...others] = routePath.split('/');
return {
method: first.toUpperCase(),
path: `/${others.join('/')}`,
};
}
export function isPathInDir(targetPath, dirPath) {
targetPath = unixifyPath(resolve(targetPath));
dirPath = unixifyPath(resolve(dirPath));
return targetPath !== dirPath && targetPath?.length >= dirPath?.length && targetPath?.startsWith(dirPath);
}