UNPKG

cjstoesm

Version:

A tool that can transform CommonJS to ESM

1,842 lines (1,826 loc) 110 kB
// src/transformer/util/resolve-path.ts import resolve from "resolve"; import path2 from "crosspath"; // src/transformer/util/path-util.ts import { normalize } from "crosspath"; var KNOWN_EXTENSIONS = [ ".d.ts", ".d.dts.map", ".js.map", ".ts", ".tsx", ".js", ".jsx", ".mjs", ".mjs.map", ".mjsx", ".cjs", ".cjs.map", ".csjx", ".d.cts", ".d.cts.map", ".d.mts", ".d.mts.map", ".json", ".tsbuildinfo" ]; function ensureHasLeadingDotAndPosix(p) { const posixPath = normalize(p); if (posixPath.startsWith(".")) return posixPath; if (posixPath.startsWith("/")) return `.${posixPath}`; return `./${posixPath}`; } function stripKnownExtension(file) { let currentExtname; for (const extName of KNOWN_EXTENSIONS) { if (file.endsWith(extName)) { currentExtname = extName; break; } } if (currentExtname == null) return file; return file.slice(0, file.lastIndexOf(currentExtname)); } function setExtension(file, extension) { return normalize(`${stripKnownExtension(file)}${extension}`); } function isExternalLibrary(p) { return !p.startsWith(".") && !p.startsWith("/"); } function isJsonModule(p) { return p.endsWith(`.json`); } // src/shared/util/util.ts import path from "crosspath"; function isArray(value) { return Array.isArray(value); } function ensureArray(item) { return Array.isArray(item) ? item : [item]; } function getFolderClosestToRoot(root, files) { const [head] = files; if (head == null) { throw new ReferenceError(`At least 1 file must be provided`); } let candidate = head; for (const file of files) { const relativeToRoot = path.relative(root, file); if (relativeToRoot.split("/").length < candidate.split("/").length) { candidate = relativeToRoot; } } return path.join(root, path.dirname(candidate)); } function normalizeGlob(glob) { return path.extname(glob) === "" && !glob.endsWith("*") ? `${glob}/*` : glob; } function isRecord(value) { return !Array.isArray(value) && typeof value === "object" && value != null && !(value instanceof Date) && !(value instanceof Set) && !(value instanceof WeakSet) && !(value instanceof Map) && !(value instanceof WeakMap); } function canHaveModifiers(node, typescript) { if ("canHaveModifiers" in typescript) { return typescript.canHaveModifiers(node); } else { return true; } } function getModifiers(node, typescript) { if ("getModifiers" in typescript) { return typescript.getModifiers(node); } else { return node.modifiers?.filter((modifier) => !("expression" in modifier)); } } function canHaveDecorators(node, typescript) { if ("canHaveDecorators" in typescript) { return typescript.canHaveDecorators(node); } else { return true; } } function getDecorators(node, typescript) { if ("getDecorators" in typescript) { return typescript.getDecorators(node); } else { const legacyDecorators = "decorators" in node && isArray(node.decorators) ? node.decorators : void 0; const decoratorModifierLikes = node.modifiers?.filter((modifier) => "expression" in modifier); return [...legacyDecorators ?? [], ...decoratorModifierLikes ?? []]; } } function addExportModifier(node, typescript, factory) { return addModifier(node, typescript, factory, typescript.SyntaxKind.ExportKeyword); } function hasExportModifier(node, typescript) { return hasModifier(node, typescript, typescript.SyntaxKind.ExportKeyword); } function hasDefaultExportModifier(node, typescript) { return hasExportModifier(node, typescript) && hasModifier(node, typescript, typescript.SyntaxKind.DefaultKeyword); } function hasModifier(node, typescript, modifier) { return canHaveModifiers(node, typescript) ? Boolean(node.modifiers?.some((m) => m.kind === modifier)) : false; } function addModifier(node, typescript, factory, modifier) { const modifiers = getModifiers(node, typescript) ?? []; if (modifiers.some((m) => m.kind === modifier)) return modifiers; if (!canHaveDecorators(node, typescript)) { return [factory.createModifier(modifier), ...modifiers.map((m) => factory.createModifier(m.kind))]; } else { const decorators = getDecorators(node, typescript) ?? []; return [factory.createModifier(modifier), ...modifiers.map((m) => factory.createModifier(m.kind)), ...decorators.map((decorator) => factory.createDecorator(decorator.expression))]; } } function isTypeAssertionExpression(node, typescript) { if ("isTypeAssertionExpression" in typescript) { return typescript.isTypeAssertionExpression(node); } else { return Boolean(typescript.isTypeAssertion?.(node)); } } // src/transformer/util/resolve-path.ts function computeCacheKey(id, parent) { return isExternalLibrary(id) ? id : `${parent == null ? "" : `${parent}->`}${id}`; } function resolvePath({ id, parent, cwd, prioritizedPackageKeys = ["exports", "es2015", "esm2015", "module", "jsnext:main", "main", "browser"], prioritizedExtensions = ["", ".js", ".mjs", ".cjs", ".jsx", ".ts", ".mts", ".cts", ".tsx", ".json"], moduleDirectory = "node_modules", fileSystem, resolveCache }) { id = path2.normalize(id); if (parent != null) { parent = path2.normalize(parent); } const cacheKey = computeCacheKey(id, parent); const cacheResult = resolveCache.get(cacheKey); if (cacheResult != null) return cacheResult; if (cacheResult === null) return; if (!isExternalLibrary(id)) { const absolute = path2.isAbsolute(id) ? path2.normalize(id) : path2.join(parent == null ? "" : path2.dirname(parent), id); const variants = [absolute, path2.join(absolute, "index")]; for (const variant of variants) { for (const ext of prioritizedExtensions) { const withExtension = `${variant}${ext}`; if (fileSystem.safeStatSync(withExtension)?.isFile() ?? false) { resolveCache.set(cacheKey, withExtension); return withExtension; } } } resolveCache.set(cacheKey, null); return void 0; } try { const resolveResult = path2.normalize( resolve.sync(id, { basedir: path2.normalize(cwd), extensions: prioritizedExtensions, moduleDirectory, readFileSync: (p) => fileSystem.readFileSync(p).toString(), isFile: (p) => fileSystem.safeStatSync(p)?.isFile() ?? false, isDirectory: (p) => fileSystem.safeStatSync(p)?.isDirectory() ?? false, packageFilter(pkg) { let property; if (property == null) { const packageKeys = Object.keys(pkg); property = prioritizedPackageKeys.find((key) => packageKeys.includes(key)); } if (property != null) { let pickedProperty = pkg[property]; while (isRecord(pickedProperty)) { if ("import" in pickedProperty) { pickedProperty = pickedProperty.import; } else if ("." in pickedProperty) { pickedProperty = pickedProperty["."]; } else if ("default" in pickedProperty) { pickedProperty = pickedProperty.default; } else if ("require" in pickedProperty) { pickedProperty = pickedProperty.require; } else { pickedProperty = pickedProperty[Object.keys(pickedProperty)[0]]; } } pkg.main = pickedProperty; } return pkg; } }) ); resolveCache.set(cacheKey, resolveResult); return resolveResult; } catch { resolveCache.set(cacheKey, null); return void 0; } } // src/transformer/util/walk-through-filler-nodes.ts function walkThroughFillerNodes(expression, typescript) { if (typescript.isParenthesizedExpression(expression) || typescript.isAsExpression(expression) || isTypeAssertionExpression(expression, typescript) || typescript.isNonNullExpression(expression) || typescript.isExpressionWithTypeArguments(expression)) { return expression.expression; } return expression; } // src/transformer/built-in/built-in-module-map.ts var BUILT_IN_MODULE = /* @__PURE__ */ new Set([ "assert", "assert/strict", "async_hooks", "buffer", "child_process", "cluster", "console", "constants", "crypto", "dgram", "diagnostics_channel", "dns", "dns/promises", "domain", "events", "fs", "fs/promises", "http", "http2", "https", "inspector", "inspector/promises", "module", "net", "os", "path", "path/posix", "path/win32", "perf_hooks", "process", "punycode", "querystring", "readline", "readline/promises", "repl", "stream", "stream/consumers", "stream/promises", "stream/web", "string_decoder", "timers", "timers/promises", "tls", "trace_events", "tty", "url", "util", "util/types", "v8", "vm", "wasi", "worker_threads", "zlib" ]); function isBuiltInModule(moduleName) { return BUILT_IN_MODULE.has(moduleName); } var BUILT_IN_MODULE_MAP = { assert: { namedExports: /* @__PURE__ */ new Set([]), hasDefaultExport: true }, "assert/strict": { namedExports: /* @__PURE__ */ new Set([]), hasDefaultExport: true }, async_hooks: { namedExports: /* @__PURE__ */ new Set(["AsyncLocalStorage", "createHook", "executionAsyncId", "triggerAsyncId", "executionAsyncResource", "asyncWrapProviders", "AsyncResource"]), hasDefaultExport: true }, buffer: { namedExports: /* @__PURE__ */ new Set([ "Buffer", "SlowBuffer", "transcode", "isUtf8", "isAscii", "kMaxLength", "kStringMaxLength", "btoa", "atob", "constants", "INSPECT_MAX_BYTES", "Blob", "resolveObjectURL", "File" ]), hasDefaultExport: true }, child_process: { namedExports: /* @__PURE__ */ new Set(["ChildProcess", "exec", "execFile", "execFileSync", "execSync", "fork", "spawn", "spawnSync"]), hasDefaultExport: true }, cluster: { namedExports: /* @__PURE__ */ new Set([ "isWorker", "isMaster", "isPrimary", "Worker", "workers", "settings", "SCHED_NONE", "SCHED_RR", "schedulingPolicy", "setupPrimary", "setupMaster", "fork", "disconnect" ]), hasDefaultExport: true }, console: { namedExports: /* @__PURE__ */ new Set([ "log", "warn", "error", "dir", "time", "timeEnd", "timeLog", "trace", "assert", "clear", "count", "countReset", "group", "groupEnd", "table", "debug", "info", "dirxml", "groupCollapsed", "Console", "profile", "profileEnd", "timeStamp", "context", "createTask" ]), hasDefaultExport: true }, constants: { namedExports: /* @__PURE__ */ new Set([ "RTLD_LAZY", "RTLD_NOW", "RTLD_GLOBAL", "RTLD_LOCAL", "E2BIG", "EACCES", "EADDRINUSE", "EADDRNOTAVAIL", "EAFNOSUPPORT", "EAGAIN", "EALREADY", "EBADF", "EBADMSG", "EBUSY", "ECANCELED", "ECHILD", "ECONNABORTED", "ECONNREFUSED", "ECONNRESET", "EDEADLK", "EDESTADDRREQ", "EDOM", "EDQUOT", "EEXIST", "EFAULT", "EFBIG", "EHOSTUNREACH", "EIDRM", "EILSEQ", "EINPROGRESS", "EINTR", "EINVAL", "EIO", "EISCONN", "EISDIR", "ELOOP", "EMFILE", "EMLINK", "EMSGSIZE", "EMULTIHOP", "ENAMETOOLONG", "ENETDOWN", "ENETRESET", "ENETUNREACH", "ENFILE", "ENOBUFS", "ENODATA", "ENODEV", "ENOENT", "ENOEXEC", "ENOLCK", "ENOLINK", "ENOMEM", "ENOMSG", "ENOPROTOOPT", "ENOSPC", "ENOSR", "ENOSTR", "ENOSYS", "ENOTCONN", "ENOTDIR", "ENOTEMPTY", "ENOTSOCK", "ENOTSUP", "ENOTTY", "ENXIO", "EOPNOTSUPP", "EOVERFLOW", "EPERM", "EPIPE", "EPROTO", "EPROTONOSUPPORT", "EPROTOTYPE", "ERANGE", "EROFS", "ESPIPE", "ESRCH", "ESTALE", "ETIME", "ETIMEDOUT", "ETXTBSY", "EWOULDBLOCK", "EXDEV", "PRIORITY_LOW", "PRIORITY_BELOW_NORMAL", "PRIORITY_NORMAL", "PRIORITY_ABOVE_NORMAL", "PRIORITY_HIGH", "PRIORITY_HIGHEST", "SIGHUP", "SIGINT", "SIGQUIT", "SIGILL", "SIGTRAP", "SIGABRT", "SIGIOT", "SIGBUS", "SIGFPE", "SIGKILL", "SIGUSR1", "SIGSEGV", "SIGUSR2", "SIGPIPE", "SIGALRM", "SIGTERM", "SIGCHLD", "SIGCONT", "SIGSTOP", "SIGTSTP", "SIGTTIN", "SIGTTOU", "SIGURG", "SIGXCPU", "SIGXFSZ", "SIGVTALRM", "SIGPROF", "SIGWINCH", "SIGIO", "SIGINFO", "SIGSYS", "UV_FS_SYMLINK_DIR", "UV_FS_SYMLINK_JUNCTION", "O_RDONLY", "O_WRONLY", "O_RDWR", "UV_DIRENT_UNKNOWN", "UV_DIRENT_FILE", "UV_DIRENT_DIR", "UV_DIRENT_LINK", "UV_DIRENT_FIFO", "UV_DIRENT_SOCKET", "UV_DIRENT_CHAR", "UV_DIRENT_BLOCK", "EXTENSIONLESS_FORMAT_JAVASCRIPT", "EXTENSIONLESS_FORMAT_WASM", "S_IFMT", "S_IFREG", "S_IFDIR", "S_IFCHR", "S_IFBLK", "S_IFIFO", "S_IFLNK", "S_IFSOCK", "O_CREAT", "O_EXCL", "UV_FS_O_FILEMAP", "O_NOCTTY", "O_TRUNC", "O_APPEND", "O_DIRECTORY", "O_NOFOLLOW", "O_SYNC", "O_DSYNC", "O_SYMLINK", "O_NONBLOCK", "S_IRWXU", "S_IRUSR", "S_IWUSR", "S_IXUSR", "S_IRWXG", "S_IRGRP", "S_IWGRP", "S_IXGRP", "S_IRWXO", "S_IROTH", "S_IWOTH", "S_IXOTH", "F_OK", "R_OK", "W_OK", "X_OK", "UV_FS_COPYFILE_EXCL", "COPYFILE_EXCL", "UV_FS_COPYFILE_FICLONE", "COPYFILE_FICLONE", "UV_FS_COPYFILE_FICLONE_FORCE", "COPYFILE_FICLONE_FORCE", "OPENSSL_VERSION_NUMBER", "SSL_OP_ALL", "SSL_OP_ALLOW_NO_DHE_KEX", "SSL_OP_ALLOW_UNSAFE_LEGACY_RENEGOTIATION", "SSL_OP_CIPHER_SERVER_PREFERENCE", "SSL_OP_CISCO_ANYCONNECT", "SSL_OP_COOKIE_EXCHANGE", "SSL_OP_CRYPTOPRO_TLSEXT_BUG", "SSL_OP_DONT_INSERT_EMPTY_FRAGMENTS", "SSL_OP_LEGACY_SERVER_CONNECT", "SSL_OP_NO_COMPRESSION", "SSL_OP_NO_ENCRYPT_THEN_MAC", "SSL_OP_NO_QUERY_MTU", "SSL_OP_NO_RENEGOTIATION", "SSL_OP_NO_SESSION_RESUMPTION_ON_RENEGOTIATION", "SSL_OP_NO_SSLv2", "SSL_OP_NO_SSLv3", "SSL_OP_NO_TICKET", "SSL_OP_NO_TLSv1", "SSL_OP_NO_TLSv1_1", "SSL_OP_NO_TLSv1_2", "SSL_OP_NO_TLSv1_3", "SSL_OP_PRIORITIZE_CHACHA", "SSL_OP_TLS_ROLLBACK_BUG", "ENGINE_METHOD_RSA", "ENGINE_METHOD_DSA", "ENGINE_METHOD_DH", "ENGINE_METHOD_RAND", "ENGINE_METHOD_EC", "ENGINE_METHOD_CIPHERS", "ENGINE_METHOD_DIGESTS", "ENGINE_METHOD_PKEY_METHS", "ENGINE_METHOD_PKEY_ASN1_METHS", "ENGINE_METHOD_ALL", "ENGINE_METHOD_NONE", "DH_CHECK_P_NOT_SAFE_PRIME", "DH_CHECK_P_NOT_PRIME", "DH_UNABLE_TO_CHECK_GENERATOR", "DH_NOT_SUITABLE_GENERATOR", "RSA_PKCS1_PADDING", "RSA_NO_PADDING", "RSA_PKCS1_OAEP_PADDING", "RSA_X931_PADDING", "RSA_PKCS1_PSS_PADDING", "RSA_PSS_SALTLEN_DIGEST", "RSA_PSS_SALTLEN_MAX_SIGN", "RSA_PSS_SALTLEN_AUTO", "defaultCoreCipherList", "TLS1_VERSION", "TLS1_1_VERSION", "TLS1_2_VERSION", "TLS1_3_VERSION", "POINT_CONVERSION_COMPRESSED", "POINT_CONVERSION_UNCOMPRESSED", "POINT_CONVERSION_HYBRID", "defaultCipherList" ]), hasDefaultExport: true }, crypto: { namedExports: /* @__PURE__ */ new Set([ "checkPrime", "checkPrimeSync", "createCipheriv", "createDecipheriv", "createDiffieHellman", "createDiffieHellmanGroup", "createECDH", "createHash", "createHmac", "createPrivateKey", "createPublicKey", "createSecretKey", "createSign", "createVerify", "diffieHellman", "generatePrime", "generatePrimeSync", "getCiphers", "getCipherInfo", "getCurves", "getDiffieHellman", "getHashes", "hkdf", "hkdfSync", "pbkdf2", "pbkdf2Sync", "generateKeyPair", "generateKeyPairSync", "generateKey", "generateKeySync", "privateDecrypt", "privateEncrypt", "publicDecrypt", "publicEncrypt", "randomBytes", "randomFill", "randomFillSync", "randomInt", "randomUUID", "scrypt", "scryptSync", "sign", "setEngine", "timingSafeEqual", "getFips", "setFips", "verify", "hash", "Certificate", "Cipher", "Cipheriv", "Decipher", "Decipheriv", "DiffieHellman", "DiffieHellmanGroup", "ECDH", "Hash", "Hmac", "KeyObject", "Sign", "Verify", "X509Certificate", "secureHeapUsed", "constants", "webcrypto", "subtle", "getRandomValues" ]), hasDefaultExport: true }, dgram: { namedExports: /* @__PURE__ */ new Set(["createSocket", "Socket"]), hasDefaultExport: true }, diagnostics_channel: { namedExports: /* @__PURE__ */ new Set(["channel", "hasSubscribers", "subscribe", "tracingChannel", "unsubscribe", "Channel"]), hasDefaultExport: true }, dns: { namedExports: /* @__PURE__ */ new Set([ "lookup", "lookupService", "Resolver", "getDefaultResultOrder", "setDefaultResultOrder", "setServers", "ADDRCONFIG", "ALL", "V4MAPPED", "NODATA", "FORMERR", "SERVFAIL", "NOTFOUND", "NOTIMP", "REFUSED", "BADQUERY", "BADNAME", "BADFAMILY", "BADRESP", "CONNREFUSED", "TIMEOUT", "EOF", "FILE", "NOMEM", "DESTRUCTION", "BADSTR", "BADFLAGS", "NONAME", "BADHINTS", "NOTINITIALIZED", "LOADIPHLPAPI", "ADDRGETNETWORKPARAMS", "CANCELLED", "getServers", "resolve", "resolve4", "resolve6", "resolveAny", "resolveCaa", "resolveCname", "resolveMx", "resolveNaptr", "resolveNs", "resolvePtr", "resolveSoa", "resolveSrv", "resolveTxt", "reverse", "promises" ]), hasDefaultExport: true }, "dns/promises": { namedExports: /* @__PURE__ */ new Set([ "lookup", "lookupService", "Resolver", "getDefaultResultOrder", "setDefaultResultOrder", "setServers", "NODATA", "FORMERR", "SERVFAIL", "NOTFOUND", "NOTIMP", "REFUSED", "BADQUERY", "BADNAME", "BADFAMILY", "BADRESP", "CONNREFUSED", "TIMEOUT", "EOF", "FILE", "NOMEM", "DESTRUCTION", "BADSTR", "BADFLAGS", "NONAME", "BADHINTS", "NOTINITIALIZED", "LOADIPHLPAPI", "ADDRGETNETWORKPARAMS", "CANCELLED", "getServers", "resolve", "resolve4", "resolve6", "resolveAny", "resolveCaa", "resolveCname", "resolveMx", "resolveNaptr", "resolveNs", "resolvePtr", "resolveSoa", "resolveSrv", "resolveTxt", "reverse" ]), hasDefaultExport: true }, domain: { namedExports: /* @__PURE__ */ new Set(["Domain", "createDomain", "create", "active"]), hasDefaultExport: true }, events: { namedExports: /* @__PURE__ */ new Set([]), hasDefaultExport: true }, fs: { namedExports: /* @__PURE__ */ new Set([ "appendFile", "appendFileSync", "access", "accessSync", "chown", "chownSync", "chmod", "chmodSync", "close", "closeSync", "copyFile", "copyFileSync", "cp", "cpSync", "createReadStream", "createWriteStream", "exists", "existsSync", "fchown", "fchownSync", "fchmod", "fchmodSync", "fdatasync", "fdatasyncSync", "fstat", "fstatSync", "fsync", "fsyncSync", "ftruncate", "ftruncateSync", "futimes", "futimesSync", "glob", "globSync", "lchown", "lchownSync", "lchmod", "lchmodSync", "link", "linkSync", "lstat", "lstatSync", "lutimes", "lutimesSync", "mkdir", "mkdirSync", "mkdtemp", "mkdtempSync", "open", "openSync", "openAsBlob", "readdir", "readdirSync", "read", "readSync", "readv", "readvSync", "readFile", "readFileSync", "readlink", "readlinkSync", "realpath", "realpathSync", "rename", "renameSync", "rm", "rmSync", "rmdir", "rmdirSync", "stat", "statfs", "statSync", "statfsSync", "symlink", "symlinkSync", "truncate", "truncateSync", "unwatchFile", "unlink", "unlinkSync", "utimes", "utimesSync", "watch", "watchFile", "writeFile", "writeFileSync", "write", "writeSync", "writev", "writevSync", "Dirent", "Stats", "ReadStream", "WriteStream", "FileReadStream", "FileWriteStream", "Dir", "opendir", "opendirSync", "F_OK", "R_OK", "W_OK", "X_OK", "constants", "promises" ]), hasDefaultExport: true }, "fs/promises": { namedExports: /* @__PURE__ */ new Set([ "access", "copyFile", "cp", "glob", "open", "opendir", "rename", "truncate", "rm", "rmdir", "mkdir", "readdir", "readlink", "symlink", "lstat", "stat", "statfs", "link", "unlink", "chmod", "lchmod", "lchown", "chown", "utimes", "lutimes", "realpath", "mkdtemp", "writeFile", "appendFile", "readFile", "watch", "constants" ]), hasDefaultExport: true }, http: { namedExports: /* @__PURE__ */ new Set([ "METHODS", "STATUS_CODES", "Agent", "ClientRequest", "IncomingMessage", "OutgoingMessage", "Server", "ServerResponse", "createServer", "validateHeaderName", "validateHeaderValue", "get", "request", "setMaxIdleHTTPParsers", "maxHeaderSize", "globalAgent", "WebSocket", "CloseEvent", "MessageEvent" ]), hasDefaultExport: true }, http2: { namedExports: /* @__PURE__ */ new Set([ "connect", "constants", "createServer", "createSecureServer", "getDefaultSettings", "getPackedSettings", "getUnpackedSettings", "performServerHandshake", "sensitiveHeaders", "Http2ServerRequest", "Http2ServerResponse" ]), hasDefaultExport: true }, https: { namedExports: /* @__PURE__ */ new Set(["Agent", "globalAgent", "Server", "createServer", "get", "request"]), hasDefaultExport: true }, inspector: { namedExports: /* @__PURE__ */ new Set(["open", "close", "url", "waitForDebugger", "console", "Session", "Network"]), hasDefaultExport: true }, "inspector/promises": { namedExports: /* @__PURE__ */ new Set(["open", "close", "url", "waitForDebugger", "console", "Session", "Network"]), hasDefaultExport: true }, module: { namedExports: /* @__PURE__ */ new Set([]), hasDefaultExport: true }, net: { namedExports: /* @__PURE__ */ new Set([ "BlockList", "SocketAddress", "connect", "createConnection", "createServer", "isIP", "isIPv4", "isIPv6", "Server", "Socket", "Stream", "getDefaultAutoSelectFamily", "setDefaultAutoSelectFamily", "getDefaultAutoSelectFamilyAttemptTimeout", "setDefaultAutoSelectFamilyAttemptTimeout" ]), hasDefaultExport: true }, os: { namedExports: /* @__PURE__ */ new Set([ "arch", "availableParallelism", "cpus", "endianness", "freemem", "getPriority", "homedir", "hostname", "loadavg", "networkInterfaces", "platform", "release", "setPriority", "tmpdir", "totalmem", "type", "userInfo", "uptime", "version", "machine", "constants", "EOL", "devNull" ]), hasDefaultExport: true }, path: { namedExports: /* @__PURE__ */ new Set([ "resolve", "normalize", "isAbsolute", "join", "relative", "toNamespacedPath", "dirname", "basename", "extname", "format", "parse", "matchesGlob", "sep", "delimiter", "win32", "posix" ]), hasDefaultExport: true }, "path/posix": { namedExports: /* @__PURE__ */ new Set([ "resolve", "normalize", "isAbsolute", "join", "relative", "toNamespacedPath", "dirname", "basename", "extname", "format", "parse", "matchesGlob", "sep", "delimiter", "win32", "posix" ]), hasDefaultExport: true }, "path/win32": { namedExports: /* @__PURE__ */ new Set([ "resolve", "normalize", "isAbsolute", "join", "relative", "toNamespacedPath", "dirname", "basename", "extname", "format", "parse", "matchesGlob", "sep", "delimiter", "win32", "posix" ]), hasDefaultExport: true }, perf_hooks: { namedExports: /* @__PURE__ */ new Set([ "Performance", "PerformanceEntry", "PerformanceMark", "PerformanceMeasure", "PerformanceObserver", "PerformanceObserverEntryList", "PerformanceResourceTiming", "monitorEventLoopDelay", "createHistogram", "performance", "constants" ]), hasDefaultExport: true }, process: { namedExports: /* @__PURE__ */ new Set([ "version", "versions", "arch", "platform", "release", "moduleLoadList", "binding", "domain", "exitCode", "config", "dlopen", "uptime", "getActiveResourcesInfo", "reallyExit", "loadEnvFile", "cpuUsage", "resourceUsage", "memoryUsage", "constrainedMemory", "availableMemory", "kill", "exit", "finalization", "hrtime", "openStdin", "getuid", "geteuid", "getgid", "getegid", "getgroups", "allowedNodeEnvironmentFlags", "assert", "features", "setUncaughtExceptionCaptureCallback", "hasUncaughtExceptionCaptureCallback", "emitWarning", "nextTick", "sourceMapsEnabled", "setSourceMapsEnabled", "getBuiltinModule", "stdout", "stdin", "stderr", "abort", "umask", "chdir", "cwd", "initgroups", "setgroups", "setegid", "seteuid", "setgid", "setuid", "env", "title", "argv", "execArgv", "pid", "ppid", "execPath", "debugPort", "argv0", "report" ]), hasDefaultExport: true }, punycode: { namedExports: /* @__PURE__ */ new Set(["version", "ucs2", "decode", "encode", "toASCII", "toUnicode"]), hasDefaultExport: true }, querystring: { namedExports: /* @__PURE__ */ new Set(["unescapeBuffer", "unescape", "escape", "stringify", "encode", "parse", "decode"]), hasDefaultExport: true }, readline: { namedExports: /* @__PURE__ */ new Set(["Interface", "clearLine", "clearScreenDown", "createInterface", "cursorTo", "emitKeypressEvents", "moveCursor", "promises"]), hasDefaultExport: true }, "readline/promises": { namedExports: /* @__PURE__ */ new Set(["Interface", "Readline", "createInterface"]), hasDefaultExport: true }, repl: { namedExports: /* @__PURE__ */ new Set(["start", "writer", "REPLServer", "REPL_MODE_SLOPPY", "REPL_MODE_STRICT", "Recoverable", "builtinModules"]), hasDefaultExport: true }, stream: { namedExports: /* @__PURE__ */ new Set([]), hasDefaultExport: true }, "stream/consumers": { namedExports: /* @__PURE__ */ new Set(["arrayBuffer", "blob", "buffer", "text", "json"]), hasDefaultExport: true }, "stream/promises": { namedExports: /* @__PURE__ */ new Set(["finished", "pipeline"]), hasDefaultExport: true }, "stream/web": { namedExports: /* @__PURE__ */ new Set([ "ReadableStream", "ReadableStreamDefaultReader", "ReadableStreamBYOBReader", "ReadableStreamBYOBRequest", "ReadableByteStreamController", "ReadableStreamDefaultController", "TransformStream", "TransformStreamDefaultController", "WritableStream", "WritableStreamDefaultWriter", "WritableStreamDefaultController", "ByteLengthQueuingStrategy", "CountQueuingStrategy", "TextEncoderStream", "TextDecoderStream", "CompressionStream", "DecompressionStream" ]), hasDefaultExport: true }, string_decoder: { namedExports: /* @__PURE__ */ new Set(["StringDecoder"]), hasDefaultExport: true }, timers: { namedExports: /* @__PURE__ */ new Set(["setTimeout", "clearTimeout", "setImmediate", "clearImmediate", "setInterval", "clearInterval", "active", "unenroll", "enroll", "promises"]), hasDefaultExport: true }, "timers/promises": { namedExports: /* @__PURE__ */ new Set(["setTimeout", "setImmediate", "setInterval", "scheduler"]), hasDefaultExport: true }, tls: { namedExports: /* @__PURE__ */ new Set([ "CLIENT_RENEG_LIMIT", "CLIENT_RENEG_WINDOW", "DEFAULT_CIPHERS", "DEFAULT_ECDH_CURVE", "DEFAULT_MIN_VERSION", "DEFAULT_MAX_VERSION", "getCiphers", "rootCertificates", "convertALPNProtocols", "checkServerIdentity", "createSecureContext", "SecureContext", "TLSSocket", "Server", "createServer", "connect", "createSecurePair" ]), hasDefaultExport: true }, trace_events: { namedExports: /* @__PURE__ */ new Set(["createTracing", "getEnabledCategories"]), hasDefaultExport: true }, tty: { namedExports: /* @__PURE__ */ new Set(["isatty", "ReadStream", "WriteStream"]), hasDefaultExport: true }, url: { namedExports: /* @__PURE__ */ new Set([ "Url", "parse", "resolve", "resolveObject", "format", "URL", "URLSearchParams", "domainToASCII", "domainToUnicode", "pathToFileURL", "fileURLToPath", "urlToHttpOptions" ]), hasDefaultExport: true }, util: { namedExports: /* @__PURE__ */ new Set([ "callbackify", "debug", "debuglog", "deprecate", "format", "styleText", "formatWithOptions", "getCallSite", "getSystemErrorMap", "getSystemErrorName", "inherits", "inspect", "isArray", "isBoolean", "isBuffer", "isDeepStrictEqual", "isNull", "isNullOrUndefined", "isNumber", "isString", "isSymbol", "isUndefined", "isRegExp", "isObject", "isDate", "isError", "isFunction", "isPrimitive", "log", "promisify", "stripVTControlCharacters", "toUSVString", "transferableAbortSignal", "transferableAbortController", "aborted", "types", "parseEnv", "parseArgs", "TextDecoder", "TextEncoder", "MIMEType", "MIMEParams" ]), hasDefaultExport: true }, "util/types": { namedExports: /* @__PURE__ */ new Set([ "isExternal", "isDate", "isArgumentsObject", "isBigIntObject", "isBooleanObject", "isNumberObject", "isStringObject", "isSymbolObject", "isNativeError", "isRegExp", "isAsyncFunction", "isGeneratorFunction", "isGeneratorObject", "isPromise", "isMap", "isSet", "isMapIterator", "isSetIterator", "isWeakMap", "isWeakSet", "isArrayBuffer", "isDataView", "isSharedArrayBuffer", "isProxy", "isModuleNamespaceObject", "isAnyArrayBuffer", "isBoxedPrimitive", "isArrayBufferView", "isTypedArray", "isUint8Array", "isUint8ClampedArray", "isUint16Array", "isUint32Array", "isInt8Array", "isInt16Array", "isInt32Array", "isFloat32Array", "isFloat64Array", "isBigInt64Array", "isBigUint64Array", "isKeyObject", "isCryptoKey" ]), hasDefaultExport: true }, v8: { namedExports: /* @__PURE__ */ new Set([ "cachedDataVersionTag", "getHeapSnapshot", "getHeapStatistics", "getHeapSpaceStatistics", "getHeapCodeStatistics", "setFlagsFromString", "Serializer", "Deserializer", "DefaultSerializer", "DefaultDeserializer", "deserialize", "takeCoverage", "stopCoverage", "serialize", "writeHeapSnapshot", "promiseHooks", "queryObjects", "startupSnapshot", "setHeapSnapshotNearHeapLimit", "GCProfiler" ]), hasDefaultExport: true }, vm: { namedExports: /* @__PURE__ */ new Set([ "Script", "createContext", "createScript", "runInContext", "runInNewContext", "runInThisContext", "isContext", "compileFunction", "measureMemory", "constants" ]), hasDefaultExport: true }, wasi: { namedExports: /* @__PURE__ */ new Set(["WASI"]), hasDefaultExport: true }, worker_threads: { namedExports: /* @__PURE__ */ new Set([ "isMainThread", "MessagePort", "MessageChannel", "markAsUntransferable", "isMarkedAsUntransferable", "moveMessagePortToContext", "receiveMessageOnPort", "resourceLimits", "postMessageToThread", "threadId", "SHARE_ENV", "Worker", "parentPort", "workerData", "BroadcastChannel", "setEnvironmentData", "getEnvironmentData" ]), hasDefaultExport: true }, zlib: { namedExports: /* @__PURE__ */ new Set([ "crc32", "Deflate", "Inflate", "Gzip", "Gunzip", "DeflateRaw", "InflateRaw", "Unzip", "BrotliCompress", "BrotliDecompress", "deflate", "deflateSync", "gzip", "gzipSync", "deflateRaw", "deflateRawSync", "unzip", "unzipSync", "inflate", "inflateSync", "gunzip", "gunzipSync", "inflateRaw", "inflateRawSync", "brotliCompress", "brotliCompressSync", "brotliDecompress", "brotliDecompressSync", "createDeflate", "createInflate", "createDeflateRaw", "createInflateRaw", "createGzip", "createGunzip", "createUnzip", "createBrotliCompress", "createBrotliDecompress", "constants", "codes" ]), hasDefaultExport: true } }; // src/transformer/util/transform-module-specifier.ts import path3 from "crosspath"; function determineNewExtension(currentExtension) { switch (currentExtension) { case ".ts": case ".tsx": case ".d.ts": case ".d.mts": case ".js": case ".jsx": case ".cjs": case ".cjsx": case ".cts": return ".js"; case ".mjs": case ".mts": case ".mjsx": case ".d.cts": return ".mjs"; default: return currentExtension; } } function transformModuleSpecifier(moduleSpecifier, { context, parent, resolvedModuleSpecifier }) { if (path3.extname(moduleSpecifier) !== "" || resolvedModuleSpecifier == null) { return moduleSpecifier; } switch (context.preserveModuleSpecifiers) { case "always": return moduleSpecifier; case "never": break; case "external": if (isExternalLibrary(moduleSpecifier)) { return moduleSpecifier; } break; case "internal": if (!isExternalLibrary(moduleSpecifier)) { return moduleSpecifier; } break; default: if (context.preserveModuleSpecifiers(moduleSpecifier)) { return moduleSpecifier; } } return setExtension(ensureHasLeadingDotAndPosix(path3.relative(path3.dirname(parent), resolvedModuleSpecifier)), determineNewExtension(path3.extname(resolvedModuleSpecifier))); } // src/transformer/util/is-require-call.ts function isRequireCall(inputExpression, sourceFile, context) { const { typescript } = context; const callExpression = walkThroughFillerNodes(inputExpression, typescript); if (!typescript.isCallExpression(callExpression)) return { match: false }; const expression = walkThroughFillerNodes(callExpression.expression, typescript); if (!typescript.isIdentifier(expression) || expression.text !== "require") return { match: false }; const [firstArgument] = callExpression.arguments; if (firstArgument == null) return { match: false }; const moduleSpecifier = typescript.isStringLiteralLike(firstArgument) ? firstArgument.text : void 0; const resolvedModuleSpecifier = moduleSpecifier == null ? void 0 : resolvePath({ ...context, id: moduleSpecifier, parent: sourceFile.fileName }); const resolvedModuleSpecifierText = resolvedModuleSpecifier == null || isBuiltInModule(resolvedModuleSpecifier) ? void 0 : context.fileSystem.safeReadFileSync(resolvedModuleSpecifier)?.toString(); if (moduleSpecifier == null || resolvedModuleSpecifier == null || resolvedModuleSpecifierText == null) { return { match: true, moduleSpecifier, transformedModuleSpecifier: moduleSpecifier, resolvedModuleSpecifier: void 0, resolvedModuleSpecifierText: void 0 }; } else { return { match: true, transformedModuleSpecifier: transformModuleSpecifier(moduleSpecifier, { resolvedModuleSpecifier, context, parent: sourceFile.fileName }), moduleSpecifier, resolvedModuleSpecifier, resolvedModuleSpecifierText }; } } // src/transformer/util/find-node-up.ts function findNodeUp(from, nodeCb, breakWhen) { let current = from; while (current.parent != null) { current = current.parent; if (breakWhen?.(current)) return void 0; if (nodeCb(current)) return current; } return void 0; } // src/transformer/util/is-statement.ts function isStatement(node, typescript) { return typescript.isStatementButNotDeclaration(node); } // src/transformer/util/is-declaration.ts function isDeclaration(node, typescript) { return typescript.isDeclaration(node); } // src/transformer/util/is-statement-or-declaration.ts function isStatementOrDeclaration(node, typescript) { return isStatement(node, typescript) || isDeclaration(node, typescript); } // src/transformer/util/generate-name-from-module-specifier.ts import { camelCase } from "@wessberg/stringutil"; import path4 from "crosspath"; function generateNameFromModuleSpecifier(moduleSpecifier) { const { name } = path4.parse(moduleSpecifier); return camelCase(name); } // src/transformer/util/get-module-exports-from-require-data-in-context.ts function getModuleExportsFromRequireDataInContext(data, context) { if (!data.match) return void 0; const { typescript } = context; const { moduleSpecifier, resolvedModuleSpecifierText, resolvedModuleSpecifier } = data; if (moduleSpecifier == null) { return void 0; } let moduleExports; if (resolvedModuleSpecifier == null && isBuiltInModule(moduleSpecifier)) { moduleExports = BUILT_IN_MODULE_MAP[moduleSpecifier]; } else if (resolvedModuleSpecifier != null) { if (isJsonModule(resolvedModuleSpecifier)) { moduleExports = { withValue: "json", hasDefaultExport: true, namedExports: /* @__PURE__ */ new Set() }; } else { moduleExports = context.getModuleExportsForPath(resolvedModuleSpecifier); if (moduleExports == null) { moduleExports = context.transformSourceFile( typescript.createSourceFile(resolvedModuleSpecifier, resolvedModuleSpecifierText, typescript.ScriptTarget.ESNext, true, typescript.ScriptKind.TS), { ...context, onlyExports: true } ).exports; } } } return moduleExports; } // src/transformer/util/should-debug.ts function shouldDebug(debug, sourceFile) { if (debug == null) return false; if (typeof debug === "boolean") return debug; if (sourceFile == null) return true; if (typeof debug === "string") return sourceFile.fileName === debug; else return debug(sourceFile.fileName); } // src/transformer/util/maybe-generate-import-attributes.ts function maybeGenerateImportAttributes(context, moduleSpecifier, withValue) { if (withValue == null) return void 0; const { factory, importAttributes } = context; if (importAttributes === false || typeof importAttributes === "function" && !importAttributes(moduleSpecifier)) { return void 0; } if (!("createImportAttributes" in context.typescript.factory)) { context.logger.warn( `The current version of TypeScript (v${context.typescript.version}) does not support Import Attributes. No Import Attributes will be added for the module with specifier '${moduleSpecifier}' in the transformed code. To remove this warning, either disable import attributes or update to TypeScript v5.3 or newer.` ); } return factory.createImportAttributes(factory.createNodeArray([factory.createImportAttribute(factory.createIdentifier("type"), factory.createStringLiteral(withValue))])); } // src/transformer/visitor/visit/visit-call-expression.ts function visitCallExpression({ node, childContinuation, sourceFile, context }) { if (context.onlyExports) { return childContinuation(node); } const requireData = isRequireCall(node, sourceFile, context); const { typescript, factory } = context; if (!requireData.match) { return childContinuation(node); } const { moduleSpecifier, transformedModuleSpecifier } = requireData; if (moduleSpecifier == null || transformedModuleSpecifier == null) { return void 0; } const moduleExports = getModuleExportsFromRequireDataInContext(requireData, context); const expressionStatementParent = findNodeUp( node, typescript.isExpressionStatement, (currentNode) => typescript.isBinaryExpression(currentNode) || typescript.isCallExpression(currentNode) || typescript.isNewExpression(currentNode) ); if (moduleExports == null || moduleExports.namedExports.size === 0 || expressionStatementParent != null && !moduleExports.hasDefaultExport) { if (expressionStatementParent != null) { if (!context.isModuleSpecifierImportedWithoutLocals(moduleSpecifier)) { context.addImport( factory.createImportDeclaration( void 0, void 0, factory.createStringLiteral(transformedModuleSpecifier), maybeGenerateImportAttributes(context, transformedModuleSpecifier, moduleExports?.withValue) ), moduleSpecifier ); } return void 0; } else { if (context.hasLocalForDefaultImportFromModule(moduleSpecifier)) { const local = context.getLocalForDefaultImportFromModule(moduleSpecifier); return factory.createIdentifier(local); } else { const identifier = factory.createIdentifier(context.getFreeIdentifier(generateNameFromModuleSpecifier(moduleSpecifier))); const importClause = factory.createImportClause(false, identifier, void 0); context.addImport( factory.createImportDeclaration( void 0, importClause, factory.createStringLiteral(transformedModuleSpecifier), maybeGenerateImportAttributes(context, transformedModuleSpecifier, moduleExports?.withValue) ), moduleSpecifier ); return identifier; } } } const elementOrPropertyAccessExpressionParent = findNodeUp( node, (child) => typescript.isElementAccessExpression(child) || typescript.isPropertyAccessExpression(child), (nextNode) => isStatementOrDeclaration(nextNode, typescript) ); if (elementOrPropertyAccessExpressionParent != null) { let rightValue; if (typescript.isPropertyAccessExpression(elementOrPropertyAccessExpressionParent)) { rightValue = elementOrPropertyAccessExpressionParent.name.text; } else { if (typescript.isStringLiteralLike(elementOrPropertyAccessExpressionParent.argumentExpression)) { rightValue = elementOrPropertyAccessExpressionParent.argumentExpression.text; } } if (rightValue != null) { if (!moduleExports.namedExports.has(rightValue)) { let identifier; if (moduleExports.hasDefaultExport && context.hasLocalForDefaultImportFromModule(moduleSpecifier)) { identifier = factory.createIdentifier(context.getLocalForDefaultImportFromModule(moduleSpecifier)); } else if (!moduleExports.hasDefaultExport && context.hasLocalForNamespaceImportFromModule(moduleSpecifier)) { identifier = factory.createIdentifier(context.getLocalForNamespaceImportFromModule(moduleSpecifier)); } else { identifier = factory.createIdentifier(context.getFreeIdentifier(generateNameFromModuleSpecifier(moduleSpecifier))); context.addImport( factory.createImportDeclaration( void 0, moduleExports.hasDefaultExport ? ( // Import the default if it has any (or if we don't know if it has) factory.createImportClause(false, identifier, void 0) ) : ( // Otherwise, import the entire namespace factory.createImportClause(false, void 0, factory.createNamespaceImport(identifier)) ), factory.createStringLiteral(transformedModuleSpecifier), maybeGenerateImportAttributes(context, transformedModuleSpecifier, moduleExports.withValue) ), moduleSpecifier ); } const objectLiteralProperties = [ identifier.text !== rightValue ? factory.createPropertyAssignment(rightValue, factory.createIdentifier(identifier.text)) : factory.createShorthandPropertyAssignment(factory.createIdentifier(identifier.text)) ]; return factory.createObjectLiteralExpression(objectLiteralProperties); } else { const importBindingPropertyName = rightValue; let importBindingName; if (context.hasLocalForNamedImportPropertyNameFromModule(importBindingPropertyName, moduleSpecifier)) { importBindingName = context.getLocalForNamedImportPropertyNameFromModule(importBindingPropertyName, moduleSpecifier); } else if (!moduleExports.hasDefaultExport && context.hasLocalForNamespaceImportFromModule(moduleSpecifier)) { importBindingName = context.getLocalForNamespaceImportFromModule(moduleSpecifier); } else { importBindingName = context.getFreeIdentifier(importBindingPropertyName); const namedImports = factory.createNamedImports([ importBindingPropertyName === importBindingName ? ( // If the property name is free within the context, don't alias the import factory.createImportSpecifier(false, void 0, factory.createIdentifier(importBindingPropertyName)) ) : ( // Otherwise, import it aliased by another name that is free within the context factory.createImportSpecifier(false, factory.createIdentifier(importBindingPropertyName), factory.createIdentifier(importBindingName)) ) ]); const importClause = factory.createImportClause(false, void 0, namedImports); context.addImport( factory.createImportDeclaration( void 0, importClause, factory.createStringLiteral(transformedModuleSpecifier), maybeGenerateImportAttributes(context, transformedModuleSpecifier, moduleExports.withValue) ), moduleSpecifier ); } if (expressionStatementParent == null) { const objectLiteralProperties = [ importBindingName !== rightValue ? factory.createPropertyAssignment(rightValue, factory.createIdentifier(importBindingName)) : factory.createShorthandPropertyAssignment(factory.createIdentifier(importBindingName)) ]; return factory.createObjectLiteralExpression(objectLiteralProperties); } else { return void 0; } } } } const variableDeclarationParent = findNodeUp(node, typescript.isVariableDeclaration, (nextNode) => isStatement(nextNode, typescript)); if (variableDeclarationParent != null) { if (typescript.isIdentifier(variableDeclarationParent.name)) { if (moduleExports.hasDefaultExport && context.hasLocalForDefaultImportFromModule(moduleSpecifier)) { const local = context.getLocalForDefaultImportFromModule(moduleSpecifier); return factory.createIdentifier(local); } else if (!moduleExports.hasDefaultExport && context.hasLocalForNamespaceI