Big News: Socket raises $60M Series C at a $1B valuation to secure software supply chains for AI-driven development.Announcement
Sign In

@rsnuxt/utils

Package Overview
Dependencies
Maintainers
1
Versions
14
Alerts
File Explorer

Advanced tools

Socket logo

Install Socket

Detect and block malicious and high-risk dependencies

Install

@rsnuxt/utils - npm Package Compare versions

Comparing version
0.2.2-alpha.1
to
0.2.2
+1
-762
dist/utils.js

@@ -1,762 +0,1 @@

/*!
* @rsnuxt/utils v0.2.2-alpha.0 (c) 2016-2025
* Released under the MIT License
* Repository: https://github.com/nuxt/nuxt.js
* Website: https://nuxtjs.org
*/
'use strict';
const ufo = require('ufo');
const path = require('path');
const consola = require('consola');
const hash = require('hash-sum');
const fs = require('fs-extra');
const properlock = require('proper-lockfile');
const signalExit = require('signal-exit');
const lodash = require('lodash');
const serialize = require('serialize-javascript');
const _createRequire = require('create-require');
const jiti = require('jiti');
const UAParser = require('ua-parser-js');
const semver = require('semver');
const TARGETS = {
server: "server",
static: "static"
};
const MODES = {
universal: "universal",
spa: "spa"
};
const getContext = function getContext2(req, res) {
return { req, res };
};
const determineGlobals = function determineGlobals2(globalName, globals) {
const _globals = {};
for (const global in globals) {
if (typeof globals[global] === "function") {
_globals[global] = globals[global](globalName);
} else {
_globals[global] = globals[global];
}
}
return _globals;
};
const isFullStatic = function(options) {
return !options.dev && !options._legacyGenerate && options.target === TARGETS.static && options.render.ssr;
};
const encodeHtml = function encodeHtml2(str) {
return str.replace(/</g, "&lt;").replace(/>/g, "&gt;");
};
const isString = (obj) => typeof obj === "string" || obj instanceof String;
const isNonEmptyString = (obj) => Boolean(obj && isString(obj));
const isPureObject = (obj) => !Array.isArray(obj) && typeof obj === "object";
const isUrl = function isUrl2(url) {
return ufo.hasProtocol(url, true);
};
const urlJoin = ufo.joinURL;
const wrapArray = (value) => Array.isArray(value) ? value : [value];
const WHITESPACE_REPLACEMENTS = [
[/[ \t\f\r]+\n/g, "\n"],
// strip empty indents
[/{\n{2,}/g, "{\n"],
// strip start padding from blocks
[/\n{2,}([ \t\f\r]*})/g, "\n$1"],
// strip end padding from blocks
[/\n{3,}/g, "\n\n"],
// strip multiple blank lines (1 allowed)
[/^\n+/, ""],
// strip blank lines at the beginning of a string
[/\n{2,}$/, "\n"]
// strip blank lines at the end of a string
];
const stripWhitespace = function stripWhitespace2(string) {
WHITESPACE_REPLACEMENTS.forEach(([regex, newSubstr]) => {
string = string.replace(regex, newSubstr);
});
return string;
};
const lockPaths = /* @__PURE__ */ new Set();
const defaultLockOptions = {
stale: 3e4,
onCompromised: (err) => consola.warn(err)
};
function getLockOptions(options) {
return Object.assign({}, defaultLockOptions, options);
}
function createLockPath({ id = "nuxt", dir, root }) {
const sum = hash(`${root}-${dir}`);
return path.resolve(root, "node_modules/.cache/nuxt", `${id}-lock-${sum}`);
}
async function getLockPath(config) {
const lockPath = createLockPath(config);
await fs.ensureDir(lockPath);
return lockPath;
}
async function lock({ id, dir, root, options }) {
const lockPath = await getLockPath({ id, dir, root });
try {
const locked = await properlock.check(lockPath);
if (locked) {
consola.fatal(`A lock with id '${id}' already exists on ${dir}`);
}
} catch (e) {
consola.debug(`Check for an existing lock with id '${id}' on ${dir} failed`, e);
}
let lockWasCompromised = false;
let release;
try {
options = getLockOptions(options);
const onCompromised = options.onCompromised;
options.onCompromised = (err) => {
onCompromised(err);
lockWasCompromised = true;
};
release = await properlock.lock(lockPath, options);
} catch (e) {
}
if (!release) {
consola.warn(`Unable to get a lock with id '${id}' on ${dir} (but will continue)`);
return false;
}
if (!lockPaths.size) {
signalExit.onExit(() => {
for (const lockPath2 of lockPaths) {
fs.removeSync(lockPath2);
}
});
}
lockPaths.add(lockPath);
return async function lockRelease() {
try {
await fs.remove(lockPath);
lockPaths.delete(lockPath);
await release();
} catch (e) {
if (!lockWasCompromised || !e.message.includes("already released")) {
consola.debug(e);
return;
}
const lockDir = `${lockPath}.lock`;
if (await fs.exists(lockDir)) {
await fs.remove(lockDir);
}
}
};
}
const startsWithAlias = (aliasArray) => (str) => aliasArray.some((c) => str.startsWith(c));
const startsWithSrcAlias = startsWithAlias(["@", "~"]);
const startsWithRootAlias = startsWithAlias(["@@", "~~"]);
const isWindows = process.platform.startsWith("win");
const wp = function wp2(p = "") {
if (isWindows) {
return p.replace(/\\/g, "\\\\");
}
return p;
};
const wChunk = function wChunk2(p = "") {
return p;
};
const reqSep = /\//g;
const sysSep = lodash.escapeRegExp(path.sep);
const normalize = (string) => string.replace(reqSep, sysSep);
const r = function r2(...args) {
const lastArg = args[args.length - 1];
if (startsWithSrcAlias(lastArg)) {
return wp(lastArg);
}
return wp(path.resolve(...args.map(normalize)));
};
const relativeTo = function relativeTo2(...args) {
const dir = args.shift();
if (args[0].includes("!")) {
const loaders = args.shift().split("!");
return loaders.concat(relativeTo2(dir, loaders.pop(), ...args)).join("!");
}
const resolvedPath = r(...args);
if (startsWithSrcAlias(resolvedPath)) {
return resolvedPath;
}
let rp = path.relative(dir, resolvedPath);
if (rp[0] !== ".") {
rp = "." + path.sep + rp;
}
return wp(rp);
};
function defineAlias(src, target, prop, opts = {}) {
const { bind = true, warn = false } = opts;
if (Array.isArray(prop)) {
for (const p of prop) {
defineAlias(src, target, p, opts);
}
return;
}
let targetVal = target[prop];
if (bind && typeof targetVal === "function") {
targetVal = targetVal.bind(target);
}
let warned = false;
Object.defineProperty(src, prop, {
get: () => {
if (warn && !warned) {
warned = true;
consola.warn({
message: `'${prop}' is deprecated'`,
// eslint-disable-next-line unicorn/error-message
additional: new Error().stack.split("\n").splice(2).join("\n")
});
}
return targetVal;
}
});
}
const isIndex = (s) => /(.*)\/index\.[^/]+$/.test(s);
function isIndexFileAndFolder(pluginFiles) {
if (pluginFiles.length !== 2) {
return false;
}
return pluginFiles.some(isIndex);
}
const getMainModule = () => {
return require && require.main || module && module.main || module;
};
const routeChildren = function(route) {
const hasChildWithEmptyPath = route.children.some((child) => child.path === "");
if (hasChildWithEmptyPath) {
return route.children;
}
return [
// Add default child to render parent page
{
...route,
children: void 0
},
...route.children
];
};
const flatRoutes = function flatRoutes2(router, fileName = "", routes = []) {
router.forEach((r2) => {
if ([":", "*"].some((c) => r2.path.includes(c))) {
return;
}
const route = `${fileName}${r2.path}/`.replace(/\/+/g, "/");
if (r2.children) {
return flatRoutes2(routeChildren(r2), route, routes);
}
if (r2.path && r2.path.startsWith("/")) {
routes.push(r2.path);
} else if (route !== "/" && route[route.length - 1] === "/") {
routes.push(route.slice(0, -1));
} else {
routes.push(route);
}
});
return routes;
};
function cleanChildrenRoutes(routes, isChild = false, routeNameSplitter = "-", trailingSlash, parentRouteName) {
const regExpIndex = new RegExp(`${routeNameSplitter}index$`);
const regExpParentRouteName = new RegExp(`^${parentRouteName}${routeNameSplitter}`);
const routesIndex = [];
routes.forEach((route) => {
if (regExpIndex.test(route.name) || route.name === "index") {
const res = route.name.replace(regExpParentRouteName, "").split(routeNameSplitter);
routesIndex.push(res);
}
});
routes.forEach((route) => {
route.path = isChild ? route.path.replace("/", "") : route.path;
if (route.path.includes("?")) {
if (route.name.endsWith(`${routeNameSplitter}index`)) {
route.path = route.path.replace(/\?\/?$/, trailingSlash ? "/" : "");
}
const names = route.name.replace(regExpParentRouteName, "").split(routeNameSplitter);
const paths = route.path.split("/");
if (!isChild) {
paths.shift();
}
routesIndex.forEach((r2) => {
const i = r2.indexOf("index");
if (i < paths.length) {
for (let a = 0; a <= i; a++) {
if (a === i) {
paths[a] = paths[a].replace("?", "");
}
if (a < i && names[a] !== r2[a]) {
break;
}
}
}
});
route.path = (isChild ? "" : "/") + paths.join("/");
}
route.name = route.name.replace(regExpIndex, "");
if (route.children) {
const defaultChildRoute = route.children.find((child) => child.path === "/" || child.path === "");
const routeName = route.name;
if (defaultChildRoute) {
route.children.forEach((child) => {
if (child.path !== defaultChildRoute.path) {
const parts = child.path.split("/");
parts[1] = parts[1].endsWith("?") ? parts[1].substr(0, parts[1].length - 1) : parts[1];
child.path = parts.join("/");
}
});
delete route.name;
}
route.children = cleanChildrenRoutes(route.children, true, routeNameSplitter, trailingSlash, routeName);
}
});
return routes;
}
const DYNAMIC_ROUTE_REGEX = /[:*]/;
const sortRoutes = function sortRoutes2(routes) {
routes.sort((a, b) => {
if (!a.path.length) {
return -1;
}
if (!b.path.length) {
return 1;
}
if (a.path === "/") {
return DYNAMIC_ROUTE_REGEX.test(b.path) ? -1 : 1;
}
if (b.path === "/") {
return DYNAMIC_ROUTE_REGEX.test(a.path) ? 1 : -1;
}
let i;
let res = 0;
let y = 0;
let z = 0;
const _a = a.path.split("/");
const _b = b.path.split("/");
for (i = 0; i < _a.length; i++) {
if (res !== 0) {
break;
}
y = _a[i] === "*" ? 3 : _a[i].includes(":") ? 2 : _a[i].includes("*") ? 1 : 0;
z = _b[i] === "*" ? 3 : _b[i].includes(":") ? 2 : _b[i].includes("*") ? 1 : 0;
res = y - z;
if (i === _b.length - 1 && res === 0) {
res = _a[i].includes("*") ? -1 : _a.length === _b.length ? a.path.localeCompare(b.path) : _a.length - _b.length;
}
}
if (res === 0) {
res = _a[i - 1].includes("*") && _b[i] ? 1 : _a.length === _b.length ? a.path.localeCompare(b.path) : _a.length - _b.length;
}
return res;
});
routes.forEach((route) => {
if (route.children) {
sortRoutes2(route.children);
}
});
return routes;
};
const createRoutes = function createRoutes2({
files,
srcDir,
pagesDir = "",
routeNameSplitter = "-",
supportedExtensions = ["vue", "js"],
trailingSlash
}) {
const routes = [];
files.forEach((file) => {
const keys = file.replace(new RegExp(`^${pagesDir}`), "").replace(new RegExp(`\\.(${supportedExtensions.join("|")})$`), "").replace(/\/{2,}/g, "/").split("/").slice(1);
const route = { name: "", path: "", component: r(srcDir, file) };
let parent = routes;
keys.forEach((key, i) => {
const sanitizedKey = key.startsWith("_") ? key.substr(1) : key;
route.name = route.name ? route.name + routeNameSplitter + sanitizedKey : sanitizedKey;
route.name += key === "_" ? "all" : "";
route.chunkName = file.replace(new RegExp(`\\.(${supportedExtensions.join("|")})$`), "");
const child = parent.find((parentRoute) => parentRoute.name === route.name);
if (child) {
child.children = child.children || [];
parent = child.children;
route.path = "";
} else if (key === "index" && i + 1 === keys.length) {
route.path += i > 0 ? "" : "/";
} else {
route.path += "/" + ufo.normalizeURL(getRoutePathExtension(key));
if (key.startsWith("_") && key.length > 1) {
route.path += "?";
}
}
});
if (trailingSlash !== void 0) {
route.pathToRegexpOptions = { ...route.pathToRegexpOptions, strict: true };
if (trailingSlash && !route.path.endsWith("*")) {
route.path = ufo.withTrailingSlash(route.path);
} else {
route.path = ufo.withoutTrailingSlash(route.path);
}
}
parent.push(route);
});
sortRoutes(routes);
return cleanChildrenRoutes(routes, false, routeNameSplitter, trailingSlash);
};
const guardDir = function guardDir2(options, key1, key2) {
const dir1 = lodash.get(options, key1, false);
const dir2 = lodash.get(options, key2, false);
if (dir1 && dir2 && (dir1 === dir2 || dir1.startsWith(dir2) && !path.basename(dir1).startsWith(path.basename(dir2)))) {
const errorMessage = `options.${key2} cannot be a parent of or same as ${key1}`;
consola.fatal(errorMessage);
throw new Error(errorMessage);
}
};
const getRoutePathExtension = (key) => {
if (key === "_") {
return "*";
}
if (key.startsWith("_")) {
return `:${key.substr(1)}`;
}
return key;
};
const promisifyRoute = function promisifyRoute2(fn, ...args) {
if (Array.isArray(fn)) {
return Promise.resolve(fn);
}
if (fn.length === arguments.length) {
return new Promise((resolve, reject) => {
fn((err, routeParams) => {
if (err) {
reject(err);
}
resolve(routeParams);
}, ...args);
});
}
let promise = fn(...args);
if (!promise || !(promise instanceof Promise) && typeof promise.then !== "function") {
promise = Promise.resolve(promise);
}
return promise;
};
function normalizeFunctions(obj) {
if (typeof obj !== "object" || Array.isArray(obj) || obj === null) {
return obj;
}
for (const key in obj) {
if (key === "__proto__" || key === "constructor") {
continue;
}
const val = obj[key];
if (val !== null && typeof val === "object" && !Array.isArray(obj)) {
obj[key] = normalizeFunctions(val);
}
if (typeof obj[key] === "function") {
const asString = obj[key].toString();
const match = asString.match(/^([^{(]+)=>\s*([\0-\uFFFF]*)/);
if (match) {
const fullFunctionBody = match[2].match(/^{?(\s*return\s+)?([\0-\uFFFF]*?)}?$/);
let functionBody = fullFunctionBody[2].trim();
if (fullFunctionBody[1] || !match[2].trim().match(/^\s*{/)) {
functionBody = `return ${functionBody}`;
}
obj[key] = new Function(...match[1].split(",").map((arg) => arg.trim()), functionBody);
}
}
}
return obj;
}
function serializeFunction(func) {
let open = false;
func = normalizeFunctions(func);
return serialize(func).replace(serializeFunction.assignmentRE, (_, spaces) => {
return `${spaces}: function (`;
}).replace(serializeFunction.internalFunctionRE, (_, spaces, name, args) => {
if (open) {
return `${spaces}${name}: function (${args}) {`;
} else {
open = true;
return _;
}
}).replace(new RegExp(`${(func.name || "function").replace("$", "\\$")}\\s*\\(`), "function(").replace("function function", "function");
}
serializeFunction.internalFunctionRE = /^(\s*)(?!(?:if)|(?:for)|(?:while)|(?:switch)|(?:catch))(\w+)\s*\((.*?)\)\s*\{/gm;
serializeFunction.assignmentRE = /^(\s*):(\w+)\(/gm;
const sequence = function sequence2(tasks, fn) {
return tasks.reduce(
(promise, task) => promise.then(() => fn(task)),
Promise.resolve()
);
};
const parallel = function parallel2(tasks, fn) {
return Promise.all(tasks.map(fn));
};
const chainFn = function chainFn2(base, fn) {
if (typeof fn !== "function") {
return base;
}
if (typeof base !== "function") {
return fn;
}
return function(arg0, ...args) {
const next = (previous = arg0) => {
const fnResult = fn.call(this, previous, ...args);
if (fnResult && typeof fnResult.then === "function") {
return fnResult.then((res) => res || previous);
}
return fnResult || previous;
};
const baseResult = base.call(this, arg0, ...args);
if (baseResult && typeof baseResult.then === "function") {
return baseResult.then((res) => next(res));
}
return next(baseResult);
};
};
async function promiseFinally(fn, finalFn) {
let result;
try {
if (typeof fn === "function") {
result = await fn();
} else {
result = await fn;
}
} finally {
finalFn();
}
return result;
}
const timeout = function timeout2(fn, ms, msg) {
let timerId;
const warpPromise = promiseFinally(fn, () => clearTimeout(timerId));
const timerPromise = new Promise((resolve, reject) => {
timerId = setTimeout(() => reject(new Error(msg)), ms);
});
return Promise.race([warpPromise, timerPromise]);
};
const waitFor = function waitFor2(ms) {
return new Promise((resolve) => setTimeout(resolve, ms || 0));
};
class Timer {
constructor() {
this._times = /* @__PURE__ */ new Map();
}
start(name, description) {
const time = {
name,
description,
start: this.hrtime()
};
this._times.set(name, time);
return time;
}
end(name) {
if (this._times.has(name)) {
const time = this._times.get(name);
time.duration = this.hrtime(time.start);
this._times.delete(name);
return time;
}
}
hrtime(start) {
const useBigInt = typeof process.hrtime.bigint === "function";
if (start) {
const end = useBigInt ? process.hrtime.bigint() : process.hrtime(start);
return useBigInt ? (end - start) / BigInt(1e6) : end[0] * 1e3 + end[1] * 1e-6;
}
return useBigInt ? process.hrtime.bigint() : process.hrtime();
}
clear() {
this._times.clear();
}
}
const createRequire = (filename, useJiti = global.__NUXT_DEV__) => {
if (useJiti && typeof jest === "undefined") {
return jiti(filename);
}
return _createRequire(filename);
};
const _require = createRequire();
function isHMRCompatible(id) {
return !/[/\\]mongoose[/\\/]/.test(id);
}
function isExternalDependency(id) {
return /[/\\]node_modules[/\\]/.test(id);
}
function clearRequireCache(id) {
if (isExternalDependency(id) && isHMRCompatible(id)) {
return;
}
const entry = getRequireCacheItem(id);
if (!entry) {
delete _require.cache[id];
return;
}
if (entry.parent) {
entry.parent.children = entry.parent.children.filter((e) => e.id !== id);
}
delete _require.cache[id];
for (const child of entry.children) {
clearRequireCache(child.id);
}
}
function scanRequireTree(id, files = /* @__PURE__ */ new Set()) {
if (isExternalDependency(id) || files.has(id)) {
return files;
}
const entry = getRequireCacheItem(id);
if (!entry) {
files.add(id);
return files;
}
files.add(entry.id);
for (const child of entry.children) {
scanRequireTree(child.id, files);
}
return files;
}
function getRequireCacheItem(id) {
try {
return _require.cache[id];
} catch (e) {
}
}
function resolveModule(id, paths) {
if (typeof paths === "string") {
paths = [paths];
}
return _require.resolve(id, {
paths: [].concat(...global.__NUXT_PREPATHS__ || [], paths || [], global.__NUXT_PATHS__ || [], process.cwd())
});
}
function requireModule(id, paths) {
return _require(resolveModule(id, paths));
}
function tryRequire(id, paths) {
try {
return requireModule(id, paths);
} catch (e) {
}
}
function tryResolve(id, paths) {
try {
return resolveModule(id, paths);
} catch (e) {
}
}
function getPKG(id, paths) {
return tryRequire(path.join(id, "package.json"), paths);
}
const ModernBrowsers = {
Edge: "16",
Firefox: "60",
Chrome: "61",
"Chrome Headless": "61",
Chromium: "61",
Iron: "61",
Safari: "10.1",
Opera: "48",
Yandex: "18",
Vivaldi: "1.14",
"Mobile Safari": "10.3"
};
let __modernBrowsers;
const getModernBrowsers = () => {
if (__modernBrowsers) {
return __modernBrowsers;
}
__modernBrowsers = Object.keys(ModernBrowsers).reduce((allBrowsers, browser) => {
allBrowsers[browser] = semver.coerce(ModernBrowsers[browser]);
return allBrowsers;
}, {});
return __modernBrowsers;
};
const isModernBrowser = (ua) => {
if (!ua) {
return false;
}
const { browser } = UAParser(ua);
const browserVersion = semver.coerce(browser.version);
if (!browserVersion) {
return false;
}
const modernBrowsers = getModernBrowsers();
return Boolean(modernBrowsers[browser.name] && semver.gte(browserVersion, modernBrowsers[browser.name]));
};
const isModernRequest = (req, modernMode = false) => {
if (modernMode === false) {
return false;
}
const { socket = {}, headers } = req;
if (socket._modern === void 0) {
const ua = headers && headers["user-agent"];
socket._modern = isModernBrowser(ua);
}
return socket._modern;
};
const safariNoModuleFix = '!function(){var e=document,t=e.createElement("script");if(!("noModule"in t)&&"onbeforeload"in t){var n=!1;e.addEventListener("beforeload",function(e){if(e.target===t)n=!0;else if(!e.target.hasAttribute("nomodule")||!n)return;e.preventDefault()},!0),t.type="module",t.src=".",e.head.appendChild(t),t.remove()}}();';
exports.MODES = MODES;
exports.ModernBrowsers = ModernBrowsers;
exports.TARGETS = TARGETS;
exports.Timer = Timer;
exports.chainFn = chainFn;
exports.clearRequireCache = clearRequireCache;
exports.createLockPath = createLockPath;
exports.createRequire = createRequire;
exports.createRoutes = createRoutes;
exports.defaultLockOptions = defaultLockOptions;
exports.defineAlias = defineAlias;
exports.determineGlobals = determineGlobals;
exports.encodeHtml = encodeHtml;
exports.flatRoutes = flatRoutes;
exports.getContext = getContext;
exports.getLockOptions = getLockOptions;
exports.getLockPath = getLockPath;
exports.getMainModule = getMainModule;
exports.getPKG = getPKG;
exports.getRequireCacheItem = getRequireCacheItem;
exports.guardDir = guardDir;
exports.isExternalDependency = isExternalDependency;
exports.isFullStatic = isFullStatic;
exports.isHMRCompatible = isHMRCompatible;
exports.isIndexFileAndFolder = isIndexFileAndFolder;
exports.isModernBrowser = isModernBrowser;
exports.isModernRequest = isModernRequest;
exports.isNonEmptyString = isNonEmptyString;
exports.isPureObject = isPureObject;
exports.isString = isString;
exports.isUrl = isUrl;
exports.isWindows = isWindows;
exports.lock = lock;
exports.lockPaths = lockPaths;
exports.normalizeFunctions = normalizeFunctions;
exports.parallel = parallel;
exports.promisifyRoute = promisifyRoute;
exports.r = r;
exports.relativeTo = relativeTo;
exports.requireModule = requireModule;
exports.resolveModule = resolveModule;
exports.safariNoModuleFix = safariNoModuleFix;
exports.scanRequireTree = scanRequireTree;
exports.sequence = sequence;
exports.serializeFunction = serializeFunction;
exports.sortRoutes = sortRoutes;
exports.startsWithAlias = startsWithAlias;
exports.startsWithRootAlias = startsWithRootAlias;
exports.startsWithSrcAlias = startsWithSrcAlias;
exports.stripWhitespace = stripWhitespace;
exports.timeout = timeout;
exports.tryRequire = tryRequire;
exports.tryResolve = tryResolve;
exports.urlJoin = urlJoin;
exports.wChunk = wChunk;
exports.waitFor = waitFor;
exports.wp = wp;
exports.wrapArray = wrapArray;
export * from '../src/index'
+2
-2
{
"name": "@rsnuxt/utils",
"version": "0.2.2-alpha.1",
"version": "0.2.2",
"repository": {

@@ -34,3 +34,3 @@ "type": "git",

},
"gitHead": "718e7d507ed82140f714c8ca4f914dc6558dd370"
"gitHead": "19faf6ad2a17cd919376be02f6c8ebb3fa2ce4dc"
}