UNPKG

@sizium/core

Version:

Get the actual size of any local or remote package

85 lines (81 loc) 2.4 kB
import { stat, readFile } from 'node:fs/promises'; import { isAbsolute, join, resolve } from 'node:path'; import { P as PackageSuper } from './core.om_a9q2E.mjs'; const isUrl = (value) => { try { new URL(value); return true; } catch { return false; } }; const isJsonString = (value) => { try { JSON.parse(value); return true; } catch { return false; } }; const isPath = (value) => { if (isAbsolute(value) || /^(\.\/|\.\.\/|[A-Za-z]:\\|\/)/.test(value)) { if (isAbsolute(value) || /^(\.\/|\.\.\/|[A-Za-z]:\\|\/)/.test(value)) { if (/\s(?!\\)/.test(value) && !/\\\s/.test(value)) return false; try { const normalizedPath = join(value); return normalizedPath !== ""; } catch { return false; } } } return false; }; const isString = (value) => { return typeof value === "string" && value.trim().length > 0; }; const getInputType = (value) => { if (!isString(value)) throw new Error("Input is not a valid string"); if (isUrl(value)) return "url"; if (isJsonString(value)) return "json"; if (isPath(value)) return "path"; return "string"; }; class SiziumLocal extends PackageSuper { async #getPackage() { try { if (isUrl(this.input)) { const response = await fetch(this.input); if (!response.ok) throw new Error(`Failed to fetch package file from URL: ${response.statusText}`); const content = await response.text(); return JSON.parse(content); } else if (isJsonString(this.input)) { return JSON.parse(this.input); } else { let filePath = resolve(this.input); const stats = await stat(filePath); if (stats.isDirectory()) filePath = join(filePath, "package.json"); const content = await readFile(filePath, "utf-8"); return JSON.parse(content); } } catch (e) { throw new this.Error( this.ERROR_ID.GETTING_LOCAL_DATA, { msg: `Error processing package file: ${e instanceof Error ? e.message : ""}`, e } ); } } async get() { const packageData = await this.#getPackage(); const mainPackage = await this.getPkgData(packageData, 0); const allPackages = await this.getPackagesData(mainPackage); return this.getMainPkgData(allPackages); } } export { SiziumLocal as S, getInputType as g };