Something went wrong. Try again.
[READ-ONLY] Mirror of https://github.com/okikio/bundlejs-api.
Something went wrong. Try again.
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324/** * Package name validation following npm's validate-npm-package-name rules. * * npm package names must: * - Be 214 characters or less (including scope) * - Not start with . or _ * - Not have uppercase letters * - Not contain URL-unsafe characters * - Not be a Node.js core module name * * @module * * @example * ```ts * import { validatePackageName, isValidPackageName } from "./validate-package-name.ts"; * * const result = validatePackageName("my-package"); * // { valid: true, errors: [], warnings: [] } * * const invalid = validatePackageName("My-Package"); * // { valid: false, errors: ["name must be lowercase"], warnings: [] } * * if (isValidPackageName("lodash")) { * // Safe to use * } * ``` * * @see https://github.com/npm/validate-npm-package-name */
// =============================================================================// Types// =============================================================================
/** * Result of package name validation. */export interface ValidateResult { /** Whether the name is valid for npm */ valid: boolean; /** Errors that make the name invalid */ errors: string[]; /** Warnings that don't invalidate but are discouraged */ warnings: string[];}
// =============================================================================// Constants// =============================================================================
/** * Node.js built-in module names. * These cannot be used as package names. */const NODE_BUILTINS = new Set([ "assert", "async_hooks", "buffer", "child_process", "cluster", "console", "constants", "crypto", "dgram", "diagnostics_channel", "dns", "domain", "events", "fs", "http", "http2", "https", "inspector", "module", "net", "os", "path", "perf_hooks", "process", "punycode", "querystring", "readline", "repl", "stream", "string_decoder", "sys", "timers", "tls", "trace_events", "tty", "url", "util", "v8", "vm", "wasi", "worker_threads", "zlib",]);
/** * "Blacklisted" names that npm reserves. */const BLACKLIST = new Set([ "node_modules", "favicon.ico",]);
/** * Characters that must not appear in package names. * These make URLs problematic. */const SPECIAL_CHARS = /[~'!()*]/;
/** * URL-unsafe characters that would need encoding. * We check this separately from SPECIAL_CHARS for more specific errors. */const URL_UNSAFE = /[^a-z0-9\-._@/]/;
// =============================================================================// Main Validation// =============================================================================
/** * Validate an npm package name. * * @param name Package name to validate * @returns Validation result with errors and warnings * * @example Valid names * ```ts * validatePackageName("lodash") * // { valid: true, errors: [], warnings: [] } * * validatePackageName("@scope/package") * // { valid: true, errors: [], warnings: [] } * * validatePackageName("my-package-123") * // { valid: true, errors: [], warnings: [] } * ``` * * @example Invalid names * ```ts * validatePackageName("My-Package") * // { valid: false, errors: ["name must be lowercase"], ... } * * validatePackageName(".hidden") * // { valid: false, errors: ["name cannot start with a period"], ... } * * validatePackageName("http") * // { valid: false, errors: ["http is a core Node.js module"], ... } * ``` */export function validatePackageName(name: string): ValidateResult { const errors: string[] = []; const warnings: string[] = [];
// Null/undefined check if (name == null) { errors.push("name cannot be null or undefined"); return { valid: false, errors, warnings }; }
// Must be a string if (typeof name !== "string") { errors.push("name must be a string"); return { valid: false, errors, warnings }; }
// Cannot be empty if (name.length === 0) { errors.push("name cannot be empty"); return { valid: false, errors, warnings }; }
// Length limit (214 characters including scope) if (name.length > 214) { errors.push("name cannot be longer than 214 characters"); }
// Cannot start with . or _ if (name.startsWith(".")) { errors.push("name cannot start with a period"); } if (name.startsWith("_")) { errors.push("name cannot start with an underscore"); }
// Cannot have leading or trailing spaces if (name !== name.trim()) { errors.push("name cannot have leading or trailing spaces"); }
// Must be lowercase if (name !== name.toLowerCase()) { errors.push("name must be lowercase"); }
// Cannot contain special characters if (SPECIAL_CHARS.test(name)) { errors.push("name cannot contain special characters: ~ ' ! ( ) *"); }
// Check for URL-unsafe characters (scoped packages handled separately) const nameWithoutScope = name.startsWith("@") ? name.slice(name.indexOf("/") + 1) : name;
if (URL_UNSAFE.test(nameWithoutScope)) { // More specific error for common issues if (/\s/.test(nameWithoutScope)) { errors.push("name cannot contain spaces"); } else { errors.push("name contains URL-unsafe characters"); } }
// Scoped package validation if (name.startsWith("@")) { const slashIndex = name.indexOf("/"); if (slashIndex === -1) { errors.push("scoped package name must include a slash"); } else { const scope = name.slice(1, slashIndex); const pkg = name.slice(slashIndex + 1);
if (scope.length === 0) { errors.push("scope cannot be empty"); } if (pkg.length === 0) { errors.push("package name cannot be empty after scope"); }
// Validate scope characters if (URL_UNSAFE.test(scope)) { errors.push("scope contains URL-unsafe characters"); } } }
// Cannot be a Node.js core module const baseName = name.startsWith("@") ? name.slice(name.indexOf("/") + 1) : name;
if (NODE_BUILTINS.has(baseName)) { errors.push(`"${baseName}" is a Node.js core module name`); }
// Cannot be blacklisted if (BLACKLIST.has(baseName)) { errors.push(`"${baseName}" is a reserved name`); }
// Warnings (not errors but discouraged) if (/^node-/.test(baseName) || /^nodejs-/.test(baseName)) { warnings.push("name starting with 'node-' or 'nodejs-' is discouraged"); } if (/-js$/.test(baseName) || /\.js$/.test(baseName)) { warnings.push("name ending with '-js' or '.js' is discouraged"); }
return { valid: errors.length === 0, errors, warnings, };}
// =============================================================================// Convenience Functions// =============================================================================
/** * Quick check if a package name is valid. * * @param name Package name to check * @returns True if valid * * @example * ```ts * if (isValidPackageName(userInput)) { * // Safe to use * } * ``` */export function isValidPackageName(name: string): boolean { return validatePackageName(name).valid;}
/** * Check if a name is a Node.js built-in module. * * @param name Module name to check * @returns True if it's a built-in * * @example * ```ts * isNodeBuiltin("fs") // true * isNodeBuiltin("lodash") // false * ``` */export function isNodeBuiltin(name: string): boolean { // Handle node: prefix const baseName = name.startsWith("node:") ? name.slice(5) : name; // Handle subpaths like "fs/promises" const moduleName = baseName.split("/")[0]; return NODE_BUILTINS.has(moduleName);}
/** * Get a list of all Node.js built-in module names. * * @returns Array of built-in module names */export function getNodeBuiltins(): string[] { return Array.from(NODE_BUILTINS);}
// =============================================================================// Exports for testing// =============================================================================
export { NODE_BUILTINS, BLACKLIST };