@cainiaofe/cn-utils
Version:
菜鸟前端基础工具库
104 lines (103 loc) • 3.67 kB
JavaScript
import { LOCAL, DAILY, TEST, PRE, PROD } from './types';
function parseHostname(options) {
var _a;
var hostname = options.hostname;
// 解析用户提供的 hostname
if (hostname) {
if (hostname.indexOf('//') !== -1) {
_a = hostname.split('//'), hostname = _a[1];
}
if (hostname.indexOf('/') !== -1) {
hostname = hostname.split('/')[0];
}
if (hostname.indexOf(':') !== -1) {
hostname = hostname.split(':')[0];
}
}
else {
hostname = window.location.hostname;
}
return hostname && hostname.trim();
}
function parseCurrentScriptSrc(options) {
var currentScriptSrc = options.currentScriptSrc;
if (currentScriptSrc) {
return currentScriptSrc;
}
if (window.__CURRENT_SCRIPT_SRC__) {
currentScriptSrc = window.__CURRENT_SCRIPT_SRC__;
}
else if (window.__current_micro_config__ && window.__current_micro_config__.prefix) {
currentScriptSrc = window.__current_micro_config__.prefix;
}
else if (window.document.currentScript) {
var script = window.document.currentScript;
currentScriptSrc = script.src;
}
return currentScriptSrc && currentScriptSrc.trim();
}
var regIp = /^\d+\.\d+\.\d+\.\d+$/;
export function getCnEnv(options) {
if (options === void 0) { options = {}; }
try {
// case: 读取外界注入的 window.__CN_ENV__, 优先级最高, 这样也可以在本地 public/index.html 模拟其他环境
if (typeof window !== 'undefined' && window.__CN_ENV__) {
return window.__CN_ENV__;
}
var hostname = parseHostname(options);
if (!hostname) {
return PROD;
}
// case: localhost/127.0.0.1
if (hostname === 'localhost' || hostname === '127.0.0.1') {
return LOCAL;
}
// case: ip 30.117.72.7
if (regIp.test(hostname)) {
return LOCAL;
}
var parts = hostname.split('.');
var head = parts[0] || '';
var tail = parts[parts.length - 1] || '';
// case: pre.xxx pre-xxx.yyy pre2-xxx.yyy page-pre.xxxx
if (head === PRE ||
head.indexOf("".concat(PRE, "-")) === 0 ||
head.indexOf("".concat(PRE, "2-")) === 0 ||
head.indexOf("page-".concat(PRE)) === 0) {
return PRE;
}
// case: daily.xxx daily-xxx.yyy page-daily.xxx
if (head === DAILY ||
head.indexOf("".concat(DAILY, "-")) === 0 ||
head.indexOf("page-".concat(DAILY)) === 0 ||
tail === TEST) {
return DAILY;
}
// case: currentScriptSrc
var currentScriptSrc = parseCurrentScriptSrc(options);
if (!currentScriptSrc) {
return PROD;
}
if (currentScriptSrc.indexOf('https://g.alicdn.com') === 0 ||
currentScriptSrc.indexOf('https://cn.alicdn.com') === 0) {
return PROD;
}
if (currentScriptSrc.indexOf('https://dev.g.alicdn.com') === 0 ||
currentScriptSrc.indexOf('https://assets-daily.cainiao-inc.com') === 0) {
return DAILY;
}
}
catch (err) {
// ignore err
}
return PROD;
}
/**
* 判断当前运行环境是否为菜鸟内部环境,即域名以 .cainiao-inc.com 结尾
* @returns boolean
*/
export function isCnRuntime() {
var _a = ((window === null || window === void 0 ? void 0 : window.location) || {}).hostname, hostname = _a === void 0 ? '' : _a;
return !!hostname.endsWith('.cainiao-inc.com');
}
export { LOCAL, TEST, DAILY, PRE, PROD } from './types';