Website Structure

This commit is contained in:
supalerk-ar66 2026-01-13 10:46:40 +07:00
parent 62812f2090
commit 71f0676a62
22365 changed files with 4265753 additions and 791 deletions

21
Frontend-Learner/node_modules/vite-node/LICENSE generated vendored Normal file
View file

@ -0,0 +1,21 @@
MIT License
Copyright (c) 2021-PRESENT Anthony Fu <https://github.com/antfu>
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.

197
Frontend-Learner/node_modules/vite-node/README.md generated vendored Normal file
View file

@ -0,0 +1,197 @@
<p align="center">
<img src="https://github.com/antfu/vite-node/blob/main/assets/vite-node.svg?raw=true" height="120">
</p>
<h1 align="center">
vite-node
</h1>
<p align="center">
Vite as Node runtime.<br>The engine that powers <a href="https://github.com/nuxt/nuxt">Nuxt 3 Dev SSR</a> and <i><a href="https://github.com/vitest-dev/vitest/pull/8208">used to</a></i> power <a href="https://github.com/vitest-dev/vitest">Vitest</a>.
<p>
<p align="center">
<a href="https://www.npmjs.com/package/vite-node"><img src="https://img.shields.io/npm/v/vite-node?color=FCC72B&label="></a>
<p>
> [!NOTE]
> This project is firstly inspired by [Nuxt 3's SSR](https://antfu.me/posts/dev-ssr-on-nuxt) implementation made by [@pi0](https://github.com/pi0), as a PoC. Later, it made [Vitest](https://github.com/vitest-dev/vitest) possible by providing the same pipeline as in Vite. It served the ecosystem well for a few years and later became a more generalized built-in solution as [Vite Environment Module Runner](https://vite.dev/guide/api-environment.html). Vitest has [migrated to the new official solution](https://github.com/vitest-dev/vitest/pull/8208), which means `vite-node` has finished its mission. We will still keep it around for the ecosystem that built around it, but for new projects, please consider using the builtin Vite one instead.
## Features
- On-demand evaluation
- Vite's pipeline, plugins, resolve, aliasing
- Out-of-box ESM & TypeScript support
- Respect `vite.config.ts`
- Hot module replacement (HMR)
- Separate server/client architecture
- Top-level `await`
- Shims for `__dirname` and `__filename` in ESM
- Access to native node modules like `fs`, `path`, etc.
## CLI Usage
Run JS/TS file on Node.js using Vite's resolvers and transformers.
```bash
npx vite-node index.ts
```
Options:
```bash
npx vite-node -h
```
### Options via CLI
[All `ViteNodeServer` options](https://github.com/antfu-collective/vite-node/blob/main/src/types.ts#L92-L111) are supported by the CLI. They may be defined through the dot syntax, as shown below:
```bash
npx vite-node --options.deps.inline="module-name" --options.deps.external="/module-regexp/" index.ts
```
Note that for options supporting RegExps, strings passed to the CLI must start _and_ end with a `/`;
### Hashbang
If you prefer to write scripts that don't need to be passed into Vite Node, you can declare it in the [hashbang](https://bash.cyberciti.biz/guide/Shebang).
Simply add `#!/usr/bin/env vite-node --script` at the top of your file:
_file.ts_
```ts
#!/usr/bin/env vite-node --script
console.log('argv:', process.argv.slice(2))
```
And make the file executable:
```sh
chmod +x ./file.ts
```
Now, you can run the file without passing it into Vite Node:
```sh
$ ./file.ts hello
argv: [ 'hello' ]
```
Note that when using the `--script` option, Vite Node forwards every argument and option to the script to execute, even the one supported by Vite Node itself.
## Programmatic Usage
In Vite Node, the server and runner (client) are separated, so you can integrate them in different contexts (workers, cross-process, or remote) if needed. The demo below shows a simple example of having both (server and runner) running in the same context
```ts
import { createServer, version as viteVersion } from 'vite'
import { ViteNodeRunner } from 'vite-node/client'
import { ViteNodeServer } from 'vite-node/server'
import { installSourcemapsSupport } from 'vite-node/source-map'
// create vite server
const server = await createServer({
optimizeDeps: {
// It's recommended to disable deps optimization
noDiscovery: true,
include: undefined,
},
})
// For old Vite, this is needed to initialize the plugins.
if (Number(viteVersion.split('.')[0]) < 6) {
await server.pluginContainer.buildStart({})
}
// create vite-node server
const node = new ViteNodeServer(server)
// fixes stacktraces in Errors
installSourcemapsSupport({
getSourceMap: source => node.getSourceMap(source),
})
// create vite-node runner
const runner = new ViteNodeRunner({
root: server.config.root,
base: server.config.base,
// when having the server and runner in a different context,
// you will need to handle the communication between them
// and pass to this function
fetchModule(id) {
return node.fetchModule(id)
},
resolveId(id, importer) {
return node.resolveId(id, importer)
},
})
// execute the file
await runner.executeFile('./example.ts')
// close the vite server
await server.close()
```
## Debugging
### Debug Transformation
Sometimes you might want to inspect the transformed code to investigate issues. You can set environment variable `VITE_NODE_DEBUG_DUMP=true` to let vite-node write the transformed result of each module under `.vite-node/dump`.
If you want to debug by modifying the dumped code, you can change the value of `VITE_NODE_DEBUG_DUMP` to `load` and search for the dumped files and use them for executing.
```bash
VITE_NODE_DEBUG_DUMP=load vite-node example.ts
```
Or programmatically:
```js
import { ViteNodeServer } from 'vite-node/server'
const server = new ViteNodeServer(viteServer, {
debug: {
dumpModules: true,
loadDumppedModules: true,
},
})
```
### Debug Execution
If the process gets stuck, it might be because there are unresolvable circular dependencies. You can set `VITE_NODE_DEBUG_RUNNER=true` for vite-node to warn about this.
```bash
VITE_NODE_DEBUG_RUNNER=true vite-node example.ts
```
Or programmatically:
```js
import { ViteNodeRunner } from 'vite-node/client'
const runner = new ViteNodeRunner({
debug: true,
})
```
## Credits
Based on [@pi0](https://github.com/pi0)'s brilliant idea of having a Vite server as the on-demand transforming service for [Nuxt's Vite SSR](https://github.com/nuxt/vite/pull/201).
Thanks [@brillout](https://github.com/brillout) for kindly sharing this package name.
## Sponsors
<p align="center">
<a href="https://cdn.jsdelivr.net/gh/antfu/static/sponsors.svg">
<img src='https://cdn.jsdelivr.net/gh/antfu/static/sponsors.svg'/>
</a>
</p>
## License
[MIT](./LICENSE) License © 2021 [Anthony Fu](https://github.com/antfu)

21
Frontend-Learner/node_modules/vite-node/dist/cli.d.mts generated vendored Normal file
View file

@ -0,0 +1,21 @@
import { b as ViteNodeServerOptions } from "./types-Dtew7m7O.mjs";
//#region src/cli.d.ts
interface CliOptions {
"root"?: string;
"script"?: boolean;
"config"?: string;
"mode"?: string;
"watch"?: boolean;
"inspect"?: boolean;
"inspectAddr"?: string;
"options"?: ViteNodeServerOptionsCLI;
"version"?: boolean;
"help"?: boolean;
"--"?: string[];
}
type Optional<T> = T | undefined;
type ComputeViteNodeServerOptionsCLI<T extends Record<string, any>> = { [K in keyof T]: T[K] extends Optional<RegExp[]> ? string | string[] : T[K] extends Optional<(string | RegExp)[]> ? string | string[] : T[K] extends Optional<(string | RegExp)[] | true> ? string | string[] | true : T[K] extends Optional<Record<string, any>> ? ComputeViteNodeServerOptionsCLI<T[K]> : T[K] };
type ViteNodeServerOptionsCLI = ComputeViteNodeServerOptionsCLI<ViteNodeServerOptions>;
//#endregion
export { CliOptions, ViteNodeServerOptionsCLI };

145
Frontend-Learner/node_modules/vite-node/dist/cli.mjs generated vendored Normal file
View file

@ -0,0 +1,145 @@
#!/usr/bin/env node
import { t as C } from "./dist-B2ebky9O.mjs";
import { t as ViteNodeServer } from "./server-BWywEVuB.mjs";
import "./constants-DRkacFwN.mjs";
import { h as toArray } from "./utils-ExLpYVUV.mjs";
import { n as installSourcemapsSupport } from "./source-map-DQLD3K8K.mjs";
import { r as ViteNodeRunner } from "./client-CyS7w_FB.mjs";
import { r as handleMessage, s as viteNodeHmrPlugin, t as createHotContext } from "./hmr-qEG3qSgW.mjs";
import process from "node:process";
import { createServer, loadEnv, version } from "vite";
import { resolve } from "node:path";
import cac from "cac";
//#region package.json
var version$1 = "5.2.0";
//#endregion
//#region src/cli.ts
const cli = cac("vite-node");
cli.option("-r, --root <path>", "Use specified root directory").option("-c, --config <path>", "Use specified config file").option("-m, --mode <mode>", "Set env mode").option("-w, --watch", "Restart on file changes, similar to \"nodemon\"").option("--inspect", "Enable Node.js inspector").option("--inspect-addr [host:port]", "Enable Node.js inspector with specified address").option("--script", "Use vite-node as a script runner").option("--options <options>", "Use specified Vite server options").option("-v, --version", "Output the version number").option("-h, --help", "Display help for command");
cli.command("[...files]").allowUnknownOptions().action(run);
cli.parse(process.argv, { run: false });
if (cli.args.length === 0) cli.runMatchedCommand();
else {
const i = cli.rawArgs.indexOf(cli.args[0]) + 1;
const scriptArgs = cli.rawArgs.slice(i).filter((it) => it !== "--");
const executeArgs = [
...cli.rawArgs.slice(0, i),
"--",
...scriptArgs
];
cli.parse(executeArgs);
}
async function run(files, options = {}) {
if (options.inspect || options.inspectAddr) {
const { open } = await import("node:inspector");
const [host, port] = options.inspectAddr?.split(":") || ["127.0.0.1", "9229"];
open(Number(port), host, false);
}
if (options.script) {
files = [files[0]];
options = {};
process.argv = [
process.argv[0],
resolve(files[0]),
...process.argv.slice(2).filter((arg) => arg !== "--script" && arg !== files[0])
];
} else process.argv = [...process.argv.slice(0, 2), ...options["--"] || []];
if (options.version) {
cli.version(version$1);
cli.outputVersion();
process.exit(0);
}
if (options.help) {
cli.version(version$1).outputHelp();
process.exit(0);
}
if (!files.length) {
console.error(C.red("No files specified."));
cli.version(version$1).outputHelp();
process.exit(1);
}
const serverOptions = options.options ? parseServerOptions(options.options) : {};
const server = await createServer({
logLevel: "error",
configFile: options.config,
root: options.root,
mode: options.mode,
server: {
hmr: !!options.watch,
watch: options.watch ? void 0 : null
},
plugins: [options.watch && viteNodeHmrPlugin()]
});
if (Number(version.split(".")[0]) < 6) await server.pluginContainer.buildStart({});
else await server.environments.client.pluginContainer.buildStart({});
const env = loadEnv(server.config.mode, server.config.envDir, "");
for (const key in env) process.env[key] ??= env[key];
const node = new ViteNodeServer(server, serverOptions);
installSourcemapsSupport({ getSourceMap: (source) => node.getSourceMap(source) });
const runner = new ViteNodeRunner({
root: server.config.root,
base: server.config.base,
fetchModule(id) {
return node.fetchModule(id);
},
resolveId(id, importer) {
return node.resolveId(id, importer);
},
createHotContext(runner$1, url) {
return createHotContext(runner$1, server.emitter, files, url);
}
});
await runner.executeId("/@vite/env");
for (const file of files) await runner.executeFile(file);
if (!options.watch) await server.close();
server.emitter?.on("message", (payload) => {
handleMessage(runner, server.emitter, files, payload);
});
if (options.watch) {
process.on("uncaughtException", (err) => {
console.error(C.red("[vite-node] Failed to execute file: \n"), err);
});
if (process.env.VITE_TEST_WATCHER_DEBUG) {
const nodePath = await import("node:path");
async function waitForWatched(files$1) {
while (!files$1.every((file) => isWatched(file))) await new Promise((resolve$1) => setTimeout(resolve$1, 20));
}
function isWatched(file) {
const watched = server.watcher.getWatched();
const resolved = nodePath.resolve(file);
const dir = nodePath.dirname(resolved);
const base = nodePath.basename(resolved);
return watched[dir]?.includes(base);
}
await waitForWatched(files);
console.log("[debug] watcher is ready");
}
}
}
function parseServerOptions(serverOptions) {
const inlineOptions = serverOptions.deps?.inline === true ? true : toArray(serverOptions.deps?.inline);
return {
...serverOptions,
deps: {
...serverOptions.deps,
inlineFiles: toArray(serverOptions.deps?.inlineFiles),
inline: inlineOptions !== true ? inlineOptions.map((dep) => {
return dep.startsWith("/") && dep.endsWith("/") ? new RegExp(dep) : dep;
}) : true,
external: toArray(serverOptions.deps?.external).map((dep) => {
return dep.startsWith("/") && dep.endsWith("/") ? new RegExp(dep) : dep;
}),
moduleDirectories: serverOptions.deps?.moduleDirectories ? toArray(serverOptions.deps?.moduleDirectories) : void 0
},
transformMode: {
...serverOptions.transformMode,
ssr: toArray(serverOptions.transformMode?.ssr).map((dep) => new RegExp(dep)),
web: toArray(serverOptions.transformMode?.web).map((dep) => new RegExp(dep))
}
};
}
//#endregion
export { };

View file

@ -0,0 +1,474 @@
import { c as isNodeBuiltin, d as normalizeModuleId, f as normalizeRequestId, g as toFilePath, l as isPrimitive, m as slash, n as cleanUrl, o as isBareImport, r as createImportMetaEnvProxy, s as isInternalRequest } from "./utils-ExLpYVUV.mjs";
import { t as extractSourceMap } from "./source-map-DQLD3K8K.mjs";
import { createRequire } from "node:module";
import process from "node:process";
import { fileURLToPath, pathToFileURL } from "node:url";
import { createDebug } from "obug";
import { dirname, resolve } from "node:path";
import vm from "node:vm";
//#region src/client.ts
const { setTimeout, clearTimeout } = globalThis;
const debugExecute = createDebug("vite-node:client:execute");
const debugNative = createDebug("vite-node:client:native");
const clientStub = {
injectQuery: (id) => id,
createHotContext: () => {
return {
accept: () => {},
prune: () => {},
dispose: () => {},
decline: () => {},
invalidate: () => {},
on: () => {},
send: () => {}
};
},
updateStyle: () => {},
removeStyle: () => {}
};
const env = createImportMetaEnvProxy();
const DEFAULT_REQUEST_STUBS = {
"/@vite/client": clientStub,
"@vite/client": clientStub
};
var ModuleCacheMap = class extends Map {
normalizePath(fsPath) {
return normalizeModuleId(fsPath);
}
/**
* Assign partial data to the map
*/
update(fsPath, mod) {
fsPath = this.normalizePath(fsPath);
if (!super.has(fsPath)) this.setByModuleId(fsPath, mod);
else Object.assign(super.get(fsPath), mod);
return this;
}
setByModuleId(modulePath, mod) {
return super.set(modulePath, mod);
}
set(fsPath, mod) {
return this.setByModuleId(this.normalizePath(fsPath), mod);
}
getByModuleId(modulePath) {
if (!super.has(modulePath)) this.setByModuleId(modulePath, {});
const mod = super.get(modulePath);
if (!mod.imports) Object.assign(mod, {
imports: /* @__PURE__ */ new Set(),
importers: /* @__PURE__ */ new Set()
});
return mod;
}
get(fsPath) {
return this.getByModuleId(this.normalizePath(fsPath));
}
deleteByModuleId(modulePath) {
return super.delete(modulePath);
}
delete(fsPath) {
return this.deleteByModuleId(this.normalizePath(fsPath));
}
invalidateModule(mod) {
delete mod.evaluated;
delete mod.resolving;
delete mod.promise;
delete mod.exports;
mod.importers?.clear();
mod.imports?.clear();
return true;
}
/**
* Invalidate modules that dependent on the given modules, up to the main entry
*/
invalidateDepTree(ids, invalidated = /* @__PURE__ */ new Set()) {
for (const _id of ids) {
const id = this.normalizePath(_id);
if (invalidated.has(id)) continue;
invalidated.add(id);
const mod = super.get(id);
if (mod?.importers) this.invalidateDepTree(mod.importers, invalidated);
super.delete(id);
}
return invalidated;
}
/**
* Invalidate dependency modules of the given modules, down to the bottom-level dependencies
*/
invalidateSubDepTree(ids, invalidated = /* @__PURE__ */ new Set()) {
for (const _id of ids) {
const id = this.normalizePath(_id);
if (invalidated.has(id)) continue;
invalidated.add(id);
const subIds = Array.from(super.entries()).filter(([, mod]) => mod.importers?.has(id)).map(([key]) => key);
if (subIds.length) this.invalidateSubDepTree(subIds, invalidated);
super.delete(id);
}
return invalidated;
}
/**
* Return parsed source map based on inlined source map of the module
*/
getSourceMap(id) {
const cache = this.get(id);
if (cache.map) return cache.map;
const map = cache.code && extractSourceMap(cache.code);
if (map) {
cache.map = map;
return map;
}
return null;
}
};
var ViteNodeRunner = class {
root;
debug;
/**
* Holds the cache of modules
* Keys of the map are filepaths, or plain package names
*/
moduleCache;
/**
* Tracks the stack of modules being executed for the purpose of calculating import self-time.
*
* Note that while in most cases, imports are a linear stack of modules,
* this is occasionally not the case, for example when you have parallel top-level dynamic imports like so:
*
* ```ts
* await Promise.all([
* import('./module1'),
* import('./module2'),
* ]);
* ```
*
* In this case, the self time will be reported incorrectly for one of the modules (could go negative).
* As top-level awaits with dynamic imports like this are uncommon, we don't handle this case specifically.
*/
executionStack = [];
performanceNow = performance.now.bind(performance);
constructor(options) {
this.options = options;
this.root = options.root ?? process.cwd();
this.moduleCache = options.moduleCache ?? new ModuleCacheMap();
this.debug = options.debug ?? (typeof process !== "undefined" ? !!process.env.VITE_NODE_DEBUG_RUNNER : false);
}
async executeFile(file) {
const url = `/@fs/${slash(resolve(file))}`;
return await this.cachedRequest(url, url, []);
}
async executeId(rawId) {
const [id, url] = await this.resolveUrl(rawId);
return await this.cachedRequest(id, url, []);
}
/** @internal */
async cachedRequest(id, fsPath, callstack) {
const importee = callstack[callstack.length - 1];
const mod = this.moduleCache.get(fsPath);
const { imports, importers } = mod;
if (importee) importers.add(importee);
const getStack = () => `stack:\n${[...callstack, fsPath].reverse().map((p) => ` - ${p}`).join("\n")}`;
if (callstack.includes(fsPath) || Array.from(imports.values()).some((i) => importers.has(i))) {
if (mod.exports) return mod.exports;
}
let debugTimer;
if (this.debug) debugTimer = setTimeout(() => console.warn(`[vite-node] module ${fsPath} takes over 2s to load.\n${getStack()}`), 2e3);
try {
if (mod.promise) return await mod.promise;
const promise = this.directRequest(id, fsPath, callstack);
Object.assign(mod, {
promise,
evaluated: false
});
return await promise;
} finally {
mod.evaluated = true;
if (debugTimer) clearTimeout(debugTimer);
}
}
shouldResolveId(id, _importee) {
return !isInternalRequest(id) && !isNodeBuiltin(id) && !id.startsWith("data:");
}
async _resolveUrl(id, importer) {
const dep = normalizeRequestId(id, this.options.base);
if (!this.shouldResolveId(dep)) return [dep, dep];
const { path: path$1, exists } = toFilePath(dep, this.root);
if (!this.options.resolveId || exists) return [dep, path$1];
const resolved = await this.options.resolveId(dep, importer);
if (resolved?.meta?.["vite:alias"]?.noResolved) {
const error = /* @__PURE__ */ new Error(`Cannot find module '${id}'${importer ? ` imported from '${importer}'` : ""}.
- If you rely on tsconfig.json's "paths" to resolve modules, please install "vite-tsconfig-paths" plugin to handle module resolution.
- Make sure you don't have relative aliases in your Vitest config. Use absolute paths instead. Read more: https://vitest.dev/guide/common-errors`);
Object.defineProperty(error, "code", {
value: "ERR_MODULE_NOT_FOUND",
enumerable: true
});
Object.defineProperty(error, Symbol.for("vitest.error.not_found.data"), {
value: {
id: dep,
importer
},
enumerable: false
});
throw error;
}
const resolvedId = resolved ? normalizeRequestId(resolved.id, this.options.base) : dep;
return [resolvedId, resolvedId];
}
async resolveUrl(id, importee) {
const resolveKey = `resolve:${id}`;
this.moduleCache.setByModuleId(resolveKey, { resolving: true });
try {
return await this._resolveUrl(id, importee);
} finally {
this.moduleCache.deleteByModuleId(resolveKey);
}
}
/** @internal */
async dependencyRequest(id, fsPath, callstack) {
return await this.cachedRequest(id, fsPath, callstack);
}
async _fetchModule(id, importer) {
try {
return await this.options.fetchModule(id);
} catch (cause) {
if (typeof cause === "object" && cause.code === "ERR_LOAD_URL" || typeof cause?.message === "string" && cause.message.includes("Failed to load url")) {
const error = new Error(`Cannot find ${isBareImport(id) ? "package" : "module"} '${id}'${importer ? ` imported from '${importer}'` : ""}`, { cause });
error.code = "ERR_MODULE_NOT_FOUND";
throw error;
}
throw cause;
}
}
/** @internal */
async directRequest(id, fsPath, _callstack) {
const moduleId = normalizeModuleId(fsPath);
const callstack = [..._callstack, moduleId];
const mod = this.moduleCache.getByModuleId(moduleId);
const request = async (dep) => {
const [id$1, depFsPath] = await this.resolveUrl(String(dep), fsPath);
this.moduleCache.getByModuleId(depFsPath).importers.add(moduleId);
mod.imports.add(depFsPath);
return this.dependencyRequest(id$1, depFsPath, callstack);
};
const requestStubs = this.options.requestStubs || DEFAULT_REQUEST_STUBS;
if (id in requestStubs) return requestStubs[id];
let { code: transformed, externalize } = await this._fetchModule(id, callstack[callstack.length - 2]);
if (externalize) {
debugNative(externalize);
const exports$1 = await this.interopedImport(externalize);
mod.exports = exports$1;
return exports$1;
}
if (transformed == null) throw new Error(`[vite-node] Failed to load "${id}" imported from ${callstack[callstack.length - 2]}`);
const { Object: Object$1, Reflect: Reflect$1, Symbol: Symbol$1 } = this.getContextPrimitives();
const modulePath = cleanUrl(moduleId);
const href = pathToFileURL(modulePath).href;
const __filename = fileURLToPath(href);
const __dirname = dirname(__filename);
const meta = {
url: href,
env,
filename: __filename,
dirname: __dirname
};
const exports = Object$1.create(null);
Object$1.defineProperty(exports, Symbol$1.toStringTag, {
value: "Module",
enumerable: false,
configurable: false
});
const SYMBOL_NOT_DEFINED = Symbol$1("not defined");
let moduleExports = SYMBOL_NOT_DEFINED;
const cjsExports = new Proxy(exports, {
get: (target, p, receiver) => {
if (Reflect$1.has(target, p)) return Reflect$1.get(target, p, receiver);
return Reflect$1.get(Object$1.prototype, p, receiver);
},
getPrototypeOf: () => Object$1.prototype,
set: (_, p, value) => {
if (p === "default" && this.shouldInterop(modulePath, { default: value }) && cjsExports !== value) {
exportAll(cjsExports, value);
exports.default = value;
return true;
}
if (!Reflect$1.has(exports, "default")) exports.default = {};
if (moduleExports !== SYMBOL_NOT_DEFINED && isPrimitive(moduleExports)) {
defineExport(exports, p, () => void 0);
return true;
}
if (!isPrimitive(exports.default)) exports.default[p] = value;
if (p !== "default") defineExport(exports, p, () => value);
return true;
}
});
Object$1.assign(mod, {
code: transformed,
exports
});
const moduleProxy = {
set exports(value) {
exportAll(cjsExports, value);
exports.default = value;
moduleExports = value;
},
get exports() {
return cjsExports;
}
};
let hotContext;
if (this.options.createHotContext) Object$1.defineProperty(meta, "hot", {
enumerable: true,
get: () => {
hotContext ||= this.options.createHotContext?.(this, moduleId);
return hotContext;
},
set: (value) => {
hotContext = value;
}
});
const context = this.prepareContext({
__vite_ssr_import__: request,
__vite_ssr_dynamic_import__: request,
__vite_ssr_exports__: exports,
__vite_ssr_exportAll__: (obj) => exportAll(exports, obj),
__vite_ssr_exportName__: (name, getter) => Object$1.defineProperty(exports, name, {
enumerable: true,
configurable: true,
get: getter
}),
__vite_ssr_import_meta__: meta,
require: createRequire(href),
exports: cjsExports,
module: moduleProxy,
__filename,
__dirname
});
debugExecute(__filename);
if (transformed[0] === "#") transformed = transformed.replace(/^#!.*/, (s) => " ".repeat(s.length));
await this.runModule(context, transformed);
return exports;
}
getContextPrimitives() {
return {
Object,
Reflect,
Symbol
};
}
async runModule(context, transformed) {
const codeDefinition = `'use strict';async (${Object.keys(context).join(",")})=>{{`;
const code = `${codeDefinition}${transformed}\n}}`;
const options = {
filename: context.__filename,
lineOffset: 0,
columnOffset: -codeDefinition.length
};
const finishModuleExecutionInfo = this.startCalculateModuleExecutionInfo(options.filename, codeDefinition.length);
try {
await vm.runInThisContext(code, options)(...Object.values(context));
} finally {
this.options.moduleExecutionInfo?.set(options.filename, finishModuleExecutionInfo());
}
}
/**
* Starts calculating the module execution info such as the total duration and self time spent on executing the module.
* Returns a function to call once the module has finished executing.
*/
startCalculateModuleExecutionInfo(filename, startOffset) {
const startTime = this.performanceNow();
this.executionStack.push({
filename,
startTime,
subImportTime: 0
});
return () => {
const duration = this.performanceNow() - startTime;
const currentExecution = this.executionStack.pop();
if (currentExecution == null) throw new Error("Execution stack is empty, this should never happen");
const selfTime = duration - currentExecution.subImportTime;
if (this.executionStack.length > 0) this.executionStack.at(-1).subImportTime += duration;
return {
startOffset,
duration,
selfTime
};
};
}
prepareContext(context) {
return context;
}
/**
* Define if a module should be interop-ed
* This function mostly for the ability to override by subclass
*/
shouldInterop(path$1, mod) {
if (this.options.interopDefault === false) return false;
return !path$1.endsWith(".mjs") && "default" in mod;
}
importExternalModule(path$1) {
return import(
/* @vite-ignore */
path$1
);
}
/**
* Import a module and interop it
*/
async interopedImport(path$1) {
const importedModule = await this.importExternalModule(path$1);
if (!this.shouldInterop(path$1, importedModule)) return importedModule;
const { mod, defaultExport } = interopModule(importedModule);
return new Proxy(mod, {
get(mod$1, prop) {
if (prop === "default") return defaultExport;
return mod$1[prop] ?? defaultExport?.[prop];
},
has(mod$1, prop) {
if (prop === "default") return defaultExport !== void 0;
return prop in mod$1 || defaultExport && prop in defaultExport;
},
getOwnPropertyDescriptor(mod$1, prop) {
const descriptor = Reflect.getOwnPropertyDescriptor(mod$1, prop);
if (descriptor) return descriptor;
if (prop === "default" && defaultExport !== void 0) return {
value: defaultExport,
enumerable: true,
configurable: true
};
}
});
}
};
function interopModule(mod) {
if (isPrimitive(mod)) return {
mod: { default: mod },
defaultExport: mod
};
let defaultExport = "default" in mod ? mod.default : mod;
if (!isPrimitive(defaultExport) && "__esModule" in defaultExport) {
mod = defaultExport;
if ("default" in defaultExport) defaultExport = defaultExport.default;
}
return {
mod,
defaultExport
};
}
function defineExport(exports, key, value) {
Object.defineProperty(exports, key, {
enumerable: true,
configurable: true,
get: value
});
}
function exportAll(exports, sourceModule) {
if (exports === sourceModule) return;
if (isPrimitive(sourceModule) || Array.isArray(sourceModule) || sourceModule instanceof Promise) return;
for (const key in sourceModule) if (key !== "default" && !(key in exports)) try {
defineExport(exports, key, () => sourceModule[key]);
} catch {}
}
//#endregion
export { ModuleCacheMap as n, ViteNodeRunner as r, DEFAULT_REQUEST_STUBS as t };

View file

@ -0,0 +1,2 @@
import { C as ModuleExecutionInfo, S as ModuleCacheMap, T as ViteNodeRunner, w as ModuleExecutionInfoEntry, x as DEFAULT_REQUEST_STUBS } from "./types-Dtew7m7O.mjs";
export { DEFAULT_REQUEST_STUBS, ModuleCacheMap, ModuleExecutionInfo, ModuleExecutionInfoEntry, ViteNodeRunner };

View file

@ -0,0 +1,5 @@
import "./utils-ExLpYVUV.mjs";
import "./source-map-DQLD3K8K.mjs";
import { n as ModuleCacheMap, r as ViteNodeRunner, t as DEFAULT_REQUEST_STUBS } from "./client-CyS7w_FB.mjs";
export { DEFAULT_REQUEST_STUBS, ModuleCacheMap, ViteNodeRunner };

View file

@ -0,0 +1,34 @@
//#region src/constants.ts
const KNOWN_ASSET_TYPES = [
"apng",
"bmp",
"png",
"jpe?g",
"jfif",
"pjpeg",
"pjp",
"gif",
"svg",
"ico",
"webp",
"avif",
"mp4",
"webm",
"ogg",
"mp3",
"wav",
"flac",
"aac",
"woff2?",
"eot",
"ttf",
"otf",
"webmanifest",
"pdf",
"txt"
];
const KNOWN_ASSET_RE = /* @__PURE__ */ new RegExp(`\\.(${KNOWN_ASSET_TYPES.join("|")})$`);
const CSS_LANGS_RE = /\.(css|less|sass|scss|styl|stylus|pcss|postcss|sss)(?:$|\?)/;
//#endregion
export { KNOWN_ASSET_RE as n, KNOWN_ASSET_TYPES as r, CSS_LANGS_RE as t };

View file

@ -0,0 +1,6 @@
//#region src/constants.d.ts
declare const KNOWN_ASSET_TYPES: string[];
declare const KNOWN_ASSET_RE: RegExp;
declare const CSS_LANGS_RE: RegExp;
//#endregion
export { CSS_LANGS_RE, KNOWN_ASSET_RE, KNOWN_ASSET_TYPES };

View file

@ -0,0 +1,3 @@
import { n as KNOWN_ASSET_RE, r as KNOWN_ASSET_TYPES, t as CSS_LANGS_RE } from "./constants-DRkacFwN.mjs";
export { CSS_LANGS_RE, KNOWN_ASSET_RE, KNOWN_ASSET_TYPES };

View file

@ -0,0 +1,85 @@
//#region node_modules/.pnpm/tinyrainbow@3.0.3/node_modules/tinyrainbow/dist/index.js
var d = {
reset: [0, 0],
bold: [
1,
22,
"\x1B[22m\x1B[1m"
],
dim: [
2,
22,
"\x1B[22m\x1B[2m"
],
italic: [3, 23],
underline: [4, 24],
inverse: [7, 27],
hidden: [8, 28],
strikethrough: [9, 29],
black: [30, 39],
red: [31, 39],
green: [32, 39],
yellow: [33, 39],
blue: [34, 39],
magenta: [35, 39],
cyan: [36, 39],
white: [37, 39],
gray: [90, 39],
bgBlack: [40, 49],
bgRed: [41, 49],
bgGreen: [42, 49],
bgYellow: [43, 49],
bgBlue: [44, 49],
bgMagenta: [45, 49],
bgCyan: [46, 49],
bgWhite: [47, 49],
blackBright: [90, 39],
redBright: [91, 39],
greenBright: [92, 39],
yellowBright: [93, 39],
blueBright: [94, 39],
magentaBright: [95, 39],
cyanBright: [96, 39],
whiteBright: [97, 39],
bgBlackBright: [100, 49],
bgRedBright: [101, 49],
bgGreenBright: [102, 49],
bgYellowBright: [103, 49],
bgBlueBright: [104, 49],
bgMagentaBright: [105, 49],
bgCyanBright: [106, 49],
bgWhiteBright: [107, 49]
};
function g(e) {
return String(e);
}
g.open = "";
g.close = "";
function h() {
let e = typeof process != "undefined" ? process : void 0, n = (e == null ? void 0 : e.env) || {}, a = n.FORCE_TTY !== "false", i = (e == null ? void 0 : e.argv) || [];
return !("NO_COLOR" in n || i.includes("--no-color")) && ("FORCE_COLOR" in n || i.includes("--color") || (e == null ? void 0 : e.platform) === "win32" || a && n.TERM !== "dumb" || "CI" in n) || typeof window != "undefined" && !!window.chrome;
}
function f() {
let e = h(), n = (r, t, u, o) => {
let l = "", s = 0;
do
l += r.substring(s, o) + u, s = o + t.length, o = r.indexOf(t, s);
while (~o);
return l + r.substring(s);
}, a = (r, t, u = r) => {
let o = (l) => {
let s = String(l), b = s.indexOf(t, r.length);
return ~b ? r + n(s, t, u, b) + t : r + s + t;
};
return o.open = r, o.close = t, o;
}, i = { isColorSupported: e }, c = (r) => `\x1B[${r}m`;
for (let r in d) {
let t = d[r];
i[r] = e ? a(c(t[0]), c(t[1]), t[2]) : g;
}
return i;
}
var C = f();
//#endregion
export { C as t };

View file

@ -0,0 +1,230 @@
import { t as C } from "./dist-B2ebky9O.mjs";
import { f as normalizeRequestId } from "./utils-ExLpYVUV.mjs";
import process from "node:process";
import { createDebug } from "obug";
import { EventEmitter } from "node:events";
//#region src/hmr/emitter.ts
function createHmrEmitter() {
return new EventEmitter();
}
function viteNodeHmrPlugin() {
const emitter = createHmrEmitter();
return {
name: "vite-node:hmr",
config() {
if (process.platform === "darwin" && process.env.VITE_TEST_WATCHER_DEBUG) return { server: { watch: {
useFsEvents: false,
usePolling: false
} } };
},
configureServer(server) {
const _send = server.ws.send;
server.emitter = emitter;
server.ws.send = function(payload) {
_send(payload);
emitter.emit("message", payload);
};
const environments = server.environments;
if (environments) environments.ssr.hot.send = function(payload) {
_send(payload);
emitter.emit("message", payload);
};
}
};
}
//#endregion
//#region src/hmr/hmr.ts
const debugHmr = createDebug("vite-node:hmr");
const cache = /* @__PURE__ */ new WeakMap();
function getCache(runner) {
if (!cache.has(runner)) cache.set(runner, {
hotModulesMap: /* @__PURE__ */ new Map(),
dataMap: /* @__PURE__ */ new Map(),
disposeMap: /* @__PURE__ */ new Map(),
pruneMap: /* @__PURE__ */ new Map(),
customListenersMap: /* @__PURE__ */ new Map(),
ctxToListenersMap: /* @__PURE__ */ new Map(),
messageBuffer: [],
isFirstUpdate: false,
pending: false,
queued: []
});
return cache.get(runner);
}
function sendMessageBuffer(runner, emitter) {
const maps = getCache(runner);
maps.messageBuffer.forEach((msg) => emitter.emit("custom", msg));
maps.messageBuffer.length = 0;
}
async function reload(runner, files) {
Array.from(runner.moduleCache.keys()).forEach((fsPath) => {
if (!fsPath.includes("node_modules")) runner.moduleCache.delete(fsPath);
});
return Promise.all(files.map((file) => runner.executeId(file)));
}
async function notifyListeners(runner, event, data) {
const cbs = getCache(runner).customListenersMap.get(event);
if (cbs) await Promise.all(cbs.map((cb) => cb(data)));
}
async function queueUpdate(runner, p) {
const maps = getCache(runner);
maps.queued.push(p);
if (!maps.pending) {
maps.pending = true;
await Promise.resolve();
maps.pending = false;
const loading = [...maps.queued];
maps.queued = [];
(await Promise.all(loading)).forEach((fn) => fn && fn());
}
}
async function fetchUpdate(runner, { path, acceptedPath }) {
path = normalizeRequestId(path);
acceptedPath = normalizeRequestId(acceptedPath);
const maps = getCache(runner);
const mod = maps.hotModulesMap.get(path);
if (!mod) return;
const isSelfUpdate = path === acceptedPath;
let fetchedModule;
const qualifiedCallbacks = mod.callbacks.filter(({ deps }) => deps.includes(acceptedPath));
if (isSelfUpdate || qualifiedCallbacks.length > 0) {
const disposer = maps.disposeMap.get(acceptedPath);
if (disposer) await disposer(maps.dataMap.get(acceptedPath));
try {
[fetchedModule] = await reload(runner, [acceptedPath]);
} catch (e) {
warnFailedFetch(e, acceptedPath);
}
}
return () => {
for (const { deps, fn } of qualifiedCallbacks) fn(deps.map((dep) => dep === acceptedPath ? fetchedModule : void 0));
const loggedPath = isSelfUpdate ? path : `${acceptedPath} via ${path}`;
console.log(`${C.cyan("[vite-node]")} hot updated: ${loggedPath}`);
};
}
function warnFailedFetch(err, path) {
if (!(err instanceof Error) || !err.message.match("fetch")) console.error(err);
console.error(`[hmr] Failed to reload ${path}. This could be due to syntax errors or importing non-existent modules. (see errors above)`);
}
async function handleMessage(runner, emitter, files, payload) {
const maps = getCache(runner);
switch (payload.type) {
case "connected":
sendMessageBuffer(runner, emitter);
break;
case "update":
await notifyListeners(runner, "vite:beforeUpdate", payload);
await Promise.all(payload.updates.map((update) => {
if (update.type === "js-update") return queueUpdate(runner, fetchUpdate(runner, update));
console.error(`${C.cyan("[vite-node]")} no support css hmr.}`);
return null;
}));
await notifyListeners(runner, "vite:afterUpdate", payload);
break;
case "full-reload":
await notifyListeners(runner, "vite:beforeFullReload", payload);
maps.customListenersMap.delete("vite:beforeFullReload");
await reload(runner, files);
break;
case "custom":
await notifyListeners(runner, payload.event, payload.data);
break;
case "prune":
await notifyListeners(runner, "vite:beforePrune", payload);
payload.paths.forEach((path) => {
const fn = maps.pruneMap.get(path);
if (fn) fn(maps.dataMap.get(path));
});
break;
case "error": {
await notifyListeners(runner, "vite:error", payload);
const err = payload.err;
console.error(`${C.cyan("[vite-node]")} Internal Server Error\n${err.message}\n${err.stack}`);
break;
}
}
}
function createHotContext(runner, emitter, files, ownerPath) {
debugHmr("createHotContext", ownerPath);
const maps = getCache(runner);
if (!maps.dataMap.has(ownerPath)) maps.dataMap.set(ownerPath, {});
const mod = maps.hotModulesMap.get(ownerPath);
if (mod) mod.callbacks = [];
const newListeners = /* @__PURE__ */ new Map();
maps.ctxToListenersMap.set(ownerPath, newListeners);
function acceptDeps(deps, callback = () => {}) {
const mod$1 = maps.hotModulesMap.get(ownerPath) || {
id: ownerPath,
callbacks: []
};
mod$1.callbacks.push({
deps,
fn: callback
});
maps.hotModulesMap.set(ownerPath, mod$1);
}
return {
get data() {
return maps.dataMap.get(ownerPath);
},
acceptExports(_, callback) {
acceptDeps([ownerPath], callback && (([mod$1]) => callback(mod$1)));
},
accept(deps, callback) {
if (typeof deps === "function" || !deps) acceptDeps([ownerPath], ([mod$1]) => deps && deps(mod$1));
else if (typeof deps === "string") acceptDeps([deps], ([mod$1]) => callback && callback(mod$1));
else if (Array.isArray(deps)) acceptDeps(deps, callback);
else throw new TypeError("invalid hot.accept() usage.");
},
dispose(cb) {
maps.disposeMap.set(ownerPath, cb);
},
prune(cb) {
maps.pruneMap.set(ownerPath, cb);
},
invalidate() {
notifyListeners(runner, "vite:invalidate", {
path: ownerPath,
message: void 0,
firstInvalidatedBy: ownerPath
});
return reload(runner, files);
},
on(event, cb) {
const addToMap = (map) => {
const existing = map.get(event) || [];
existing.push(cb);
map.set(event, existing);
};
addToMap(maps.customListenersMap);
addToMap(newListeners);
},
off(event, cb) {
const removeFromMap = (map) => {
const existing = map.get(event);
if (existing === void 0) return;
const pruned = existing.filter((l) => l !== cb);
if (pruned.length === 0) {
map.delete(event);
return;
}
map.set(event, pruned);
};
removeFromMap(maps.customListenersMap);
removeFromMap(newListeners);
},
send(event, data) {
maps.messageBuffer.push(JSON.stringify({
type: "custom",
event,
data
}));
sendMessageBuffer(runner, emitter);
}
};
}
//#endregion
export { sendMessageBuffer as a, reload as i, getCache as n, createHmrEmitter as o, handleMessage as r, viteNodeHmrPlugin as s, createHotContext as t };

57
Frontend-Learner/node_modules/vite-node/dist/hmr.d.mts generated vendored Normal file
View file

@ -0,0 +1,57 @@
import { T as ViteNodeRunner, u as HotContext } from "./types-Dtew7m7O.mjs";
import { HMRPayload, Plugin } from "vite";
import { EventEmitter } from "node:events";
import { CustomEventMap } from "vite/types/customEvent.js";
import { HMRPayload as HMRPayload$1 } from "vite/types/hmrPayload.js";
//#region src/hmr/emitter.d.ts
type EventType = string | symbol;
type Handler<T = unknown> = (event: T) => void;
interface Emitter<Events extends Record<EventType, unknown>> {
on: <Key extends keyof Events>(type: Key, handler: Handler<Events[Key]>) => void;
off: <Key extends keyof Events>(type: Key, handler?: Handler<Events[Key]>) => void;
emit: (<Key extends keyof Events>(type: Key, event: Events[Key]) => void) & (<Key extends keyof Events>(type: undefined extends Events[Key] ? Key : never) => void);
}
type HMREmitter = Emitter<{
message: HMRPayload;
}> & EventEmitter;
declare module "vite" {
interface ViteDevServer {
emitter: HMREmitter;
}
}
declare function createHmrEmitter(): HMREmitter;
declare function viteNodeHmrPlugin(): Plugin;
//#endregion
//#region src/hmr/hmr.d.ts
type ModuleNamespace = Record<string, any> & {
[Symbol.toStringTag]: "Module";
};
type InferCustomEventPayload<T extends string> = T extends keyof CustomEventMap ? CustomEventMap[T] : any;
interface HotModule {
id: string;
callbacks: HotCallback[];
}
interface HotCallback {
deps: string[];
fn: (modules: (ModuleNamespace | undefined)[]) => void;
}
interface CacheData {
hotModulesMap: Map<string, HotModule>;
dataMap: Map<string, any>;
disposeMap: Map<string, (data: any) => void | Promise<void>>;
pruneMap: Map<string, (data: any) => void | Promise<void>>;
customListenersMap: Map<string, ((data: any) => void)[]>;
ctxToListenersMap: Map<string, Map<string, ((data: any) => void)[]>>;
messageBuffer: string[];
isFirstUpdate: boolean;
pending: boolean;
queued: Promise<(() => void) | undefined>[];
}
declare function getCache(runner: ViteNodeRunner): CacheData;
declare function sendMessageBuffer(runner: ViteNodeRunner, emitter: HMREmitter): void;
declare function reload(runner: ViteNodeRunner, files: string[]): Promise<any[]>;
declare function handleMessage(runner: ViteNodeRunner, emitter: HMREmitter, files: string[], payload: HMRPayload$1): Promise<void>;
declare function createHotContext(runner: ViteNodeRunner, emitter: HMREmitter, files: string[], ownerPath: string): HotContext;
//#endregion
export { Emitter, EventType, HMREmitter, Handler, HotCallback, HotModule, InferCustomEventPayload, ModuleNamespace, createHmrEmitter, createHotContext, getCache, handleMessage, reload, sendMessageBuffer, viteNodeHmrPlugin };

5
Frontend-Learner/node_modules/vite-node/dist/hmr.mjs generated vendored Normal file
View file

@ -0,0 +1,5 @@
import "./dist-B2ebky9O.mjs";
import "./utils-ExLpYVUV.mjs";
import { a as sendMessageBuffer, i as reload, n as getCache, o as createHmrEmitter, r as handleMessage, s as viteNodeHmrPlugin, t as createHotContext } from "./hmr-qEG3qSgW.mjs";
export { createHmrEmitter, createHotContext, getCache, handleMessage, reload, sendMessageBuffer, viteNodeHmrPlugin };

View file

@ -0,0 +1,2 @@
import { C as ModuleExecutionInfo, S as ModuleCacheMap, _ as ViteNodeResolveId, a as DecodedSourceMap, b as ViteNodeServerOptions, c as FetchFunction, d as ModuleCache, f as Nullable, g as StartOfSourceMap, h as SourceMapInput, i as DebuggerOptions, l as FetchResult, m as ResolveIdFunction, n as Awaitable, o as DepsHandlingOptions, p as RawSourceMap, r as CreateHotContextFunction, s as EncodedSourceMap, t as Arrayable, u as HotContext, v as ViteNodeResolveModule, y as ViteNodeRunnerOptions } from "./types-Dtew7m7O.mjs";
export { Arrayable, Awaitable, CreateHotContextFunction, DebuggerOptions, DecodedSourceMap, DepsHandlingOptions, EncodedSourceMap, FetchFunction, FetchResult, HotContext, ModuleCache, ModuleCacheMap, ModuleExecutionInfo, Nullable, RawSourceMap, ResolveIdFunction, SourceMapInput, StartOfSourceMap, ViteNodeResolveId, ViteNodeResolveModule, ViteNodeRunnerOptions, ViteNodeServerOptions };

View file

@ -0,0 +1,3 @@
import "./types-55T_-8KG.mjs";
export { };

View file

@ -0,0 +1,378 @@
import { t as C } from "./dist-B2ebky9O.mjs";
import { n as KNOWN_ASSET_RE } from "./constants-DRkacFwN.mjs";
import { _ as withTrailingSlash, c as isNodeBuiltin, d as normalizeModuleId, g as toFilePath, h as toArray, i as findNearestPackageData, m as slash } from "./utils-ExLpYVUV.mjs";
import { r as withInlineSourcemap } from "./source-map-DQLD3K8K.mjs";
import assert from "node:assert";
import { existsSync, promises } from "node:fs";
import { performance } from "node:perf_hooks";
import process from "node:process";
import { pathToFileURL } from "node:url";
import { createDebug } from "obug";
import { dirname, extname, join, normalize, relative, resolve } from "pathe";
import { version } from "vite";
import * as esModuleLexer from "es-module-lexer";
//#region src/debug.ts
function hashCode(s) {
return s.split("").reduce((a, b) => {
a = (a << 5) - a + b.charCodeAt(0);
return a & a;
}, 0);
}
var Debugger = class {
dumpDir;
initPromise;
externalizeMap = /* @__PURE__ */ new Map();
constructor(root, options) {
this.options = options;
if (options.dumpModules) this.dumpDir = resolve(root, options.dumpModules === true ? ".vite-node/dump" : options.dumpModules);
if (this.dumpDir) if (options.loadDumppedModules) console.info(C.gray(`[vite-node] [debug] load modules from ${this.dumpDir}`));
else console.info(C.gray(`[vite-node] [debug] dump modules to ${this.dumpDir}`));
this.initPromise = this.clearDump();
}
async clearDump() {
if (!this.dumpDir) return;
if (!this.options.loadDumppedModules && existsSync(this.dumpDir)) await promises.rm(this.dumpDir, {
recursive: true,
force: true
});
await promises.mkdir(this.dumpDir, { recursive: true });
}
encodeId(id) {
return `${id.replace(/[^\w@\-]/g, "_").replace(/_+/g, "_")}-${hashCode(id)}.js`;
}
async recordExternalize(id, path) {
if (!this.dumpDir) return;
this.externalizeMap.set(id, path);
await this.writeInfo();
}
async dumpFile(id, result) {
if (!result || !this.dumpDir) return;
await this.initPromise;
const name = this.encodeId(id);
return await promises.writeFile(join(this.dumpDir, name), `// ${id.replace(/\0/g, "\\0")}\n${result.code}`, "utf-8");
}
async loadDump(id) {
if (!this.dumpDir) return null;
await this.initPromise;
const name = this.encodeId(id);
const path = join(this.dumpDir, name);
if (!existsSync(path)) return null;
return {
code: (await promises.readFile(path, "utf-8")).replace(/^\/\/.*\n/, ""),
map: void 0
};
}
async writeInfo() {
if (!this.dumpDir) return;
const info = JSON.stringify({
time: (/* @__PURE__ */ new Date()).toLocaleString(),
externalize: Object.fromEntries(this.externalizeMap.entries())
}, null, 2);
return promises.writeFile(join(this.dumpDir, "info.json"), info, "utf-8");
}
};
//#endregion
//#region src/externalize.ts
const BUILTIN_EXTENSIONS = new Set([
".mjs",
".cjs",
".node",
".wasm"
]);
const ESM_EXT_RE = /\.(es|esm|esm-browser|esm-bundler|es6|module)\.js$/;
const ESM_FOLDER_RE = /\/(es|esm)\/(.*\.js)$/;
const defaultInline = [
/virtual:/,
/\.[mc]?ts$/,
/[?&](init|raw|url|inline)\b/,
KNOWN_ASSET_RE
];
const depsExternal = [/\/node_modules\/.*\.cjs\.js$/, /\/node_modules\/.*\.mjs$/];
function guessCJSversion(id) {
if (id.match(ESM_EXT_RE)) {
for (const i of [
id.replace(ESM_EXT_RE, ".mjs"),
id.replace(ESM_EXT_RE, ".umd.js"),
id.replace(ESM_EXT_RE, ".cjs.js"),
id.replace(ESM_EXT_RE, ".js")
]) if (existsSync(i)) return i;
}
if (id.match(ESM_FOLDER_RE)) {
for (const i of [
id.replace(ESM_FOLDER_RE, "/umd/$1"),
id.replace(ESM_FOLDER_RE, "/cjs/$1"),
id.replace(ESM_FOLDER_RE, "/lib/$1"),
id.replace(ESM_FOLDER_RE, "/$1")
]) if (existsSync(i)) return i;
}
}
async function isValidNodeImport(id) {
const extension = extname(id);
if (BUILTIN_EXTENSIONS.has(extension)) return true;
if (extension !== ".js") return false;
id = id.replace("file:///", "");
if ((await findNearestPackageData(dirname(id))).type === "module") return true;
if (/\.(?:\w+-)?esm?(?:-\w+)?\.js$|\/esm?\//.test(id)) return false;
try {
await esModuleLexer.init;
const code = await promises.readFile(id, "utf8");
const [, , , hasModuleSyntax] = esModuleLexer.parse(code);
return !hasModuleSyntax;
} catch {
return false;
}
}
const _defaultExternalizeCache = /* @__PURE__ */ new Map();
async function shouldExternalize(id, options, cache = _defaultExternalizeCache) {
if (!cache.has(id)) cache.set(id, _shouldExternalize(id, options));
return cache.get(id);
}
async function _shouldExternalize(id, options) {
if (isNodeBuiltin(id)) return id;
if (id.startsWith("data:") || /^(?:https?:)?\/\//.test(id)) return id;
id = patchWindowsImportPath(id);
const moduleDirectories = options?.moduleDirectories || ["/node_modules/"];
if (matchExternalizePattern(id, moduleDirectories, options?.inline)) return false;
if (options?.inlineFiles && options?.inlineFiles.includes(id)) return false;
if (matchExternalizePattern(id, moduleDirectories, options?.external)) return id;
if (options?.cacheDir && id.includes(options.cacheDir)) return id;
const isLibraryModule = moduleDirectories.some((dir) => id.includes(dir));
id = isLibraryModule && options?.fallbackCJS ? guessCJSversion(id) || id : id;
if (matchExternalizePattern(id, moduleDirectories, defaultInline)) return false;
if (matchExternalizePattern(id, moduleDirectories, depsExternal)) return id;
if (isLibraryModule && await isValidNodeImport(id)) return id;
return false;
}
function matchExternalizePattern(id, moduleDirectories, patterns) {
if (patterns == null) return false;
if (patterns === true) return true;
for (const ex of patterns) if (typeof ex === "string") {
if (moduleDirectories.some((dir) => id.includes(join(dir, ex)))) return true;
} else if (ex.test(id)) return true;
return false;
}
function patchWindowsImportPath(path) {
if (path.match(/^\w:\\/)) return `file:///${slash(path)}`;
else if (path.match(/^\w:\//)) return `file:///${path}`;
else return path;
}
//#endregion
//#region src/server.ts
const debugRequest = createDebug("vite-node:server:request");
var ViteNodeServer = class {
fetchPromiseMap = {
ssr: /* @__PURE__ */ new Map(),
web: /* @__PURE__ */ new Map()
};
transformPromiseMap = {
ssr: /* @__PURE__ */ new Map(),
web: /* @__PURE__ */ new Map()
};
durations = {
ssr: /* @__PURE__ */ new Map(),
web: /* @__PURE__ */ new Map()
};
existingOptimizedDeps = /* @__PURE__ */ new Set();
fetchCaches = {
ssr: /* @__PURE__ */ new Map(),
web: /* @__PURE__ */ new Map()
};
fetchCache = /* @__PURE__ */ new Map();
externalizeCache = /* @__PURE__ */ new Map();
debugger;
constructor(server, options = {}) {
this.server = server;
this.options = options;
const ssrOptions = server.config.ssr;
options.deps ??= {};
options.deps.cacheDir = relative(server.config.root, options.deps.cacheDir || server.config.cacheDir);
if (ssrOptions) {
if (ssrOptions.noExternal === true) options.deps.inline ??= true;
else if (options.deps.inline !== true) {
options.deps.inline ??= [];
const inline = options.deps.inline;
options.deps.inline.push(...toArray(ssrOptions.noExternal).filter((dep) => !inline.includes(dep)));
}
}
if (process.env.VITE_NODE_DEBUG_DUMP) options.debug = Object.assign({
dumpModules: !!process.env.VITE_NODE_DEBUG_DUMP,
loadDumppedModules: process.env.VITE_NODE_DEBUG_DUMP === "load"
}, options.debug ?? {});
if (options.debug) this.debugger = new Debugger(server.config.root, options.debug);
if (options.deps.inlineFiles) options.deps.inlineFiles = options.deps.inlineFiles.flatMap((file) => {
if (file.startsWith("file://")) return file;
const resolvedId = resolve(file);
return [resolvedId, pathToFileURL(resolvedId).href];
});
options.deps.moduleDirectories ??= [];
const customModuleDirectories = (process.env.VITE_NODE_DEPS_MODULE_DIRECTORIES || process.env.npm_config_VITE_NODE_DEPS_MODULE_DIRECTORIES)?.split(",");
if (customModuleDirectories) options.deps.moduleDirectories.push(...customModuleDirectories);
options.deps.moduleDirectories = options.deps.moduleDirectories.map((dir) => {
if (!dir.startsWith("/")) dir = `/${dir}`;
if (!dir.endsWith("/")) dir += "/";
return normalize(dir);
});
if (!options.deps.moduleDirectories.includes("/node_modules/")) options.deps.moduleDirectories.push("/node_modules/");
}
shouldExternalize(id) {
return shouldExternalize(id, this.options.deps, this.externalizeCache);
}
getTotalDuration() {
const ssrDurations = [...this.durations.ssr.values()].flat();
const webDurations = [...this.durations.web.values()].flat();
return [...ssrDurations, ...webDurations].reduce((a, b) => a + b, 0);
}
async ensureExists(id) {
if (this.existingOptimizedDeps.has(id)) return true;
if (existsSync(id)) {
this.existingOptimizedDeps.add(id);
return true;
}
return new Promise((resolve$1) => {
setTimeout(() => {
this.ensureExists(id).then(() => {
resolve$1(true);
});
});
});
}
async resolveId(id, importer, transformMode) {
if (importer && !importer.startsWith(withTrailingSlash(this.server.config.root))) importer = resolve(this.server.config.root, importer);
const mode = transformMode ?? (importer && this.getTransformMode(importer) || "ssr");
return this.server.pluginContainer.resolveId(id, importer, { ssr: mode === "ssr" });
}
getSourceMap(source) {
source = normalizeModuleId(source);
const fetchResult = this.fetchCache.get(source)?.result;
if (fetchResult?.map) return fetchResult.map;
return (this.server.moduleGraph.getModuleById(source)?.ssrTransformResult)?.map || null;
}
assertMode(mode) {
assert(mode === "web" || mode === "ssr", `"transformMode" can only be "web" or "ssr", received "${mode}".`);
}
async fetchModule(id, transformMode) {
const mode = transformMode || this.getTransformMode(id);
return this.fetchResult(id, mode).then((r) => {
return this.options.sourcemap !== true ? {
...r,
map: void 0
} : r;
});
}
async fetchResult(id, mode) {
const moduleId = normalizeModuleId(id);
this.assertMode(mode);
const promiseMap = this.fetchPromiseMap[mode];
if (!promiseMap.has(moduleId)) promiseMap.set(moduleId, this._fetchModule(moduleId, mode).finally(() => {
promiseMap.delete(moduleId);
}));
return promiseMap.get(moduleId);
}
async transformRequest(id, filepath = id, transformMode) {
const mode = transformMode || this.getTransformMode(id);
this.assertMode(mode);
const promiseMap = this.transformPromiseMap[mode];
if (!promiseMap.has(id)) promiseMap.set(id, this._transformRequest(id, filepath, mode).finally(() => {
promiseMap.delete(id);
}));
return promiseMap.get(id);
}
async transformModule(id, transformMode) {
if (transformMode !== "web") throw new Error("`transformModule` only supports `transformMode: \"web\"`.");
const normalizedId = normalizeModuleId(id);
return { code: (this.server.moduleGraph.getModuleById(normalizedId)?.transformResult || await this.server.transformRequest(normalizedId))?.code };
}
getTransformMode(id) {
const withoutQuery = id.split("?")[0];
if (this.options.transformMode?.web?.some((r) => withoutQuery.match(r))) return "web";
if (this.options.transformMode?.ssr?.some((r) => withoutQuery.match(r))) return "ssr";
if (withoutQuery.match(/\.([cm]?[jt]sx?|json)$/)) return "ssr";
return "web";
}
getChangedModule(id, file) {
const module = this.server.moduleGraph.getModuleById(id) || this.server.moduleGraph.getModuleById(file);
if (module) return module;
const _modules = this.server.moduleGraph.getModulesByFile(file);
if (!_modules || !_modules.size) return null;
let mod = [..._modules][0];
let latestMax = -1;
for (const m of _modules) {
const timestamp = Math.max(m.lastHMRTimestamp, m.lastInvalidationTimestamp);
if (timestamp > latestMax) {
latestMax = timestamp;
mod = m;
}
}
return mod;
}
async _fetchModule(id, transformMode) {
let result;
const cacheDir = this.options.deps?.cacheDir;
if (cacheDir && id.includes(cacheDir)) {
if (!id.startsWith(withTrailingSlash(this.server.config.root))) id = join(this.server.config.root, id);
const timeout = setTimeout(() => {
throw new Error(`ViteNodeServer: ${id} not found. This is a bug, please report it.`);
}, 5e3);
await this.ensureExists(id);
clearTimeout(timeout);
}
const { path: filePath } = toFilePath(id, this.server.config.root);
const moduleNode = this.getChangedModule(id, filePath);
const cache = this.fetchCaches[transformMode].get(filePath);
const timestamp = moduleNode ? Math.max(moduleNode.lastHMRTimestamp, moduleNode.lastInvalidationTimestamp) : 0;
if (cache && (timestamp === 0 || cache.timestamp >= timestamp)) return cache.result;
const time = Date.now();
const externalize = await this.shouldExternalize(filePath);
let duration;
if (externalize) {
result = { externalize };
this.debugger?.recordExternalize(id, externalize);
} else {
const start = performance.now();
const r = await this._transformRequest(id, filePath, transformMode);
duration = performance.now() - start;
result = {
code: r?.code,
map: r?.map
};
}
const cacheEntry = {
duration,
timestamp: time,
result
};
const durations = this.durations[transformMode].get(filePath) || [];
this.durations[transformMode].set(filePath, [...durations, duration ?? 0]);
this.fetchCaches[transformMode].set(filePath, cacheEntry);
this.fetchCache.set(filePath, cacheEntry);
return result;
}
async processTransformResult(filepath, result) {
return withInlineSourcemap(result, {
filepath: this.server.moduleGraph.getModuleById(filepath)?.file || filepath,
root: this.server.config.root,
noFirstLineMapping: Number(version.split(".")[0]) >= 6
});
}
async _transformRequest(id, filepath, transformMode) {
debugRequest(id);
let result = null;
if (this.options.debug?.loadDumppedModules) {
result = await this.debugger?.loadDump(id) ?? null;
if (result) return result;
}
if (transformMode === "web") {
result = await this.server.transformRequest(id);
if (result) result = await this.server.ssrTransform(result.code, result.map, id);
} else result = await this.server.transformRequest(id, { ssr: true });
if ((this.options.sourcemap ?? "inline") === "inline" && result) result = await this.processTransformResult(filepath, result);
if (this.options.debug?.dumpModules) await this.debugger?.dumpFile(id, result);
return result;
}
};
//#endregion
export { guessCJSversion as n, shouldExternalize as r, ViteNodeServer as t };

View file

@ -0,0 +1,60 @@
import { _ as ViteNodeResolveId, b as ViteNodeServerOptions, i as DebuggerOptions, l as FetchResult, o as DepsHandlingOptions, s as EncodedSourceMap } from "./types-Dtew7m7O.mjs";
import { TransformResult, ViteDevServer } from "vite";
//#region src/debug.d.ts
declare class Debugger {
options: DebuggerOptions;
dumpDir: string | undefined;
initPromise: Promise<void> | undefined;
externalizeMap: Map<string, string>;
constructor(root: string, options: DebuggerOptions);
clearDump(): Promise<void>;
encodeId(id: string): string;
recordExternalize(id: string, path: string): Promise<void>;
dumpFile(id: string, result: TransformResult | null): Promise<void>;
loadDump(id: string): Promise<TransformResult | null>;
writeInfo(): Promise<void>;
}
//#endregion
//#region src/externalize.d.ts
declare function guessCJSversion(id: string): string | undefined;
declare function shouldExternalize(id: string, options?: DepsHandlingOptions, cache?: Map<string, Promise<string | false>>): Promise<string | false>;
//#endregion
//#region src/server.d.ts
interface FetchCache {
duration?: number;
timestamp: number;
result: FetchResult;
}
declare class ViteNodeServer {
server: ViteDevServer;
options: ViteNodeServerOptions;
private fetchPromiseMap;
private transformPromiseMap;
private durations;
private existingOptimizedDeps;
fetchCaches: Record<"ssr" | "web", Map<string, FetchCache>>;
fetchCache: Map<string, FetchCache>;
externalizeCache: Map<string, Promise<string | false>>;
debugger?: Debugger;
constructor(server: ViteDevServer, options?: ViteNodeServerOptions);
shouldExternalize(id: string): Promise<string | false>;
getTotalDuration(): number;
private ensureExists;
resolveId(id: string, importer?: string, transformMode?: "web" | "ssr"): Promise<ViteNodeResolveId | null>;
getSourceMap(source: string): EncodedSourceMap | null;
private assertMode;
fetchModule(id: string, transformMode?: "web" | "ssr"): Promise<FetchResult>;
fetchResult(id: string, mode: "web" | "ssr"): Promise<FetchResult>;
transformRequest(id: string, filepath?: string, transformMode?: "web" | "ssr"): Promise<TransformResult | null | undefined>;
transformModule(id: string, transformMode?: "web" | "ssr"): Promise<{
code: string | undefined;
}>;
getTransformMode(id: string): "ssr" | "web";
private getChangedModule;
private _fetchModule;
protected processTransformResult(filepath: string, result: TransformResult): Promise<TransformResult>;
private _transformRequest;
}
//#endregion
export { ViteNodeServer, guessCJSversion, shouldExternalize };

View file

@ -0,0 +1,7 @@
import "./dist-B2ebky9O.mjs";
import { n as guessCJSversion, r as shouldExternalize, t as ViteNodeServer } from "./server-BWywEVuB.mjs";
import "./constants-DRkacFwN.mjs";
import "./utils-ExLpYVUV.mjs";
import "./source-map-DQLD3K8K.mjs";
export { ViteNodeServer, guessCJSversion, shouldExternalize };

View file

@ -0,0 +1,737 @@
import { _ as withTrailingSlash } from "./utils-ExLpYVUV.mjs";
import fs from "node:fs";
import process from "node:process";
import { dirname, isAbsolute, relative, resolve } from "pathe";
import { Buffer as Buffer$1 } from "node:buffer";
import path from "node:path";
//#region node_modules/.pnpm/@jridgewell+sourcemap-codec@1.5.5/node_modules/@jridgewell/sourcemap-codec/dist/sourcemap-codec.mjs
var comma = ",".charCodeAt(0);
var semicolon = ";".charCodeAt(0);
var chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
var intToChar = new Uint8Array(64);
var charToInt = new Uint8Array(128);
for (let i = 0; i < chars.length; i++) {
const c = chars.charCodeAt(i);
intToChar[i] = c;
charToInt[c] = i;
}
function decodeInteger(reader, relative$1) {
let value = 0;
let shift = 0;
let integer = 0;
do {
integer = charToInt[reader.next()];
value |= (integer & 31) << shift;
shift += 5;
} while (integer & 32);
const shouldNegate = value & 1;
value >>>= 1;
if (shouldNegate) value = -2147483648 | -value;
return relative$1 + value;
}
function hasMoreVlq(reader, max) {
if (reader.pos >= max) return false;
return reader.peek() !== comma;
}
var bufLength = 1024 * 16;
var StringReader = class {
constructor(buffer) {
this.pos = 0;
this.buffer = buffer;
}
next() {
return this.buffer.charCodeAt(this.pos++);
}
peek() {
return this.buffer.charCodeAt(this.pos);
}
indexOf(char) {
const { buffer, pos } = this;
const idx = buffer.indexOf(char, pos);
return idx === -1 ? buffer.length : idx;
}
};
function decode(mappings) {
const { length } = mappings;
const reader = new StringReader(mappings);
const decoded = [];
let genColumn = 0;
let sourcesIndex = 0;
let sourceLine = 0;
let sourceColumn = 0;
let namesIndex = 0;
do {
const semi = reader.indexOf(";");
const line = [];
let sorted = true;
let lastCol = 0;
genColumn = 0;
while (reader.pos < semi) {
let seg;
genColumn = decodeInteger(reader, genColumn);
if (genColumn < lastCol) sorted = false;
lastCol = genColumn;
if (hasMoreVlq(reader, semi)) {
sourcesIndex = decodeInteger(reader, sourcesIndex);
sourceLine = decodeInteger(reader, sourceLine);
sourceColumn = decodeInteger(reader, sourceColumn);
if (hasMoreVlq(reader, semi)) {
namesIndex = decodeInteger(reader, namesIndex);
seg = [
genColumn,
sourcesIndex,
sourceLine,
sourceColumn,
namesIndex
];
} else seg = [
genColumn,
sourcesIndex,
sourceLine,
sourceColumn
];
} else seg = [genColumn];
line.push(seg);
reader.pos++;
}
if (!sorted) sort(line);
decoded.push(line);
reader.pos = semi + 1;
} while (reader.pos <= length);
return decoded;
}
function sort(line) {
line.sort(sortComparator$1);
}
function sortComparator$1(a, b) {
return a[0] - b[0];
}
//#endregion
//#region node_modules/.pnpm/@jridgewell+resolve-uri@3.1.2/node_modules/@jridgewell/resolve-uri/dist/resolve-uri.mjs
const schemeRegex = /^[\w+.-]+:\/\//;
/**
* Matches the parts of a URL:
* 1. Scheme, including ":", guaranteed.
* 2. User/password, including "@", optional.
* 3. Host, guaranteed.
* 4. Port, including ":", optional.
* 5. Path, including "/", optional.
* 6. Query, including "?", optional.
* 7. Hash, including "#", optional.
*/
const urlRegex = /^([\w+.-]+:)\/\/([^@/#?]*@)?([^:/#?]*)(:\d+)?(\/[^#?]*)?(\?[^#]*)?(#.*)?/;
/**
* File URLs are weird. They dont' need the regular `//` in the scheme, they may or may not start
* with a leading `/`, they can have a domain (but only if they don't start with a Windows drive).
*
* 1. Host, optional.
* 2. Path, which may include "/", guaranteed.
* 3. Query, including "?", optional.
* 4. Hash, including "#", optional.
*/
const fileRegex = /^file:(?:\/\/((?![a-z]:)[^/#?]*)?)?(\/?[^#?]*)(\?[^#]*)?(#.*)?/i;
function isAbsoluteUrl(input) {
return schemeRegex.test(input);
}
function isSchemeRelativeUrl(input) {
return input.startsWith("//");
}
function isAbsolutePath(input) {
return input.startsWith("/");
}
function isFileUrl(input) {
return input.startsWith("file:");
}
function isRelative(input) {
return /^[.?#]/.test(input);
}
function parseAbsoluteUrl(input) {
const match = urlRegex.exec(input);
return makeUrl(match[1], match[2] || "", match[3], match[4] || "", match[5] || "/", match[6] || "", match[7] || "");
}
function parseFileUrl(input) {
const match = fileRegex.exec(input);
const path$1 = match[2];
return makeUrl("file:", "", match[1] || "", "", isAbsolutePath(path$1) ? path$1 : "/" + path$1, match[3] || "", match[4] || "");
}
function makeUrl(scheme, user, host, port, path$1, query, hash) {
return {
scheme,
user,
host,
port,
path: path$1,
query,
hash,
type: 7
};
}
function parseUrl(input) {
if (isSchemeRelativeUrl(input)) {
const url$1 = parseAbsoluteUrl("http:" + input);
url$1.scheme = "";
url$1.type = 6;
return url$1;
}
if (isAbsolutePath(input)) {
const url$1 = parseAbsoluteUrl("http://foo.com" + input);
url$1.scheme = "";
url$1.host = "";
url$1.type = 5;
return url$1;
}
if (isFileUrl(input)) return parseFileUrl(input);
if (isAbsoluteUrl(input)) return parseAbsoluteUrl(input);
const url = parseAbsoluteUrl("http://foo.com/" + input);
url.scheme = "";
url.host = "";
url.type = input ? input.startsWith("?") ? 3 : input.startsWith("#") ? 2 : 4 : 1;
return url;
}
function stripPathFilename(path$1) {
if (path$1.endsWith("/..")) return path$1;
const index = path$1.lastIndexOf("/");
return path$1.slice(0, index + 1);
}
function mergePaths(url, base) {
normalizePath(base, base.type);
if (url.path === "/") url.path = base.path;
else url.path = stripPathFilename(base.path) + url.path;
}
/**
* The path can have empty directories "//", unneeded parents "foo/..", or current directory
* "foo/.". We need to normalize to a standard representation.
*/
function normalizePath(url, type) {
const rel = type <= 4;
const pieces = url.path.split("/");
let pointer = 1;
let positive = 0;
let addTrailingSlash = false;
for (let i = 1; i < pieces.length; i++) {
const piece = pieces[i];
if (!piece) {
addTrailingSlash = true;
continue;
}
addTrailingSlash = false;
if (piece === ".") continue;
if (piece === "..") {
if (positive) {
addTrailingSlash = true;
positive--;
pointer--;
} else if (rel) pieces[pointer++] = piece;
continue;
}
pieces[pointer++] = piece;
positive++;
}
let path$1 = "";
for (let i = 1; i < pointer; i++) path$1 += "/" + pieces[i];
if (!path$1 || addTrailingSlash && !path$1.endsWith("/..")) path$1 += "/";
url.path = path$1;
}
/**
* Attempts to resolve `input` URL/path relative to `base`.
*/
function resolve$2(input, base) {
if (!input && !base) return "";
const url = parseUrl(input);
let inputType = url.type;
if (base && inputType !== 7) {
const baseUrl = parseUrl(base);
const baseType = baseUrl.type;
switch (inputType) {
case 1: url.hash = baseUrl.hash;
case 2: url.query = baseUrl.query;
case 3:
case 4: mergePaths(url, baseUrl);
case 5:
url.user = baseUrl.user;
url.host = baseUrl.host;
url.port = baseUrl.port;
case 6: url.scheme = baseUrl.scheme;
}
if (baseType > inputType) inputType = baseType;
}
normalizePath(url, inputType);
const queryHash = url.query + url.hash;
switch (inputType) {
case 2:
case 3: return queryHash;
case 4: {
const path$1 = url.path.slice(1);
if (!path$1) return queryHash || ".";
if (isRelative(base || input) && !isRelative(path$1)) return "./" + path$1 + queryHash;
return path$1 + queryHash;
}
case 5: return url.path + queryHash;
default: return url.scheme + "//" + url.user + url.host + url.port + url.path + queryHash;
}
}
//#endregion
//#region node_modules/.pnpm/@jridgewell+trace-mapping@0.3.31/node_modules/@jridgewell/trace-mapping/dist/trace-mapping.mjs
function stripFilename(path$1) {
if (!path$1) return "";
const index = path$1.lastIndexOf("/");
return path$1.slice(0, index + 1);
}
function resolver(mapUrl, sourceRoot) {
const from = stripFilename(mapUrl);
const prefix = sourceRoot ? sourceRoot + "/" : "";
return (source) => resolve$2(prefix + (source || ""), from);
}
var COLUMN = 0;
var SOURCES_INDEX = 1;
var SOURCE_LINE = 2;
var SOURCE_COLUMN = 3;
var NAMES_INDEX = 4;
function maybeSort(mappings, owned) {
const unsortedIndex = nextUnsortedSegmentLine(mappings, 0);
if (unsortedIndex === mappings.length) return mappings;
if (!owned) mappings = mappings.slice();
for (let i = unsortedIndex; i < mappings.length; i = nextUnsortedSegmentLine(mappings, i + 1)) mappings[i] = sortSegments(mappings[i], owned);
return mappings;
}
function nextUnsortedSegmentLine(mappings, start) {
for (let i = start; i < mappings.length; i++) if (!isSorted(mappings[i])) return i;
return mappings.length;
}
function isSorted(line) {
for (let j = 1; j < line.length; j++) if (line[j][COLUMN] < line[j - 1][COLUMN]) return false;
return true;
}
function sortSegments(line, owned) {
if (!owned) line = line.slice();
return line.sort(sortComparator);
}
function sortComparator(a, b) {
return a[COLUMN] - b[COLUMN];
}
var found = false;
function binarySearch(haystack, needle, low, high) {
while (low <= high) {
const mid = low + (high - low >> 1);
const cmp = haystack[mid][COLUMN] - needle;
if (cmp === 0) {
found = true;
return mid;
}
if (cmp < 0) low = mid + 1;
else high = mid - 1;
}
found = false;
return low - 1;
}
function upperBound(haystack, needle, index) {
for (let i = index + 1; i < haystack.length; index = i++) if (haystack[i][COLUMN] !== needle) break;
return index;
}
function lowerBound(haystack, needle, index) {
for (let i = index - 1; i >= 0; index = i--) if (haystack[i][COLUMN] !== needle) break;
return index;
}
function memoizedState() {
return {
lastKey: -1,
lastNeedle: -1,
lastIndex: -1
};
}
function memoizedBinarySearch(haystack, needle, state, key) {
const { lastKey, lastNeedle, lastIndex } = state;
let low = 0;
let high = haystack.length - 1;
if (key === lastKey) {
if (needle === lastNeedle) {
found = lastIndex !== -1 && haystack[lastIndex][COLUMN] === needle;
return lastIndex;
}
if (needle >= lastNeedle) low = lastIndex === -1 ? 0 : lastIndex;
else high = lastIndex;
}
state.lastKey = key;
state.lastNeedle = needle;
return state.lastIndex = binarySearch(haystack, needle, low, high);
}
function parse(map) {
return typeof map === "string" ? JSON.parse(map) : map;
}
var LINE_GTR_ZERO = "`line` must be greater than 0 (lines start at line 1)";
var COL_GTR_EQ_ZERO = "`column` must be greater than or equal to 0 (columns start at column 0)";
var LEAST_UPPER_BOUND = -1;
var GREATEST_LOWER_BOUND = 1;
var TraceMap = class {
constructor(map, mapUrl) {
const isString = typeof map === "string";
if (!isString && map._decodedMemo) return map;
const parsed = parse(map);
const { version, file, names, sourceRoot, sources, sourcesContent } = parsed;
this.version = version;
this.file = file;
this.names = names || [];
this.sourceRoot = sourceRoot;
this.sources = sources;
this.sourcesContent = sourcesContent;
this.ignoreList = parsed.ignoreList || parsed.x_google_ignoreList || void 0;
const resolve$3 = resolver(mapUrl, sourceRoot);
this.resolvedSources = sources.map(resolve$3);
const { mappings } = parsed;
if (typeof mappings === "string") {
this._encoded = mappings;
this._decoded = void 0;
} else if (Array.isArray(mappings)) {
this._encoded = void 0;
this._decoded = maybeSort(mappings, isString);
} else if (parsed.sections) throw new Error(`TraceMap passed sectioned source map, please use FlattenMap export instead`);
else throw new Error(`invalid source map: ${JSON.stringify(parsed)}`);
this._decodedMemo = memoizedState();
this._bySources = void 0;
this._bySourceMemos = void 0;
}
};
function cast(map) {
return map;
}
function decodedMappings(map) {
var _a;
return (_a = cast(map))._decoded || (_a._decoded = decode(cast(map)._encoded));
}
function originalPositionFor(map, needle) {
let { line, column, bias } = needle;
line--;
if (line < 0) throw new Error(LINE_GTR_ZERO);
if (column < 0) throw new Error(COL_GTR_EQ_ZERO);
const decoded = decodedMappings(map);
if (line >= decoded.length) return OMapping(null, null, null, null);
const segments = decoded[line];
const index = traceSegmentInternal(segments, cast(map)._decodedMemo, line, column, bias || GREATEST_LOWER_BOUND);
if (index === -1) return OMapping(null, null, null, null);
const segment = segments[index];
if (segment.length === 1) return OMapping(null, null, null, null);
const { names, resolvedSources } = map;
return OMapping(resolvedSources[segment[SOURCES_INDEX]], segment[SOURCE_LINE] + 1, segment[SOURCE_COLUMN], segment.length === 5 ? names[segment[NAMES_INDEX]] : null);
}
function OMapping(source, line, column, name) {
return {
source,
line,
column,
name
};
}
function traceSegmentInternal(segments, memo, line, column, bias) {
let index = memoizedBinarySearch(segments, column, memo, line);
if (found) index = (bias === LEAST_UPPER_BOUND ? upperBound : lowerBound)(segments, column, index);
else if (bias === LEAST_UPPER_BOUND) index++;
if (index === -1 || index === segments.length) return -1;
return index;
}
//#endregion
//#region src/source-map-handler.ts
let errorFormatterInstalled = false;
const fileContentsCache = {};
const sourceMapCache = {};
const reSourceMap = /^data:application\/json[^,]+base64,/;
let retrieveFileHandlers = [];
let retrieveMapHandlers = [];
function globalProcessVersion() {
if (typeof process === "object" && process !== null) return process.version;
else return "";
}
function handlerExec(list) {
return function(arg) {
for (let i = 0; i < list.length; i++) {
const ret = list[i](arg);
if (ret) return ret;
}
return null;
};
}
let retrieveFile = handlerExec(retrieveFileHandlers);
retrieveFileHandlers.push((path$1) => {
path$1 = path$1.trim();
if (path$1.startsWith("file:")) path$1 = path$1.replace(/file:\/\/\/(\w:)?/, (protocol, drive) => {
return drive ? "" : "/";
});
if (path$1 in fileContentsCache) return fileContentsCache[path$1];
let contents = "";
try {
if (fs.existsSync(path$1)) contents = fs.readFileSync(path$1, "utf8");
} catch {}
return fileContentsCache[path$1] = contents;
});
function supportRelativeURL(file, url) {
if (!file) return url;
const dir = path.dirname(file);
const match = /^\w+:\/\/[^/]*/.exec(dir);
let protocol = match ? match[0] : "";
const startPath = dir.slice(protocol.length);
if (protocol && /^\/\w:/.test(startPath)) {
protocol += "/";
return protocol + path.resolve(dir.slice(protocol.length), url).replace(/\\/g, "/");
}
return protocol + path.resolve(dir.slice(protocol.length), url);
}
function retrieveSourceMapURL(source) {
const fileData = retrieveFile(source);
if (!fileData) return null;
const re = /\/\/[@#]\s*sourceMappingURL=([^\s'"]+)\s*$|\/\*[@#]\s*sourceMappingURL=[^\s*'"]+\s*\*\/\s*$/gm;
let lastMatch, match;
while (match = re.exec(fileData)) lastMatch = match;
if (!lastMatch) return null;
return lastMatch[1];
}
let retrieveSourceMap = handlerExec(retrieveMapHandlers);
retrieveMapHandlers.push((source) => {
let sourceMappingURL = retrieveSourceMapURL(source);
if (!sourceMappingURL) return null;
let sourceMapData;
if (reSourceMap.test(sourceMappingURL)) {
const rawData = sourceMappingURL.slice(sourceMappingURL.indexOf(",") + 1);
sourceMapData = Buffer$1.from(rawData, "base64").toString();
sourceMappingURL = source;
} else {
sourceMappingURL = supportRelativeURL(source, sourceMappingURL);
sourceMapData = retrieveFile(sourceMappingURL);
}
if (!sourceMapData) return null;
return {
url: sourceMappingURL,
map: sourceMapData
};
});
function mapSourcePosition(position) {
if (!position.source) return position;
let sourceMap = sourceMapCache[position.source];
if (!sourceMap) {
const urlAndMap = retrieveSourceMap(position.source);
const map = urlAndMap && urlAndMap.map;
if (map && !(typeof map === "object" && "mappings" in map && map.mappings === "")) {
sourceMap = sourceMapCache[position.source] = {
url: urlAndMap.url,
map: new TraceMap(map)
};
if (sourceMap.map?.sourcesContent) sourceMap.map.sources.forEach((source, i) => {
const contents = sourceMap.map?.sourcesContent?.[i];
if (contents && source && sourceMap.url) {
const url = supportRelativeURL(sourceMap.url, source);
fileContentsCache[url] = contents;
}
});
} else sourceMap = sourceMapCache[position.source] = {
url: null,
map: null
};
}
if (sourceMap && sourceMap.map && sourceMap.url) {
const originalPosition = originalPositionFor(sourceMap.map, position);
if (originalPosition.source !== null) {
originalPosition.source = supportRelativeURL(sourceMap.url, originalPosition.source);
return originalPosition;
}
}
return position;
}
function mapEvalOrigin(origin) {
let match = /^eval at ([^(]+) \((.+):(\d+):(\d+)\)$/.exec(origin);
if (match) {
const position = mapSourcePosition({
name: null,
source: match[2],
line: +match[3],
column: +match[4] - 1
});
return `eval at ${match[1]} (${position.source}:${position.line}:${position.column + 1})`;
}
match = /^eval at ([^(]+) \((.+)\)$/.exec(origin);
if (match) return `eval at ${match[1]} (${mapEvalOrigin(match[2])})`;
return origin;
}
function CallSiteToString() {
let fileName;
let fileLocation = "";
if (this.isNative()) fileLocation = "native";
else {
fileName = this.getScriptNameOrSourceURL();
if (!fileName && this.isEval()) {
fileLocation = this.getEvalOrigin();
fileLocation += ", ";
}
if (fileName) fileLocation += fileName;
else fileLocation += "<anonymous>";
const lineNumber = this.getLineNumber();
if (lineNumber != null) {
fileLocation += `:${lineNumber}`;
const columnNumber = this.getColumnNumber();
if (columnNumber) fileLocation += `:${columnNumber}`;
}
}
let line = "";
const functionName = this.getFunctionName();
let addSuffix = true;
const isConstructor = this.isConstructor();
if (!(this.isToplevel() || isConstructor)) {
let typeName = this.getTypeName();
if (typeName === "[object Object]") typeName = "null";
const methodName = this.getMethodName();
if (functionName) {
if (typeName && functionName.indexOf(typeName) !== 0) line += `${typeName}.`;
line += functionName;
if (methodName && functionName.indexOf(`.${methodName}`) !== functionName.length - methodName.length - 1) line += ` [as ${methodName}]`;
} else line += `${typeName}.${methodName || "<anonymous>"}`;
} else if (isConstructor) line += `new ${functionName || "<anonymous>"}`;
else if (functionName) line += functionName;
else {
line += fileLocation;
addSuffix = false;
}
if (addSuffix) line += ` (${fileLocation})`;
return line;
}
function cloneCallSite(frame) {
const object = {};
Object.getOwnPropertyNames(Object.getPrototypeOf(frame)).forEach((name) => {
const key = name;
object[key] = /^(?:is|get)/.test(name) ? function() {
return frame[key].call(frame);
} : frame[key];
});
object.toString = CallSiteToString;
return object;
}
function wrapCallSite(frame, state) {
if (state === void 0) state = {
nextPosition: null,
curPosition: null
};
if (frame.isNative()) {
state.curPosition = null;
return frame;
}
const source = frame.getFileName() || frame.getScriptNameOrSourceURL();
if (source) {
const line = frame.getLineNumber();
let column = frame.getColumnNumber() - 1;
const headerLength = /^v(?:10\.1[6-9]|10\.[2-9]\d|10\.\d{3,}|1[2-9]\d*|[2-9]\d|\d{3,}|11\.11)/.test(globalProcessVersion()) ? 0 : 62;
if (line === 1 && column > headerLength && !frame.isEval()) column -= headerLength;
const position = mapSourcePosition({
name: null,
source,
line,
column
});
state.curPosition = position;
frame = cloneCallSite(frame);
const originalFunctionName = frame.getFunctionName;
frame.getFunctionName = function() {
if (state.nextPosition == null) return originalFunctionName();
return state.nextPosition.name || originalFunctionName();
};
frame.getFileName = function() {
return position.source ?? null;
};
frame.getLineNumber = function() {
return position.line;
};
frame.getColumnNumber = function() {
return position.column + 1;
};
frame.getScriptNameOrSourceURL = function() {
return position.source;
};
return frame;
}
let origin = frame.isEval() && frame.getEvalOrigin();
if (origin) {
origin = mapEvalOrigin(origin);
frame = cloneCallSite(frame);
frame.getEvalOrigin = function() {
return origin || void 0;
};
return frame;
}
return frame;
}
function prepareStackTrace(error, stack) {
const errorString = `${error.name || "Error"}: ${error.message || ""}`;
const state = {
nextPosition: null,
curPosition: null
};
const processedStack = [];
for (let i = stack.length - 1; i >= 0; i--) {
processedStack.push(`\n at ${wrapCallSite(stack[i], state)}`);
state.nextPosition = state.curPosition;
}
state.curPosition = state.nextPosition = null;
return errorString + processedStack.reverse().join("");
}
const originalRetrieveFileHandlers = retrieveFileHandlers.slice(0);
const originalRetrieveMapHandlers = retrieveMapHandlers.slice(0);
function install(options) {
options = options || {};
if (options.retrieveFile) {
if (options.overrideRetrieveFile) retrieveFileHandlers.length = 0;
retrieveFileHandlers.unshift(options.retrieveFile);
}
if (options.retrieveSourceMap) {
if (options.overrideRetrieveSourceMap) retrieveMapHandlers.length = 0;
retrieveMapHandlers.unshift(options.retrieveSourceMap);
}
if (!errorFormatterInstalled) {
errorFormatterInstalled = true;
Error.prepareStackTrace = prepareStackTrace;
}
}
//#endregion
//#region src/source-map.ts
let SOURCEMAPPING_URL = "sourceMa";
SOURCEMAPPING_URL += "ppingURL";
const VITE_NODE_SOURCEMAPPING_SOURCE = "//# sourceMappingSource=vite-node";
const VITE_NODE_SOURCEMAPPING_URL = `${SOURCEMAPPING_URL}=data:application/json;charset=utf-8`;
function withInlineSourcemap(result, options) {
const map = result.map;
let code = result.code;
if (!map || code.includes(VITE_NODE_SOURCEMAPPING_SOURCE)) return result;
if ("sources" in map) map.sources = map.sources?.map((source) => {
if (!source) return source;
if (isAbsolute(source)) {
const actualPath = !source.startsWith(withTrailingSlash(options.root)) && source.startsWith("/") ? resolve(options.root, source.slice(1)) : source;
return relative(dirname(options.filepath), actualPath);
}
return source;
});
const OTHER_SOURCE_MAP_REGEXP = new RegExp(`//# ${SOURCEMAPPING_URL}=data:application/json[^,]+base64,([A-Za-z0-9+/=]+)$`, "gm");
while (OTHER_SOURCE_MAP_REGEXP.test(code)) code = code.replace(OTHER_SOURCE_MAP_REGEXP, "");
if (!options.noFirstLineMapping && map.mappings.startsWith(";")) map.mappings = `AAAA,CAAA${map.mappings}`;
const sourceMap = Buffer$1.from(JSON.stringify(map), "utf-8").toString("base64");
result.code = `${code.trimEnd()}\n\n${VITE_NODE_SOURCEMAPPING_SOURCE}\n//# ${VITE_NODE_SOURCEMAPPING_URL};base64,${sourceMap}\n`;
return result;
}
function extractSourceMap(code) {
const regexp = new RegExp(`//# ${VITE_NODE_SOURCEMAPPING_URL};base64,(.+)`, "gm");
let lastMatch, match;
while (match = regexp.exec(code)) lastMatch = match;
if (lastMatch) return JSON.parse(Buffer$1.from(lastMatch[1], "base64").toString("utf-8"));
return null;
}
function installSourcemapsSupport(options) {
install({ retrieveSourceMap(source) {
const map = options.getSourceMap(source);
if (map) return {
url: source,
map
};
return null;
} });
}
//#endregion
export { installSourcemapsSupport as n, withInlineSourcemap as r, extractSourceMap as t };

View file

@ -0,0 +1,16 @@
import { s as EncodedSourceMap } from "./types-Dtew7m7O.mjs";
import { TransformResult } from "vite";
//#region src/source-map.d.ts
interface InstallSourceMapSupportOptions {
getSourceMap: (source: string) => EncodedSourceMap | null | undefined;
}
declare function withInlineSourcemap(result: TransformResult, options: {
root: string;
filepath: string;
noFirstLineMapping?: boolean;
}): TransformResult;
declare function extractSourceMap(code: string): EncodedSourceMap | null;
declare function installSourcemapsSupport(options: InstallSourceMapSupportOptions): void;
//#endregion
export { extractSourceMap, installSourcemapsSupport, withInlineSourcemap };

View file

@ -0,0 +1,4 @@
import "./utils-ExLpYVUV.mjs";
import { n as installSourcemapsSupport, r as withInlineSourcemap, t as extractSourceMap } from "./source-map-DQLD3K8K.mjs";
export { extractSourceMap, installSourcemapsSupport, withInlineSourcemap };

View file

@ -0,0 +1 @@
export { };

View file

@ -0,0 +1,212 @@
import * as _jridgewell_trace_mapping0 from "@jridgewell/trace-mapping";
import { DecodedSourceMap, EncodedSourceMap, EncodedSourceMap as EncodedSourceMap$1, SourceMapInput } from "@jridgewell/trace-mapping";
import { ViteHotContext } from "vite/types/hot.js";
//#region src/client.d.ts
declare const DEFAULT_REQUEST_STUBS: Record<string, Record<string, unknown>>;
declare class ModuleCacheMap extends Map<string, ModuleCache> {
normalizePath(fsPath: string): string;
/**
* Assign partial data to the map
*/
update(fsPath: string, mod: ModuleCache): this;
setByModuleId(modulePath: string, mod: ModuleCache): this;
set(fsPath: string, mod: ModuleCache): this;
getByModuleId(modulePath: string): ModuleCache & Required<Pick<ModuleCache, "imports" | "importers">>;
get(fsPath: string): ModuleCache & Required<Pick<ModuleCache, "importers" | "imports">>;
deleteByModuleId(modulePath: string): boolean;
delete(fsPath: string): boolean;
invalidateModule(mod: ModuleCache): boolean;
/**
* Invalidate modules that dependent on the given modules, up to the main entry
*/
invalidateDepTree(ids: string[] | Set<string>, invalidated?: Set<string>): Set<string>;
/**
* Invalidate dependency modules of the given modules, down to the bottom-level dependencies
*/
invalidateSubDepTree(ids: string[] | Set<string>, invalidated?: Set<string>): Set<string>;
/**
* Return parsed source map based on inlined source map of the module
*/
getSourceMap(id: string): _jridgewell_trace_mapping0.EncodedSourceMap | null;
}
type ModuleExecutionInfo = Map<string, ModuleExecutionInfoEntry>;
interface ModuleExecutionInfoEntry {
startOffset: number;
/** The duration that was spent executing the module. */
duration: number;
/** The time that was spent executing the module itself and externalized imports. */
selfTime: number;
}
declare class ViteNodeRunner {
options: ViteNodeRunnerOptions;
root: string;
debug: boolean;
/**
* Holds the cache of modules
* Keys of the map are filepaths, or plain package names
*/
moduleCache: ModuleCacheMap;
/**
* Tracks the stack of modules being executed for the purpose of calculating import self-time.
*
* Note that while in most cases, imports are a linear stack of modules,
* this is occasionally not the case, for example when you have parallel top-level dynamic imports like so:
*
* ```ts
* await Promise.all([
* import('./module1'),
* import('./module2'),
* ]);
* ```
*
* In this case, the self time will be reported incorrectly for one of the modules (could go negative).
* As top-level awaits with dynamic imports like this are uncommon, we don't handle this case specifically.
*/
private executionStack;
private performanceNow;
constructor(options: ViteNodeRunnerOptions);
executeFile(file: string): Promise<any>;
executeId(rawId: string): Promise<any>;
shouldResolveId(id: string, _importee?: string): boolean;
private _resolveUrl;
resolveUrl(id: string, importee?: string): Promise<[url: string, fsPath: string]>;
private _fetchModule;
protected getContextPrimitives(): {
Object: ObjectConstructor;
Reflect: typeof Reflect;
Symbol: SymbolConstructor;
};
protected runModule(context: Record<string, any>, transformed: string): Promise<void>;
/**
* Starts calculating the module execution info such as the total duration and self time spent on executing the module.
* Returns a function to call once the module has finished executing.
*/
protected startCalculateModuleExecutionInfo(filename: string, startOffset: number): () => ModuleExecutionInfoEntry;
prepareContext(context: Record<string, any>): Record<string, any>;
/**
* Define if a module should be interop-ed
* This function mostly for the ability to override by subclass
*/
shouldInterop(path: string, mod: any): boolean;
protected importExternalModule(path: string): Promise<any>;
/**
* Import a module and interop it
*/
interopedImport(path: string): Promise<any>;
}
//#endregion
//#region src/types.d.ts
type Nullable<T> = T | null | undefined;
type Arrayable<T> = T | Array<T>;
type Awaitable<T> = T | PromiseLike<T>;
interface DepsHandlingOptions {
external?: (string | RegExp)[];
inline?: (string | RegExp)[] | true;
inlineFiles?: string[];
/**
* A list of directories that are considered to hold Node.js modules
* Have to include "/" at the start and end of the path
*
* Vite-Node checks the whole absolute path of the import, so make sure you don't include
* unwanted files accidentally
* @default ['/node_modules/']
*/
moduleDirectories?: string[];
cacheDir?: string;
/**
* Try to guess the CJS version of a package when it's invalid ESM
* @default false
*/
fallbackCJS?: boolean;
}
interface StartOfSourceMap {
file?: string;
sourceRoot?: string;
}
interface RawSourceMap extends StartOfSourceMap {
version: number;
sources: string[];
names: string[];
sourcesContent?: (string | null)[];
mappings: string;
}
interface FetchResult {
code?: string;
externalize?: string;
map?: EncodedSourceMap | null;
}
type HotContext = Omit<ViteHotContext, "acceptDeps" | "decline">;
type FetchFunction = (id: string) => Promise<FetchResult>;
type ResolveIdFunction = (id: string, importer?: string) => Awaitable<ViteNodeResolveId | null | undefined | void>;
type CreateHotContextFunction = (runner: ViteNodeRunner, url: string) => HotContext;
interface ModuleCache {
promise?: Promise<any>;
exports?: any;
evaluated?: boolean;
resolving?: boolean;
code?: string;
map?: EncodedSourceMap;
/**
* Module ids that imports this module
*/
importers?: Set<string>;
imports?: Set<string>;
}
interface ViteNodeRunnerOptions {
root: string;
fetchModule: FetchFunction;
resolveId?: ResolveIdFunction;
createHotContext?: CreateHotContextFunction;
base?: string;
moduleCache?: ModuleCacheMap;
moduleExecutionInfo?: ModuleExecutionInfo;
interopDefault?: boolean;
requestStubs?: Record<string, any>;
debug?: boolean;
}
interface ViteNodeResolveId {
external?: boolean | "absolute" | "relative";
id: string;
meta?: Record<string, any> | null;
moduleSideEffects?: boolean | "no-treeshake" | null;
syntheticNamedExports?: boolean | string | null;
}
interface ViteNodeResolveModule {
external: string | null;
id: string;
fsPath: string;
}
interface ViteNodeServerOptions {
/**
* Inject inline sourcemap to modules
* @default 'inline'
*/
sourcemap?: "inline" | boolean;
/**
* Deps handling
*/
deps?: DepsHandlingOptions;
/**
* Transform method for modules
*/
transformMode?: {
ssr?: RegExp[];
web?: RegExp[];
};
debug?: DebuggerOptions;
}
interface DebuggerOptions {
/**
* Dump the transformed module to filesystem
* Passing a string will dump to the specified path
*/
dumpModules?: boolean | string;
/**
* Read dumpped module from filesystem whenever exists.
* Useful for debugging by modifying the dump result from the filesystem.
*/
loadDumppedModules?: boolean;
}
//#endregion
export { ModuleExecutionInfo as C, ModuleCacheMap as S, ViteNodeRunner as T, ViteNodeResolveId as _, DecodedSourceMap as a, ViteNodeServerOptions as b, FetchFunction as c, ModuleCache as d, Nullable as f, StartOfSourceMap as g, SourceMapInput as h, DebuggerOptions as i, FetchResult as l, ResolveIdFunction as m, Awaitable as n, DepsHandlingOptions as o, RawSourceMap as p, CreateHotContextFunction as r, EncodedSourceMap$1 as s, Arrayable as t, HotContext as u, ViteNodeResolveModule as v, ModuleExecutionInfoEntry as w, DEFAULT_REQUEST_STUBS as x, ViteNodeRunnerOptions as y };

View file

@ -0,0 +1,2 @@
import { C as ModuleExecutionInfo, S as ModuleCacheMap, _ as ViteNodeResolveId, a as DecodedSourceMap, b as ViteNodeServerOptions, c as FetchFunction, d as ModuleCache, f as Nullable, g as StartOfSourceMap, h as SourceMapInput, i as DebuggerOptions, l as FetchResult, m as ResolveIdFunction, n as Awaitable, o as DepsHandlingOptions, p as RawSourceMap, r as CreateHotContextFunction, s as EncodedSourceMap, t as Arrayable, u as HotContext, v as ViteNodeResolveModule, y as ViteNodeRunnerOptions } from "./types-Dtew7m7O.mjs";
export { Arrayable, Awaitable, CreateHotContextFunction, DebuggerOptions, DecodedSourceMap, DepsHandlingOptions, EncodedSourceMap, FetchFunction, FetchResult, HotContext, ModuleCache, ModuleCacheMap, ModuleExecutionInfo, Nullable, RawSourceMap, ResolveIdFunction, SourceMapInput, StartOfSourceMap, ViteNodeResolveId, ViteNodeResolveModule, ViteNodeRunnerOptions, ViteNodeServerOptions };

View file

@ -0,0 +1,3 @@
import "./types-55T_-8KG.mjs";
export { };

View file

@ -0,0 +1,190 @@
import { builtinModules } from "node:module";
import { existsSync, promises } from "node:fs";
import process from "node:process";
import { fileURLToPath, pathToFileURL } from "node:url";
import { dirname, join, resolve } from "pathe";
//#region src/utils.ts
const isWindows = process.platform === "win32";
const drive = isWindows ? process.cwd()[0] : null;
const driveOpposite = drive ? drive === drive.toUpperCase() ? drive.toLowerCase() : drive.toUpperCase() : null;
const driveRegexp = drive ? /* @__PURE__ */ new RegExp(`(?:^|/@fs/)${drive}(\:[\\/])`) : null;
const driveOppositeRegext = driveOpposite ? /* @__PURE__ */ new RegExp(`(?:^|/@fs/)${driveOpposite}(\:[\\/])`) : null;
function slash(str) {
return str.replace(/\\/g, "/");
}
const bareImportRE = /^(?![a-z]:)[\w@](?!.*:\/\/)/i;
function isBareImport(id) {
return bareImportRE.test(id);
}
const VALID_ID_PREFIX = "/@id/";
function normalizeRequestId(id, base) {
if (base && id.startsWith(withTrailingSlash(base))) id = `/${id.slice(base.length)}`;
if (driveRegexp && !driveRegexp?.test(id) && driveOppositeRegext?.test(id)) id = id.replace(driveOppositeRegext, `${drive}$1`);
if (id.startsWith("file://")) {
const { file, postfix } = splitFileAndPostfix(id);
return fileURLToPath(file) + postfix;
}
return id.replace(/^\/@id\/__x00__/, "\0").replace(/^\/@id\//, "").replace(/^__vite-browser-external:/, "").replace(/\?v=\w+/, "?").replace(/&v=\w+/, "").replace(/\?t=\w+/, "?").replace(/&t=\w+/, "").replace(/\?import/, "?").replace(/&import/, "").replace(/\?&/, "?").replace(/\?+$/, "");
}
const postfixRE = /[?#].*$/;
function cleanUrl(url) {
return url.replace(postfixRE, "");
}
function splitFileAndPostfix(path) {
const file = cleanUrl(path);
return {
file,
postfix: path.slice(file.length)
};
}
const internalRequestRegexp = /* @__PURE__ */ new RegExp(`^/?(?:${["@vite/client", "@vite/env"].join("|")})$`);
function isInternalRequest(id) {
return internalRequestRegexp.test(id);
}
const prefixedBuiltins = new Set([
"node:sea",
"node:sqlite",
"node:test",
"node:test/reporters"
]);
const builtins = new Set([
...builtinModules,
"assert/strict",
"diagnostics_channel",
"dns/promises",
"fs/promises",
"path/posix",
"path/win32",
"readline/promises",
"stream/consumers",
"stream/promises",
"stream/web",
"timers/promises",
"util/types",
"wasi"
]);
function normalizeModuleId(id) {
if (prefixedBuiltins.has(id)) return id;
if (id.startsWith("file://")) return fileURLToPath(id);
return id.replace(/\\/g, "/").replace(/^\/@fs\//, isWindows ? "" : "/").replace(/^node:/, "").replace(/^\/+/, "/");
}
function isPrimitive(v) {
return v !== Object(v);
}
function toFilePath(id, root) {
let { absolute, exists } = (() => {
if (id.startsWith("/@fs/")) return {
absolute: id.slice(4),
exists: true
};
if (!id.startsWith(withTrailingSlash(root)) && id.startsWith("/")) {
const resolved = resolve(root, id.slice(1));
if (existsSync(cleanUrl(resolved))) return {
absolute: resolved,
exists: true
};
} else if (id.startsWith(withTrailingSlash(root)) && existsSync(cleanUrl(id))) return {
absolute: id,
exists: true
};
return {
absolute: id,
exists: false
};
})();
if (absolute.startsWith("//")) absolute = absolute.slice(1);
return {
path: isWindows && absolute.startsWith("/") ? slash(fileURLToPath(pathToFileURL(absolute.slice(1)).href)) : absolute,
exists
};
}
const NODE_BUILTIN_NAMESPACE = "node:";
function isNodeBuiltin(id) {
if (prefixedBuiltins.has(id)) return true;
return builtins.has(id.startsWith(NODE_BUILTIN_NAMESPACE) ? id.slice(5) : id);
}
/**
* Convert `Arrayable<T>` to `Array<T>`
*
* @category Array
*/
function toArray(array) {
if (array === null || array === void 0) array = [];
if (Array.isArray(array)) return array;
return [array];
}
function getCachedData(cache, basedir, originalBasedir) {
const pkgData = cache.get(getFnpdCacheKey(basedir));
if (pkgData) {
traverseBetweenDirs(originalBasedir, basedir, (dir) => {
cache.set(getFnpdCacheKey(dir), pkgData);
});
return pkgData;
}
}
function setCacheData(cache, data, basedir, originalBasedir) {
cache.set(getFnpdCacheKey(basedir), data);
traverseBetweenDirs(originalBasedir, basedir, (dir) => {
cache.set(getFnpdCacheKey(dir), data);
});
}
function getFnpdCacheKey(basedir) {
return `fnpd_${basedir}`;
}
/**
* Traverse between `longerDir` (inclusive) and `shorterDir` (exclusive) and call `cb` for each dir.
* @param longerDir Longer dir path, e.g. `/User/foo/bar/baz`
* @param shorterDir Shorter dir path, e.g. `/User/foo`
*/
function traverseBetweenDirs(longerDir, shorterDir, cb) {
while (longerDir !== shorterDir) {
cb(longerDir);
longerDir = dirname(longerDir);
}
}
function withTrailingSlash(path) {
if (path[path.length - 1] !== "/") return `${path}/`;
return path;
}
function createImportMetaEnvProxy() {
const booleanKeys = [
"DEV",
"PROD",
"SSR"
];
return new Proxy(process.env, {
get(_, key) {
if (typeof key !== "string") return;
if (booleanKeys.includes(key)) return !!process.env[key];
return process.env[key];
},
set(_, key, value) {
if (typeof key !== "string") return true;
if (booleanKeys.includes(key)) process.env[key] = value ? "1" : "";
else process.env[key] = value;
return true;
}
});
}
const packageCache = /* @__PURE__ */ new Map();
async function findNearestPackageData(basedir) {
const originalBasedir = basedir;
while (basedir) {
const cached = getCachedData(packageCache, basedir, originalBasedir);
if (cached) return cached;
const pkgPath = join(basedir, "package.json");
if ((await promises.stat(pkgPath).catch(() => {}))?.isFile()) {
const pkgData = JSON.parse(await promises.readFile(pkgPath, "utf8"));
if (packageCache) setCacheData(packageCache, pkgData, basedir, originalBasedir);
return pkgData;
}
const nextBasedir = dirname(basedir);
if (nextBasedir === basedir) break;
basedir = nextBasedir;
}
return {};
}
//#endregion
export { withTrailingSlash as _, getCachedData as a, isNodeBuiltin as c, normalizeModuleId as d, normalizeRequestId as f, toFilePath as g, toArray as h, findNearestPackageData as i, isPrimitive as l, slash as m, cleanUrl as n, isBareImport as o, setCacheData as p, createImportMetaEnvProxy as r, isInternalRequest as s, VALID_ID_PREFIX as t, isWindows as u };

View file

@ -0,0 +1,32 @@
import { f as Nullable, t as Arrayable } from "./types-Dtew7m7O.mjs";
//#region src/utils.d.ts
declare const isWindows: boolean;
declare function slash(str: string): string;
declare function isBareImport(id: string): boolean;
declare const VALID_ID_PREFIX = "/@id/";
declare function normalizeRequestId(id: string, base?: string): string;
declare function cleanUrl(url: string): string;
declare function isInternalRequest(id: string): boolean;
declare function normalizeModuleId(id: string): string;
declare function isPrimitive(v: any): boolean;
declare function toFilePath(id: string, root: string): {
path: string;
exists: boolean;
};
declare function isNodeBuiltin(id: string): boolean;
/**
* Convert `Arrayable<T>` to `Array<T>`
*
* @category Array
*/
declare function toArray<T>(array?: Nullable<Arrayable<T>>): Array<T>;
declare function getCachedData<T>(cache: Map<string, T>, basedir: string, originalBasedir: string): NonNullable<T> | undefined;
declare function setCacheData<T>(cache: Map<string, T>, data: T, basedir: string, originalBasedir: string): void;
declare function withTrailingSlash(path: string): string;
declare function createImportMetaEnvProxy(): NodeJS.ProcessEnv;
declare function findNearestPackageData(basedir: string): Promise<{
type?: "module" | "commonjs";
}>;
//#endregion
export { VALID_ID_PREFIX, cleanUrl, createImportMetaEnvProxy, findNearestPackageData, getCachedData, isBareImport, isInternalRequest, isNodeBuiltin, isPrimitive, isWindows, normalizeModuleId, normalizeRequestId, setCacheData, slash, toArray, toFilePath, withTrailingSlash };

View file

@ -0,0 +1,3 @@
import { _ as withTrailingSlash, a as getCachedData, c as isNodeBuiltin, d as normalizeModuleId, f as normalizeRequestId, g as toFilePath, h as toArray, i as findNearestPackageData, l as isPrimitive, m as slash, n as cleanUrl, o as isBareImport, p as setCacheData, r as createImportMetaEnvProxy, s as isInternalRequest, t as VALID_ID_PREFIX, u as isWindows } from "./utils-ExLpYVUV.mjs";
export { VALID_ID_PREFIX, cleanUrl, createImportMetaEnvProxy, findNearestPackageData, getCachedData, isBareImport, isInternalRequest, isNodeBuiltin, isPrimitive, isWindows, normalizeModuleId, normalizeRequestId, setCacheData, slash, toArray, toFilePath, withTrailingSlash };

70
Frontend-Learner/node_modules/vite-node/package.json generated vendored Normal file
View file

@ -0,0 +1,70 @@
{
"name": "vite-node",
"type": "module",
"version": "5.2.0",
"description": "Vite as Node.js runtime",
"author": "Anthony Fu <anthonyfu117@hotmail.com>",
"license": "MIT",
"funding": "https://opencollective.com/antfu",
"homepage": "https://github.com/antfu-collective/vite-node#readme",
"repository": {
"type": "git",
"url": "git+https://github.com/antfu-collective/vite-node.git"
},
"bugs": {
"url": "https://github.com/antfu-collective/vite-node/issues"
},
"sideEffects": false,
"exports": {
".": "./dist/index.mjs",
"./cli": "./dist/cli.mjs",
"./client": "./dist/client.mjs",
"./constants": "./dist/constants.mjs",
"./hmr": "./dist/hmr.mjs",
"./server": "./dist/server.mjs",
"./source-map": "./dist/source-map.mjs",
"./types": "./dist/types.mjs",
"./utils": "./dist/utils.mjs",
"./package.json": "./package.json"
},
"main": "./dist/index.mjs",
"module": "./dist/index.mjs",
"types": "./dist/index.d.mts",
"bin": {
"vite-node": "./dist/cli.mjs"
},
"files": [
"dist"
],
"engines": {
"node": "^20.19.0 || >=22.12.0"
},
"dependencies": {
"cac": "^6.7.14",
"es-module-lexer": "^1.7.0",
"obug": "^2.0.0",
"pathe": "^2.0.3",
"vite": "^7.2.2"
},
"devDependencies": {
"@antfu/eslint-config": "^6.2.0",
"@jridgewell/trace-mapping": "^0.3.31",
"@types/node": "^24.10.1",
"bumpp": "^10.3.1",
"eslint": "^9.39.1",
"inquirer": "^13.0.1",
"tinyexec": "^1.0.2",
"tinyrainbow": "^3.0.3",
"tsdown": "^0.16.5",
"typescript": "^5.9.3",
"vitest": "^4.0.10"
},
"scripts": {
"lint": "eslint",
"build": "tsdown",
"dev": "tsdown -w",
"typecheck": "tsc --noEmit",
"test": "vitest",
"release": "bumpp"
}
}