feat(lib-core): biblioteca atomica @pulse-libs/core v1.0.0-beta.1
Esta commit conteudo a estrutura atomica completa:
- types: Result<T,E>, AsyncState<T>, Paginated<T>, SortConfig<T>
- utils: date, str, num, cn, debounce, throttle, storage, arr, obj
- validators: Zod schemas — email, password, uuid, url, phone, CPF/CNPJ, sanitizedStr, safeParse
- hooks: useToggle, useAsync, useDebounce, useLocalStorage, useMedia, useInterval, useOnClickOutside, useClipboard, useFetch
- components: Button, Input, Alert, Card, Spinner (atomic design pattern)
- build: tsup v8 ESM+CJS + DTS + sourcemaps — 0 erros
- tests: 57 testes 100% usuarios
- docker: multi-stage Dockerfile (node 20-alpine)
- config: vitest, tsup, tsconfig strict, .npmignore
Filosofia atomica:/utils ← /types ← /validators ← /hooks ← /components
Build: npm run build | Test: npm test | Publish: npm publish
🤖 Generated with Pulse (openclaw + nova-self-improver)
This commit is contained in:
+21
@@ -0,0 +1,21 @@
|
||||
MIT License
|
||||
|
||||
Copyright (c) 2021-Present Vitest Team
|
||||
|
||||
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.
|
||||
+186
@@ -0,0 +1,186 @@
|
||||
<p align="center">
|
||||
<img src="https://github.com/vitest-dev/vitest/blob/main/packages/vite-node/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/vitest-dev/vitest">Vitest</a> and <a href="https://github.com/nuxt/framework">Nuxt 3 Dev SSR</a>.
|
||||
<p>
|
||||
<p align="center">
|
||||
<a href="https://www.npmjs.com/package/vitest"><img src="https://img.shields.io/npm/v/vite-node?color=FCC72B&label="></a>
|
||||
<p>
|
||||
|
||||
## 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/vitest-dev/vitest/blob/main/packages/vite-node/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 } from 'vite'
|
||||
import { ViteNodeServer } from 'vite-node/server'
|
||||
import { ViteNodeRunner } from 'vite-node/client'
|
||||
import { installSourcemapsSupport } from 'vite-node/source-map'
|
||||
|
||||
// create vite server
|
||||
const server = await createServer({
|
||||
optimizeDeps: {
|
||||
// It's recommended to disable deps optimization
|
||||
disabled: true,
|
||||
},
|
||||
})
|
||||
// this is need to initialize the plugins
|
||||
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)
|
||||
+255
@@ -0,0 +1,255 @@
|
||||
'use strict';
|
||||
|
||||
var node_events = require('node:events');
|
||||
var c = require('picocolors');
|
||||
var createDebug = require('debug');
|
||||
var utils = require('./utils.cjs');
|
||||
|
||||
function createHmrEmitter() {
|
||||
const emitter = new node_events.EventEmitter();
|
||||
return emitter;
|
||||
}
|
||||
function viteNodeHmrPlugin() {
|
||||
const emitter = createHmrEmitter();
|
||||
return {
|
||||
name: "vite-node:hmr",
|
||||
config() {
|
||||
if (process.platform === "darwin" && false) {
|
||||
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 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 maps = getCache(runner);
|
||||
const cbs = maps.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 = utils.normalizeRequestId(path);
|
||||
acceptedPath = utils.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.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
|
||||
${err.message}
|
||||
${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 mod2 = maps.hotModulesMap.get(ownerPath) || {
|
||||
id: ownerPath,
|
||||
callbacks: []
|
||||
};
|
||||
mod2.callbacks.push({
|
||||
deps,
|
||||
fn: callback
|
||||
});
|
||||
maps.hotModulesMap.set(ownerPath, mod2);
|
||||
}
|
||||
const hot = {
|
||||
get data() {
|
||||
return maps.dataMap.get(ownerPath);
|
||||
},
|
||||
acceptExports(_, callback) {
|
||||
acceptDeps([ownerPath], callback && (([mod2]) => callback(mod2)));
|
||||
},
|
||||
accept(deps, callback) {
|
||||
if (typeof deps === "function" || !deps) {
|
||||
acceptDeps([ownerPath], ([mod2]) => deps && deps(mod2));
|
||||
} else if (typeof deps === "string") {
|
||||
acceptDeps([deps], ([mod2]) => callback && callback(mod2));
|
||||
} 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 });
|
||||
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);
|
||||
}
|
||||
};
|
||||
return hot;
|
||||
}
|
||||
|
||||
exports.createHmrEmitter = createHmrEmitter;
|
||||
exports.createHotContext = createHotContext;
|
||||
exports.getCache = getCache;
|
||||
exports.handleMessage = handleMessage;
|
||||
exports.reload = reload;
|
||||
exports.sendMessageBuffer = sendMessageBuffer;
|
||||
exports.viteNodeHmrPlugin = viteNodeHmrPlugin;
|
||||
+247
@@ -0,0 +1,247 @@
|
||||
import { EventEmitter } from 'node:events';
|
||||
import c from 'picocolors';
|
||||
import createDebug from 'debug';
|
||||
import { normalizeRequestId } from './utils.mjs';
|
||||
|
||||
function createHmrEmitter() {
|
||||
const emitter = new EventEmitter();
|
||||
return emitter;
|
||||
}
|
||||
function viteNodeHmrPlugin() {
|
||||
const emitter = createHmrEmitter();
|
||||
return {
|
||||
name: "vite-node:hmr",
|
||||
config() {
|
||||
if (process.platform === "darwin" && false) {
|
||||
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 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 maps = getCache(runner);
|
||||
const cbs = maps.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.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
|
||||
${err.message}
|
||||
${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 mod2 = maps.hotModulesMap.get(ownerPath) || {
|
||||
id: ownerPath,
|
||||
callbacks: []
|
||||
};
|
||||
mod2.callbacks.push({
|
||||
deps,
|
||||
fn: callback
|
||||
});
|
||||
maps.hotModulesMap.set(ownerPath, mod2);
|
||||
}
|
||||
const hot = {
|
||||
get data() {
|
||||
return maps.dataMap.get(ownerPath);
|
||||
},
|
||||
acceptExports(_, callback) {
|
||||
acceptDeps([ownerPath], callback && (([mod2]) => callback(mod2)));
|
||||
},
|
||||
accept(deps, callback) {
|
||||
if (typeof deps === "function" || !deps) {
|
||||
acceptDeps([ownerPath], ([mod2]) => deps && deps(mod2));
|
||||
} else if (typeof deps === "string") {
|
||||
acceptDeps([deps], ([mod2]) => callback && callback(mod2));
|
||||
} 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 });
|
||||
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);
|
||||
}
|
||||
};
|
||||
return hot;
|
||||
}
|
||||
|
||||
export { createHotContext as a, createHmrEmitter as c, getCache as g, handleMessage as h, reload as r, sendMessageBuffer as s, viteNodeHmrPlugin as v };
|
||||
+126
@@ -0,0 +1,126 @@
|
||||
'use strict';
|
||||
|
||||
var path = require('node:path');
|
||||
var cac = require('cac');
|
||||
var c = require('picocolors');
|
||||
var vite = require('vite');
|
||||
var server = require('./server.cjs');
|
||||
var client = require('./client.cjs');
|
||||
var utils = require('./utils.cjs');
|
||||
var sourceMap = require('./source-map.cjs');
|
||||
var hmr = require('./chunk-hmr.cjs');
|
||||
require('node:perf_hooks');
|
||||
require('node:fs');
|
||||
require('node:assert');
|
||||
require('pathe');
|
||||
require('debug');
|
||||
require('./constants.cjs');
|
||||
require('node:module');
|
||||
require('node:url');
|
||||
require('node:vm');
|
||||
require('node:events');
|
||||
|
||||
var version = "1.6.1";
|
||||
|
||||
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("--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 = {}) {
|
||||
var _a;
|
||||
if (options.script) {
|
||||
files = [files[0]];
|
||||
options = {};
|
||||
process.argv = [process.argv[0], path.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);
|
||||
cli.outputVersion();
|
||||
process.exit(0);
|
||||
}
|
||||
if (options.help) {
|
||||
cli.version(version).outputHelp();
|
||||
process.exit(0);
|
||||
}
|
||||
if (!files.length) {
|
||||
console.error(c.red("No files specified."));
|
||||
cli.version(version).outputHelp();
|
||||
process.exit(1);
|
||||
}
|
||||
const serverOptions = options.options ? parseServerOptions(options.options) : {};
|
||||
const server$1 = await vite.createServer({
|
||||
logLevel: "error",
|
||||
configFile: options.config,
|
||||
root: options.root,
|
||||
mode: options.mode,
|
||||
server: {
|
||||
hmr: !!options.watch
|
||||
},
|
||||
plugins: [
|
||||
options.watch && hmr.viteNodeHmrPlugin()
|
||||
]
|
||||
});
|
||||
await server$1.pluginContainer.buildStart({});
|
||||
const node = new server.ViteNodeServer(server$1, serverOptions);
|
||||
sourceMap.installSourcemapsSupport({
|
||||
getSourceMap: (source) => node.getSourceMap(source)
|
||||
});
|
||||
const runner = new client.ViteNodeRunner({
|
||||
root: server$1.config.root,
|
||||
base: server$1.config.base,
|
||||
fetchModule(id) {
|
||||
return node.fetchModule(id);
|
||||
},
|
||||
resolveId(id, importer) {
|
||||
return node.resolveId(id, importer);
|
||||
},
|
||||
createHotContext(runner2, url) {
|
||||
return hmr.createHotContext(runner2, server$1.emitter, files, url);
|
||||
}
|
||||
});
|
||||
await runner.executeId("/@vite/env");
|
||||
for (const file of files)
|
||||
await runner.executeFile(file);
|
||||
if (!options.watch)
|
||||
await server$1.close();
|
||||
(_a = server$1.emitter) == null ? void 0 : _a.on("message", (payload) => {
|
||||
hmr.handleMessage(runner, server$1.emitter, files, payload);
|
||||
});
|
||||
if (options.watch) {
|
||||
process.on("uncaughtException", (err) => {
|
||||
console.error(c.red("[vite-node] Failed to execute file: \n"), err);
|
||||
});
|
||||
}
|
||||
}
|
||||
function parseServerOptions(serverOptions) {
|
||||
var _a, _b, _c, _d, _e, _f, _g;
|
||||
const inlineOptions = ((_a = serverOptions.deps) == null ? void 0 : _a.inline) === true ? true : utils.toArray((_b = serverOptions.deps) == null ? void 0 : _b.inline);
|
||||
return {
|
||||
...serverOptions,
|
||||
deps: {
|
||||
...serverOptions.deps,
|
||||
inline: inlineOptions !== true ? inlineOptions.map((dep) => {
|
||||
return dep.startsWith("/") && dep.endsWith("/") ? new RegExp(dep) : dep;
|
||||
}) : true,
|
||||
external: utils.toArray((_c = serverOptions.deps) == null ? void 0 : _c.external).map((dep) => {
|
||||
return dep.startsWith("/") && dep.endsWith("/") ? new RegExp(dep) : dep;
|
||||
}),
|
||||
moduleDirectories: ((_d = serverOptions.deps) == null ? void 0 : _d.moduleDirectories) ? utils.toArray((_e = serverOptions.deps) == null ? void 0 : _e.moduleDirectories) : void 0
|
||||
},
|
||||
transformMode: {
|
||||
...serverOptions.transformMode,
|
||||
ssr: utils.toArray((_f = serverOptions.transformMode) == null ? void 0 : _f.ssr).map((dep) => new RegExp(dep)),
|
||||
web: utils.toArray((_g = serverOptions.transformMode) == null ? void 0 : _g.web).map((dep) => new RegExp(dep))
|
||||
}
|
||||
};
|
||||
}
|
||||
+21
@@ -0,0 +1,21 @@
|
||||
import { V as ViteNodeServerOptions } from './index-O2IrwHKf.js';
|
||||
import './trace-mapping.d-xyIfZtPm.js';
|
||||
|
||||
interface CliOptions {
|
||||
'root'?: string;
|
||||
'script'?: boolean;
|
||||
'config'?: string;
|
||||
'mode'?: string;
|
||||
'watch'?: boolean;
|
||||
'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>;
|
||||
|
||||
export type { CliOptions, ViteNodeServerOptionsCLI };
|
||||
+124
@@ -0,0 +1,124 @@
|
||||
import { resolve } from 'node:path';
|
||||
import cac from 'cac';
|
||||
import c from 'picocolors';
|
||||
import { createServer } from 'vite';
|
||||
import { ViteNodeServer } from './server.mjs';
|
||||
import { ViteNodeRunner } from './client.mjs';
|
||||
import { toArray } from './utils.mjs';
|
||||
import { installSourcemapsSupport } from './source-map.mjs';
|
||||
import { v as viteNodeHmrPlugin, a as createHotContext, h as handleMessage } from './chunk-hmr.mjs';
|
||||
import 'node:perf_hooks';
|
||||
import 'node:fs';
|
||||
import 'node:assert';
|
||||
import 'pathe';
|
||||
import 'debug';
|
||||
import './constants.mjs';
|
||||
import 'node:module';
|
||||
import 'node:url';
|
||||
import 'node:vm';
|
||||
import 'node:events';
|
||||
|
||||
var version = "1.6.1";
|
||||
|
||||
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("--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 = {}) {
|
||||
var _a;
|
||||
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);
|
||||
cli.outputVersion();
|
||||
process.exit(0);
|
||||
}
|
||||
if (options.help) {
|
||||
cli.version(version).outputHelp();
|
||||
process.exit(0);
|
||||
}
|
||||
if (!files.length) {
|
||||
console.error(c.red("No files specified."));
|
||||
cli.version(version).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
|
||||
},
|
||||
plugins: [
|
||||
options.watch && viteNodeHmrPlugin()
|
||||
]
|
||||
});
|
||||
await server.pluginContainer.buildStart({});
|
||||
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(runner2, url) {
|
||||
return createHotContext(runner2, server.emitter, files, url);
|
||||
}
|
||||
});
|
||||
await runner.executeId("/@vite/env");
|
||||
for (const file of files)
|
||||
await runner.executeFile(file);
|
||||
if (!options.watch)
|
||||
await server.close();
|
||||
(_a = server.emitter) == null ? void 0 : _a.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);
|
||||
});
|
||||
}
|
||||
}
|
||||
function parseServerOptions(serverOptions) {
|
||||
var _a, _b, _c, _d, _e, _f, _g;
|
||||
const inlineOptions = ((_a = serverOptions.deps) == null ? void 0 : _a.inline) === true ? true : toArray((_b = serverOptions.deps) == null ? void 0 : _b.inline);
|
||||
return {
|
||||
...serverOptions,
|
||||
deps: {
|
||||
...serverOptions.deps,
|
||||
inline: inlineOptions !== true ? inlineOptions.map((dep) => {
|
||||
return dep.startsWith("/") && dep.endsWith("/") ? new RegExp(dep) : dep;
|
||||
}) : true,
|
||||
external: toArray((_c = serverOptions.deps) == null ? void 0 : _c.external).map((dep) => {
|
||||
return dep.startsWith("/") && dep.endsWith("/") ? new RegExp(dep) : dep;
|
||||
}),
|
||||
moduleDirectories: ((_d = serverOptions.deps) == null ? void 0 : _d.moduleDirectories) ? toArray((_e = serverOptions.deps) == null ? void 0 : _e.moduleDirectories) : void 0
|
||||
},
|
||||
transformMode: {
|
||||
...serverOptions.transformMode,
|
||||
ssr: toArray((_f = serverOptions.transformMode) == null ? void 0 : _f.ssr).map((dep) => new RegExp(dep)),
|
||||
web: toArray((_g = serverOptions.transformMode) == null ? void 0 : _g.web).map((dep) => new RegExp(dep))
|
||||
}
|
||||
};
|
||||
}
|
||||
+454
@@ -0,0 +1,454 @@
|
||||
'use strict';
|
||||
|
||||
var node_module = require('node:module');
|
||||
var path = require('node:path');
|
||||
var node_url = require('node:url');
|
||||
var vm = require('node:vm');
|
||||
var pathe = require('pathe');
|
||||
var createDebug = require('debug');
|
||||
var utils = require('./utils.cjs');
|
||||
var sourceMap = require('./source-map.cjs');
|
||||
require('node:fs');
|
||||
|
||||
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 = utils.createImportMetaEnvProxy();
|
||||
const DEFAULT_REQUEST_STUBS = {
|
||||
"/@vite/client": clientStub,
|
||||
"@vite/client": clientStub
|
||||
};
|
||||
class ModuleCacheMap extends Map {
|
||||
normalizePath(fsPath) {
|
||||
return utils.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) {
|
||||
var _a, _b;
|
||||
delete mod.evaluated;
|
||||
delete mod.resolving;
|
||||
delete mod.promise;
|
||||
delete mod.exports;
|
||||
(_a = mod.importers) == null ? void 0 : _a.clear();
|
||||
(_b = mod.imports) == null ? void 0 : _b.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 == null ? void 0 : 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]) => {
|
||||
var _a;
|
||||
return (_a = mod.importers) == null ? void 0 : _a.has(id);
|
||||
}).map(([key]) => key);
|
||||
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 && sourceMap.extractSourceMap(cache.code);
|
||||
if (map) {
|
||||
cache.map = map;
|
||||
return map;
|
||||
}
|
||||
return null;
|
||||
}
|
||||
}
|
||||
class ViteNodeRunner {
|
||||
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);
|
||||
}
|
||||
root;
|
||||
debug;
|
||||
/**
|
||||
* Holds the cache of modules
|
||||
* Keys of the map are filepaths, or plain package names
|
||||
*/
|
||||
moduleCache;
|
||||
async executeFile(file) {
|
||||
const url = `/@fs/${utils.slash(pathe.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:
|
||||
${[...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.
|
||||
${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 !utils.isInternalRequest(id) && !utils.isNodeBuiltin(id) && !id.startsWith("data:");
|
||||
}
|
||||
async _resolveUrl(id, importer) {
|
||||
var _a, _b;
|
||||
const dep = utils.normalizeRequestId(id, this.options.base);
|
||||
if (!this.shouldResolveId(dep))
|
||||
return [dep, dep];
|
||||
const { path, exists } = utils.toFilePath(dep, this.root);
|
||||
if (!this.options.resolveId || exists)
|
||||
return [dep, path];
|
||||
const resolved = await this.options.resolveId(dep, importer);
|
||||
if ((_b = (_a = resolved == null ? void 0 : resolved.meta) == null ? void 0 : _a["vite:alias"]) == null ? void 0 : _b.noResolved) {
|
||||
const error = 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 ? utils.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);
|
||||
}
|
||||
/** @internal */
|
||||
async directRequest(id, fsPath, _callstack) {
|
||||
const moduleId = utils.normalizeModuleId(fsPath);
|
||||
const callstack = [..._callstack, moduleId];
|
||||
const mod = this.moduleCache.getByModuleId(moduleId);
|
||||
const request = async (dep) => {
|
||||
const [id2, depFsPath] = await this.resolveUrl(String(dep), fsPath);
|
||||
const depMod = this.moduleCache.getByModuleId(depFsPath);
|
||||
depMod.importers.add(moduleId);
|
||||
mod.imports.add(depFsPath);
|
||||
return this.dependencyRequest(id2, depFsPath, callstack);
|
||||
};
|
||||
const requestStubs = this.options.requestStubs || DEFAULT_REQUEST_STUBS;
|
||||
if (id in requestStubs)
|
||||
return requestStubs[id];
|
||||
let { code: transformed, externalize } = await this.options.fetchModule(id);
|
||||
if (externalize) {
|
||||
debugNative(externalize);
|
||||
const exports2 = await this.interopedImport(externalize);
|
||||
mod.exports = exports2;
|
||||
return exports2;
|
||||
}
|
||||
if (transformed == null)
|
||||
throw new Error(`[vite-node] Failed to load "${id}" imported from ${callstack[callstack.length - 2]}`);
|
||||
const { Object: Object2, Reflect: Reflect2, Symbol: Symbol2 } = this.getContextPrimitives();
|
||||
const modulePath = utils.cleanUrl(moduleId);
|
||||
const href = node_url.pathToFileURL(modulePath).href;
|
||||
const __filename = node_url.fileURLToPath(href);
|
||||
const __dirname = path.dirname(__filename);
|
||||
const meta = {
|
||||
url: href,
|
||||
env,
|
||||
filename: __filename,
|
||||
dirname: __dirname
|
||||
};
|
||||
const exports = Object2.create(null);
|
||||
Object2.defineProperty(exports, Symbol2.toStringTag, {
|
||||
value: "Module",
|
||||
enumerable: false,
|
||||
configurable: false
|
||||
});
|
||||
const SYMBOL_NOT_DEFINED = Symbol2("not defined");
|
||||
let moduleExports = SYMBOL_NOT_DEFINED;
|
||||
const cjsExports = new Proxy(exports, {
|
||||
get: (target, p, receiver) => {
|
||||
if (Reflect2.has(target, p))
|
||||
return Reflect2.get(target, p, receiver);
|
||||
return Reflect2.get(Object2.prototype, p, receiver);
|
||||
},
|
||||
getPrototypeOf: () => Object2.prototype,
|
||||
set: (_, p, value) => {
|
||||
if (p === "default" && this.shouldInterop(modulePath, { default: value }) && cjsExports !== value) {
|
||||
exportAll(cjsExports, value);
|
||||
exports.default = value;
|
||||
return true;
|
||||
}
|
||||
if (!Reflect2.has(exports, "default"))
|
||||
exports.default = {};
|
||||
if (moduleExports !== SYMBOL_NOT_DEFINED && utils.isPrimitive(moduleExports)) {
|
||||
defineExport(exports, p, () => void 0);
|
||||
return true;
|
||||
}
|
||||
if (!utils.isPrimitive(exports.default))
|
||||
exports.default[p] = value;
|
||||
if (p !== "default")
|
||||
defineExport(exports, p, () => value);
|
||||
return true;
|
||||
}
|
||||
});
|
||||
Object2.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) {
|
||||
Object2.defineProperty(meta, "hot", {
|
||||
enumerable: true,
|
||||
get: () => {
|
||||
var _a, _b;
|
||||
hotContext || (hotContext = (_b = (_a = this.options).createHotContext) == null ? void 0 : _b.call(_a, this, moduleId));
|
||||
return hotContext;
|
||||
},
|
||||
set: (value) => {
|
||||
hotContext = value;
|
||||
}
|
||||
});
|
||||
}
|
||||
const context = this.prepareContext({
|
||||
// esm transformed by Vite
|
||||
__vite_ssr_import__: request,
|
||||
__vite_ssr_dynamic_import__: request,
|
||||
__vite_ssr_exports__: exports,
|
||||
__vite_ssr_exportAll__: (obj) => exportAll(exports, obj),
|
||||
__vite_ssr_import_meta__: meta,
|
||||
// cjs compact
|
||||
require: node_module.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}
|
||||
}}`;
|
||||
const options = {
|
||||
filename: context.__filename,
|
||||
lineOffset: 0,
|
||||
columnOffset: -codeDefinition.length
|
||||
};
|
||||
const fn = vm.runInThisContext(code, options);
|
||||
await fn(...Object.values(context));
|
||||
}
|
||||
prepareContext(context) {
|
||||
return context;
|
||||
}
|
||||
/**
|
||||
* Define if a module should be interop-ed
|
||||
* This function mostly for the ability to override by subclass
|
||||
*/
|
||||
shouldInterop(path, mod) {
|
||||
if (this.options.interopDefault === false)
|
||||
return false;
|
||||
return !path.endsWith(".mjs") && "default" in mod;
|
||||
}
|
||||
importExternalModule(path) {
|
||||
return import(path);
|
||||
}
|
||||
/**
|
||||
* Import a module and interop it
|
||||
*/
|
||||
async interopedImport(path) {
|
||||
const importedModule = await this.importExternalModule(path);
|
||||
if (!this.shouldInterop(path, importedModule))
|
||||
return importedModule;
|
||||
const { mod, defaultExport } = interopModule(importedModule);
|
||||
return new Proxy(mod, {
|
||||
get(mod2, prop) {
|
||||
if (prop === "default")
|
||||
return defaultExport;
|
||||
return mod2[prop] ?? (defaultExport == null ? void 0 : defaultExport[prop]);
|
||||
},
|
||||
has(mod2, prop) {
|
||||
if (prop === "default")
|
||||
return defaultExport !== void 0;
|
||||
return prop in mod2 || defaultExport && prop in defaultExport;
|
||||
},
|
||||
getOwnPropertyDescriptor(mod2, prop) {
|
||||
const descriptor = Reflect.getOwnPropertyDescriptor(mod2, prop);
|
||||
if (descriptor)
|
||||
return descriptor;
|
||||
if (prop === "default" && defaultExport !== void 0) {
|
||||
return {
|
||||
value: defaultExport,
|
||||
enumerable: true,
|
||||
configurable: true
|
||||
};
|
||||
}
|
||||
}
|
||||
});
|
||||
}
|
||||
}
|
||||
function interopModule(mod) {
|
||||
if (utils.isPrimitive(mod)) {
|
||||
return {
|
||||
mod: { default: mod },
|
||||
defaultExport: mod
|
||||
};
|
||||
}
|
||||
let defaultExport = "default" in mod ? mod.default : mod;
|
||||
if (!utils.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 (utils.isPrimitive(sourceModule) || Array.isArray(sourceModule) || sourceModule instanceof Promise)
|
||||
return;
|
||||
for (const key in sourceModule) {
|
||||
if (key !== "default") {
|
||||
try {
|
||||
defineExport(exports, key, () => sourceModule[key]);
|
||||
} catch (_err) {
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
exports.DEFAULT_REQUEST_STUBS = DEFAULT_REQUEST_STUBS;
|
||||
exports.ModuleCacheMap = ModuleCacheMap;
|
||||
exports.ViteNodeRunner = ViteNodeRunner;
|
||||
+2
@@ -0,0 +1,2 @@
|
||||
export { e as DEFAULT_REQUEST_STUBS, M as ModuleCacheMap, a as ViteNodeRunner } from './index-O2IrwHKf.js';
|
||||
import './trace-mapping.d-xyIfZtPm.js';
|
||||
+450
@@ -0,0 +1,450 @@
|
||||
import { createRequire } from 'node:module';
|
||||
import { dirname } from 'node:path';
|
||||
import { pathToFileURL, fileURLToPath } from 'node:url';
|
||||
import vm from 'node:vm';
|
||||
import { resolve } from 'pathe';
|
||||
import createDebug from 'debug';
|
||||
import { createImportMetaEnvProxy, normalizeModuleId, slash, isInternalRequest, isNodeBuiltin, normalizeRequestId, toFilePath, cleanUrl, isPrimitive } from './utils.mjs';
|
||||
import { extractSourceMap } from './source-map.mjs';
|
||||
import 'node:fs';
|
||||
|
||||
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
|
||||
};
|
||||
class ModuleCacheMap 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) {
|
||||
var _a, _b;
|
||||
delete mod.evaluated;
|
||||
delete mod.resolving;
|
||||
delete mod.promise;
|
||||
delete mod.exports;
|
||||
(_a = mod.importers) == null ? void 0 : _a.clear();
|
||||
(_b = mod.imports) == null ? void 0 : _b.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 == null ? void 0 : 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]) => {
|
||||
var _a;
|
||||
return (_a = mod.importers) == null ? void 0 : _a.has(id);
|
||||
}).map(([key]) => key);
|
||||
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;
|
||||
}
|
||||
}
|
||||
class ViteNodeRunner {
|
||||
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);
|
||||
}
|
||||
root;
|
||||
debug;
|
||||
/**
|
||||
* Holds the cache of modules
|
||||
* Keys of the map are filepaths, or plain package names
|
||||
*/
|
||||
moduleCache;
|
||||
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:
|
||||
${[...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.
|
||||
${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) {
|
||||
var _a, _b;
|
||||
const dep = normalizeRequestId(id, this.options.base);
|
||||
if (!this.shouldResolveId(dep))
|
||||
return [dep, dep];
|
||||
const { path, exists } = toFilePath(dep, this.root);
|
||||
if (!this.options.resolveId || exists)
|
||||
return [dep, path];
|
||||
const resolved = await this.options.resolveId(dep, importer);
|
||||
if ((_b = (_a = resolved == null ? void 0 : resolved.meta) == null ? void 0 : _a["vite:alias"]) == null ? void 0 : _b.noResolved) {
|
||||
const error = 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);
|
||||
}
|
||||
/** @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 [id2, depFsPath] = await this.resolveUrl(String(dep), fsPath);
|
||||
const depMod = this.moduleCache.getByModuleId(depFsPath);
|
||||
depMod.importers.add(moduleId);
|
||||
mod.imports.add(depFsPath);
|
||||
return this.dependencyRequest(id2, depFsPath, callstack);
|
||||
};
|
||||
const requestStubs = this.options.requestStubs || DEFAULT_REQUEST_STUBS;
|
||||
if (id in requestStubs)
|
||||
return requestStubs[id];
|
||||
let { code: transformed, externalize } = await this.options.fetchModule(id);
|
||||
if (externalize) {
|
||||
debugNative(externalize);
|
||||
const exports2 = await this.interopedImport(externalize);
|
||||
mod.exports = exports2;
|
||||
return exports2;
|
||||
}
|
||||
if (transformed == null)
|
||||
throw new Error(`[vite-node] Failed to load "${id}" imported from ${callstack[callstack.length - 2]}`);
|
||||
const { Object: Object2, Reflect: Reflect2, Symbol: Symbol2 } = 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 = Object2.create(null);
|
||||
Object2.defineProperty(exports, Symbol2.toStringTag, {
|
||||
value: "Module",
|
||||
enumerable: false,
|
||||
configurable: false
|
||||
});
|
||||
const SYMBOL_NOT_DEFINED = Symbol2("not defined");
|
||||
let moduleExports = SYMBOL_NOT_DEFINED;
|
||||
const cjsExports = new Proxy(exports, {
|
||||
get: (target, p, receiver) => {
|
||||
if (Reflect2.has(target, p))
|
||||
return Reflect2.get(target, p, receiver);
|
||||
return Reflect2.get(Object2.prototype, p, receiver);
|
||||
},
|
||||
getPrototypeOf: () => Object2.prototype,
|
||||
set: (_, p, value) => {
|
||||
if (p === "default" && this.shouldInterop(modulePath, { default: value }) && cjsExports !== value) {
|
||||
exportAll(cjsExports, value);
|
||||
exports.default = value;
|
||||
return true;
|
||||
}
|
||||
if (!Reflect2.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;
|
||||
}
|
||||
});
|
||||
Object2.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) {
|
||||
Object2.defineProperty(meta, "hot", {
|
||||
enumerable: true,
|
||||
get: () => {
|
||||
var _a, _b;
|
||||
hotContext || (hotContext = (_b = (_a = this.options).createHotContext) == null ? void 0 : _b.call(_a, this, moduleId));
|
||||
return hotContext;
|
||||
},
|
||||
set: (value) => {
|
||||
hotContext = value;
|
||||
}
|
||||
});
|
||||
}
|
||||
const context = this.prepareContext({
|
||||
// esm transformed by Vite
|
||||
__vite_ssr_import__: request,
|
||||
__vite_ssr_dynamic_import__: request,
|
||||
__vite_ssr_exports__: exports,
|
||||
__vite_ssr_exportAll__: (obj) => exportAll(exports, obj),
|
||||
__vite_ssr_import_meta__: meta,
|
||||
// cjs compact
|
||||
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}
|
||||
}}`;
|
||||
const options = {
|
||||
filename: context.__filename,
|
||||
lineOffset: 0,
|
||||
columnOffset: -codeDefinition.length
|
||||
};
|
||||
const fn = vm.runInThisContext(code, options);
|
||||
await fn(...Object.values(context));
|
||||
}
|
||||
prepareContext(context) {
|
||||
return context;
|
||||
}
|
||||
/**
|
||||
* Define if a module should be interop-ed
|
||||
* This function mostly for the ability to override by subclass
|
||||
*/
|
||||
shouldInterop(path, mod) {
|
||||
if (this.options.interopDefault === false)
|
||||
return false;
|
||||
return !path.endsWith(".mjs") && "default" in mod;
|
||||
}
|
||||
importExternalModule(path) {
|
||||
return import(path);
|
||||
}
|
||||
/**
|
||||
* Import a module and interop it
|
||||
*/
|
||||
async interopedImport(path) {
|
||||
const importedModule = await this.importExternalModule(path);
|
||||
if (!this.shouldInterop(path, importedModule))
|
||||
return importedModule;
|
||||
const { mod, defaultExport } = interopModule(importedModule);
|
||||
return new Proxy(mod, {
|
||||
get(mod2, prop) {
|
||||
if (prop === "default")
|
||||
return defaultExport;
|
||||
return mod2[prop] ?? (defaultExport == null ? void 0 : defaultExport[prop]);
|
||||
},
|
||||
has(mod2, prop) {
|
||||
if (prop === "default")
|
||||
return defaultExport !== void 0;
|
||||
return prop in mod2 || defaultExport && prop in defaultExport;
|
||||
},
|
||||
getOwnPropertyDescriptor(mod2, prop) {
|
||||
const descriptor = Reflect.getOwnPropertyDescriptor(mod2, 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") {
|
||||
try {
|
||||
defineExport(exports, key, () => sourceModule[key]);
|
||||
} catch (_err) {
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
export { DEFAULT_REQUEST_STUBS, ModuleCacheMap, ViteNodeRunner };
|
||||
+39
@@ -0,0 +1,39 @@
|
||||
'use strict';
|
||||
|
||||
const KNOWN_ASSET_TYPES = [
|
||||
// images
|
||||
"apng",
|
||||
"png",
|
||||
"jpe?g",
|
||||
"jfif",
|
||||
"pjpeg",
|
||||
"pjp",
|
||||
"gif",
|
||||
"svg",
|
||||
"ico",
|
||||
"webp",
|
||||
"avif",
|
||||
// media
|
||||
"mp4",
|
||||
"webm",
|
||||
"ogg",
|
||||
"mp3",
|
||||
"wav",
|
||||
"flac",
|
||||
"aac",
|
||||
// fonts
|
||||
"woff2?",
|
||||
"eot",
|
||||
"ttf",
|
||||
"otf",
|
||||
// other
|
||||
"webmanifest",
|
||||
"pdf",
|
||||
"txt"
|
||||
];
|
||||
const KNOWN_ASSET_RE = new RegExp(`\\.(${KNOWN_ASSET_TYPES.join("|")})$`);
|
||||
const CSS_LANGS_RE = /\.(css|less|sass|scss|styl|stylus|pcss|postcss|sss)(?:$|\?)/;
|
||||
|
||||
exports.CSS_LANGS_RE = CSS_LANGS_RE;
|
||||
exports.KNOWN_ASSET_RE = KNOWN_ASSET_RE;
|
||||
exports.KNOWN_ASSET_TYPES = KNOWN_ASSET_TYPES;
|
||||
+5
@@ -0,0 +1,5 @@
|
||||
declare const KNOWN_ASSET_TYPES: string[];
|
||||
declare const KNOWN_ASSET_RE: RegExp;
|
||||
declare const CSS_LANGS_RE: RegExp;
|
||||
|
||||
export { CSS_LANGS_RE, KNOWN_ASSET_RE, KNOWN_ASSET_TYPES };
|
||||
+35
@@ -0,0 +1,35 @@
|
||||
const KNOWN_ASSET_TYPES = [
|
||||
// images
|
||||
"apng",
|
||||
"png",
|
||||
"jpe?g",
|
||||
"jfif",
|
||||
"pjpeg",
|
||||
"pjp",
|
||||
"gif",
|
||||
"svg",
|
||||
"ico",
|
||||
"webp",
|
||||
"avif",
|
||||
// media
|
||||
"mp4",
|
||||
"webm",
|
||||
"ogg",
|
||||
"mp3",
|
||||
"wav",
|
||||
"flac",
|
||||
"aac",
|
||||
// fonts
|
||||
"woff2?",
|
||||
"eot",
|
||||
"ttf",
|
||||
"otf",
|
||||
// other
|
||||
"webmanifest",
|
||||
"pdf",
|
||||
"txt"
|
||||
];
|
||||
const KNOWN_ASSET_RE = new RegExp(`\\.(${KNOWN_ASSET_TYPES.join("|")})$`);
|
||||
const CSS_LANGS_RE = /\.(css|less|sass|scss|styl|stylus|pcss|postcss|sss)(?:$|\?)/;
|
||||
|
||||
export { CSS_LANGS_RE, KNOWN_ASSET_RE, KNOWN_ASSET_TYPES };
|
||||
+21
@@ -0,0 +1,21 @@
|
||||
'use strict';
|
||||
|
||||
var hmr = require('./chunk-hmr.cjs');
|
||||
require('node:events');
|
||||
require('picocolors');
|
||||
require('debug');
|
||||
require('./utils.cjs');
|
||||
require('node:url');
|
||||
require('node:module');
|
||||
require('node:fs');
|
||||
require('pathe');
|
||||
|
||||
|
||||
|
||||
exports.createHmrEmitter = hmr.createHmrEmitter;
|
||||
exports.createHotContext = hmr.createHotContext;
|
||||
exports.getCache = hmr.getCache;
|
||||
exports.handleMessage = hmr.handleMessage;
|
||||
exports.reload = hmr.reload;
|
||||
exports.sendMessageBuffer = hmr.sendMessageBuffer;
|
||||
exports.viteNodeHmrPlugin = hmr.viteNodeHmrPlugin;
|
||||
+54
@@ -0,0 +1,54 @@
|
||||
import { EventEmitter } from 'node:events';
|
||||
import { HMRPayload, Plugin } from 'vite';
|
||||
import { C as CustomEventMap, a as ViteNodeRunner, H as HMRPayload$1, b as HotContext } from './index-O2IrwHKf.js';
|
||||
import './trace-mapping.d-xyIfZtPm.js';
|
||||
|
||||
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;
|
||||
|
||||
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;
|
||||
|
||||
export { type Emitter, type EventType, type HMREmitter, type Handler, type HotCallback, type HotModule, type InferCustomEventPayload, type ModuleNamespace, createHmrEmitter, createHotContext, getCache, handleMessage, reload, sendMessageBuffer, viteNodeHmrPlugin };
|
||||
+9
@@ -0,0 +1,9 @@
|
||||
export { c as createHmrEmitter, a as createHotContext, g as getCache, h as handleMessage, r as reload, s as sendMessageBuffer, v as viteNodeHmrPlugin } from './chunk-hmr.mjs';
|
||||
import 'node:events';
|
||||
import 'picocolors';
|
||||
import 'debug';
|
||||
import './utils.mjs';
|
||||
import 'node:url';
|
||||
import 'node:module';
|
||||
import 'node:fs';
|
||||
import 'pathe';
|
||||
+309
@@ -0,0 +1,309 @@
|
||||
import { E as EncodedSourceMap } from './trace-mapping.d-xyIfZtPm.js';
|
||||
|
||||
type HMRPayload =
|
||||
| ConnectedPayload
|
||||
| UpdatePayload
|
||||
| FullReloadPayload
|
||||
| CustomPayload
|
||||
| ErrorPayload
|
||||
| PrunePayload
|
||||
|
||||
interface ConnectedPayload {
|
||||
type: 'connected'
|
||||
}
|
||||
|
||||
interface UpdatePayload {
|
||||
type: 'update'
|
||||
updates: Update[]
|
||||
}
|
||||
|
||||
interface Update {
|
||||
type: 'js-update' | 'css-update'
|
||||
path: string
|
||||
acceptedPath: string
|
||||
timestamp: number
|
||||
/** @internal */
|
||||
explicitImportRequired?: boolean
|
||||
/** @internal */
|
||||
isWithinCircularImport?: boolean
|
||||
/** @internal */
|
||||
ssrInvalidates?: string[]
|
||||
}
|
||||
|
||||
interface PrunePayload {
|
||||
type: 'prune'
|
||||
paths: string[]
|
||||
}
|
||||
|
||||
interface FullReloadPayload {
|
||||
type: 'full-reload'
|
||||
path?: string
|
||||
/** @internal */
|
||||
triggeredBy?: string
|
||||
}
|
||||
|
||||
interface CustomPayload {
|
||||
type: 'custom'
|
||||
event: string
|
||||
data?: any
|
||||
}
|
||||
|
||||
interface ErrorPayload {
|
||||
type: 'error'
|
||||
err: {
|
||||
[name: string]: any
|
||||
message: string
|
||||
stack: string
|
||||
id?: string
|
||||
frame?: string
|
||||
plugin?: string
|
||||
pluginCode?: string
|
||||
loc?: {
|
||||
file?: string
|
||||
line: number
|
||||
column: number
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
interface CustomEventMap {
|
||||
'vite:beforeUpdate': UpdatePayload
|
||||
'vite:afterUpdate': UpdatePayload
|
||||
'vite:beforePrune': PrunePayload
|
||||
'vite:beforeFullReload': FullReloadPayload
|
||||
'vite:error': ErrorPayload
|
||||
'vite:invalidate': InvalidatePayload
|
||||
'vite:ws:connect': WebSocketConnectionPayload
|
||||
'vite:ws:disconnect': WebSocketConnectionPayload
|
||||
}
|
||||
|
||||
interface WebSocketConnectionPayload {
|
||||
/**
|
||||
* @experimental
|
||||
* We expose this instance experimentally to see potential usage.
|
||||
* This might be removed in the future if we didn't find reasonable use cases.
|
||||
* If you find this useful, please open an issue with details so we can discuss and make it stable API.
|
||||
*/
|
||||
webSocket: WebSocket
|
||||
}
|
||||
|
||||
interface InvalidatePayload {
|
||||
path: string
|
||||
message: string | undefined
|
||||
}
|
||||
|
||||
/**
|
||||
* provides types for built-in Vite events
|
||||
*/
|
||||
type InferCustomEventPayload<T extends string> =
|
||||
T extends keyof CustomEventMap ? CustomEventMap[T] : any
|
||||
|
||||
type ModuleNamespace = Record<string, any> & {
|
||||
[Symbol.toStringTag]: 'Module'
|
||||
}
|
||||
|
||||
interface ViteHotContext {
|
||||
readonly data: any
|
||||
|
||||
accept(): void
|
||||
accept(cb: (mod: ModuleNamespace | undefined) => void): void
|
||||
accept(dep: string, cb: (mod: ModuleNamespace | undefined) => void): void
|
||||
accept(
|
||||
deps: readonly string[],
|
||||
cb: (mods: Array<ModuleNamespace | undefined>) => void,
|
||||
): void
|
||||
|
||||
acceptExports(
|
||||
exportNames: string | readonly string[],
|
||||
cb?: (mod: ModuleNamespace | undefined) => void,
|
||||
): void
|
||||
|
||||
dispose(cb: (data: any) => void): void
|
||||
prune(cb: (data: any) => void): void
|
||||
invalidate(message?: string): void
|
||||
|
||||
on<T extends string>(
|
||||
event: T,
|
||||
cb: (payload: InferCustomEventPayload<T>) => void,
|
||||
): void
|
||||
off<T extends string>(
|
||||
event: T,
|
||||
cb: (payload: InferCustomEventPayload<T>) => void,
|
||||
): void
|
||||
send<T extends string>(event: T, data?: InferCustomEventPayload<T>): void
|
||||
}
|
||||
|
||||
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, "imports" | "importers">>;
|
||||
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): EncodedSourceMap | null;
|
||||
}
|
||||
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;
|
||||
constructor(options: ViteNodeRunnerOptions);
|
||||
executeFile(file: string): Promise<any>;
|
||||
executeId(rawId: string): Promise<any>;
|
||||
/** @internal */
|
||||
cachedRequest(id: string, fsPath: string, callstack: string[]): Promise<any>;
|
||||
shouldResolveId(id: string, _importee?: string): boolean;
|
||||
private _resolveUrl;
|
||||
resolveUrl(id: string, importee?: string): Promise<[url: string, fsPath: string]>;
|
||||
/** @internal */
|
||||
dependencyRequest(id: string, fsPath: string, callstack: string[]): Promise<any>;
|
||||
/** @internal */
|
||||
directRequest(id: string, fsPath: string, _callstack: string[]): Promise<any>;
|
||||
protected getContextPrimitives(): {
|
||||
Object: ObjectConstructor;
|
||||
Reflect: typeof Reflect;
|
||||
Symbol: SymbolConstructor;
|
||||
};
|
||||
protected runModule(context: Record<string, any>, transformed: string): Promise<void>;
|
||||
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>;
|
||||
}
|
||||
|
||||
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;
|
||||
/**
|
||||
* 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;
|
||||
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 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;
|
||||
}
|
||||
|
||||
export { type Arrayable as A, type CustomEventMap as C, type DebuggerOptions as D, type FetchResult as F, type HMRPayload as H, ModuleCacheMap as M, type Nullable as N, type RawSourceMap as R, type StartOfSourceMap as S, type ViteNodeServerOptions as V, ViteNodeRunner as a, type HotContext as b, type DepsHandlingOptions as c, type ViteNodeResolveId as d, DEFAULT_REQUEST_STUBS as e, type Awaitable as f, type FetchFunction as g, type ResolveIdFunction as h, type CreateHotContextFunction as i, type ModuleCache as j, type ViteNodeRunnerOptions as k };
|
||||
+2
@@ -0,0 +1,2 @@
|
||||
'use strict';
|
||||
|
||||
+2
@@ -0,0 +1,2 @@
|
||||
export { A as Arrayable, f as Awaitable, i as CreateHotContextFunction, D as DebuggerOptions, c as DepsHandlingOptions, g as FetchFunction, F as FetchResult, b as HotContext, j as ModuleCache, M as ModuleCacheMap, N as Nullable, R as RawSourceMap, h as ResolveIdFunction, S as StartOfSourceMap, d as ViteNodeResolveId, k as ViteNodeRunnerOptions, V as ViteNodeServerOptions } from './index-O2IrwHKf.js';
|
||||
export { D as DecodedSourceMap, E as EncodedSourceMap, S as SourceMapInput } from './trace-mapping.d-xyIfZtPm.js';
|
||||
+1
@@ -0,0 +1 @@
|
||||
|
||||
+445
@@ -0,0 +1,445 @@
|
||||
'use strict';
|
||||
|
||||
var node_perf_hooks = require('node:perf_hooks');
|
||||
var fs = require('node:fs');
|
||||
var assert = require('node:assert');
|
||||
var pathe = require('pathe');
|
||||
var createDebug = require('debug');
|
||||
var utils = require('./utils.cjs');
|
||||
var constants = require('./constants.cjs');
|
||||
var c = require('picocolors');
|
||||
var sourceMap = require('./source-map.cjs');
|
||||
require('node:url');
|
||||
require('node:module');
|
||||
require('node:path');
|
||||
|
||||
const BUILTIN_EXTENSIONS = /* @__PURE__ */ new Set([".mjs", ".cjs", ".node", ".wasm"]);
|
||||
const ESM_SYNTAX_RE = /([\s;]|^)(import[\s\w*,{}]*from|import\s*["'*{]|export\b\s*(?:[*{]|default|class|type|function|const|var|let|async function)|import\.meta\b)/m;
|
||||
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$/,
|
||||
// special Vite query strings
|
||||
/[?&](init|raw|url|inline)\b/,
|
||||
// Vite returns a string for assets imports, even if it's inside "node_modules"
|
||||
new RegExp(`\\.(${constants.KNOWN_ASSET_TYPES.join("|")})$`)
|
||||
];
|
||||
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 (fs.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 (fs.existsSync(i))
|
||||
return i;
|
||||
}
|
||||
}
|
||||
}
|
||||
async function isValidNodeImport(id) {
|
||||
const extension = pathe.extname(id);
|
||||
if (BUILTIN_EXTENSIONS.has(extension))
|
||||
return true;
|
||||
if (extension !== ".js")
|
||||
return false;
|
||||
id = id.replace("file:///", "");
|
||||
const package_ = await utils.findNearestPackageData(pathe.dirname(id));
|
||||
if (package_.type === "module")
|
||||
return true;
|
||||
if (/\.(\w+-)?esm?(-\w+)?\.js$|\/(esm?)\//.test(id))
|
||||
return false;
|
||||
const code = await fs.promises.readFile(id, "utf8").catch(() => "");
|
||||
return !ESM_SYNTAX_RE.test(code);
|
||||
}
|
||||
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 (utils.isNodeBuiltin(id))
|
||||
return id;
|
||||
if (id.startsWith("data:") || /^(https?:)?\/\//.test(id))
|
||||
return id;
|
||||
id = patchWindowsImportPath(id);
|
||||
if ((options == null ? void 0 : options.cacheDir) && id.includes(options.cacheDir))
|
||||
return id;
|
||||
const moduleDirectories = (options == null ? void 0 : options.moduleDirectories) || ["/node_modules/"];
|
||||
if (matchExternalizePattern(id, moduleDirectories, options == null ? void 0 : options.inline))
|
||||
return false;
|
||||
if (matchExternalizePattern(id, moduleDirectories, options == null ? void 0 : options.external))
|
||||
return id;
|
||||
const isLibraryModule = moduleDirectories.some((dir) => id.includes(dir));
|
||||
const guessCJS = isLibraryModule && (options == null ? void 0 : options.fallbackCJS);
|
||||
id = guessCJS ? 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(pathe.join(dir, ex))))
|
||||
return true;
|
||||
} else {
|
||||
if (ex.test(id))
|
||||
return true;
|
||||
}
|
||||
}
|
||||
return false;
|
||||
}
|
||||
function patchWindowsImportPath(path) {
|
||||
if (path.match(/^\w:\\/))
|
||||
return `file:///${utils.slash(path)}`;
|
||||
else if (path.match(/^\w:\//))
|
||||
return `file:///${path}`;
|
||||
else
|
||||
return path;
|
||||
}
|
||||
|
||||
function hashCode(s) {
|
||||
return s.split("").reduce((a, b) => {
|
||||
a = (a << 5) - a + b.charCodeAt(0);
|
||||
return a & a;
|
||||
}, 0);
|
||||
}
|
||||
class Debugger {
|
||||
constructor(root, options) {
|
||||
this.options = options;
|
||||
if (options.dumpModules)
|
||||
this.dumpDir = pathe.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();
|
||||
}
|
||||
dumpDir;
|
||||
initPromise;
|
||||
externalizeMap = /* @__PURE__ */ new Map();
|
||||
async clearDump() {
|
||||
if (!this.dumpDir)
|
||||
return;
|
||||
if (!this.options.loadDumppedModules && fs.existsSync(this.dumpDir))
|
||||
await fs.promises.rm(this.dumpDir, { recursive: true, force: true });
|
||||
await fs.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 fs.promises.writeFile(pathe.join(this.dumpDir, name), `// ${id.replace(/\0/g, "\\0")}
|
||||
${result.code}`, "utf-8");
|
||||
}
|
||||
async loadDump(id) {
|
||||
if (!this.dumpDir)
|
||||
return null;
|
||||
await this.initPromise;
|
||||
const name = this.encodeId(id);
|
||||
const path = pathe.join(this.dumpDir, name);
|
||||
if (!fs.existsSync(path))
|
||||
return null;
|
||||
const code = await fs.promises.readFile(path, "utf-8");
|
||||
return {
|
||||
code: code.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 fs.promises.writeFile(pathe.join(this.dumpDir, "info.json"), info, "utf-8");
|
||||
}
|
||||
}
|
||||
|
||||
const debugRequest = createDebug("vite-node:server:request");
|
||||
class ViteNodeServer {
|
||||
constructor(server, options = {}) {
|
||||
this.server = server;
|
||||
this.options = options;
|
||||
var _a, _b, _c;
|
||||
const ssrOptions = server.config.ssr;
|
||||
options.deps ?? (options.deps = {});
|
||||
options.deps.cacheDir = pathe.relative(server.config.root, options.deps.cacheDir || server.config.cacheDir);
|
||||
if (ssrOptions) {
|
||||
if (ssrOptions.noExternal === true) {
|
||||
(_a = options.deps).inline ?? (_a.inline = true);
|
||||
} else if (options.deps.inline !== true) {
|
||||
(_b = options.deps).inline ?? (_b.inline = []);
|
||||
const inline = options.deps.inline;
|
||||
options.deps.inline.push(...utils.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);
|
||||
(_c = options.deps).moduleDirectories ?? (_c.moduleDirectories = []);
|
||||
const envValue = process.env.VITE_NODE_DEPS_MODULE_DIRECTORIES || process.env.npm_config_VITE_NODE_DEPS_MODULE_DIRECTORIES;
|
||||
const customModuleDirectories = envValue == null ? void 0 : envValue.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 pathe.normalize(dir);
|
||||
});
|
||||
if (!options.deps.moduleDirectories.includes("/node_modules/"))
|
||||
options.deps.moduleDirectories.push("/node_modules/");
|
||||
}
|
||||
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;
|
||||
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 (fs.existsSync(id)) {
|
||||
this.existingOptimizedDeps.add(id);
|
||||
return true;
|
||||
}
|
||||
return new Promise((resolve2) => {
|
||||
setTimeout(() => {
|
||||
this.ensureExists(id).then(() => {
|
||||
resolve2(true);
|
||||
});
|
||||
});
|
||||
});
|
||||
}
|
||||
async resolveId(id, importer, transformMode) {
|
||||
if (importer && !importer.startsWith(utils.withTrailingSlash(this.server.config.root)))
|
||||
importer = pathe.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) {
|
||||
var _a, _b;
|
||||
const fetchResult = (_a = this.fetchCache.get(source)) == null ? void 0 : _a.result;
|
||||
if (fetchResult == null ? void 0 : fetchResult.map)
|
||||
return fetchResult.map;
|
||||
const ssrTransformResult = (_b = this.server.moduleGraph.getModuleById(source)) == null ? void 0 : _b.ssrTransformResult;
|
||||
return (ssrTransformResult == null ? void 0 : 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 = utils.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 = utils.normalizeModuleId(id);
|
||||
const mod = this.server.moduleGraph.getModuleById(normalizedId);
|
||||
const result = (mod == null ? void 0 : mod.transformResult) || await this.server.transformRequest(normalizedId);
|
||||
return {
|
||||
code: result == null ? void 0 : result.code
|
||||
};
|
||||
}
|
||||
getTransformMode(id) {
|
||||
var _a, _b, _c, _d;
|
||||
const withoutQuery = id.split("?")[0];
|
||||
if ((_b = (_a = this.options.transformMode) == null ? void 0 : _a.web) == null ? void 0 : _b.some((r) => withoutQuery.match(r)))
|
||||
return "web";
|
||||
if ((_d = (_c = this.options.transformMode) == null ? void 0 : _c.ssr) == null ? void 0 : _d.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;
|
||||
const modules = [..._modules];
|
||||
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) {
|
||||
var _a, _b;
|
||||
let result;
|
||||
const cacheDir = (_a = this.options.deps) == null ? void 0 : _a.cacheDir;
|
||||
if (cacheDir && id.includes(cacheDir)) {
|
||||
if (!id.startsWith(utils.withTrailingSlash(this.server.config.root)))
|
||||
id = pathe.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 } = utils.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 };
|
||||
(_b = this.debugger) == null ? void 0 : _b.recordExternalize(id, externalize);
|
||||
} else {
|
||||
const start = node_perf_hooks.performance.now();
|
||||
const r = await this._transformRequest(id, filePath, transformMode);
|
||||
duration = node_perf_hooks.performance.now() - start;
|
||||
result = { code: r == null ? void 0 : r.code, map: r == null ? void 0 : 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) {
|
||||
const mod = this.server.moduleGraph.getModuleById(filepath);
|
||||
return sourceMap.withInlineSourcemap(result, {
|
||||
filepath: (mod == null ? void 0 : mod.file) || filepath,
|
||||
root: this.server.config.root
|
||||
});
|
||||
}
|
||||
async _transformRequest(id, filepath, transformMode) {
|
||||
var _a, _b, _c, _d;
|
||||
debugRequest(id);
|
||||
let result = null;
|
||||
if ((_a = this.options.debug) == null ? void 0 : _a.loadDumppedModules) {
|
||||
result = await ((_b = this.debugger) == null ? void 0 : _b.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 });
|
||||
}
|
||||
const sourcemap = this.options.sourcemap ?? "inline";
|
||||
if (sourcemap === "inline" && result && !id.includes("node_modules"))
|
||||
result = await this.processTransformResult(filepath, result);
|
||||
if ((_c = this.options.debug) == null ? void 0 : _c.dumpModules)
|
||||
await ((_d = this.debugger) == null ? void 0 : _d.dumpFile(id, result));
|
||||
return result;
|
||||
}
|
||||
}
|
||||
|
||||
exports.ViteNodeServer = ViteNodeServer;
|
||||
exports.guessCJSversion = guessCJSversion;
|
||||
exports.shouldExternalize = shouldExternalize;
|
||||
+61
@@ -0,0 +1,61 @@
|
||||
import { TransformResult, ViteDevServer } from 'vite';
|
||||
import { D as DebuggerOptions, c as DepsHandlingOptions, V as ViteNodeServerOptions, d as ViteNodeResolveId, F as FetchResult } from './index-O2IrwHKf.js';
|
||||
import { E as EncodedSourceMap } from './trace-mapping.d-xyIfZtPm.js';
|
||||
|
||||
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>;
|
||||
}
|
||||
|
||||
declare function guessCJSversion(id: string): string | undefined;
|
||||
declare function shouldExternalize(id: string, options?: DepsHandlingOptions, cache?: Map<string, Promise<string | false>>): Promise<string | false>;
|
||||
|
||||
interface FetchCache {
|
||||
duration?: number;
|
||||
timestamp: number;
|
||||
result: FetchResult;
|
||||
}
|
||||
declare class ViteNodeServer {
|
||||
server: ViteDevServer;
|
||||
options: ViteNodeServerOptions;
|
||||
private fetchPromiseMap;
|
||||
private transformPromiseMap;
|
||||
private durations;
|
||||
private existingOptimizedDeps;
|
||||
fetchCaches: {
|
||||
ssr: Map<string, FetchCache>;
|
||||
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): "web" | "ssr";
|
||||
private getChangedModule;
|
||||
private _fetchModule;
|
||||
protected processTransformResult(filepath: string, result: TransformResult): Promise<TransformResult>;
|
||||
private _transformRequest;
|
||||
}
|
||||
|
||||
export { ViteNodeServer, guessCJSversion, shouldExternalize };
|
||||
+441
@@ -0,0 +1,441 @@
|
||||
import { performance } from 'node:perf_hooks';
|
||||
import { existsSync, promises } from 'node:fs';
|
||||
import assert from 'node:assert';
|
||||
import { join, extname, dirname, resolve, relative, normalize } from 'pathe';
|
||||
import createDebug from 'debug';
|
||||
import { isNodeBuiltin, slash, findNearestPackageData, toArray, withTrailingSlash, normalizeModuleId, toFilePath } from './utils.mjs';
|
||||
import { KNOWN_ASSET_TYPES } from './constants.mjs';
|
||||
import c from 'picocolors';
|
||||
import { withInlineSourcemap } from './source-map.mjs';
|
||||
import 'node:url';
|
||||
import 'node:module';
|
||||
import 'node:path';
|
||||
|
||||
const BUILTIN_EXTENSIONS = /* @__PURE__ */ new Set([".mjs", ".cjs", ".node", ".wasm"]);
|
||||
const ESM_SYNTAX_RE = /([\s;]|^)(import[\s\w*,{}]*from|import\s*["'*{]|export\b\s*(?:[*{]|default|class|type|function|const|var|let|async function)|import\.meta\b)/m;
|
||||
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$/,
|
||||
// special Vite query strings
|
||||
/[?&](init|raw|url|inline)\b/,
|
||||
// Vite returns a string for assets imports, even if it's inside "node_modules"
|
||||
new RegExp(`\\.(${KNOWN_ASSET_TYPES.join("|")})$`)
|
||||
];
|
||||
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:///", "");
|
||||
const package_ = await findNearestPackageData(dirname(id));
|
||||
if (package_.type === "module")
|
||||
return true;
|
||||
if (/\.(\w+-)?esm?(-\w+)?\.js$|\/(esm?)\//.test(id))
|
||||
return false;
|
||||
const code = await promises.readFile(id, "utf8").catch(() => "");
|
||||
return !ESM_SYNTAX_RE.test(code);
|
||||
}
|
||||
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);
|
||||
if ((options == null ? void 0 : options.cacheDir) && id.includes(options.cacheDir))
|
||||
return id;
|
||||
const moduleDirectories = (options == null ? void 0 : options.moduleDirectories) || ["/node_modules/"];
|
||||
if (matchExternalizePattern(id, moduleDirectories, options == null ? void 0 : options.inline))
|
||||
return false;
|
||||
if (matchExternalizePattern(id, moduleDirectories, options == null ? void 0 : options.external))
|
||||
return id;
|
||||
const isLibraryModule = moduleDirectories.some((dir) => id.includes(dir));
|
||||
const guessCJS = isLibraryModule && (options == null ? void 0 : options.fallbackCJS);
|
||||
id = guessCJS ? 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;
|
||||
}
|
||||
|
||||
function hashCode(s) {
|
||||
return s.split("").reduce((a, b) => {
|
||||
a = (a << 5) - a + b.charCodeAt(0);
|
||||
return a & a;
|
||||
}, 0);
|
||||
}
|
||||
class Debugger {
|
||||
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();
|
||||
}
|
||||
dumpDir;
|
||||
initPromise;
|
||||
externalizeMap = /* @__PURE__ */ new Map();
|
||||
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")}
|
||||
${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;
|
||||
const code = await promises.readFile(path, "utf-8");
|
||||
return {
|
||||
code: code.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");
|
||||
}
|
||||
}
|
||||
|
||||
const debugRequest = createDebug("vite-node:server:request");
|
||||
class ViteNodeServer {
|
||||
constructor(server, options = {}) {
|
||||
this.server = server;
|
||||
this.options = options;
|
||||
var _a, _b, _c;
|
||||
const ssrOptions = server.config.ssr;
|
||||
options.deps ?? (options.deps = {});
|
||||
options.deps.cacheDir = relative(server.config.root, options.deps.cacheDir || server.config.cacheDir);
|
||||
if (ssrOptions) {
|
||||
if (ssrOptions.noExternal === true) {
|
||||
(_a = options.deps).inline ?? (_a.inline = true);
|
||||
} else if (options.deps.inline !== true) {
|
||||
(_b = options.deps).inline ?? (_b.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);
|
||||
(_c = options.deps).moduleDirectories ?? (_c.moduleDirectories = []);
|
||||
const envValue = process.env.VITE_NODE_DEPS_MODULE_DIRECTORIES || process.env.npm_config_VITE_NODE_DEPS_MODULE_DIRECTORIES;
|
||||
const customModuleDirectories = envValue == null ? void 0 : envValue.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/");
|
||||
}
|
||||
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;
|
||||
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((resolve2) => {
|
||||
setTimeout(() => {
|
||||
this.ensureExists(id).then(() => {
|
||||
resolve2(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) {
|
||||
var _a, _b;
|
||||
const fetchResult = (_a = this.fetchCache.get(source)) == null ? void 0 : _a.result;
|
||||
if (fetchResult == null ? void 0 : fetchResult.map)
|
||||
return fetchResult.map;
|
||||
const ssrTransformResult = (_b = this.server.moduleGraph.getModuleById(source)) == null ? void 0 : _b.ssrTransformResult;
|
||||
return (ssrTransformResult == null ? void 0 : 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);
|
||||
const mod = this.server.moduleGraph.getModuleById(normalizedId);
|
||||
const result = (mod == null ? void 0 : mod.transformResult) || await this.server.transformRequest(normalizedId);
|
||||
return {
|
||||
code: result == null ? void 0 : result.code
|
||||
};
|
||||
}
|
||||
getTransformMode(id) {
|
||||
var _a, _b, _c, _d;
|
||||
const withoutQuery = id.split("?")[0];
|
||||
if ((_b = (_a = this.options.transformMode) == null ? void 0 : _a.web) == null ? void 0 : _b.some((r) => withoutQuery.match(r)))
|
||||
return "web";
|
||||
if ((_d = (_c = this.options.transformMode) == null ? void 0 : _c.ssr) == null ? void 0 : _d.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;
|
||||
const modules = [..._modules];
|
||||
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) {
|
||||
var _a, _b;
|
||||
let result;
|
||||
const cacheDir = (_a = this.options.deps) == null ? void 0 : _a.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 };
|
||||
(_b = this.debugger) == null ? void 0 : _b.recordExternalize(id, externalize);
|
||||
} else {
|
||||
const start = performance.now();
|
||||
const r = await this._transformRequest(id, filePath, transformMode);
|
||||
duration = performance.now() - start;
|
||||
result = { code: r == null ? void 0 : r.code, map: r == null ? void 0 : 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) {
|
||||
const mod = this.server.moduleGraph.getModuleById(filepath);
|
||||
return withInlineSourcemap(result, {
|
||||
filepath: (mod == null ? void 0 : mod.file) || filepath,
|
||||
root: this.server.config.root
|
||||
});
|
||||
}
|
||||
async _transformRequest(id, filepath, transformMode) {
|
||||
var _a, _b, _c, _d;
|
||||
debugRequest(id);
|
||||
let result = null;
|
||||
if ((_a = this.options.debug) == null ? void 0 : _a.loadDumppedModules) {
|
||||
result = await ((_b = this.debugger) == null ? void 0 : _b.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 });
|
||||
}
|
||||
const sourcemap = this.options.sourcemap ?? "inline";
|
||||
if (sourcemap === "inline" && result && !id.includes("node_modules"))
|
||||
result = await this.processTransformResult(filepath, result);
|
||||
if ((_c = this.options.debug) == null ? void 0 : _c.dumpModules)
|
||||
await ((_d = this.debugger) == null ? void 0 : _d.dumpFile(id, result));
|
||||
return result;
|
||||
}
|
||||
}
|
||||
|
||||
export { ViteNodeServer, guessCJSversion, shouldExternalize };
|
||||
+918
@@ -0,0 +1,918 @@
|
||||
'use strict';
|
||||
|
||||
var pathe = require('pathe');
|
||||
var utils = require('./utils.cjs');
|
||||
var path = require('node:path');
|
||||
var fs = require('node:fs');
|
||||
require('node:url');
|
||||
require('node:module');
|
||||
|
||||
const comma = ','.charCodeAt(0);
|
||||
const chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/';
|
||||
const intToChar = new Uint8Array(64); // 64 possible chars.
|
||||
const charToInt = new Uint8Array(128); // z is 122 in ASCII
|
||||
for (let i = 0; i < chars.length; i++) {
|
||||
const c = chars.charCodeAt(i);
|
||||
intToChar[i] = c;
|
||||
charToInt[c] = i;
|
||||
}
|
||||
function decode(mappings) {
|
||||
const state = new Int32Array(5);
|
||||
const decoded = [];
|
||||
let index = 0;
|
||||
do {
|
||||
const semi = indexOf(mappings, index);
|
||||
const line = [];
|
||||
let sorted = true;
|
||||
let lastCol = 0;
|
||||
state[0] = 0;
|
||||
for (let i = index; i < semi; i++) {
|
||||
let seg;
|
||||
i = decodeInteger(mappings, i, state, 0); // genColumn
|
||||
const col = state[0];
|
||||
if (col < lastCol)
|
||||
sorted = false;
|
||||
lastCol = col;
|
||||
if (hasMoreVlq(mappings, i, semi)) {
|
||||
i = decodeInteger(mappings, i, state, 1); // sourcesIndex
|
||||
i = decodeInteger(mappings, i, state, 2); // sourceLine
|
||||
i = decodeInteger(mappings, i, state, 3); // sourceColumn
|
||||
if (hasMoreVlq(mappings, i, semi)) {
|
||||
i = decodeInteger(mappings, i, state, 4); // namesIndex
|
||||
seg = [col, state[1], state[2], state[3], state[4]];
|
||||
}
|
||||
else {
|
||||
seg = [col, state[1], state[2], state[3]];
|
||||
}
|
||||
}
|
||||
else {
|
||||
seg = [col];
|
||||
}
|
||||
line.push(seg);
|
||||
}
|
||||
if (!sorted)
|
||||
sort(line);
|
||||
decoded.push(line);
|
||||
index = semi + 1;
|
||||
} while (index <= mappings.length);
|
||||
return decoded;
|
||||
}
|
||||
function indexOf(mappings, index) {
|
||||
const idx = mappings.indexOf(';', index);
|
||||
return idx === -1 ? mappings.length : idx;
|
||||
}
|
||||
function decodeInteger(mappings, pos, state, j) {
|
||||
let value = 0;
|
||||
let shift = 0;
|
||||
let integer = 0;
|
||||
do {
|
||||
const c = mappings.charCodeAt(pos++);
|
||||
integer = charToInt[c];
|
||||
value |= (integer & 31) << shift;
|
||||
shift += 5;
|
||||
} while (integer & 32);
|
||||
const shouldNegate = value & 1;
|
||||
value >>>= 1;
|
||||
if (shouldNegate) {
|
||||
value = -0x80000000 | -value;
|
||||
}
|
||||
state[j] += value;
|
||||
return pos;
|
||||
}
|
||||
function hasMoreVlq(mappings, i, length) {
|
||||
if (i >= length)
|
||||
return false;
|
||||
return mappings.charCodeAt(i) !== comma;
|
||||
}
|
||||
function sort(line) {
|
||||
line.sort(sortComparator$1);
|
||||
}
|
||||
function sortComparator$1(a, b) {
|
||||
return a[0] - b[0];
|
||||
}
|
||||
|
||||
// Matches the scheme of a URL, eg "http://"
|
||||
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;
|
||||
var UrlType;
|
||||
(function (UrlType) {
|
||||
UrlType[UrlType["Empty"] = 1] = "Empty";
|
||||
UrlType[UrlType["Hash"] = 2] = "Hash";
|
||||
UrlType[UrlType["Query"] = 3] = "Query";
|
||||
UrlType[UrlType["RelativePath"] = 4] = "RelativePath";
|
||||
UrlType[UrlType["AbsolutePath"] = 5] = "AbsolutePath";
|
||||
UrlType[UrlType["SchemeRelative"] = 6] = "SchemeRelative";
|
||||
UrlType[UrlType["Absolute"] = 7] = "Absolute";
|
||||
})(UrlType || (UrlType = {}));
|
||||
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 = match[2];
|
||||
return makeUrl('file:', '', match[1] || '', '', isAbsolutePath(path) ? path : '/' + path, match[3] || '', match[4] || '');
|
||||
}
|
||||
function makeUrl(scheme, user, host, port, path, query, hash) {
|
||||
return {
|
||||
scheme,
|
||||
user,
|
||||
host,
|
||||
port,
|
||||
path,
|
||||
query,
|
||||
hash,
|
||||
type: UrlType.Absolute,
|
||||
};
|
||||
}
|
||||
function parseUrl(input) {
|
||||
if (isSchemeRelativeUrl(input)) {
|
||||
const url = parseAbsoluteUrl('http:' + input);
|
||||
url.scheme = '';
|
||||
url.type = UrlType.SchemeRelative;
|
||||
return url;
|
||||
}
|
||||
if (isAbsolutePath(input)) {
|
||||
const url = parseAbsoluteUrl('http://foo.com' + input);
|
||||
url.scheme = '';
|
||||
url.host = '';
|
||||
url.type = UrlType.AbsolutePath;
|
||||
return url;
|
||||
}
|
||||
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('?')
|
||||
? UrlType.Query
|
||||
: input.startsWith('#')
|
||||
? UrlType.Hash
|
||||
: UrlType.RelativePath
|
||||
: UrlType.Empty;
|
||||
return url;
|
||||
}
|
||||
function stripPathFilename(path) {
|
||||
// If a path ends with a parent directory "..", then it's a relative path with excess parent
|
||||
// paths. It's not a file, so we can't strip it.
|
||||
if (path.endsWith('/..'))
|
||||
return path;
|
||||
const index = path.lastIndexOf('/');
|
||||
return path.slice(0, index + 1);
|
||||
}
|
||||
function mergePaths(url, base) {
|
||||
normalizePath(base, base.type);
|
||||
// If the path is just a "/", then it was an empty path to begin with (remember, we're a relative
|
||||
// path).
|
||||
if (url.path === '/') {
|
||||
url.path = base.path;
|
||||
}
|
||||
else {
|
||||
// Resolution happens relative to the base path's directory, not the file.
|
||||
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 <= UrlType.RelativePath;
|
||||
const pieces = url.path.split('/');
|
||||
// We need to preserve the first piece always, so that we output a leading slash. The item at
|
||||
// pieces[0] is an empty string.
|
||||
let pointer = 1;
|
||||
// Positive is the number of real directories we've output, used for popping a parent directory.
|
||||
// Eg, "foo/bar/.." will have a positive 2, and we can decrement to be left with just "foo".
|
||||
let positive = 0;
|
||||
// We need to keep a trailing slash if we encounter an empty directory (eg, splitting "foo/" will
|
||||
// generate `["foo", ""]` pieces). And, if we pop a parent directory. But once we encounter a
|
||||
// real directory, we won't need to append, unless the other conditions happen again.
|
||||
let addTrailingSlash = false;
|
||||
for (let i = 1; i < pieces.length; i++) {
|
||||
const piece = pieces[i];
|
||||
// An empty directory, could be a trailing slash, or just a double "//" in the path.
|
||||
if (!piece) {
|
||||
addTrailingSlash = true;
|
||||
continue;
|
||||
}
|
||||
// If we encounter a real directory, then we don't need to append anymore.
|
||||
addTrailingSlash = false;
|
||||
// A current directory, which we can always drop.
|
||||
if (piece === '.')
|
||||
continue;
|
||||
// A parent directory, we need to see if there are any real directories we can pop. Else, we
|
||||
// have an excess of parents, and we'll need to keep the "..".
|
||||
if (piece === '..') {
|
||||
if (positive) {
|
||||
addTrailingSlash = true;
|
||||
positive--;
|
||||
pointer--;
|
||||
}
|
||||
else if (rel) {
|
||||
// If we're in a relativePath, then we need to keep the excess parents. Else, in an absolute
|
||||
// URL, protocol relative URL, or an absolute path, we don't need to keep excess.
|
||||
pieces[pointer++] = piece;
|
||||
}
|
||||
continue;
|
||||
}
|
||||
// We've encountered a real directory. Move it to the next insertion pointer, which accounts for
|
||||
// any popped or dropped directories.
|
||||
pieces[pointer++] = piece;
|
||||
positive++;
|
||||
}
|
||||
let path = '';
|
||||
for (let i = 1; i < pointer; i++) {
|
||||
path += '/' + pieces[i];
|
||||
}
|
||||
if (!path || (addTrailingSlash && !path.endsWith('/..'))) {
|
||||
path += '/';
|
||||
}
|
||||
url.path = path;
|
||||
}
|
||||
/**
|
||||
* Attempts to resolve `input` URL/path relative to `base`.
|
||||
*/
|
||||
function resolve$1(input, base) {
|
||||
if (!input && !base)
|
||||
return '';
|
||||
const url = parseUrl(input);
|
||||
let inputType = url.type;
|
||||
if (base && inputType !== UrlType.Absolute) {
|
||||
const baseUrl = parseUrl(base);
|
||||
const baseType = baseUrl.type;
|
||||
switch (inputType) {
|
||||
case UrlType.Empty:
|
||||
url.hash = baseUrl.hash;
|
||||
// fall through
|
||||
case UrlType.Hash:
|
||||
url.query = baseUrl.query;
|
||||
// fall through
|
||||
case UrlType.Query:
|
||||
case UrlType.RelativePath:
|
||||
mergePaths(url, baseUrl);
|
||||
// fall through
|
||||
case UrlType.AbsolutePath:
|
||||
// The host, user, and port are joined, you can't copy one without the others.
|
||||
url.user = baseUrl.user;
|
||||
url.host = baseUrl.host;
|
||||
url.port = baseUrl.port;
|
||||
// fall through
|
||||
case UrlType.SchemeRelative:
|
||||
// The input doesn't have a schema at least, so we need to copy at least that over.
|
||||
url.scheme = baseUrl.scheme;
|
||||
}
|
||||
if (baseType > inputType)
|
||||
inputType = baseType;
|
||||
}
|
||||
normalizePath(url, inputType);
|
||||
const queryHash = url.query + url.hash;
|
||||
switch (inputType) {
|
||||
// This is impossible, because of the empty checks at the start of the function.
|
||||
// case UrlType.Empty:
|
||||
case UrlType.Hash:
|
||||
case UrlType.Query:
|
||||
return queryHash;
|
||||
case UrlType.RelativePath: {
|
||||
// The first char is always a "/", and we need it to be relative.
|
||||
const path = url.path.slice(1);
|
||||
if (!path)
|
||||
return queryHash || '.';
|
||||
if (isRelative(base || input) && !isRelative(path)) {
|
||||
// If base started with a leading ".", or there is no base and input started with a ".",
|
||||
// then we need to ensure that the relative path starts with a ".". We don't know if
|
||||
// relative starts with a "..", though, so check before prepending.
|
||||
return './' + path + queryHash;
|
||||
}
|
||||
return path + queryHash;
|
||||
}
|
||||
case UrlType.AbsolutePath:
|
||||
return url.path + queryHash;
|
||||
default:
|
||||
return url.scheme + '//' + url.user + url.host + url.port + url.path + queryHash;
|
||||
}
|
||||
}
|
||||
|
||||
function resolve(input, base) {
|
||||
// The base is always treated as a directory, if it's not empty.
|
||||
// https://github.com/mozilla/source-map/blob/8cb3ee57/lib/util.js#L327
|
||||
// https://github.com/chromium/chromium/blob/da4adbb3/third_party/blink/renderer/devtools/front_end/sdk/SourceMap.js#L400-L401
|
||||
if (base && !base.endsWith('/'))
|
||||
base += '/';
|
||||
return resolve$1(input, base);
|
||||
}
|
||||
|
||||
/**
|
||||
* Removes everything after the last "/", but leaves the slash.
|
||||
*/
|
||||
function stripFilename(path) {
|
||||
if (!path)
|
||||
return '';
|
||||
const index = path.lastIndexOf('/');
|
||||
return path.slice(0, index + 1);
|
||||
}
|
||||
|
||||
const COLUMN = 0;
|
||||
const SOURCES_INDEX = 1;
|
||||
const SOURCE_LINE = 2;
|
||||
const SOURCE_COLUMN = 3;
|
||||
const NAMES_INDEX = 4;
|
||||
|
||||
function maybeSort(mappings, owned) {
|
||||
const unsortedIndex = nextUnsortedSegmentLine(mappings, 0);
|
||||
if (unsortedIndex === mappings.length)
|
||||
return mappings;
|
||||
// If we own the array (meaning we parsed it from JSON), then we're free to directly mutate it. If
|
||||
// not, we do not want to modify the consumer's input array.
|
||||
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];
|
||||
}
|
||||
|
||||
let found = false;
|
||||
/**
|
||||
* A binary search implementation that returns the index if a match is found.
|
||||
* If no match is found, then the left-index (the index associated with the item that comes just
|
||||
* before the desired index) is returned. To maintain proper sort order, a splice would happen at
|
||||
* the next index:
|
||||
*
|
||||
* ```js
|
||||
* const array = [1, 3];
|
||||
* const needle = 2;
|
||||
* const index = binarySearch(array, needle, (item, needle) => item - needle);
|
||||
*
|
||||
* assert.equal(index, 0);
|
||||
* array.splice(index + 1, 0, needle);
|
||||
* assert.deepEqual(array, [1, 2, 3]);
|
||||
* ```
|
||||
*/
|
||||
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,
|
||||
};
|
||||
}
|
||||
/**
|
||||
* This overly complicated beast is just to record the last tested line/column and the resulting
|
||||
* index, allowing us to skip a few tests if mappings are monotonically increasing.
|
||||
*/
|
||||
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) {
|
||||
// lastIndex may be -1 if the previous needle was not found.
|
||||
low = lastIndex === -1 ? 0 : lastIndex;
|
||||
}
|
||||
else {
|
||||
high = lastIndex;
|
||||
}
|
||||
}
|
||||
state.lastKey = key;
|
||||
state.lastNeedle = needle;
|
||||
return (state.lastIndex = binarySearch(haystack, needle, low, high));
|
||||
}
|
||||
|
||||
const LINE_GTR_ZERO = '`line` must be greater than 0 (lines start at line 1)';
|
||||
const COL_GTR_EQ_ZERO = '`column` must be greater than or equal to 0 (columns start at column 0)';
|
||||
const LEAST_UPPER_BOUND = -1;
|
||||
const GREATEST_LOWER_BOUND = 1;
|
||||
/**
|
||||
* Returns the decoded (array of lines of segments) form of the SourceMap's mappings field.
|
||||
*/
|
||||
let decodedMappings;
|
||||
/**
|
||||
* A higher-level API to find the source/line/column associated with a generated line/column
|
||||
* (think, from a stack trace). Line is 1-based, but column is 0-based, due to legacy behavior in
|
||||
* `source-map` library.
|
||||
*/
|
||||
let originalPositionFor;
|
||||
class TraceMap {
|
||||
constructor(map, mapUrl) {
|
||||
const isString = typeof map === 'string';
|
||||
if (!isString && map._decodedMemo)
|
||||
return map;
|
||||
const parsed = (isString ? JSON.parse(map) : 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;
|
||||
const from = resolve(sourceRoot || '', stripFilename(mapUrl));
|
||||
this.resolvedSources = sources.map((s) => resolve(s || '', from));
|
||||
const { mappings } = parsed;
|
||||
if (typeof mappings === 'string') {
|
||||
this._encoded = mappings;
|
||||
this._decoded = undefined;
|
||||
}
|
||||
else {
|
||||
this._encoded = undefined;
|
||||
this._decoded = maybeSort(mappings, isString);
|
||||
}
|
||||
this._decodedMemo = memoizedState();
|
||||
this._bySources = undefined;
|
||||
this._bySourceMemos = undefined;
|
||||
}
|
||||
}
|
||||
(() => {
|
||||
decodedMappings = (map) => {
|
||||
return (map._decoded || (map._decoded = decode(map._encoded)));
|
||||
};
|
||||
originalPositionFor = (map, { line, column, bias }) => {
|
||||
line--;
|
||||
if (line < 0)
|
||||
throw new Error(LINE_GTR_ZERO);
|
||||
if (column < 0)
|
||||
throw new Error(COL_GTR_EQ_ZERO);
|
||||
const decoded = decodedMappings(map);
|
||||
// It's common for parent source maps to have pointers to lines that have no
|
||||
// mapping (like a "//# sourceMappingURL=") at the end of the child file.
|
||||
if (line >= decoded.length)
|
||||
return OMapping(null, null, null, null);
|
||||
const segments = decoded[line];
|
||||
const index = traceSegmentInternal(segments, 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;
|
||||
}
|
||||
|
||||
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((path2) => {
|
||||
path2 = path2.trim();
|
||||
if (path2.startsWith("file:")) {
|
||||
path2 = path2.replace(/file:\/\/\/(\w:)?/, (protocol, drive) => {
|
||||
return drive ? "" : "/";
|
||||
});
|
||||
}
|
||||
if (path2 in fileContentsCache)
|
||||
return fileContentsCache[path2];
|
||||
let contents = "";
|
||||
try {
|
||||
if (fs.existsSync(path2))
|
||||
contents = fs.readFileSync(path2, "utf8");
|
||||
} catch (er) {
|
||||
}
|
||||
return fileContentsCache[path2] = 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]*$)/mg;
|
||||
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.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) {
|
||||
var _a;
|
||||
if (!position.source)
|
||||
return position;
|
||||
let sourceMap = sourceMapCache[position.source];
|
||||
if (!sourceMap) {
|
||||
const urlAndMap = retrieveSourceMap(position.source);
|
||||
if (urlAndMap && urlAndMap.map) {
|
||||
sourceMap = sourceMapCache[position.source] = {
|
||||
url: urlAndMap.url,
|
||||
map: new TraceMap(urlAndMap.map)
|
||||
};
|
||||
if ((_a = sourceMap.map) == null ? void 0 : _a.sourcesContent) {
|
||||
sourceMap.map.sources.forEach((source, i) => {
|
||||
var _a2, _b;
|
||||
const contents = (_b = (_a2 = sourceMap.map) == null ? void 0 : _a2.sourcesContent) == null ? void 0 : _b[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();
|
||||
const isMethodCall = !(this.isToplevel() || isConstructor);
|
||||
if (isMethodCall) {
|
||||
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 noHeader = /^v(10\.1[6-9]|10\.[2-9][0-9]|10\.[0-9]{3,}|1[2-9]\d*|[2-9]\d|\d{3,}|11\.11)/;
|
||||
const headerLength = noHeader.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 ?? void 0;
|
||||
};
|
||||
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 name = error.name || "Error";
|
||||
const message = error.message || "";
|
||||
const errorString = `${name}: ${message}`;
|
||||
const state = { nextPosition: null, curPosition: null };
|
||||
const processedStack = [];
|
||||
for (let i = stack.length - 1; i >= 0; i--) {
|
||||
processedStack.push(`
|
||||
at ${wrapCallSite(stack[i], state)}`);
|
||||
state.nextPosition = state.curPosition;
|
||||
}
|
||||
state.curPosition = state.nextPosition = null;
|
||||
return errorString + processedStack.reverse().join("");
|
||||
}
|
||||
retrieveFileHandlers.slice(0);
|
||||
retrieveMapHandlers.slice(0);
|
||||
const install = function(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;
|
||||
}
|
||||
};
|
||||
|
||||
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`;
|
||||
const VITE_NODE_SOURCEMAPPING_REGEXP = new RegExp(`//# ${VITE_NODE_SOURCEMAPPING_URL};base64,(.+)`);
|
||||
function withInlineSourcemap(result, options) {
|
||||
var _a;
|
||||
const map = result.map;
|
||||
let code = result.code;
|
||||
if (!map || code.includes(VITE_NODE_SOURCEMAPPING_SOURCE))
|
||||
return result;
|
||||
if ("sources" in map) {
|
||||
map.sources = (_a = map.sources) == null ? void 0 : _a.map((source) => {
|
||||
if (!source)
|
||||
return source;
|
||||
if (pathe.isAbsolute(source)) {
|
||||
const actualPath = !source.startsWith(utils.withTrailingSlash(options.root)) && source.startsWith("/") ? pathe.resolve(options.root, source.slice(1)) : source;
|
||||
return pathe.relative(pathe.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 (map.mappings.startsWith(";"))
|
||||
map.mappings = `AAAA,CAAA${map.mappings}`;
|
||||
const sourceMap = Buffer.from(JSON.stringify(map), "utf-8").toString("base64");
|
||||
result.code = `${code.trimEnd()}
|
||||
|
||||
${VITE_NODE_SOURCEMAPPING_SOURCE}
|
||||
//# ${VITE_NODE_SOURCEMAPPING_URL};base64,${sourceMap}
|
||||
`;
|
||||
return result;
|
||||
}
|
||||
function extractSourceMap(code) {
|
||||
var _a;
|
||||
const mapString = (_a = code.match(VITE_NODE_SOURCEMAPPING_REGEXP)) == null ? void 0 : _a[1];
|
||||
if (mapString)
|
||||
return JSON.parse(Buffer.from(mapString, "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;
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
exports.extractSourceMap = extractSourceMap;
|
||||
exports.installSourcemapsSupport = installSourcemapsSupport;
|
||||
exports.withInlineSourcemap = withInlineSourcemap;
|
||||
+14
@@ -0,0 +1,14 @@
|
||||
import { TransformResult } from 'vite';
|
||||
import { E as EncodedSourceMap } from './trace-mapping.d-xyIfZtPm.js';
|
||||
|
||||
interface InstallSourceMapSupportOptions {
|
||||
getSourceMap: (source: string) => EncodedSourceMap | null | undefined;
|
||||
}
|
||||
declare function withInlineSourcemap(result: TransformResult, options: {
|
||||
root: string;
|
||||
filepath: string;
|
||||
}): TransformResult;
|
||||
declare function extractSourceMap(code: string): EncodedSourceMap | null;
|
||||
declare function installSourcemapsSupport(options: InstallSourceMapSupportOptions): void;
|
||||
|
||||
export { extractSourceMap, installSourcemapsSupport, withInlineSourcemap };
|
||||
+914
@@ -0,0 +1,914 @@
|
||||
import { isAbsolute, resolve as resolve$2, relative, dirname } from 'pathe';
|
||||
import { withTrailingSlash } from './utils.mjs';
|
||||
import path from 'node:path';
|
||||
import fs from 'node:fs';
|
||||
import 'node:url';
|
||||
import 'node:module';
|
||||
|
||||
const comma = ','.charCodeAt(0);
|
||||
const chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/';
|
||||
const intToChar = new Uint8Array(64); // 64 possible chars.
|
||||
const charToInt = new Uint8Array(128); // z is 122 in ASCII
|
||||
for (let i = 0; i < chars.length; i++) {
|
||||
const c = chars.charCodeAt(i);
|
||||
intToChar[i] = c;
|
||||
charToInt[c] = i;
|
||||
}
|
||||
function decode(mappings) {
|
||||
const state = new Int32Array(5);
|
||||
const decoded = [];
|
||||
let index = 0;
|
||||
do {
|
||||
const semi = indexOf(mappings, index);
|
||||
const line = [];
|
||||
let sorted = true;
|
||||
let lastCol = 0;
|
||||
state[0] = 0;
|
||||
for (let i = index; i < semi; i++) {
|
||||
let seg;
|
||||
i = decodeInteger(mappings, i, state, 0); // genColumn
|
||||
const col = state[0];
|
||||
if (col < lastCol)
|
||||
sorted = false;
|
||||
lastCol = col;
|
||||
if (hasMoreVlq(mappings, i, semi)) {
|
||||
i = decodeInteger(mappings, i, state, 1); // sourcesIndex
|
||||
i = decodeInteger(mappings, i, state, 2); // sourceLine
|
||||
i = decodeInteger(mappings, i, state, 3); // sourceColumn
|
||||
if (hasMoreVlq(mappings, i, semi)) {
|
||||
i = decodeInteger(mappings, i, state, 4); // namesIndex
|
||||
seg = [col, state[1], state[2], state[3], state[4]];
|
||||
}
|
||||
else {
|
||||
seg = [col, state[1], state[2], state[3]];
|
||||
}
|
||||
}
|
||||
else {
|
||||
seg = [col];
|
||||
}
|
||||
line.push(seg);
|
||||
}
|
||||
if (!sorted)
|
||||
sort(line);
|
||||
decoded.push(line);
|
||||
index = semi + 1;
|
||||
} while (index <= mappings.length);
|
||||
return decoded;
|
||||
}
|
||||
function indexOf(mappings, index) {
|
||||
const idx = mappings.indexOf(';', index);
|
||||
return idx === -1 ? mappings.length : idx;
|
||||
}
|
||||
function decodeInteger(mappings, pos, state, j) {
|
||||
let value = 0;
|
||||
let shift = 0;
|
||||
let integer = 0;
|
||||
do {
|
||||
const c = mappings.charCodeAt(pos++);
|
||||
integer = charToInt[c];
|
||||
value |= (integer & 31) << shift;
|
||||
shift += 5;
|
||||
} while (integer & 32);
|
||||
const shouldNegate = value & 1;
|
||||
value >>>= 1;
|
||||
if (shouldNegate) {
|
||||
value = -0x80000000 | -value;
|
||||
}
|
||||
state[j] += value;
|
||||
return pos;
|
||||
}
|
||||
function hasMoreVlq(mappings, i, length) {
|
||||
if (i >= length)
|
||||
return false;
|
||||
return mappings.charCodeAt(i) !== comma;
|
||||
}
|
||||
function sort(line) {
|
||||
line.sort(sortComparator$1);
|
||||
}
|
||||
function sortComparator$1(a, b) {
|
||||
return a[0] - b[0];
|
||||
}
|
||||
|
||||
// Matches the scheme of a URL, eg "http://"
|
||||
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;
|
||||
var UrlType;
|
||||
(function (UrlType) {
|
||||
UrlType[UrlType["Empty"] = 1] = "Empty";
|
||||
UrlType[UrlType["Hash"] = 2] = "Hash";
|
||||
UrlType[UrlType["Query"] = 3] = "Query";
|
||||
UrlType[UrlType["RelativePath"] = 4] = "RelativePath";
|
||||
UrlType[UrlType["AbsolutePath"] = 5] = "AbsolutePath";
|
||||
UrlType[UrlType["SchemeRelative"] = 6] = "SchemeRelative";
|
||||
UrlType[UrlType["Absolute"] = 7] = "Absolute";
|
||||
})(UrlType || (UrlType = {}));
|
||||
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 = match[2];
|
||||
return makeUrl('file:', '', match[1] || '', '', isAbsolutePath(path) ? path : '/' + path, match[3] || '', match[4] || '');
|
||||
}
|
||||
function makeUrl(scheme, user, host, port, path, query, hash) {
|
||||
return {
|
||||
scheme,
|
||||
user,
|
||||
host,
|
||||
port,
|
||||
path,
|
||||
query,
|
||||
hash,
|
||||
type: UrlType.Absolute,
|
||||
};
|
||||
}
|
||||
function parseUrl(input) {
|
||||
if (isSchemeRelativeUrl(input)) {
|
||||
const url = parseAbsoluteUrl('http:' + input);
|
||||
url.scheme = '';
|
||||
url.type = UrlType.SchemeRelative;
|
||||
return url;
|
||||
}
|
||||
if (isAbsolutePath(input)) {
|
||||
const url = parseAbsoluteUrl('http://foo.com' + input);
|
||||
url.scheme = '';
|
||||
url.host = '';
|
||||
url.type = UrlType.AbsolutePath;
|
||||
return url;
|
||||
}
|
||||
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('?')
|
||||
? UrlType.Query
|
||||
: input.startsWith('#')
|
||||
? UrlType.Hash
|
||||
: UrlType.RelativePath
|
||||
: UrlType.Empty;
|
||||
return url;
|
||||
}
|
||||
function stripPathFilename(path) {
|
||||
// If a path ends with a parent directory "..", then it's a relative path with excess parent
|
||||
// paths. It's not a file, so we can't strip it.
|
||||
if (path.endsWith('/..'))
|
||||
return path;
|
||||
const index = path.lastIndexOf('/');
|
||||
return path.slice(0, index + 1);
|
||||
}
|
||||
function mergePaths(url, base) {
|
||||
normalizePath(base, base.type);
|
||||
// If the path is just a "/", then it was an empty path to begin with (remember, we're a relative
|
||||
// path).
|
||||
if (url.path === '/') {
|
||||
url.path = base.path;
|
||||
}
|
||||
else {
|
||||
// Resolution happens relative to the base path's directory, not the file.
|
||||
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 <= UrlType.RelativePath;
|
||||
const pieces = url.path.split('/');
|
||||
// We need to preserve the first piece always, so that we output a leading slash. The item at
|
||||
// pieces[0] is an empty string.
|
||||
let pointer = 1;
|
||||
// Positive is the number of real directories we've output, used for popping a parent directory.
|
||||
// Eg, "foo/bar/.." will have a positive 2, and we can decrement to be left with just "foo".
|
||||
let positive = 0;
|
||||
// We need to keep a trailing slash if we encounter an empty directory (eg, splitting "foo/" will
|
||||
// generate `["foo", ""]` pieces). And, if we pop a parent directory. But once we encounter a
|
||||
// real directory, we won't need to append, unless the other conditions happen again.
|
||||
let addTrailingSlash = false;
|
||||
for (let i = 1; i < pieces.length; i++) {
|
||||
const piece = pieces[i];
|
||||
// An empty directory, could be a trailing slash, or just a double "//" in the path.
|
||||
if (!piece) {
|
||||
addTrailingSlash = true;
|
||||
continue;
|
||||
}
|
||||
// If we encounter a real directory, then we don't need to append anymore.
|
||||
addTrailingSlash = false;
|
||||
// A current directory, which we can always drop.
|
||||
if (piece === '.')
|
||||
continue;
|
||||
// A parent directory, we need to see if there are any real directories we can pop. Else, we
|
||||
// have an excess of parents, and we'll need to keep the "..".
|
||||
if (piece === '..') {
|
||||
if (positive) {
|
||||
addTrailingSlash = true;
|
||||
positive--;
|
||||
pointer--;
|
||||
}
|
||||
else if (rel) {
|
||||
// If we're in a relativePath, then we need to keep the excess parents. Else, in an absolute
|
||||
// URL, protocol relative URL, or an absolute path, we don't need to keep excess.
|
||||
pieces[pointer++] = piece;
|
||||
}
|
||||
continue;
|
||||
}
|
||||
// We've encountered a real directory. Move it to the next insertion pointer, which accounts for
|
||||
// any popped or dropped directories.
|
||||
pieces[pointer++] = piece;
|
||||
positive++;
|
||||
}
|
||||
let path = '';
|
||||
for (let i = 1; i < pointer; i++) {
|
||||
path += '/' + pieces[i];
|
||||
}
|
||||
if (!path || (addTrailingSlash && !path.endsWith('/..'))) {
|
||||
path += '/';
|
||||
}
|
||||
url.path = path;
|
||||
}
|
||||
/**
|
||||
* Attempts to resolve `input` URL/path relative to `base`.
|
||||
*/
|
||||
function resolve$1(input, base) {
|
||||
if (!input && !base)
|
||||
return '';
|
||||
const url = parseUrl(input);
|
||||
let inputType = url.type;
|
||||
if (base && inputType !== UrlType.Absolute) {
|
||||
const baseUrl = parseUrl(base);
|
||||
const baseType = baseUrl.type;
|
||||
switch (inputType) {
|
||||
case UrlType.Empty:
|
||||
url.hash = baseUrl.hash;
|
||||
// fall through
|
||||
case UrlType.Hash:
|
||||
url.query = baseUrl.query;
|
||||
// fall through
|
||||
case UrlType.Query:
|
||||
case UrlType.RelativePath:
|
||||
mergePaths(url, baseUrl);
|
||||
// fall through
|
||||
case UrlType.AbsolutePath:
|
||||
// The host, user, and port are joined, you can't copy one without the others.
|
||||
url.user = baseUrl.user;
|
||||
url.host = baseUrl.host;
|
||||
url.port = baseUrl.port;
|
||||
// fall through
|
||||
case UrlType.SchemeRelative:
|
||||
// The input doesn't have a schema at least, so we need to copy at least that over.
|
||||
url.scheme = baseUrl.scheme;
|
||||
}
|
||||
if (baseType > inputType)
|
||||
inputType = baseType;
|
||||
}
|
||||
normalizePath(url, inputType);
|
||||
const queryHash = url.query + url.hash;
|
||||
switch (inputType) {
|
||||
// This is impossible, because of the empty checks at the start of the function.
|
||||
// case UrlType.Empty:
|
||||
case UrlType.Hash:
|
||||
case UrlType.Query:
|
||||
return queryHash;
|
||||
case UrlType.RelativePath: {
|
||||
// The first char is always a "/", and we need it to be relative.
|
||||
const path = url.path.slice(1);
|
||||
if (!path)
|
||||
return queryHash || '.';
|
||||
if (isRelative(base || input) && !isRelative(path)) {
|
||||
// If base started with a leading ".", or there is no base and input started with a ".",
|
||||
// then we need to ensure that the relative path starts with a ".". We don't know if
|
||||
// relative starts with a "..", though, so check before prepending.
|
||||
return './' + path + queryHash;
|
||||
}
|
||||
return path + queryHash;
|
||||
}
|
||||
case UrlType.AbsolutePath:
|
||||
return url.path + queryHash;
|
||||
default:
|
||||
return url.scheme + '//' + url.user + url.host + url.port + url.path + queryHash;
|
||||
}
|
||||
}
|
||||
|
||||
function resolve(input, base) {
|
||||
// The base is always treated as a directory, if it's not empty.
|
||||
// https://github.com/mozilla/source-map/blob/8cb3ee57/lib/util.js#L327
|
||||
// https://github.com/chromium/chromium/blob/da4adbb3/third_party/blink/renderer/devtools/front_end/sdk/SourceMap.js#L400-L401
|
||||
if (base && !base.endsWith('/'))
|
||||
base += '/';
|
||||
return resolve$1(input, base);
|
||||
}
|
||||
|
||||
/**
|
||||
* Removes everything after the last "/", but leaves the slash.
|
||||
*/
|
||||
function stripFilename(path) {
|
||||
if (!path)
|
||||
return '';
|
||||
const index = path.lastIndexOf('/');
|
||||
return path.slice(0, index + 1);
|
||||
}
|
||||
|
||||
const COLUMN = 0;
|
||||
const SOURCES_INDEX = 1;
|
||||
const SOURCE_LINE = 2;
|
||||
const SOURCE_COLUMN = 3;
|
||||
const NAMES_INDEX = 4;
|
||||
|
||||
function maybeSort(mappings, owned) {
|
||||
const unsortedIndex = nextUnsortedSegmentLine(mappings, 0);
|
||||
if (unsortedIndex === mappings.length)
|
||||
return mappings;
|
||||
// If we own the array (meaning we parsed it from JSON), then we're free to directly mutate it. If
|
||||
// not, we do not want to modify the consumer's input array.
|
||||
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];
|
||||
}
|
||||
|
||||
let found = false;
|
||||
/**
|
||||
* A binary search implementation that returns the index if a match is found.
|
||||
* If no match is found, then the left-index (the index associated with the item that comes just
|
||||
* before the desired index) is returned. To maintain proper sort order, a splice would happen at
|
||||
* the next index:
|
||||
*
|
||||
* ```js
|
||||
* const array = [1, 3];
|
||||
* const needle = 2;
|
||||
* const index = binarySearch(array, needle, (item, needle) => item - needle);
|
||||
*
|
||||
* assert.equal(index, 0);
|
||||
* array.splice(index + 1, 0, needle);
|
||||
* assert.deepEqual(array, [1, 2, 3]);
|
||||
* ```
|
||||
*/
|
||||
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,
|
||||
};
|
||||
}
|
||||
/**
|
||||
* This overly complicated beast is just to record the last tested line/column and the resulting
|
||||
* index, allowing us to skip a few tests if mappings are monotonically increasing.
|
||||
*/
|
||||
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) {
|
||||
// lastIndex may be -1 if the previous needle was not found.
|
||||
low = lastIndex === -1 ? 0 : lastIndex;
|
||||
}
|
||||
else {
|
||||
high = lastIndex;
|
||||
}
|
||||
}
|
||||
state.lastKey = key;
|
||||
state.lastNeedle = needle;
|
||||
return (state.lastIndex = binarySearch(haystack, needle, low, high));
|
||||
}
|
||||
|
||||
const LINE_GTR_ZERO = '`line` must be greater than 0 (lines start at line 1)';
|
||||
const COL_GTR_EQ_ZERO = '`column` must be greater than or equal to 0 (columns start at column 0)';
|
||||
const LEAST_UPPER_BOUND = -1;
|
||||
const GREATEST_LOWER_BOUND = 1;
|
||||
/**
|
||||
* Returns the decoded (array of lines of segments) form of the SourceMap's mappings field.
|
||||
*/
|
||||
let decodedMappings;
|
||||
/**
|
||||
* A higher-level API to find the source/line/column associated with a generated line/column
|
||||
* (think, from a stack trace). Line is 1-based, but column is 0-based, due to legacy behavior in
|
||||
* `source-map` library.
|
||||
*/
|
||||
let originalPositionFor;
|
||||
class TraceMap {
|
||||
constructor(map, mapUrl) {
|
||||
const isString = typeof map === 'string';
|
||||
if (!isString && map._decodedMemo)
|
||||
return map;
|
||||
const parsed = (isString ? JSON.parse(map) : 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;
|
||||
const from = resolve(sourceRoot || '', stripFilename(mapUrl));
|
||||
this.resolvedSources = sources.map((s) => resolve(s || '', from));
|
||||
const { mappings } = parsed;
|
||||
if (typeof mappings === 'string') {
|
||||
this._encoded = mappings;
|
||||
this._decoded = undefined;
|
||||
}
|
||||
else {
|
||||
this._encoded = undefined;
|
||||
this._decoded = maybeSort(mappings, isString);
|
||||
}
|
||||
this._decodedMemo = memoizedState();
|
||||
this._bySources = undefined;
|
||||
this._bySourceMemos = undefined;
|
||||
}
|
||||
}
|
||||
(() => {
|
||||
decodedMappings = (map) => {
|
||||
return (map._decoded || (map._decoded = decode(map._encoded)));
|
||||
};
|
||||
originalPositionFor = (map, { line, column, bias }) => {
|
||||
line--;
|
||||
if (line < 0)
|
||||
throw new Error(LINE_GTR_ZERO);
|
||||
if (column < 0)
|
||||
throw new Error(COL_GTR_EQ_ZERO);
|
||||
const decoded = decodedMappings(map);
|
||||
// It's common for parent source maps to have pointers to lines that have no
|
||||
// mapping (like a "//# sourceMappingURL=") at the end of the child file.
|
||||
if (line >= decoded.length)
|
||||
return OMapping(null, null, null, null);
|
||||
const segments = decoded[line];
|
||||
const index = traceSegmentInternal(segments, 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;
|
||||
}
|
||||
|
||||
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((path2) => {
|
||||
path2 = path2.trim();
|
||||
if (path2.startsWith("file:")) {
|
||||
path2 = path2.replace(/file:\/\/\/(\w:)?/, (protocol, drive) => {
|
||||
return drive ? "" : "/";
|
||||
});
|
||||
}
|
||||
if (path2 in fileContentsCache)
|
||||
return fileContentsCache[path2];
|
||||
let contents = "";
|
||||
try {
|
||||
if (fs.existsSync(path2))
|
||||
contents = fs.readFileSync(path2, "utf8");
|
||||
} catch (er) {
|
||||
}
|
||||
return fileContentsCache[path2] = 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]*$)/mg;
|
||||
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.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) {
|
||||
var _a;
|
||||
if (!position.source)
|
||||
return position;
|
||||
let sourceMap = sourceMapCache[position.source];
|
||||
if (!sourceMap) {
|
||||
const urlAndMap = retrieveSourceMap(position.source);
|
||||
if (urlAndMap && urlAndMap.map) {
|
||||
sourceMap = sourceMapCache[position.source] = {
|
||||
url: urlAndMap.url,
|
||||
map: new TraceMap(urlAndMap.map)
|
||||
};
|
||||
if ((_a = sourceMap.map) == null ? void 0 : _a.sourcesContent) {
|
||||
sourceMap.map.sources.forEach((source, i) => {
|
||||
var _a2, _b;
|
||||
const contents = (_b = (_a2 = sourceMap.map) == null ? void 0 : _a2.sourcesContent) == null ? void 0 : _b[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();
|
||||
const isMethodCall = !(this.isToplevel() || isConstructor);
|
||||
if (isMethodCall) {
|
||||
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 noHeader = /^v(10\.1[6-9]|10\.[2-9][0-9]|10\.[0-9]{3,}|1[2-9]\d*|[2-9]\d|\d{3,}|11\.11)/;
|
||||
const headerLength = noHeader.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 ?? void 0;
|
||||
};
|
||||
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 name = error.name || "Error";
|
||||
const message = error.message || "";
|
||||
const errorString = `${name}: ${message}`;
|
||||
const state = { nextPosition: null, curPosition: null };
|
||||
const processedStack = [];
|
||||
for (let i = stack.length - 1; i >= 0; i--) {
|
||||
processedStack.push(`
|
||||
at ${wrapCallSite(stack[i], state)}`);
|
||||
state.nextPosition = state.curPosition;
|
||||
}
|
||||
state.curPosition = state.nextPosition = null;
|
||||
return errorString + processedStack.reverse().join("");
|
||||
}
|
||||
retrieveFileHandlers.slice(0);
|
||||
retrieveMapHandlers.slice(0);
|
||||
const install = function(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;
|
||||
}
|
||||
};
|
||||
|
||||
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`;
|
||||
const VITE_NODE_SOURCEMAPPING_REGEXP = new RegExp(`//# ${VITE_NODE_SOURCEMAPPING_URL};base64,(.+)`);
|
||||
function withInlineSourcemap(result, options) {
|
||||
var _a;
|
||||
const map = result.map;
|
||||
let code = result.code;
|
||||
if (!map || code.includes(VITE_NODE_SOURCEMAPPING_SOURCE))
|
||||
return result;
|
||||
if ("sources" in map) {
|
||||
map.sources = (_a = map.sources) == null ? void 0 : _a.map((source) => {
|
||||
if (!source)
|
||||
return source;
|
||||
if (isAbsolute(source)) {
|
||||
const actualPath = !source.startsWith(withTrailingSlash(options.root)) && source.startsWith("/") ? resolve$2(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 (map.mappings.startsWith(";"))
|
||||
map.mappings = `AAAA,CAAA${map.mappings}`;
|
||||
const sourceMap = Buffer.from(JSON.stringify(map), "utf-8").toString("base64");
|
||||
result.code = `${code.trimEnd()}
|
||||
|
||||
${VITE_NODE_SOURCEMAPPING_SOURCE}
|
||||
//# ${VITE_NODE_SOURCEMAPPING_URL};base64,${sourceMap}
|
||||
`;
|
||||
return result;
|
||||
}
|
||||
function extractSourceMap(code) {
|
||||
var _a;
|
||||
const mapString = (_a = code.match(VITE_NODE_SOURCEMAPPING_REGEXP)) == null ? void 0 : _a[1];
|
||||
if (mapString)
|
||||
return JSON.parse(Buffer.from(mapString, "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;
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
export { extractSourceMap, installSourcemapsSupport, withInlineSourcemap };
|
||||
Generated
Vendored
+54
@@ -0,0 +1,54 @@
|
||||
type GeneratedColumn = number;
|
||||
type SourcesIndex = number;
|
||||
type SourceLine = number;
|
||||
type SourceColumn = number;
|
||||
type NamesIndex = number;
|
||||
type SourceMapSegment = [GeneratedColumn] | [GeneratedColumn, SourcesIndex, SourceLine, SourceColumn] | [GeneratedColumn, SourcesIndex, SourceLine, SourceColumn, NamesIndex];
|
||||
|
||||
interface SourceMapV3 {
|
||||
file?: string | null;
|
||||
names: string[];
|
||||
sourceRoot?: string;
|
||||
sources: (string | null)[];
|
||||
sourcesContent?: (string | null)[];
|
||||
version: 3;
|
||||
}
|
||||
interface EncodedSourceMap extends SourceMapV3 {
|
||||
mappings: string;
|
||||
}
|
||||
interface DecodedSourceMap extends SourceMapV3 {
|
||||
mappings: SourceMapSegment[][];
|
||||
}
|
||||
type SourceMapInput = string | Ro<EncodedSourceMap> | Ro<DecodedSourceMap> | TraceMap;
|
||||
declare abstract class SourceMap {
|
||||
version: SourceMapV3['version'];
|
||||
file: SourceMapV3['file'];
|
||||
names: SourceMapV3['names'];
|
||||
sourceRoot: SourceMapV3['sourceRoot'];
|
||||
sources: SourceMapV3['sources'];
|
||||
sourcesContent: SourceMapV3['sourcesContent'];
|
||||
resolvedSources: SourceMapV3['sources'];
|
||||
}
|
||||
type Ro<T> = T extends Array<infer V> ? V[] | Readonly<V[]> | RoArray<V> | Readonly<RoArray<V>> : T extends object ? T | Readonly<T> | RoObject<T> | Readonly<RoObject<T>> : T;
|
||||
type RoArray<T> = Ro<T>[];
|
||||
type RoObject<T> = {
|
||||
[K in keyof T]: T[K] | Ro<T[K]>;
|
||||
};
|
||||
|
||||
declare class TraceMap implements SourceMap {
|
||||
version: SourceMapV3['version'];
|
||||
file: SourceMapV3['file'];
|
||||
names: SourceMapV3['names'];
|
||||
sourceRoot: SourceMapV3['sourceRoot'];
|
||||
sources: SourceMapV3['sources'];
|
||||
sourcesContent: SourceMapV3['sourcesContent'];
|
||||
resolvedSources: string[];
|
||||
private _encoded;
|
||||
private _decoded;
|
||||
private _decodedMemo;
|
||||
private _bySources;
|
||||
private _bySourceMemos;
|
||||
constructor(map: SourceMapInput, mapUrl?: string | null);
|
||||
}
|
||||
|
||||
export type { DecodedSourceMap as D, EncodedSourceMap as E, SourceMapInput as S };
|
||||
+2
@@ -0,0 +1,2 @@
|
||||
'use strict';
|
||||
|
||||
+2
@@ -0,0 +1,2 @@
|
||||
export { A as Arrayable, f as Awaitable, i as CreateHotContextFunction, D as DebuggerOptions, c as DepsHandlingOptions, g as FetchFunction, F as FetchResult, b as HotContext, j as ModuleCache, M as ModuleCacheMap, N as Nullable, R as RawSourceMap, h as ResolveIdFunction, S as StartOfSourceMap, d as ViteNodeResolveId, k as ViteNodeRunnerOptions, V as ViteNodeServerOptions } from './index-O2IrwHKf.js';
|
||||
export { D as DecodedSourceMap, E as EncodedSourceMap, S as SourceMapInput } from './trace-mapping.d-xyIfZtPm.js';
|
||||
+1
@@ -0,0 +1 @@
|
||||
|
||||
+194
@@ -0,0 +1,194 @@
|
||||
'use strict';
|
||||
|
||||
var node_url = require('node:url');
|
||||
var node_module = require('node:module');
|
||||
var fs = require('node:fs');
|
||||
var pathe = require('pathe');
|
||||
|
||||
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 ? new RegExp(`(?:^|/@fs/)${drive}(:[\\/])`) : null;
|
||||
const driveOppositeRegext = driveOpposite ? new RegExp(`(?:^|/@fs/)${driveOpposite}(:[\\/])`) : null;
|
||||
function slash(str) {
|
||||
return str.replace(/\\/g, "/");
|
||||
}
|
||||
const VALID_ID_PREFIX = "/@id/";
|
||||
function normalizeRequestId(id, base) {
|
||||
if (base && id.startsWith(withTrailingSlash(base)))
|
||||
id = `/${id.slice(base.length)}`;
|
||||
if (driveRegexp && !(driveRegexp == null ? void 0 : driveRegexp.test(id)) && (driveOppositeRegext == null ? void 0 : driveOppositeRegext.test(id)))
|
||||
id = id.replace(driveOppositeRegext, `${drive}$1`);
|
||||
return id.replace(/^\/@id\/__x00__/, "\0").replace(/^\/@id\//, "").replace(/^__vite-browser-external:/, "").replace(/^file:/, "").replace(/^\/+/, "/").replace(/\?v=\w+/, "?").replace(/&v=\w+/, "").replace(/\?t=\w+/, "?").replace(/&t=\w+/, "").replace(/\?import/, "?").replace(/&import/, "").replace(/\?&/, "?").replace(/\?+$/, "");
|
||||
}
|
||||
const queryRE = /\?.*$/s;
|
||||
const hashRE = /#.*$/s;
|
||||
function cleanUrl(url) {
|
||||
return url.replace(hashRE, "").replace(queryRE, "");
|
||||
}
|
||||
const internalRequests = [
|
||||
"@vite/client",
|
||||
"@vite/env"
|
||||
];
|
||||
const internalRequestRegexp = new RegExp(`^/?(${internalRequests.join("|")})$`);
|
||||
function isInternalRequest(id) {
|
||||
return internalRequestRegexp.test(id);
|
||||
}
|
||||
const prefixedBuiltins = /* @__PURE__ */ new Set([
|
||||
"node:test"
|
||||
]);
|
||||
const builtins = /* @__PURE__ */ new Set([
|
||||
...node_module.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;
|
||||
return id.replace(/\\/g, "/").replace(/^\/@fs\//, isWindows ? "" : "/").replace(/^file:\//, "/").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 = pathe.resolve(root, id.slice(1));
|
||||
if (fs.existsSync(cleanUrl(resolved)))
|
||||
return { absolute: resolved, exists: true };
|
||||
} else if (id.startsWith(withTrailingSlash(root)) && fs.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(node_url.fileURLToPath(node_url.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(NODE_BUILTIN_NAMESPACE.length) : id
|
||||
);
|
||||
}
|
||||
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}`;
|
||||
}
|
||||
function traverseBetweenDirs(longerDir, shorterDir, cb) {
|
||||
while (longerDir !== shorterDir) {
|
||||
cb(longerDir);
|
||||
longerDir = pathe.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 void 0;
|
||||
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) {
|
||||
var _a;
|
||||
const originalBasedir = basedir;
|
||||
while (basedir) {
|
||||
const cached = getCachedData(packageCache, basedir, originalBasedir);
|
||||
if (cached)
|
||||
return cached;
|
||||
const pkgPath = pathe.join(basedir, "package.json");
|
||||
if ((_a = await fs.promises.stat(pkgPath).catch(() => {
|
||||
})) == null ? void 0 : _a.isFile()) {
|
||||
const pkgData = JSON.parse(await fs.promises.readFile(pkgPath, "utf8"));
|
||||
if (packageCache)
|
||||
setCacheData(packageCache, pkgData, basedir, originalBasedir);
|
||||
return pkgData;
|
||||
}
|
||||
const nextBasedir = pathe.dirname(basedir);
|
||||
if (nextBasedir === basedir)
|
||||
break;
|
||||
basedir = nextBasedir;
|
||||
}
|
||||
return {};
|
||||
}
|
||||
|
||||
exports.VALID_ID_PREFIX = VALID_ID_PREFIX;
|
||||
exports.cleanUrl = cleanUrl;
|
||||
exports.createImportMetaEnvProxy = createImportMetaEnvProxy;
|
||||
exports.findNearestPackageData = findNearestPackageData;
|
||||
exports.getCachedData = getCachedData;
|
||||
exports.hashRE = hashRE;
|
||||
exports.isInternalRequest = isInternalRequest;
|
||||
exports.isNodeBuiltin = isNodeBuiltin;
|
||||
exports.isPrimitive = isPrimitive;
|
||||
exports.isWindows = isWindows;
|
||||
exports.normalizeModuleId = normalizeModuleId;
|
||||
exports.normalizeRequestId = normalizeRequestId;
|
||||
exports.queryRE = queryRE;
|
||||
exports.setCacheData = setCacheData;
|
||||
exports.slash = slash;
|
||||
exports.toArray = toArray;
|
||||
exports.toFilePath = toFilePath;
|
||||
exports.withTrailingSlash = withTrailingSlash;
|
||||
+33
@@ -0,0 +1,33 @@
|
||||
import { N as Nullable, A as Arrayable } from './index-O2IrwHKf.js';
|
||||
import './trace-mapping.d-xyIfZtPm.js';
|
||||
|
||||
declare const isWindows: boolean;
|
||||
declare function slash(str: string): string;
|
||||
declare const VALID_ID_PREFIX = "/@id/";
|
||||
declare function normalizeRequestId(id: string, base?: string): string;
|
||||
declare const queryRE: RegExp;
|
||||
declare const hashRE: RegExp;
|
||||
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';
|
||||
}>;
|
||||
|
||||
export { VALID_ID_PREFIX, cleanUrl, createImportMetaEnvProxy, findNearestPackageData, getCachedData, hashRE, isInternalRequest, isNodeBuiltin, isPrimitive, isWindows, normalizeModuleId, normalizeRequestId, queryRE, setCacheData, slash, toArray, toFilePath, withTrailingSlash };
|
||||
+175
@@ -0,0 +1,175 @@
|
||||
import { fileURLToPath, pathToFileURL } from 'node:url';
|
||||
import { builtinModules } from 'node:module';
|
||||
import { existsSync, promises } from 'node:fs';
|
||||
import { resolve, dirname, join } from 'pathe';
|
||||
|
||||
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 ? new RegExp(`(?:^|/@fs/)${drive}(:[\\/])`) : null;
|
||||
const driveOppositeRegext = driveOpposite ? new RegExp(`(?:^|/@fs/)${driveOpposite}(:[\\/])`) : null;
|
||||
function slash(str) {
|
||||
return str.replace(/\\/g, "/");
|
||||
}
|
||||
const VALID_ID_PREFIX = "/@id/";
|
||||
function normalizeRequestId(id, base) {
|
||||
if (base && id.startsWith(withTrailingSlash(base)))
|
||||
id = `/${id.slice(base.length)}`;
|
||||
if (driveRegexp && !(driveRegexp == null ? void 0 : driveRegexp.test(id)) && (driveOppositeRegext == null ? void 0 : driveOppositeRegext.test(id)))
|
||||
id = id.replace(driveOppositeRegext, `${drive}$1`);
|
||||
return id.replace(/^\/@id\/__x00__/, "\0").replace(/^\/@id\//, "").replace(/^__vite-browser-external:/, "").replace(/^file:/, "").replace(/^\/+/, "/").replace(/\?v=\w+/, "?").replace(/&v=\w+/, "").replace(/\?t=\w+/, "?").replace(/&t=\w+/, "").replace(/\?import/, "?").replace(/&import/, "").replace(/\?&/, "?").replace(/\?+$/, "");
|
||||
}
|
||||
const queryRE = /\?.*$/s;
|
||||
const hashRE = /#.*$/s;
|
||||
function cleanUrl(url) {
|
||||
return url.replace(hashRE, "").replace(queryRE, "");
|
||||
}
|
||||
const internalRequests = [
|
||||
"@vite/client",
|
||||
"@vite/env"
|
||||
];
|
||||
const internalRequestRegexp = new RegExp(`^/?(${internalRequests.join("|")})$`);
|
||||
function isInternalRequest(id) {
|
||||
return internalRequestRegexp.test(id);
|
||||
}
|
||||
const prefixedBuiltins = /* @__PURE__ */ new Set([
|
||||
"node:test"
|
||||
]);
|
||||
const builtins = /* @__PURE__ */ 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;
|
||||
return id.replace(/\\/g, "/").replace(/^\/@fs\//, isWindows ? "" : "/").replace(/^file:\//, "/").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(NODE_BUILTIN_NAMESPACE.length) : id
|
||||
);
|
||||
}
|
||||
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}`;
|
||||
}
|
||||
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 void 0;
|
||||
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) {
|
||||
var _a;
|
||||
const originalBasedir = basedir;
|
||||
while (basedir) {
|
||||
const cached = getCachedData(packageCache, basedir, originalBasedir);
|
||||
if (cached)
|
||||
return cached;
|
||||
const pkgPath = join(basedir, "package.json");
|
||||
if ((_a = await promises.stat(pkgPath).catch(() => {
|
||||
})) == null ? void 0 : _a.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 {};
|
||||
}
|
||||
|
||||
export { VALID_ID_PREFIX, cleanUrl, createImportMetaEnvProxy, findNearestPackageData, getCachedData, hashRE, isInternalRequest, isNodeBuiltin, isPrimitive, isWindows, normalizeModuleId, normalizeRequestId, queryRE, setCacheData, slash, toArray, toFilePath, withTrailingSlash };
|
||||
+44
@@ -0,0 +1,44 @@
|
||||
MIT License
|
||||
|
||||
Copyright (c) Pooya Parsa <pooya@pi0.io> - Daniel Roe <daniel@roe.dev>
|
||||
|
||||
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.
|
||||
|
||||
--------------------------------------------------------------------------------
|
||||
|
||||
Copyright Joyent, Inc. and other Node contributors.
|
||||
|
||||
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.
|
||||
+69
@@ -0,0 +1,69 @@
|
||||
# 🛣️ pathe
|
||||
|
||||
> Universal filesystem path utils
|
||||
|
||||
[![version][npm-v-src]][npm-v-href]
|
||||
[![downloads][npm-d-src]][npm-d-href]
|
||||
[![size][size-src]][size-href]
|
||||
|
||||
> **❓ Why**
|
||||
>
|
||||
> For [historical reasons](https://docs.microsoft.com/en-us/archive/blogs/larryosterman/why-is-the-dos-path-character), windows followed MS-DOS and using backslash for separating paths rather than slash used for macOS, Linux, and other Posix operating systems. Nowadays, [Windows](https://docs.microsoft.com/en-us/windows/win32/fileio/naming-a-file?redirectedfrom=MSDN) supports both Slash and Backslash for paths. [Node.js's built in `path` module](https://nodejs.org/api/path.html) in the default operation of the path module varies based on the operating system on which a Node.js application is running. Specifically, when running on a Windows operating system, the path module will assume that Windows-style paths are being used. **This makes inconsistent code behavior between Windows and POSIX.**
|
||||
> Compared to popular [upath](https://github.com/anodynos/upath), pathe is providing **identical exports** of Node.js with normalization on **all operations** and written in modern **ESM/Typescript** and has **no dependency on Node.js**!
|
||||
|
||||
This package is a drop-in replacement of the Node.js's [path module](https://nodejs.org/api/path.html) module and ensures paths are normalized with slash `/` and work in environments including Node.js.
|
||||
|
||||
## 💿 Usage
|
||||
|
||||
Install using npm or yarn:
|
||||
|
||||
```bash
|
||||
# npm
|
||||
npm i pathe
|
||||
|
||||
# yarn
|
||||
yarn add pathe
|
||||
|
||||
# pnpm
|
||||
pnpm i pathe
|
||||
```
|
||||
|
||||
Import:
|
||||
|
||||
```js
|
||||
// ESM / Typescript
|
||||
import { resolve } from 'pathe'
|
||||
|
||||
// CommonJS
|
||||
const { resolve } = require('pathe')
|
||||
```
|
||||
|
||||
Read more about path utils from [Node.js documentation](https://nodejs.org/api/path.html) and rest assured behavior is ALWAYS like POSIX regardless of your input paths format and running platform!
|
||||
|
||||
### Extra utilties
|
||||
|
||||
Pathe exports some extra utilities that do not exist in standard Node.js [path module](https://nodejs.org/api/path.html).
|
||||
In order to use them, you can import from `pathe/utils` subpath:
|
||||
|
||||
```js
|
||||
import { filename, normalizeAliases, resolveAlias } from 'pathe/utils'
|
||||
```
|
||||
|
||||
## License
|
||||
|
||||
MIT. Made with 💖
|
||||
|
||||
Some code used from Node.js project. See [LICENSE](./LICENSE).
|
||||
|
||||
<!-- Refs -->
|
||||
[npm-v-src]: https://img.shields.io/npm/v/pathe?style=flat-square
|
||||
[npm-v-href]: https://npmjs.com/package/pathe
|
||||
|
||||
[npm-d-src]: https://img.shields.io/npm/dm/pathe?style=flat-square
|
||||
[npm-d-href]: https://npmjs.com/package/pathe
|
||||
|
||||
[github-actions-src]: https://img.shields.io/github/workflow/status/unjs/pathe/ci/main?style=flat-square
|
||||
[github-actions-href]: https://github.com/unjs/pathe/actions?query=workflow%3Aci
|
||||
|
||||
[size-src]: https://packagephobia.now.sh/badge?p=pathe
|
||||
[size-href]: https://packagephobia.now.sh/result?p=pathe
|
||||
Generated
Vendored
+23
@@ -0,0 +1,23 @@
|
||||
'use strict';
|
||||
|
||||
Object.defineProperty(exports, '__esModule', { value: true });
|
||||
|
||||
const index = require('./shared/pathe.1f0a373c.cjs');
|
||||
|
||||
|
||||
|
||||
exports.basename = index.basename;
|
||||
exports.default = index.path;
|
||||
exports.delimiter = index.delimiter;
|
||||
exports.dirname = index.dirname;
|
||||
exports.extname = index.extname;
|
||||
exports.format = index.format;
|
||||
exports.isAbsolute = index.isAbsolute;
|
||||
exports.join = index.join;
|
||||
exports.normalize = index.normalize;
|
||||
exports.normalizeString = index.normalizeString;
|
||||
exports.parse = index.parse;
|
||||
exports.relative = index.relative;
|
||||
exports.resolve = index.resolve;
|
||||
exports.sep = index.sep;
|
||||
exports.toNamespacedPath = index.toNamespacedPath;
|
||||
Generated
Vendored
+36
@@ -0,0 +1,36 @@
|
||||
import path$1 from 'node:path';
|
||||
|
||||
declare const sep = "/";
|
||||
declare const delimiter = ":";
|
||||
declare const normalize: typeof path$1.normalize;
|
||||
declare const join: typeof path$1.join;
|
||||
declare const resolve: typeof path$1.resolve;
|
||||
declare function normalizeString(path: string, allowAboveRoot: boolean): string;
|
||||
declare const isAbsolute: typeof path$1.isAbsolute;
|
||||
declare const toNamespacedPath: typeof path$1.toNamespacedPath;
|
||||
declare const extname: typeof path$1.extname;
|
||||
declare const relative: typeof path$1.relative;
|
||||
declare const dirname: typeof path$1.dirname;
|
||||
declare const format: typeof path$1.format;
|
||||
declare const basename: typeof path$1.basename;
|
||||
declare const parse: typeof path$1.parse;
|
||||
|
||||
declare const path_basename: typeof basename;
|
||||
declare const path_delimiter: typeof delimiter;
|
||||
declare const path_dirname: typeof dirname;
|
||||
declare const path_extname: typeof extname;
|
||||
declare const path_format: typeof format;
|
||||
declare const path_isAbsolute: typeof isAbsolute;
|
||||
declare const path_join: typeof join;
|
||||
declare const path_normalize: typeof normalize;
|
||||
declare const path_normalizeString: typeof normalizeString;
|
||||
declare const path_parse: typeof parse;
|
||||
declare const path_relative: typeof relative;
|
||||
declare const path_resolve: typeof resolve;
|
||||
declare const path_sep: typeof sep;
|
||||
declare const path_toNamespacedPath: typeof toNamespacedPath;
|
||||
declare namespace path {
|
||||
export { path_basename as basename, path_delimiter as delimiter, path_dirname as dirname, path_extname as extname, path_format as format, path_isAbsolute as isAbsolute, path_join as join, path_normalize as normalize, path_normalizeString as normalizeString, path_parse as parse, path_relative as relative, path_resolve as resolve, path_sep as sep, path_toNamespacedPath as toNamespacedPath };
|
||||
}
|
||||
|
||||
export { basename, path as default, delimiter, dirname, extname, format, isAbsolute, join, normalize, normalizeString, parse, relative, resolve, sep, toNamespacedPath };
|
||||
Generated
Vendored
+36
@@ -0,0 +1,36 @@
|
||||
import path$1 from 'node:path';
|
||||
|
||||
declare const sep = "/";
|
||||
declare const delimiter = ":";
|
||||
declare const normalize: typeof path$1.normalize;
|
||||
declare const join: typeof path$1.join;
|
||||
declare const resolve: typeof path$1.resolve;
|
||||
declare function normalizeString(path: string, allowAboveRoot: boolean): string;
|
||||
declare const isAbsolute: typeof path$1.isAbsolute;
|
||||
declare const toNamespacedPath: typeof path$1.toNamespacedPath;
|
||||
declare const extname: typeof path$1.extname;
|
||||
declare const relative: typeof path$1.relative;
|
||||
declare const dirname: typeof path$1.dirname;
|
||||
declare const format: typeof path$1.format;
|
||||
declare const basename: typeof path$1.basename;
|
||||
declare const parse: typeof path$1.parse;
|
||||
|
||||
declare const path_basename: typeof basename;
|
||||
declare const path_delimiter: typeof delimiter;
|
||||
declare const path_dirname: typeof dirname;
|
||||
declare const path_extname: typeof extname;
|
||||
declare const path_format: typeof format;
|
||||
declare const path_isAbsolute: typeof isAbsolute;
|
||||
declare const path_join: typeof join;
|
||||
declare const path_normalize: typeof normalize;
|
||||
declare const path_normalizeString: typeof normalizeString;
|
||||
declare const path_parse: typeof parse;
|
||||
declare const path_relative: typeof relative;
|
||||
declare const path_resolve: typeof resolve;
|
||||
declare const path_sep: typeof sep;
|
||||
declare const path_toNamespacedPath: typeof toNamespacedPath;
|
||||
declare namespace path {
|
||||
export { path_basename as basename, path_delimiter as delimiter, path_dirname as dirname, path_extname as extname, path_format as format, path_isAbsolute as isAbsolute, path_join as join, path_normalize as normalize, path_normalizeString as normalizeString, path_parse as parse, path_relative as relative, path_resolve as resolve, path_sep as sep, path_toNamespacedPath as toNamespacedPath };
|
||||
}
|
||||
|
||||
export { basename, path as default, delimiter, dirname, extname, format, isAbsolute, join, normalize, normalizeString, parse, relative, resolve, sep, toNamespacedPath };
|
||||
Generated
Vendored
+36
@@ -0,0 +1,36 @@
|
||||
import path$1 from 'node:path';
|
||||
|
||||
declare const sep = "/";
|
||||
declare const delimiter = ":";
|
||||
declare const normalize: typeof path$1.normalize;
|
||||
declare const join: typeof path$1.join;
|
||||
declare const resolve: typeof path$1.resolve;
|
||||
declare function normalizeString(path: string, allowAboveRoot: boolean): string;
|
||||
declare const isAbsolute: typeof path$1.isAbsolute;
|
||||
declare const toNamespacedPath: typeof path$1.toNamespacedPath;
|
||||
declare const extname: typeof path$1.extname;
|
||||
declare const relative: typeof path$1.relative;
|
||||
declare const dirname: typeof path$1.dirname;
|
||||
declare const format: typeof path$1.format;
|
||||
declare const basename: typeof path$1.basename;
|
||||
declare const parse: typeof path$1.parse;
|
||||
|
||||
declare const path_basename: typeof basename;
|
||||
declare const path_delimiter: typeof delimiter;
|
||||
declare const path_dirname: typeof dirname;
|
||||
declare const path_extname: typeof extname;
|
||||
declare const path_format: typeof format;
|
||||
declare const path_isAbsolute: typeof isAbsolute;
|
||||
declare const path_join: typeof join;
|
||||
declare const path_normalize: typeof normalize;
|
||||
declare const path_normalizeString: typeof normalizeString;
|
||||
declare const path_parse: typeof parse;
|
||||
declare const path_relative: typeof relative;
|
||||
declare const path_resolve: typeof resolve;
|
||||
declare const path_sep: typeof sep;
|
||||
declare const path_toNamespacedPath: typeof toNamespacedPath;
|
||||
declare namespace path {
|
||||
export { path_basename as basename, path_delimiter as delimiter, path_dirname as dirname, path_extname as extname, path_format as format, path_isAbsolute as isAbsolute, path_join as join, path_normalize as normalize, path_normalizeString as normalizeString, path_parse as parse, path_relative as relative, path_resolve as resolve, path_sep as sep, path_toNamespacedPath as toNamespacedPath };
|
||||
}
|
||||
|
||||
export { basename, path as default, delimiter, dirname, extname, format, isAbsolute, join, normalize, normalizeString, parse, relative, resolve, sep, toNamespacedPath };
|
||||
Generated
Vendored
+1
@@ -0,0 +1 @@
|
||||
export { h as basename, p as default, d as delimiter, f as dirname, e as extname, g as format, i as isAbsolute, j as join, a as normalize, b as normalizeString, k as parse, c as relative, r as resolve, s as sep, t as toNamespacedPath } from './shared/pathe.ff20891b.mjs';
|
||||
Generated
Vendored
+238
@@ -0,0 +1,238 @@
|
||||
'use strict';
|
||||
|
||||
const _DRIVE_LETTER_START_RE = /^[A-Za-z]:\//;
|
||||
function normalizeWindowsPath(input = "") {
|
||||
if (!input) {
|
||||
return input;
|
||||
}
|
||||
return input.replace(/\\/g, "/").replace(_DRIVE_LETTER_START_RE, (r) => r.toUpperCase());
|
||||
}
|
||||
|
||||
const _UNC_REGEX = /^[/\\]{2}/;
|
||||
const _IS_ABSOLUTE_RE = /^[/\\](?![/\\])|^[/\\]{2}(?!\.)|^[A-Za-z]:[/\\]/;
|
||||
const _DRIVE_LETTER_RE = /^[A-Za-z]:$/;
|
||||
const _ROOT_FOLDER_RE = /^\/([A-Za-z]:)?$/;
|
||||
const sep = "/";
|
||||
const delimiter = ":";
|
||||
const normalize = function(path) {
|
||||
if (path.length === 0) {
|
||||
return ".";
|
||||
}
|
||||
path = normalizeWindowsPath(path);
|
||||
const isUNCPath = path.match(_UNC_REGEX);
|
||||
const isPathAbsolute = isAbsolute(path);
|
||||
const trailingSeparator = path[path.length - 1] === "/";
|
||||
path = normalizeString(path, !isPathAbsolute);
|
||||
if (path.length === 0) {
|
||||
if (isPathAbsolute) {
|
||||
return "/";
|
||||
}
|
||||
return trailingSeparator ? "./" : ".";
|
||||
}
|
||||
if (trailingSeparator) {
|
||||
path += "/";
|
||||
}
|
||||
if (_DRIVE_LETTER_RE.test(path)) {
|
||||
path += "/";
|
||||
}
|
||||
if (isUNCPath) {
|
||||
if (!isPathAbsolute) {
|
||||
return `//./${path}`;
|
||||
}
|
||||
return `//${path}`;
|
||||
}
|
||||
return isPathAbsolute && !isAbsolute(path) ? `/${path}` : path;
|
||||
};
|
||||
const join = function(...arguments_) {
|
||||
if (arguments_.length === 0) {
|
||||
return ".";
|
||||
}
|
||||
let joined;
|
||||
for (const argument of arguments_) {
|
||||
if (argument && argument.length > 0) {
|
||||
if (joined === void 0) {
|
||||
joined = argument;
|
||||
} else {
|
||||
joined += `/${argument}`;
|
||||
}
|
||||
}
|
||||
}
|
||||
if (joined === void 0) {
|
||||
return ".";
|
||||
}
|
||||
return normalize(joined.replace(/\/\/+/g, "/"));
|
||||
};
|
||||
function cwd() {
|
||||
if (typeof process !== "undefined" && typeof process.cwd === "function") {
|
||||
return process.cwd().replace(/\\/g, "/");
|
||||
}
|
||||
return "/";
|
||||
}
|
||||
const resolve = function(...arguments_) {
|
||||
arguments_ = arguments_.map((argument) => normalizeWindowsPath(argument));
|
||||
let resolvedPath = "";
|
||||
let resolvedAbsolute = false;
|
||||
for (let index = arguments_.length - 1; index >= -1 && !resolvedAbsolute; index--) {
|
||||
const path = index >= 0 ? arguments_[index] : cwd();
|
||||
if (!path || path.length === 0) {
|
||||
continue;
|
||||
}
|
||||
resolvedPath = `${path}/${resolvedPath}`;
|
||||
resolvedAbsolute = isAbsolute(path);
|
||||
}
|
||||
resolvedPath = normalizeString(resolvedPath, !resolvedAbsolute);
|
||||
if (resolvedAbsolute && !isAbsolute(resolvedPath)) {
|
||||
return `/${resolvedPath}`;
|
||||
}
|
||||
return resolvedPath.length > 0 ? resolvedPath : ".";
|
||||
};
|
||||
function normalizeString(path, allowAboveRoot) {
|
||||
let res = "";
|
||||
let lastSegmentLength = 0;
|
||||
let lastSlash = -1;
|
||||
let dots = 0;
|
||||
let char = null;
|
||||
for (let index = 0; index <= path.length; ++index) {
|
||||
if (index < path.length) {
|
||||
char = path[index];
|
||||
} else if (char === "/") {
|
||||
break;
|
||||
} else {
|
||||
char = "/";
|
||||
}
|
||||
if (char === "/") {
|
||||
if (lastSlash === index - 1 || dots === 1) ; else if (dots === 2) {
|
||||
if (res.length < 2 || lastSegmentLength !== 2 || res[res.length - 1] !== "." || res[res.length - 2] !== ".") {
|
||||
if (res.length > 2) {
|
||||
const lastSlashIndex = res.lastIndexOf("/");
|
||||
if (lastSlashIndex === -1) {
|
||||
res = "";
|
||||
lastSegmentLength = 0;
|
||||
} else {
|
||||
res = res.slice(0, lastSlashIndex);
|
||||
lastSegmentLength = res.length - 1 - res.lastIndexOf("/");
|
||||
}
|
||||
lastSlash = index;
|
||||
dots = 0;
|
||||
continue;
|
||||
} else if (res.length > 0) {
|
||||
res = "";
|
||||
lastSegmentLength = 0;
|
||||
lastSlash = index;
|
||||
dots = 0;
|
||||
continue;
|
||||
}
|
||||
}
|
||||
if (allowAboveRoot) {
|
||||
res += res.length > 0 ? "/.." : "..";
|
||||
lastSegmentLength = 2;
|
||||
}
|
||||
} else {
|
||||
if (res.length > 0) {
|
||||
res += `/${path.slice(lastSlash + 1, index)}`;
|
||||
} else {
|
||||
res = path.slice(lastSlash + 1, index);
|
||||
}
|
||||
lastSegmentLength = index - lastSlash - 1;
|
||||
}
|
||||
lastSlash = index;
|
||||
dots = 0;
|
||||
} else if (char === "." && dots !== -1) {
|
||||
++dots;
|
||||
} else {
|
||||
dots = -1;
|
||||
}
|
||||
}
|
||||
return res;
|
||||
}
|
||||
const isAbsolute = function(p) {
|
||||
return _IS_ABSOLUTE_RE.test(p);
|
||||
};
|
||||
const toNamespacedPath = function(p) {
|
||||
return normalizeWindowsPath(p);
|
||||
};
|
||||
const _EXTNAME_RE = /.(\.[^./]+)$/;
|
||||
const extname = function(p) {
|
||||
const match = _EXTNAME_RE.exec(normalizeWindowsPath(p));
|
||||
return match && match[1] || "";
|
||||
};
|
||||
const relative = function(from, to) {
|
||||
const _from = resolve(from).replace(_ROOT_FOLDER_RE, "$1").split("/");
|
||||
const _to = resolve(to).replace(_ROOT_FOLDER_RE, "$1").split("/");
|
||||
if (_to[0][1] === ":" && _from[0][1] === ":" && _from[0] !== _to[0]) {
|
||||
return _to.join("/");
|
||||
}
|
||||
const _fromCopy = [..._from];
|
||||
for (const segment of _fromCopy) {
|
||||
if (_to[0] !== segment) {
|
||||
break;
|
||||
}
|
||||
_from.shift();
|
||||
_to.shift();
|
||||
}
|
||||
return [..._from.map(() => ".."), ..._to].join("/");
|
||||
};
|
||||
const dirname = function(p) {
|
||||
const segments = normalizeWindowsPath(p).replace(/\/$/, "").split("/").slice(0, -1);
|
||||
if (segments.length === 1 && _DRIVE_LETTER_RE.test(segments[0])) {
|
||||
segments[0] += "/";
|
||||
}
|
||||
return segments.join("/") || (isAbsolute(p) ? "/" : ".");
|
||||
};
|
||||
const format = function(p) {
|
||||
const segments = [p.root, p.dir, p.base ?? p.name + p.ext].filter(Boolean);
|
||||
return normalizeWindowsPath(
|
||||
p.root ? resolve(...segments) : segments.join("/")
|
||||
);
|
||||
};
|
||||
const basename = function(p, extension) {
|
||||
const lastSegment = normalizeWindowsPath(p).split("/").pop();
|
||||
return extension && lastSegment.endsWith(extension) ? lastSegment.slice(0, -extension.length) : lastSegment;
|
||||
};
|
||||
const parse = function(p) {
|
||||
const root = normalizeWindowsPath(p).split("/").shift() || "/";
|
||||
const base = basename(p);
|
||||
const extension = extname(base);
|
||||
return {
|
||||
root,
|
||||
dir: dirname(p),
|
||||
base,
|
||||
ext: extension,
|
||||
name: base.slice(0, base.length - extension.length)
|
||||
};
|
||||
};
|
||||
|
||||
const path = {
|
||||
__proto__: null,
|
||||
basename: basename,
|
||||
delimiter: delimiter,
|
||||
dirname: dirname,
|
||||
extname: extname,
|
||||
format: format,
|
||||
isAbsolute: isAbsolute,
|
||||
join: join,
|
||||
normalize: normalize,
|
||||
normalizeString: normalizeString,
|
||||
parse: parse,
|
||||
relative: relative,
|
||||
resolve: resolve,
|
||||
sep: sep,
|
||||
toNamespacedPath: toNamespacedPath
|
||||
};
|
||||
|
||||
exports.basename = basename;
|
||||
exports.delimiter = delimiter;
|
||||
exports.dirname = dirname;
|
||||
exports.extname = extname;
|
||||
exports.format = format;
|
||||
exports.isAbsolute = isAbsolute;
|
||||
exports.join = join;
|
||||
exports.normalize = normalize;
|
||||
exports.normalizeString = normalizeString;
|
||||
exports.normalizeWindowsPath = normalizeWindowsPath;
|
||||
exports.parse = parse;
|
||||
exports.path = path;
|
||||
exports.relative = relative;
|
||||
exports.resolve = resolve;
|
||||
exports.sep = sep;
|
||||
exports.toNamespacedPath = toNamespacedPath;
|
||||
Generated
Vendored
+221
@@ -0,0 +1,221 @@
|
||||
const _DRIVE_LETTER_START_RE = /^[A-Za-z]:\//;
|
||||
function normalizeWindowsPath(input = "") {
|
||||
if (!input) {
|
||||
return input;
|
||||
}
|
||||
return input.replace(/\\/g, "/").replace(_DRIVE_LETTER_START_RE, (r) => r.toUpperCase());
|
||||
}
|
||||
|
||||
const _UNC_REGEX = /^[/\\]{2}/;
|
||||
const _IS_ABSOLUTE_RE = /^[/\\](?![/\\])|^[/\\]{2}(?!\.)|^[A-Za-z]:[/\\]/;
|
||||
const _DRIVE_LETTER_RE = /^[A-Za-z]:$/;
|
||||
const _ROOT_FOLDER_RE = /^\/([A-Za-z]:)?$/;
|
||||
const sep = "/";
|
||||
const delimiter = ":";
|
||||
const normalize = function(path) {
|
||||
if (path.length === 0) {
|
||||
return ".";
|
||||
}
|
||||
path = normalizeWindowsPath(path);
|
||||
const isUNCPath = path.match(_UNC_REGEX);
|
||||
const isPathAbsolute = isAbsolute(path);
|
||||
const trailingSeparator = path[path.length - 1] === "/";
|
||||
path = normalizeString(path, !isPathAbsolute);
|
||||
if (path.length === 0) {
|
||||
if (isPathAbsolute) {
|
||||
return "/";
|
||||
}
|
||||
return trailingSeparator ? "./" : ".";
|
||||
}
|
||||
if (trailingSeparator) {
|
||||
path += "/";
|
||||
}
|
||||
if (_DRIVE_LETTER_RE.test(path)) {
|
||||
path += "/";
|
||||
}
|
||||
if (isUNCPath) {
|
||||
if (!isPathAbsolute) {
|
||||
return `//./${path}`;
|
||||
}
|
||||
return `//${path}`;
|
||||
}
|
||||
return isPathAbsolute && !isAbsolute(path) ? `/${path}` : path;
|
||||
};
|
||||
const join = function(...arguments_) {
|
||||
if (arguments_.length === 0) {
|
||||
return ".";
|
||||
}
|
||||
let joined;
|
||||
for (const argument of arguments_) {
|
||||
if (argument && argument.length > 0) {
|
||||
if (joined === void 0) {
|
||||
joined = argument;
|
||||
} else {
|
||||
joined += `/${argument}`;
|
||||
}
|
||||
}
|
||||
}
|
||||
if (joined === void 0) {
|
||||
return ".";
|
||||
}
|
||||
return normalize(joined.replace(/\/\/+/g, "/"));
|
||||
};
|
||||
function cwd() {
|
||||
if (typeof process !== "undefined" && typeof process.cwd === "function") {
|
||||
return process.cwd().replace(/\\/g, "/");
|
||||
}
|
||||
return "/";
|
||||
}
|
||||
const resolve = function(...arguments_) {
|
||||
arguments_ = arguments_.map((argument) => normalizeWindowsPath(argument));
|
||||
let resolvedPath = "";
|
||||
let resolvedAbsolute = false;
|
||||
for (let index = arguments_.length - 1; index >= -1 && !resolvedAbsolute; index--) {
|
||||
const path = index >= 0 ? arguments_[index] : cwd();
|
||||
if (!path || path.length === 0) {
|
||||
continue;
|
||||
}
|
||||
resolvedPath = `${path}/${resolvedPath}`;
|
||||
resolvedAbsolute = isAbsolute(path);
|
||||
}
|
||||
resolvedPath = normalizeString(resolvedPath, !resolvedAbsolute);
|
||||
if (resolvedAbsolute && !isAbsolute(resolvedPath)) {
|
||||
return `/${resolvedPath}`;
|
||||
}
|
||||
return resolvedPath.length > 0 ? resolvedPath : ".";
|
||||
};
|
||||
function normalizeString(path, allowAboveRoot) {
|
||||
let res = "";
|
||||
let lastSegmentLength = 0;
|
||||
let lastSlash = -1;
|
||||
let dots = 0;
|
||||
let char = null;
|
||||
for (let index = 0; index <= path.length; ++index) {
|
||||
if (index < path.length) {
|
||||
char = path[index];
|
||||
} else if (char === "/") {
|
||||
break;
|
||||
} else {
|
||||
char = "/";
|
||||
}
|
||||
if (char === "/") {
|
||||
if (lastSlash === index - 1 || dots === 1) ; else if (dots === 2) {
|
||||
if (res.length < 2 || lastSegmentLength !== 2 || res[res.length - 1] !== "." || res[res.length - 2] !== ".") {
|
||||
if (res.length > 2) {
|
||||
const lastSlashIndex = res.lastIndexOf("/");
|
||||
if (lastSlashIndex === -1) {
|
||||
res = "";
|
||||
lastSegmentLength = 0;
|
||||
} else {
|
||||
res = res.slice(0, lastSlashIndex);
|
||||
lastSegmentLength = res.length - 1 - res.lastIndexOf("/");
|
||||
}
|
||||
lastSlash = index;
|
||||
dots = 0;
|
||||
continue;
|
||||
} else if (res.length > 0) {
|
||||
res = "";
|
||||
lastSegmentLength = 0;
|
||||
lastSlash = index;
|
||||
dots = 0;
|
||||
continue;
|
||||
}
|
||||
}
|
||||
if (allowAboveRoot) {
|
||||
res += res.length > 0 ? "/.." : "..";
|
||||
lastSegmentLength = 2;
|
||||
}
|
||||
} else {
|
||||
if (res.length > 0) {
|
||||
res += `/${path.slice(lastSlash + 1, index)}`;
|
||||
} else {
|
||||
res = path.slice(lastSlash + 1, index);
|
||||
}
|
||||
lastSegmentLength = index - lastSlash - 1;
|
||||
}
|
||||
lastSlash = index;
|
||||
dots = 0;
|
||||
} else if (char === "." && dots !== -1) {
|
||||
++dots;
|
||||
} else {
|
||||
dots = -1;
|
||||
}
|
||||
}
|
||||
return res;
|
||||
}
|
||||
const isAbsolute = function(p) {
|
||||
return _IS_ABSOLUTE_RE.test(p);
|
||||
};
|
||||
const toNamespacedPath = function(p) {
|
||||
return normalizeWindowsPath(p);
|
||||
};
|
||||
const _EXTNAME_RE = /.(\.[^./]+)$/;
|
||||
const extname = function(p) {
|
||||
const match = _EXTNAME_RE.exec(normalizeWindowsPath(p));
|
||||
return match && match[1] || "";
|
||||
};
|
||||
const relative = function(from, to) {
|
||||
const _from = resolve(from).replace(_ROOT_FOLDER_RE, "$1").split("/");
|
||||
const _to = resolve(to).replace(_ROOT_FOLDER_RE, "$1").split("/");
|
||||
if (_to[0][1] === ":" && _from[0][1] === ":" && _from[0] !== _to[0]) {
|
||||
return _to.join("/");
|
||||
}
|
||||
const _fromCopy = [..._from];
|
||||
for (const segment of _fromCopy) {
|
||||
if (_to[0] !== segment) {
|
||||
break;
|
||||
}
|
||||
_from.shift();
|
||||
_to.shift();
|
||||
}
|
||||
return [..._from.map(() => ".."), ..._to].join("/");
|
||||
};
|
||||
const dirname = function(p) {
|
||||
const segments = normalizeWindowsPath(p).replace(/\/$/, "").split("/").slice(0, -1);
|
||||
if (segments.length === 1 && _DRIVE_LETTER_RE.test(segments[0])) {
|
||||
segments[0] += "/";
|
||||
}
|
||||
return segments.join("/") || (isAbsolute(p) ? "/" : ".");
|
||||
};
|
||||
const format = function(p) {
|
||||
const segments = [p.root, p.dir, p.base ?? p.name + p.ext].filter(Boolean);
|
||||
return normalizeWindowsPath(
|
||||
p.root ? resolve(...segments) : segments.join("/")
|
||||
);
|
||||
};
|
||||
const basename = function(p, extension) {
|
||||
const lastSegment = normalizeWindowsPath(p).split("/").pop();
|
||||
return extension && lastSegment.endsWith(extension) ? lastSegment.slice(0, -extension.length) : lastSegment;
|
||||
};
|
||||
const parse = function(p) {
|
||||
const root = normalizeWindowsPath(p).split("/").shift() || "/";
|
||||
const base = basename(p);
|
||||
const extension = extname(base);
|
||||
return {
|
||||
root,
|
||||
dir: dirname(p),
|
||||
base,
|
||||
ext: extension,
|
||||
name: base.slice(0, base.length - extension.length)
|
||||
};
|
||||
};
|
||||
|
||||
const path = {
|
||||
__proto__: null,
|
||||
basename: basename,
|
||||
delimiter: delimiter,
|
||||
dirname: dirname,
|
||||
extname: extname,
|
||||
format: format,
|
||||
isAbsolute: isAbsolute,
|
||||
join: join,
|
||||
normalize: normalize,
|
||||
normalizeString: normalizeString,
|
||||
parse: parse,
|
||||
relative: relative,
|
||||
resolve: resolve,
|
||||
sep: sep,
|
||||
toNamespacedPath: toNamespacedPath
|
||||
};
|
||||
|
||||
export { normalize as a, normalizeString as b, relative as c, delimiter as d, extname as e, dirname as f, format as g, basename as h, isAbsolute as i, join as j, parse as k, normalizeWindowsPath as n, path as p, resolve as r, sep as s, toNamespacedPath as t };
|
||||
Generated
Vendored
+58
@@ -0,0 +1,58 @@
|
||||
'use strict';
|
||||
|
||||
const index = require('./shared/pathe.1f0a373c.cjs');
|
||||
|
||||
const pathSeparators = /* @__PURE__ */ new Set(["/", "\\", void 0]);
|
||||
const normalizedAliasSymbol = Symbol.for("pathe:normalizedAlias");
|
||||
function normalizeAliases(_aliases) {
|
||||
if (_aliases[normalizedAliasSymbol]) {
|
||||
return _aliases;
|
||||
}
|
||||
const aliases = Object.fromEntries(
|
||||
Object.entries(_aliases).sort(([a], [b]) => _compareAliases(a, b))
|
||||
);
|
||||
for (const key in aliases) {
|
||||
for (const alias in aliases) {
|
||||
if (alias === key || key.startsWith(alias)) {
|
||||
continue;
|
||||
}
|
||||
if (aliases[key].startsWith(alias) && pathSeparators.has(aliases[key][alias.length])) {
|
||||
aliases[key] = aliases[alias] + aliases[key].slice(alias.length);
|
||||
}
|
||||
}
|
||||
}
|
||||
Object.defineProperty(aliases, normalizedAliasSymbol, {
|
||||
value: true,
|
||||
enumerable: false
|
||||
});
|
||||
return aliases;
|
||||
}
|
||||
function resolveAlias(path, aliases) {
|
||||
const _path = index.normalizeWindowsPath(path);
|
||||
aliases = normalizeAliases(aliases);
|
||||
for (const [alias, to] of Object.entries(aliases)) {
|
||||
if (!_path.startsWith(alias)) {
|
||||
continue;
|
||||
}
|
||||
const _alias = hasTrailingSlash(alias) ? alias.slice(0, -1) : alias;
|
||||
if (hasTrailingSlash(_path[_alias.length])) {
|
||||
return index.join(to, _path.slice(alias.length));
|
||||
}
|
||||
}
|
||||
return _path;
|
||||
}
|
||||
const FILENAME_RE = /(^|[/\\])([^/\\]+?)(?=(\.[^.]+)?$)/;
|
||||
function filename(path) {
|
||||
return path.match(FILENAME_RE)?.[2];
|
||||
}
|
||||
function _compareAliases(a, b) {
|
||||
return b.split("/").length - a.split("/").length;
|
||||
}
|
||||
function hasTrailingSlash(path = "/") {
|
||||
const lastChar = path[path.length - 1];
|
||||
return lastChar === "/" || lastChar === "\\";
|
||||
}
|
||||
|
||||
exports.filename = filename;
|
||||
exports.normalizeAliases = normalizeAliases;
|
||||
exports.resolveAlias = resolveAlias;
|
||||
Generated
Vendored
+5
@@ -0,0 +1,5 @@
|
||||
declare function normalizeAliases(_aliases: Record<string, string>): Record<string, string>;
|
||||
declare function resolveAlias(path: string, aliases: Record<string, string>): string;
|
||||
declare function filename(path: string): string;
|
||||
|
||||
export { filename, normalizeAliases, resolveAlias };
|
||||
Generated
Vendored
+5
@@ -0,0 +1,5 @@
|
||||
declare function normalizeAliases(_aliases: Record<string, string>): Record<string, string>;
|
||||
declare function resolveAlias(path: string, aliases: Record<string, string>): string;
|
||||
declare function filename(path: string): string;
|
||||
|
||||
export { filename, normalizeAliases, resolveAlias };
|
||||
Generated
Vendored
+5
@@ -0,0 +1,5 @@
|
||||
declare function normalizeAliases(_aliases: Record<string, string>): Record<string, string>;
|
||||
declare function resolveAlias(path: string, aliases: Record<string, string>): string;
|
||||
declare function filename(path: string): string;
|
||||
|
||||
export { filename, normalizeAliases, resolveAlias };
|
||||
Generated
Vendored
+54
@@ -0,0 +1,54 @@
|
||||
import { n as normalizeWindowsPath, j as join } from './shared/pathe.ff20891b.mjs';
|
||||
|
||||
const pathSeparators = /* @__PURE__ */ new Set(["/", "\\", void 0]);
|
||||
const normalizedAliasSymbol = Symbol.for("pathe:normalizedAlias");
|
||||
function normalizeAliases(_aliases) {
|
||||
if (_aliases[normalizedAliasSymbol]) {
|
||||
return _aliases;
|
||||
}
|
||||
const aliases = Object.fromEntries(
|
||||
Object.entries(_aliases).sort(([a], [b]) => _compareAliases(a, b))
|
||||
);
|
||||
for (const key in aliases) {
|
||||
for (const alias in aliases) {
|
||||
if (alias === key || key.startsWith(alias)) {
|
||||
continue;
|
||||
}
|
||||
if (aliases[key].startsWith(alias) && pathSeparators.has(aliases[key][alias.length])) {
|
||||
aliases[key] = aliases[alias] + aliases[key].slice(alias.length);
|
||||
}
|
||||
}
|
||||
}
|
||||
Object.defineProperty(aliases, normalizedAliasSymbol, {
|
||||
value: true,
|
||||
enumerable: false
|
||||
});
|
||||
return aliases;
|
||||
}
|
||||
function resolveAlias(path, aliases) {
|
||||
const _path = normalizeWindowsPath(path);
|
||||
aliases = normalizeAliases(aliases);
|
||||
for (const [alias, to] of Object.entries(aliases)) {
|
||||
if (!_path.startsWith(alias)) {
|
||||
continue;
|
||||
}
|
||||
const _alias = hasTrailingSlash(alias) ? alias.slice(0, -1) : alias;
|
||||
if (hasTrailingSlash(_path[_alias.length])) {
|
||||
return join(to, _path.slice(alias.length));
|
||||
}
|
||||
}
|
||||
return _path;
|
||||
}
|
||||
const FILENAME_RE = /(^|[/\\])([^/\\]+?)(?=(\.[^.]+)?$)/;
|
||||
function filename(path) {
|
||||
return path.match(FILENAME_RE)?.[2];
|
||||
}
|
||||
function _compareAliases(a, b) {
|
||||
return b.split("/").length - a.split("/").length;
|
||||
}
|
||||
function hasTrailingSlash(path = "/") {
|
||||
const lastChar = path[path.length - 1];
|
||||
return lastChar === "/" || lastChar === "\\";
|
||||
}
|
||||
|
||||
export { filename, normalizeAliases, resolveAlias };
|
||||
+48
@@ -0,0 +1,48 @@
|
||||
{
|
||||
"name": "pathe",
|
||||
"version": "1.1.2",
|
||||
"description": "Universal filesystem path utils",
|
||||
"repository": "unjs/pathe",
|
||||
"license": "MIT",
|
||||
"sideEffects": false,
|
||||
"exports": {
|
||||
".": {
|
||||
"types": "./dist/index.d.ts",
|
||||
"import": "./dist/index.mjs",
|
||||
"require": "./dist/index.cjs"
|
||||
},
|
||||
"./utils": {
|
||||
"types": "./dist/utils.d.ts",
|
||||
"import": "./dist/utils.mjs",
|
||||
"require": "./dist/utils.cjs"
|
||||
}
|
||||
},
|
||||
"main": "./dist/index.cjs",
|
||||
"types": "./dist/index.d.ts",
|
||||
"files": [
|
||||
"dist",
|
||||
"utils.d.ts"
|
||||
],
|
||||
"devDependencies": {
|
||||
"@types/node": "^20.10.8",
|
||||
"@vitest/coverage-v8": "^1.1.3",
|
||||
"changelogen": "^0.5.5",
|
||||
"eslint": "^8.56.0",
|
||||
"eslint-config-unjs": "^0.2.1",
|
||||
"jiti": "^1.21.0",
|
||||
"prettier": "^3.1.1",
|
||||
"typescript": "^5.3.3",
|
||||
"unbuild": "^2.0.0",
|
||||
"vitest": "^1.1.3"
|
||||
},
|
||||
"packageManager": "pnpm@8.14.0",
|
||||
"scripts": {
|
||||
"build": "unbuild",
|
||||
"dev": "vitest",
|
||||
"lint": "eslint --ext .ts . && prettier -c src test",
|
||||
"lint:fix": "eslint --cache --ext .ts,.js,.mjs,.cjs . --fix && prettier -c src test -w",
|
||||
"release": "pnpm test && pnpm build && changelogen --release && pnpm publish && git push --follow-tags",
|
||||
"test": "pnpm lint && vitest run --coverage",
|
||||
"test:types": "tsc --noEmit"
|
||||
}
|
||||
}
|
||||
+1
@@ -0,0 +1 @@
|
||||
export * from "./dist/utils";
|
||||
+95
@@ -0,0 +1,95 @@
|
||||
{
|
||||
"name": "vite-node",
|
||||
"type": "module",
|
||||
"version": "1.6.1",
|
||||
"description": "Vite as Node.js runtime",
|
||||
"author": "Anthony Fu <anthonyfu117@hotmail.com>",
|
||||
"license": "MIT",
|
||||
"funding": "https://opencollective.com/vitest",
|
||||
"homepage": "https://github.com/vitest-dev/vitest/blob/main/packages/vite-node#readme",
|
||||
"repository": {
|
||||
"type": "git",
|
||||
"url": "git+https://github.com/vitest-dev/vitest.git",
|
||||
"directory": "packages/vite-node"
|
||||
},
|
||||
"bugs": {
|
||||
"url": "https://github.com/vitest-dev/vitest/issues"
|
||||
},
|
||||
"sideEffects": false,
|
||||
"exports": {
|
||||
".": {
|
||||
"types": "./dist/index.d.ts",
|
||||
"import": "./dist/index.mjs",
|
||||
"require": "./dist/index.cjs"
|
||||
},
|
||||
"./client": {
|
||||
"types": "./dist/client.d.ts",
|
||||
"import": "./dist/client.mjs",
|
||||
"require": "./dist/client.cjs"
|
||||
},
|
||||
"./server": {
|
||||
"types": "./dist/server.d.ts",
|
||||
"import": "./dist/server.mjs",
|
||||
"require": "./dist/server.cjs"
|
||||
},
|
||||
"./utils": {
|
||||
"types": "./dist/utils.d.ts",
|
||||
"import": "./dist/utils.mjs",
|
||||
"require": "./dist/utils.cjs"
|
||||
},
|
||||
"./hmr": {
|
||||
"types": "./dist/hmr.d.ts",
|
||||
"import": "./dist/hmr.mjs",
|
||||
"require": "./dist/hmr.cjs"
|
||||
},
|
||||
"./source-map": {
|
||||
"types": "./dist/source-map.d.ts",
|
||||
"import": "./dist/source-map.mjs",
|
||||
"require": "./dist/source-map.cjs"
|
||||
},
|
||||
"./constants": {
|
||||
"types": "./dist/constants.d.ts",
|
||||
"import": "./dist/constants.mjs",
|
||||
"require": "./dist/constants.cjs"
|
||||
},
|
||||
"./*": "./*"
|
||||
},
|
||||
"main": "./dist/index.mjs",
|
||||
"module": "./dist/index.mjs",
|
||||
"types": "./dist/index.d.ts",
|
||||
"typesVersions": {
|
||||
"*": {
|
||||
"*": [
|
||||
"./dist/*",
|
||||
"./dist/index.d.ts"
|
||||
]
|
||||
}
|
||||
},
|
||||
"bin": {
|
||||
"vite-node": "./vite-node.mjs"
|
||||
},
|
||||
"files": [
|
||||
"*.d.ts",
|
||||
"*.mjs",
|
||||
"dist"
|
||||
],
|
||||
"engines": {
|
||||
"node": "^18.0.0 || >=20.0.0"
|
||||
},
|
||||
"dependencies": {
|
||||
"cac": "^6.7.14",
|
||||
"debug": "^4.3.4",
|
||||
"pathe": "^1.1.1",
|
||||
"picocolors": "^1.0.0",
|
||||
"vite": "^5.0.0"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@jridgewell/trace-mapping": "^0.3.22",
|
||||
"@types/debug": "^4.1.12"
|
||||
},
|
||||
"scripts": {
|
||||
"build": "rimraf dist && rollup -c",
|
||||
"dev": "rollup -c --watch --watch.include 'src/**' -m inline",
|
||||
"typecheck": "tsc --noEmit"
|
||||
}
|
||||
}
|
||||
+2
@@ -0,0 +1,2 @@
|
||||
#!/usr/bin/env node
|
||||
import('./dist/cli.mjs')
|
||||
Reference in New Issue
Block a user