relative-import-path
Version:
path.relative for generating short require'able paths.
92 lines (91 loc) • 2.94 kB
JavaScript
var __defProp = Object.defineProperty;
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
var __getOwnPropNames = Object.getOwnPropertyNames;
var __hasOwnProp = Object.prototype.hasOwnProperty;
var __markAsModule = (target) => __defProp(target, "__esModule", { value: true });
var __export = (target, all) => {
for (var name in all)
__defProp(target, name, { get: all[name], enumerable: true });
};
var __reExport = (target, module2, copyDefault, desc) => {
if (module2 && typeof module2 === "object" || typeof module2 === "function") {
for (let key of __getOwnPropNames(module2))
if (!__hasOwnProp.call(target, key) && (copyDefault || key !== "default"))
__defProp(target, key, { get: () => module2[key], enumerable: !(desc = __getOwnPropDesc(module2, key)) || desc.enumerable });
}
return target;
};
var __toCommonJS = /* @__PURE__ */ ((cache) => {
return (module2, temp) => {
return cache && cache.get(module2) || (temp = __reExport(__markAsModule({}), module2, 1), cache && cache.set(module2, temp), temp);
};
})(typeof WeakMap !== "undefined" ? /* @__PURE__ */ new WeakMap() : 0);
var src_exports = {};
__export(src_exports, {
relativeImportPath: () => relativeImportPath
});
var import_path = require("path");
const nms = import_path.sep + "node_modules" + import_path.sep;
const nmsLen = nms.length;
const backSep = `../`;
const toPosix = import_path.sep === "/" ? (v) => v : (v) => {
let result = "";
for (let i = v.length; i--; ) {
const c = v[i];
result = (c === import_path.sep ? "/" : c) + result;
}
return result;
};
function relativeImportPath(from, to) {
let i = 0;
let sepPos = -1;
let prevSepPos = -1;
let prevPrevSepPos = -1;
const fromLen = from.length;
const commonLen = Math.min(to.length, fromLen);
for (; i < commonLen; i++) {
const curChar = to[i];
if (curChar !== from[i])
break;
if (curChar === import_path.sep) {
prevPrevSepPos = prevSepPos;
prevSepPos = sepPos;
sepPos = i;
}
}
if (sepPos !== -1) {
if (hasNms(to, sepPos)) {
return toPosix(stripNms(to, sepPos));
}
if (prevSepPos !== -1) {
if (prevPrevSepPos !== -1 && to[prevSepPos + 1] === "@") {
prevSepPos = prevPrevSepPos;
}
if (hasNms(to, prevSepPos)) {
return toPosix(stripNms(to, prevSepPos));
}
}
}
if (sepPos <= 0)
return toPosix(to);
let back = 0;
for (; i < fromLen; i++)
if (from[i] === import_path.sep)
back++;
if (back) {
return backSep.repeat(back) + toPosix(to.slice(sepPos + 1));
} else {
return `.${toPosix(to.slice(sepPos))}`;
}
}
function hasNms(src, pos) {
return src.slice(pos).startsWith(nms);
}
function stripNms(src, pos) {
return src.slice(pos + nmsLen);
}
module.exports = __toCommonJS(src_exports);
// Annotate the CommonJS export names for ESM import in node:
0 && (module.exports = {
relativeImportPath
});