initial commit
This commit is contained in:
+22
@@ -0,0 +1,22 @@
|
||||
MIT License
|
||||
|
||||
Copyright (c) 2021-Present Anthony Fu <https://github.com/antfu>
|
||||
Copyright (c) 2021-Present Matias Capeletto <https://github.com/patak-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.
|
||||
+160
@@ -0,0 +1,160 @@
|
||||
<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 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#L70-L89) 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 `/`;
|
||||
|
||||
## 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 dumpped 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 get stuck, it might because there is a unresolvable circular dependencies, you can set `VITE_NODE_DEBUG_RUNNER=true` to vite-node warn about it.
|
||||
|
||||
```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)
|
||||
+243
@@ -0,0 +1,243 @@
|
||||
'use strict';
|
||||
|
||||
var events = require('events');
|
||||
var picocolors = require('./chunk-picocolors.cjs');
|
||||
var createDebug = require('debug');
|
||||
|
||||
function _interopDefaultLegacy (e) { return e && typeof e === 'object' && 'default' in e ? e : { 'default': e }; }
|
||||
|
||||
var createDebug__default = /*#__PURE__*/_interopDefaultLegacy(createDebug);
|
||||
|
||||
function createHmrEmitter() {
|
||||
const emitter = new events.EventEmitter();
|
||||
return emitter;
|
||||
}
|
||||
function viteNodeHmrPlugin() {
|
||||
const emitter = createHmrEmitter();
|
||||
return {
|
||||
name: "vite-node:hmr",
|
||||
configureServer(server) {
|
||||
const _send = server.ws.send;
|
||||
server.emitter = emitter;
|
||||
server.ws.send = function(payload) {
|
||||
_send(payload);
|
||||
emitter.emit("message", payload);
|
||||
};
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
const debugHmr = createDebug__default["default"]("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)));
|
||||
}
|
||||
function notifyListeners(runner, event, data) {
|
||||
const maps = getCache(runner);
|
||||
const cbs = maps.customListenersMap.get(event);
|
||||
if (cbs)
|
||||
cbs.forEach((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 }) {
|
||||
const maps = getCache(runner);
|
||||
const mod = maps.hotModulesMap.get(path);
|
||||
if (!mod) {
|
||||
return;
|
||||
}
|
||||
const moduleMap = /* @__PURE__ */ new Map();
|
||||
const isSelfUpdate = path === acceptedPath;
|
||||
const modulesToUpdate = /* @__PURE__ */ new Set();
|
||||
if (isSelfUpdate) {
|
||||
modulesToUpdate.add(path);
|
||||
} else {
|
||||
for (const { deps } of mod.callbacks) {
|
||||
deps.forEach((dep) => {
|
||||
if (acceptedPath === dep)
|
||||
modulesToUpdate.add(dep);
|
||||
});
|
||||
}
|
||||
}
|
||||
const qualifiedCallbacks = mod.callbacks.filter(({ deps }) => {
|
||||
return deps.some((dep) => modulesToUpdate.has(dep));
|
||||
});
|
||||
await Promise.all(
|
||||
Array.from(modulesToUpdate).map(async (dep) => {
|
||||
const disposer = maps.disposeMap.get(dep);
|
||||
if (disposer)
|
||||
await disposer(maps.dataMap.get(dep));
|
||||
try {
|
||||
const newMod = await reload(runner, [dep]);
|
||||
moduleMap.set(dep, newMod);
|
||||
} catch (e) {
|
||||
warnFailedFetch(e, dep);
|
||||
}
|
||||
})
|
||||
);
|
||||
return () => {
|
||||
for (const { deps, fn } of qualifiedCallbacks)
|
||||
fn(deps.map((dep) => moduleMap.get(dep)));
|
||||
const loggedPath = isSelfUpdate ? path : `${acceptedPath} via ${path}`;
|
||||
console.log(`${picocolors.picocolors.exports.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":
|
||||
notifyListeners(runner, "vite:beforeUpdate", payload);
|
||||
if (maps.isFirstUpdate) {
|
||||
reload(runner, files);
|
||||
maps.isFirstUpdate = true;
|
||||
}
|
||||
payload.updates.forEach((update) => {
|
||||
if (update.type === "js-update") {
|
||||
queueUpdate(runner, fetchUpdate(runner, update));
|
||||
} else {
|
||||
console.error(`${picocolors.picocolors.exports.cyan("[vite-node]")} no support css hmr.}`);
|
||||
}
|
||||
});
|
||||
break;
|
||||
case "full-reload":
|
||||
notifyListeners(runner, "vite:beforeFullReload", payload);
|
||||
reload(runner, files);
|
||||
break;
|
||||
case "prune":
|
||||
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": {
|
||||
notifyListeners(runner, "vite:error", payload);
|
||||
const err = payload.err;
|
||||
console.error(`${picocolors.picocolors.exports.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);
|
||||
},
|
||||
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;
|
||||
+231
@@ -0,0 +1,231 @@
|
||||
import { EventEmitter } from 'events';
|
||||
import { p as picocolors } from './chunk-picocolors.mjs';
|
||||
import createDebug from 'debug';
|
||||
|
||||
function createHmrEmitter() {
|
||||
const emitter = new EventEmitter();
|
||||
return emitter;
|
||||
}
|
||||
function viteNodeHmrPlugin() {
|
||||
const emitter = createHmrEmitter();
|
||||
return {
|
||||
name: "vite-node:hmr",
|
||||
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)));
|
||||
}
|
||||
function notifyListeners(runner, event, data) {
|
||||
const maps = getCache(runner);
|
||||
const cbs = maps.customListenersMap.get(event);
|
||||
if (cbs)
|
||||
cbs.forEach((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 }) {
|
||||
const maps = getCache(runner);
|
||||
const mod = maps.hotModulesMap.get(path);
|
||||
if (!mod) {
|
||||
return;
|
||||
}
|
||||
const moduleMap = /* @__PURE__ */ new Map();
|
||||
const isSelfUpdate = path === acceptedPath;
|
||||
const modulesToUpdate = /* @__PURE__ */ new Set();
|
||||
if (isSelfUpdate) {
|
||||
modulesToUpdate.add(path);
|
||||
} else {
|
||||
for (const { deps } of mod.callbacks) {
|
||||
deps.forEach((dep) => {
|
||||
if (acceptedPath === dep)
|
||||
modulesToUpdate.add(dep);
|
||||
});
|
||||
}
|
||||
}
|
||||
const qualifiedCallbacks = mod.callbacks.filter(({ deps }) => {
|
||||
return deps.some((dep) => modulesToUpdate.has(dep));
|
||||
});
|
||||
await Promise.all(
|
||||
Array.from(modulesToUpdate).map(async (dep) => {
|
||||
const disposer = maps.disposeMap.get(dep);
|
||||
if (disposer)
|
||||
await disposer(maps.dataMap.get(dep));
|
||||
try {
|
||||
const newMod = await reload(runner, [dep]);
|
||||
moduleMap.set(dep, newMod);
|
||||
} catch (e) {
|
||||
warnFailedFetch(e, dep);
|
||||
}
|
||||
})
|
||||
);
|
||||
return () => {
|
||||
for (const { deps, fn } of qualifiedCallbacks)
|
||||
fn(deps.map((dep) => moduleMap.get(dep)));
|
||||
const loggedPath = isSelfUpdate ? path : `${acceptedPath} via ${path}`;
|
||||
console.log(`${picocolors.exports.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":
|
||||
notifyListeners(runner, "vite:beforeUpdate", payload);
|
||||
if (maps.isFirstUpdate) {
|
||||
reload(runner, files);
|
||||
maps.isFirstUpdate = true;
|
||||
}
|
||||
payload.updates.forEach((update) => {
|
||||
if (update.type === "js-update") {
|
||||
queueUpdate(runner, fetchUpdate(runner, update));
|
||||
} else {
|
||||
console.error(`${picocolors.exports.cyan("[vite-node]")} no support css hmr.}`);
|
||||
}
|
||||
});
|
||||
break;
|
||||
case "full-reload":
|
||||
notifyListeners(runner, "vite:beforeFullReload", payload);
|
||||
reload(runner, files);
|
||||
break;
|
||||
case "prune":
|
||||
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": {
|
||||
notifyListeners(runner, "vite:error", payload);
|
||||
const err = payload.err;
|
||||
console.error(`${picocolors.exports.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);
|
||||
},
|
||||
send(event, data) {
|
||||
maps.messageBuffer.push(JSON.stringify({ type: "custom", event, data }));
|
||||
sendMessageBuffer(runner, emitter);
|
||||
}
|
||||
};
|
||||
return hot;
|
||||
}
|
||||
|
||||
export { createHmrEmitter as a, createHotContext as c, getCache as g, handleMessage as h, reload as r, sendMessageBuffer as s, viteNodeHmrPlugin as v };
|
||||
+70
@@ -0,0 +1,70 @@
|
||||
'use strict';
|
||||
|
||||
var require$$0 = require('tty');
|
||||
|
||||
function _interopDefaultLegacy (e) { return e && typeof e === 'object' && 'default' in e ? e : { 'default': e }; }
|
||||
|
||||
var require$$0__default = /*#__PURE__*/_interopDefaultLegacy(require$$0);
|
||||
|
||||
var picocolors = {exports: {}};
|
||||
|
||||
let tty = require$$0__default["default"];
|
||||
|
||||
let isColorSupported =
|
||||
!("NO_COLOR" in process.env || process.argv.includes("--no-color")) &&
|
||||
("FORCE_COLOR" in process.env ||
|
||||
process.argv.includes("--color") ||
|
||||
process.platform === "win32" ||
|
||||
(tty.isatty(1) && process.env.TERM !== "dumb") ||
|
||||
"CI" in process.env);
|
||||
|
||||
let formatter =
|
||||
(open, close, replace = open) =>
|
||||
input => {
|
||||
let string = "" + input;
|
||||
let index = string.indexOf(close, open.length);
|
||||
return ~index
|
||||
? open + replaceClose(string, close, replace, index) + close
|
||||
: open + string + close
|
||||
};
|
||||
|
||||
let replaceClose = (string, close, replace, index) => {
|
||||
let start = string.substring(0, index) + replace;
|
||||
let end = string.substring(index + close.length);
|
||||
let nextIndex = end.indexOf(close);
|
||||
return ~nextIndex ? start + replaceClose(end, close, replace, nextIndex) : start + end
|
||||
};
|
||||
|
||||
let createColors = (enabled = isColorSupported) => ({
|
||||
isColorSupported: enabled,
|
||||
reset: enabled ? s => `\x1b[0m${s}\x1b[0m` : String,
|
||||
bold: enabled ? formatter("\x1b[1m", "\x1b[22m", "\x1b[22m\x1b[1m") : String,
|
||||
dim: enabled ? formatter("\x1b[2m", "\x1b[22m", "\x1b[22m\x1b[2m") : String,
|
||||
italic: enabled ? formatter("\x1b[3m", "\x1b[23m") : String,
|
||||
underline: enabled ? formatter("\x1b[4m", "\x1b[24m") : String,
|
||||
inverse: enabled ? formatter("\x1b[7m", "\x1b[27m") : String,
|
||||
hidden: enabled ? formatter("\x1b[8m", "\x1b[28m") : String,
|
||||
strikethrough: enabled ? formatter("\x1b[9m", "\x1b[29m") : String,
|
||||
black: enabled ? formatter("\x1b[30m", "\x1b[39m") : String,
|
||||
red: enabled ? formatter("\x1b[31m", "\x1b[39m") : String,
|
||||
green: enabled ? formatter("\x1b[32m", "\x1b[39m") : String,
|
||||
yellow: enabled ? formatter("\x1b[33m", "\x1b[39m") : String,
|
||||
blue: enabled ? formatter("\x1b[34m", "\x1b[39m") : String,
|
||||
magenta: enabled ? formatter("\x1b[35m", "\x1b[39m") : String,
|
||||
cyan: enabled ? formatter("\x1b[36m", "\x1b[39m") : String,
|
||||
white: enabled ? formatter("\x1b[37m", "\x1b[39m") : String,
|
||||
gray: enabled ? formatter("\x1b[90m", "\x1b[39m") : String,
|
||||
bgBlack: enabled ? formatter("\x1b[40m", "\x1b[49m") : String,
|
||||
bgRed: enabled ? formatter("\x1b[41m", "\x1b[49m") : String,
|
||||
bgGreen: enabled ? formatter("\x1b[42m", "\x1b[49m") : String,
|
||||
bgYellow: enabled ? formatter("\x1b[43m", "\x1b[49m") : String,
|
||||
bgBlue: enabled ? formatter("\x1b[44m", "\x1b[49m") : String,
|
||||
bgMagenta: enabled ? formatter("\x1b[45m", "\x1b[49m") : String,
|
||||
bgCyan: enabled ? formatter("\x1b[46m", "\x1b[49m") : String,
|
||||
bgWhite: enabled ? formatter("\x1b[47m", "\x1b[49m") : String,
|
||||
});
|
||||
|
||||
picocolors.exports = createColors();
|
||||
picocolors.exports.createColors = createColors;
|
||||
|
||||
exports.picocolors = picocolors;
|
||||
+64
@@ -0,0 +1,64 @@
|
||||
import require$$0 from 'tty';
|
||||
|
||||
var picocolors = {exports: {}};
|
||||
|
||||
let tty = require$$0;
|
||||
|
||||
let isColorSupported =
|
||||
!("NO_COLOR" in process.env || process.argv.includes("--no-color")) &&
|
||||
("FORCE_COLOR" in process.env ||
|
||||
process.argv.includes("--color") ||
|
||||
process.platform === "win32" ||
|
||||
(tty.isatty(1) && process.env.TERM !== "dumb") ||
|
||||
"CI" in process.env);
|
||||
|
||||
let formatter =
|
||||
(open, close, replace = open) =>
|
||||
input => {
|
||||
let string = "" + input;
|
||||
let index = string.indexOf(close, open.length);
|
||||
return ~index
|
||||
? open + replaceClose(string, close, replace, index) + close
|
||||
: open + string + close
|
||||
};
|
||||
|
||||
let replaceClose = (string, close, replace, index) => {
|
||||
let start = string.substring(0, index) + replace;
|
||||
let end = string.substring(index + close.length);
|
||||
let nextIndex = end.indexOf(close);
|
||||
return ~nextIndex ? start + replaceClose(end, close, replace, nextIndex) : start + end
|
||||
};
|
||||
|
||||
let createColors = (enabled = isColorSupported) => ({
|
||||
isColorSupported: enabled,
|
||||
reset: enabled ? s => `\x1b[0m${s}\x1b[0m` : String,
|
||||
bold: enabled ? formatter("\x1b[1m", "\x1b[22m", "\x1b[22m\x1b[1m") : String,
|
||||
dim: enabled ? formatter("\x1b[2m", "\x1b[22m", "\x1b[22m\x1b[2m") : String,
|
||||
italic: enabled ? formatter("\x1b[3m", "\x1b[23m") : String,
|
||||
underline: enabled ? formatter("\x1b[4m", "\x1b[24m") : String,
|
||||
inverse: enabled ? formatter("\x1b[7m", "\x1b[27m") : String,
|
||||
hidden: enabled ? formatter("\x1b[8m", "\x1b[28m") : String,
|
||||
strikethrough: enabled ? formatter("\x1b[9m", "\x1b[29m") : String,
|
||||
black: enabled ? formatter("\x1b[30m", "\x1b[39m") : String,
|
||||
red: enabled ? formatter("\x1b[31m", "\x1b[39m") : String,
|
||||
green: enabled ? formatter("\x1b[32m", "\x1b[39m") : String,
|
||||
yellow: enabled ? formatter("\x1b[33m", "\x1b[39m") : String,
|
||||
blue: enabled ? formatter("\x1b[34m", "\x1b[39m") : String,
|
||||
magenta: enabled ? formatter("\x1b[35m", "\x1b[39m") : String,
|
||||
cyan: enabled ? formatter("\x1b[36m", "\x1b[39m") : String,
|
||||
white: enabled ? formatter("\x1b[37m", "\x1b[39m") : String,
|
||||
gray: enabled ? formatter("\x1b[90m", "\x1b[39m") : String,
|
||||
bgBlack: enabled ? formatter("\x1b[40m", "\x1b[49m") : String,
|
||||
bgRed: enabled ? formatter("\x1b[41m", "\x1b[49m") : String,
|
||||
bgGreen: enabled ? formatter("\x1b[42m", "\x1b[49m") : String,
|
||||
bgYellow: enabled ? formatter("\x1b[43m", "\x1b[49m") : String,
|
||||
bgBlue: enabled ? formatter("\x1b[44m", "\x1b[49m") : String,
|
||||
bgMagenta: enabled ? formatter("\x1b[45m", "\x1b[49m") : String,
|
||||
bgCyan: enabled ? formatter("\x1b[46m", "\x1b[49m") : String,
|
||||
bgWhite: enabled ? formatter("\x1b[47m", "\x1b[49m") : String,
|
||||
});
|
||||
|
||||
picocolors.exports = createColors();
|
||||
picocolors.exports.createColors = createColors;
|
||||
|
||||
export { picocolors as p };
|
||||
+710
@@ -0,0 +1,710 @@
|
||||
'use strict';
|
||||
|
||||
var events = require('events');
|
||||
var picocolors = require('./chunk-picocolors.cjs');
|
||||
var vite = require('vite');
|
||||
var server = require('./server.cjs');
|
||||
var client = require('./client.cjs');
|
||||
var utils = require('./utils.cjs');
|
||||
var hmr = require('./chunk-hmr.cjs');
|
||||
var sourceMap = require('./source-map.cjs');
|
||||
require('tty');
|
||||
require('perf_hooks');
|
||||
require('pathe');
|
||||
require('debug');
|
||||
require('fs');
|
||||
require('mlly');
|
||||
require('url');
|
||||
require('source-map-support');
|
||||
require('module');
|
||||
require('vm');
|
||||
|
||||
function toArr(any) {
|
||||
return any == null ? [] : Array.isArray(any) ? any : [any];
|
||||
}
|
||||
|
||||
function toVal(out, key, val, opts) {
|
||||
var x, old=out[key], nxt=(
|
||||
!!~opts.string.indexOf(key) ? (val == null || val === true ? '' : String(val))
|
||||
: typeof val === 'boolean' ? val
|
||||
: !!~opts.boolean.indexOf(key) ? (val === 'false' ? false : val === 'true' || (out._.push((x = +val,x * 0 === 0) ? x : val),!!val))
|
||||
: (x = +val,x * 0 === 0) ? x : val
|
||||
);
|
||||
out[key] = old == null ? nxt : (Array.isArray(old) ? old.concat(nxt) : [old, nxt]);
|
||||
}
|
||||
|
||||
function mri2 (args, opts) {
|
||||
args = args || [];
|
||||
opts = opts || {};
|
||||
|
||||
var k, arr, arg, name, val, out={ _:[] };
|
||||
var i=0, j=0, idx=0, len=args.length;
|
||||
|
||||
const alibi = opts.alias !== void 0;
|
||||
const strict = opts.unknown !== void 0;
|
||||
const defaults = opts.default !== void 0;
|
||||
|
||||
opts.alias = opts.alias || {};
|
||||
opts.string = toArr(opts.string);
|
||||
opts.boolean = toArr(opts.boolean);
|
||||
|
||||
if (alibi) {
|
||||
for (k in opts.alias) {
|
||||
arr = opts.alias[k] = toArr(opts.alias[k]);
|
||||
for (i=0; i < arr.length; i++) {
|
||||
(opts.alias[arr[i]] = arr.concat(k)).splice(i, 1);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
for (i=opts.boolean.length; i-- > 0;) {
|
||||
arr = opts.alias[opts.boolean[i]] || [];
|
||||
for (j=arr.length; j-- > 0;) opts.boolean.push(arr[j]);
|
||||
}
|
||||
|
||||
for (i=opts.string.length; i-- > 0;) {
|
||||
arr = opts.alias[opts.string[i]] || [];
|
||||
for (j=arr.length; j-- > 0;) opts.string.push(arr[j]);
|
||||
}
|
||||
|
||||
if (defaults) {
|
||||
for (k in opts.default) {
|
||||
name = typeof opts.default[k];
|
||||
arr = opts.alias[k] = opts.alias[k] || [];
|
||||
if (opts[name] !== void 0) {
|
||||
opts[name].push(k);
|
||||
for (i=0; i < arr.length; i++) {
|
||||
opts[name].push(arr[i]);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
const keys = strict ? Object.keys(opts.alias) : [];
|
||||
|
||||
for (i=0; i < len; i++) {
|
||||
arg = args[i];
|
||||
|
||||
if (arg === '--') {
|
||||
out._ = out._.concat(args.slice(++i));
|
||||
break;
|
||||
}
|
||||
|
||||
for (j=0; j < arg.length; j++) {
|
||||
if (arg.charCodeAt(j) !== 45) break; // "-"
|
||||
}
|
||||
|
||||
if (j === 0) {
|
||||
out._.push(arg);
|
||||
} else if (arg.substring(j, j + 3) === 'no-') {
|
||||
name = arg.substring(j + 3);
|
||||
if (strict && !~keys.indexOf(name)) {
|
||||
return opts.unknown(arg);
|
||||
}
|
||||
out[name] = false;
|
||||
} else {
|
||||
for (idx=j+1; idx < arg.length; idx++) {
|
||||
if (arg.charCodeAt(idx) === 61) break; // "="
|
||||
}
|
||||
|
||||
name = arg.substring(j, idx);
|
||||
val = arg.substring(++idx) || (i+1 === len || (''+args[i+1]).charCodeAt(0) === 45 || args[++i]);
|
||||
arr = (j === 2 ? [name] : name);
|
||||
|
||||
for (idx=0; idx < arr.length; idx++) {
|
||||
name = arr[idx];
|
||||
if (strict && !~keys.indexOf(name)) return opts.unknown('-'.repeat(j) + name);
|
||||
toVal(out, name, (idx + 1 < arr.length) || val, opts);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if (defaults) {
|
||||
for (k in opts.default) {
|
||||
if (out[k] === void 0) {
|
||||
out[k] = opts.default[k];
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if (alibi) {
|
||||
for (k in out) {
|
||||
arr = opts.alias[k] || [];
|
||||
while (arr.length > 0) {
|
||||
out[arr.shift()] = out[k];
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return out;
|
||||
}
|
||||
|
||||
const removeBrackets = (v) => v.replace(/[<[].+/, "").trim();
|
||||
const findAllBrackets = (v) => {
|
||||
const ANGLED_BRACKET_RE_GLOBAL = /<([^>]+)>/g;
|
||||
const SQUARE_BRACKET_RE_GLOBAL = /\[([^\]]+)\]/g;
|
||||
const res = [];
|
||||
const parse = (match) => {
|
||||
let variadic = false;
|
||||
let value = match[1];
|
||||
if (value.startsWith("...")) {
|
||||
value = value.slice(3);
|
||||
variadic = true;
|
||||
}
|
||||
return {
|
||||
required: match[0].startsWith("<"),
|
||||
value,
|
||||
variadic
|
||||
};
|
||||
};
|
||||
let angledMatch;
|
||||
while (angledMatch = ANGLED_BRACKET_RE_GLOBAL.exec(v)) {
|
||||
res.push(parse(angledMatch));
|
||||
}
|
||||
let squareMatch;
|
||||
while (squareMatch = SQUARE_BRACKET_RE_GLOBAL.exec(v)) {
|
||||
res.push(parse(squareMatch));
|
||||
}
|
||||
return res;
|
||||
};
|
||||
const getMriOptions = (options) => {
|
||||
const result = {alias: {}, boolean: []};
|
||||
for (const [index, option] of options.entries()) {
|
||||
if (option.names.length > 1) {
|
||||
result.alias[option.names[0]] = option.names.slice(1);
|
||||
}
|
||||
if (option.isBoolean) {
|
||||
if (option.negated) {
|
||||
const hasStringTypeOption = options.some((o, i) => {
|
||||
return i !== index && o.names.some((name) => option.names.includes(name)) && typeof o.required === "boolean";
|
||||
});
|
||||
if (!hasStringTypeOption) {
|
||||
result.boolean.push(option.names[0]);
|
||||
}
|
||||
} else {
|
||||
result.boolean.push(option.names[0]);
|
||||
}
|
||||
}
|
||||
}
|
||||
return result;
|
||||
};
|
||||
const findLongest = (arr) => {
|
||||
return arr.sort((a, b) => {
|
||||
return a.length > b.length ? -1 : 1;
|
||||
})[0];
|
||||
};
|
||||
const padRight = (str, length) => {
|
||||
return str.length >= length ? str : `${str}${" ".repeat(length - str.length)}`;
|
||||
};
|
||||
const camelcase = (input) => {
|
||||
return input.replace(/([a-z])-([a-z])/g, (_, p1, p2) => {
|
||||
return p1 + p2.toUpperCase();
|
||||
});
|
||||
};
|
||||
const setDotProp = (obj, keys, val) => {
|
||||
let i = 0;
|
||||
let length = keys.length;
|
||||
let t = obj;
|
||||
let x;
|
||||
for (; i < length; ++i) {
|
||||
x = t[keys[i]];
|
||||
t = t[keys[i]] = i === length - 1 ? val : x != null ? x : !!~keys[i + 1].indexOf(".") || !(+keys[i + 1] > -1) ? {} : [];
|
||||
}
|
||||
};
|
||||
const setByType = (obj, transforms) => {
|
||||
for (const key of Object.keys(transforms)) {
|
||||
const transform = transforms[key];
|
||||
if (transform.shouldTransform) {
|
||||
obj[key] = Array.prototype.concat.call([], obj[key]);
|
||||
if (typeof transform.transformFunction === "function") {
|
||||
obj[key] = obj[key].map(transform.transformFunction);
|
||||
}
|
||||
}
|
||||
}
|
||||
};
|
||||
const getFileName = (input) => {
|
||||
const m = /([^\\\/]+)$/.exec(input);
|
||||
return m ? m[1] : "";
|
||||
};
|
||||
const camelcaseOptionName = (name) => {
|
||||
return name.split(".").map((v, i) => {
|
||||
return i === 0 ? camelcase(v) : v;
|
||||
}).join(".");
|
||||
};
|
||||
class CACError extends Error {
|
||||
constructor(message) {
|
||||
super(message);
|
||||
this.name = this.constructor.name;
|
||||
if (typeof Error.captureStackTrace === "function") {
|
||||
Error.captureStackTrace(this, this.constructor);
|
||||
} else {
|
||||
this.stack = new Error(message).stack;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
class Option {
|
||||
constructor(rawName, description, config) {
|
||||
this.rawName = rawName;
|
||||
this.description = description;
|
||||
this.config = Object.assign({}, config);
|
||||
rawName = rawName.replace(/\.\*/g, "");
|
||||
this.negated = false;
|
||||
this.names = removeBrackets(rawName).split(",").map((v) => {
|
||||
let name = v.trim().replace(/^-{1,2}/, "");
|
||||
if (name.startsWith("no-")) {
|
||||
this.negated = true;
|
||||
name = name.replace(/^no-/, "");
|
||||
}
|
||||
return camelcaseOptionName(name);
|
||||
}).sort((a, b) => a.length > b.length ? 1 : -1);
|
||||
this.name = this.names[this.names.length - 1];
|
||||
if (this.negated && this.config.default == null) {
|
||||
this.config.default = true;
|
||||
}
|
||||
if (rawName.includes("<")) {
|
||||
this.required = true;
|
||||
} else if (rawName.includes("[")) {
|
||||
this.required = false;
|
||||
} else {
|
||||
this.isBoolean = true;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
const processArgs = process.argv;
|
||||
const platformInfo = `${process.platform}-${process.arch} node-${process.version}`;
|
||||
|
||||
class Command {
|
||||
constructor(rawName, description, config = {}, cli) {
|
||||
this.rawName = rawName;
|
||||
this.description = description;
|
||||
this.config = config;
|
||||
this.cli = cli;
|
||||
this.options = [];
|
||||
this.aliasNames = [];
|
||||
this.name = removeBrackets(rawName);
|
||||
this.args = findAllBrackets(rawName);
|
||||
this.examples = [];
|
||||
}
|
||||
usage(text) {
|
||||
this.usageText = text;
|
||||
return this;
|
||||
}
|
||||
allowUnknownOptions() {
|
||||
this.config.allowUnknownOptions = true;
|
||||
return this;
|
||||
}
|
||||
ignoreOptionDefaultValue() {
|
||||
this.config.ignoreOptionDefaultValue = true;
|
||||
return this;
|
||||
}
|
||||
version(version, customFlags = "-v, --version") {
|
||||
this.versionNumber = version;
|
||||
this.option(customFlags, "Display version number");
|
||||
return this;
|
||||
}
|
||||
example(example) {
|
||||
this.examples.push(example);
|
||||
return this;
|
||||
}
|
||||
option(rawName, description, config) {
|
||||
const option = new Option(rawName, description, config);
|
||||
this.options.push(option);
|
||||
return this;
|
||||
}
|
||||
alias(name) {
|
||||
this.aliasNames.push(name);
|
||||
return this;
|
||||
}
|
||||
action(callback) {
|
||||
this.commandAction = callback;
|
||||
return this;
|
||||
}
|
||||
isMatched(name) {
|
||||
return this.name === name || this.aliasNames.includes(name);
|
||||
}
|
||||
get isDefaultCommand() {
|
||||
return this.name === "" || this.aliasNames.includes("!");
|
||||
}
|
||||
get isGlobalCommand() {
|
||||
return this instanceof GlobalCommand;
|
||||
}
|
||||
hasOption(name) {
|
||||
name = name.split(".")[0];
|
||||
return this.options.find((option) => {
|
||||
return option.names.includes(name);
|
||||
});
|
||||
}
|
||||
outputHelp() {
|
||||
const {name, commands} = this.cli;
|
||||
const {
|
||||
versionNumber,
|
||||
options: globalOptions,
|
||||
helpCallback
|
||||
} = this.cli.globalCommand;
|
||||
let sections = [
|
||||
{
|
||||
body: `${name}${versionNumber ? `/${versionNumber}` : ""}`
|
||||
}
|
||||
];
|
||||
sections.push({
|
||||
title: "Usage",
|
||||
body: ` $ ${name} ${this.usageText || this.rawName}`
|
||||
});
|
||||
const showCommands = (this.isGlobalCommand || this.isDefaultCommand) && commands.length > 0;
|
||||
if (showCommands) {
|
||||
const longestCommandName = findLongest(commands.map((command) => command.rawName));
|
||||
sections.push({
|
||||
title: "Commands",
|
||||
body: commands.map((command) => {
|
||||
return ` ${padRight(command.rawName, longestCommandName.length)} ${command.description}`;
|
||||
}).join("\n")
|
||||
});
|
||||
sections.push({
|
||||
title: `For more info, run any command with the \`--help\` flag`,
|
||||
body: commands.map((command) => ` $ ${name}${command.name === "" ? "" : ` ${command.name}`} --help`).join("\n")
|
||||
});
|
||||
}
|
||||
let options = this.isGlobalCommand ? globalOptions : [...this.options, ...globalOptions || []];
|
||||
if (!this.isGlobalCommand && !this.isDefaultCommand) {
|
||||
options = options.filter((option) => option.name !== "version");
|
||||
}
|
||||
if (options.length > 0) {
|
||||
const longestOptionName = findLongest(options.map((option) => option.rawName));
|
||||
sections.push({
|
||||
title: "Options",
|
||||
body: options.map((option) => {
|
||||
return ` ${padRight(option.rawName, longestOptionName.length)} ${option.description} ${option.config.default === void 0 ? "" : `(default: ${option.config.default})`}`;
|
||||
}).join("\n")
|
||||
});
|
||||
}
|
||||
if (this.examples.length > 0) {
|
||||
sections.push({
|
||||
title: "Examples",
|
||||
body: this.examples.map((example) => {
|
||||
if (typeof example === "function") {
|
||||
return example(name);
|
||||
}
|
||||
return example;
|
||||
}).join("\n")
|
||||
});
|
||||
}
|
||||
if (helpCallback) {
|
||||
sections = helpCallback(sections) || sections;
|
||||
}
|
||||
console.log(sections.map((section) => {
|
||||
return section.title ? `${section.title}:
|
||||
${section.body}` : section.body;
|
||||
}).join("\n\n"));
|
||||
}
|
||||
outputVersion() {
|
||||
const {name} = this.cli;
|
||||
const {versionNumber} = this.cli.globalCommand;
|
||||
if (versionNumber) {
|
||||
console.log(`${name}/${versionNumber} ${platformInfo}`);
|
||||
}
|
||||
}
|
||||
checkRequiredArgs() {
|
||||
const minimalArgsCount = this.args.filter((arg) => arg.required).length;
|
||||
if (this.cli.args.length < minimalArgsCount) {
|
||||
throw new CACError(`missing required args for command \`${this.rawName}\``);
|
||||
}
|
||||
}
|
||||
checkUnknownOptions() {
|
||||
const {options, globalCommand} = this.cli;
|
||||
if (!this.config.allowUnknownOptions) {
|
||||
for (const name of Object.keys(options)) {
|
||||
if (name !== "--" && !this.hasOption(name) && !globalCommand.hasOption(name)) {
|
||||
throw new CACError(`Unknown option \`${name.length > 1 ? `--${name}` : `-${name}`}\``);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
checkOptionValue() {
|
||||
const {options: parsedOptions, globalCommand} = this.cli;
|
||||
const options = [...globalCommand.options, ...this.options];
|
||||
for (const option of options) {
|
||||
const value = parsedOptions[option.name.split(".")[0]];
|
||||
if (option.required) {
|
||||
const hasNegated = options.some((o) => o.negated && o.names.includes(option.name));
|
||||
if (value === true || value === false && !hasNegated) {
|
||||
throw new CACError(`option \`${option.rawName}\` value is missing`);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
class GlobalCommand extends Command {
|
||||
constructor(cli) {
|
||||
super("@@global@@", "", {}, cli);
|
||||
}
|
||||
}
|
||||
|
||||
var __assign = Object.assign;
|
||||
class CAC extends events.EventEmitter {
|
||||
constructor(name = "") {
|
||||
super();
|
||||
this.name = name;
|
||||
this.commands = [];
|
||||
this.rawArgs = [];
|
||||
this.args = [];
|
||||
this.options = {};
|
||||
this.globalCommand = new GlobalCommand(this);
|
||||
this.globalCommand.usage("<command> [options]");
|
||||
}
|
||||
usage(text) {
|
||||
this.globalCommand.usage(text);
|
||||
return this;
|
||||
}
|
||||
command(rawName, description, config) {
|
||||
const command = new Command(rawName, description || "", config, this);
|
||||
command.globalCommand = this.globalCommand;
|
||||
this.commands.push(command);
|
||||
return command;
|
||||
}
|
||||
option(rawName, description, config) {
|
||||
this.globalCommand.option(rawName, description, config);
|
||||
return this;
|
||||
}
|
||||
help(callback) {
|
||||
this.globalCommand.option("-h, --help", "Display this message");
|
||||
this.globalCommand.helpCallback = callback;
|
||||
this.showHelpOnExit = true;
|
||||
return this;
|
||||
}
|
||||
version(version, customFlags = "-v, --version") {
|
||||
this.globalCommand.version(version, customFlags);
|
||||
this.showVersionOnExit = true;
|
||||
return this;
|
||||
}
|
||||
example(example) {
|
||||
this.globalCommand.example(example);
|
||||
return this;
|
||||
}
|
||||
outputHelp() {
|
||||
if (this.matchedCommand) {
|
||||
this.matchedCommand.outputHelp();
|
||||
} else {
|
||||
this.globalCommand.outputHelp();
|
||||
}
|
||||
}
|
||||
outputVersion() {
|
||||
this.globalCommand.outputVersion();
|
||||
}
|
||||
setParsedInfo({args, options}, matchedCommand, matchedCommandName) {
|
||||
this.args = args;
|
||||
this.options = options;
|
||||
if (matchedCommand) {
|
||||
this.matchedCommand = matchedCommand;
|
||||
}
|
||||
if (matchedCommandName) {
|
||||
this.matchedCommandName = matchedCommandName;
|
||||
}
|
||||
return this;
|
||||
}
|
||||
unsetMatchedCommand() {
|
||||
this.matchedCommand = void 0;
|
||||
this.matchedCommandName = void 0;
|
||||
}
|
||||
parse(argv = processArgs, {
|
||||
run = true
|
||||
} = {}) {
|
||||
this.rawArgs = argv;
|
||||
if (!this.name) {
|
||||
this.name = argv[1] ? getFileName(argv[1]) : "cli";
|
||||
}
|
||||
let shouldParse = true;
|
||||
for (const command of this.commands) {
|
||||
const parsed = this.mri(argv.slice(2), command);
|
||||
const commandName = parsed.args[0];
|
||||
if (command.isMatched(commandName)) {
|
||||
shouldParse = false;
|
||||
const parsedInfo = __assign(__assign({}, parsed), {
|
||||
args: parsed.args.slice(1)
|
||||
});
|
||||
this.setParsedInfo(parsedInfo, command, commandName);
|
||||
this.emit(`command:${commandName}`, command);
|
||||
}
|
||||
}
|
||||
if (shouldParse) {
|
||||
for (const command of this.commands) {
|
||||
if (command.name === "") {
|
||||
shouldParse = false;
|
||||
const parsed = this.mri(argv.slice(2), command);
|
||||
this.setParsedInfo(parsed, command);
|
||||
this.emit(`command:!`, command);
|
||||
}
|
||||
}
|
||||
}
|
||||
if (shouldParse) {
|
||||
const parsed = this.mri(argv.slice(2));
|
||||
this.setParsedInfo(parsed);
|
||||
}
|
||||
if (this.options.help && this.showHelpOnExit) {
|
||||
this.outputHelp();
|
||||
run = false;
|
||||
this.unsetMatchedCommand();
|
||||
}
|
||||
if (this.options.version && this.showVersionOnExit && this.matchedCommandName == null) {
|
||||
this.outputVersion();
|
||||
run = false;
|
||||
this.unsetMatchedCommand();
|
||||
}
|
||||
const parsedArgv = {args: this.args, options: this.options};
|
||||
if (run) {
|
||||
this.runMatchedCommand();
|
||||
}
|
||||
if (!this.matchedCommand && this.args[0]) {
|
||||
this.emit("command:*");
|
||||
}
|
||||
return parsedArgv;
|
||||
}
|
||||
mri(argv, command) {
|
||||
const cliOptions = [
|
||||
...this.globalCommand.options,
|
||||
...command ? command.options : []
|
||||
];
|
||||
const mriOptions = getMriOptions(cliOptions);
|
||||
let argsAfterDoubleDashes = [];
|
||||
const doubleDashesIndex = argv.indexOf("--");
|
||||
if (doubleDashesIndex > -1) {
|
||||
argsAfterDoubleDashes = argv.slice(doubleDashesIndex + 1);
|
||||
argv = argv.slice(0, doubleDashesIndex);
|
||||
}
|
||||
let parsed = mri2(argv, mriOptions);
|
||||
parsed = Object.keys(parsed).reduce((res, name) => {
|
||||
return __assign(__assign({}, res), {
|
||||
[camelcaseOptionName(name)]: parsed[name]
|
||||
});
|
||||
}, {_: []});
|
||||
const args = parsed._;
|
||||
const options = {
|
||||
"--": argsAfterDoubleDashes
|
||||
};
|
||||
const ignoreDefault = command && command.config.ignoreOptionDefaultValue ? command.config.ignoreOptionDefaultValue : this.globalCommand.config.ignoreOptionDefaultValue;
|
||||
let transforms = Object.create(null);
|
||||
for (const cliOption of cliOptions) {
|
||||
if (!ignoreDefault && cliOption.config.default !== void 0) {
|
||||
for (const name of cliOption.names) {
|
||||
options[name] = cliOption.config.default;
|
||||
}
|
||||
}
|
||||
if (Array.isArray(cliOption.config.type)) {
|
||||
if (transforms[cliOption.name] === void 0) {
|
||||
transforms[cliOption.name] = Object.create(null);
|
||||
transforms[cliOption.name]["shouldTransform"] = true;
|
||||
transforms[cliOption.name]["transformFunction"] = cliOption.config.type[0];
|
||||
}
|
||||
}
|
||||
}
|
||||
for (const key of Object.keys(parsed)) {
|
||||
if (key !== "_") {
|
||||
const keys = key.split(".");
|
||||
setDotProp(options, keys, parsed[key]);
|
||||
setByType(options, transforms);
|
||||
}
|
||||
}
|
||||
return {
|
||||
args,
|
||||
options
|
||||
};
|
||||
}
|
||||
runMatchedCommand() {
|
||||
const {args, options, matchedCommand: command} = this;
|
||||
if (!command || !command.commandAction)
|
||||
return;
|
||||
command.checkUnknownOptions();
|
||||
command.checkOptionValue();
|
||||
command.checkRequiredArgs();
|
||||
const actionArgs = [];
|
||||
command.args.forEach((arg, index) => {
|
||||
if (arg.variadic) {
|
||||
actionArgs.push(args.slice(index));
|
||||
} else {
|
||||
actionArgs.push(args[index]);
|
||||
}
|
||||
});
|
||||
actionArgs.push(options);
|
||||
return command.commandAction.apply(this, actionArgs);
|
||||
}
|
||||
}
|
||||
|
||||
const cac = (name = "") => new CAC(name);
|
||||
|
||||
var version = "0.25.8";
|
||||
|
||||
const cli = cac("vite-node");
|
||||
cli.version(version).option("-r, --root <path>", "Use specified root directory").option("-c, --config <path>", "Use specified config file").option("-w, --watch", 'Restart on file changes, similar to "nodemon"').option("--options <options>", "Use specified Vite server options").help();
|
||||
cli.command("[...files]").action(run);
|
||||
cli.parse();
|
||||
async function run(files, options = {}) {
|
||||
var _a;
|
||||
if (!files.length) {
|
||||
console.error(picocolors.picocolors.exports.red("No files specified."));
|
||||
cli.outputHelp();
|
||||
process.exit(1);
|
||||
}
|
||||
process.argv = [...process.argv.slice(0, 2), ...options["--"] || []];
|
||||
const serverOptions = options.options ? parseServerOptions(options.options) : {};
|
||||
const server$1 = await vite.createServer({
|
||||
logLevel: "error",
|
||||
configFile: options.config,
|
||||
root: options.root,
|
||||
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(picocolors.picocolors.exports.red("[vite-node] Failed to execute file: \n"), err);
|
||||
});
|
||||
}
|
||||
}
|
||||
function parseServerOptions(serverOptions) {
|
||||
var _a, _b, _c, _d, _e;
|
||||
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;
|
||||
})
|
||||
},
|
||||
transformMode: {
|
||||
...serverOptions.transformMode,
|
||||
ssr: utils.toArray((_d = serverOptions.transformMode) == null ? void 0 : _d.ssr).map((dep) => new RegExp(dep)),
|
||||
web: utils.toArray((_e = serverOptions.transformMode) == null ? void 0 : _e.web).map((dep) => new RegExp(dep))
|
||||
}
|
||||
};
|
||||
}
|
||||
+16
@@ -0,0 +1,16 @@
|
||||
import { e as ViteNodeServerOptions } from './types-fc7e68bc.js';
|
||||
|
||||
interface CliOptions {
|
||||
root?: string;
|
||||
config?: string;
|
||||
watch?: boolean;
|
||||
options?: ViteNodeServerOptionsCLI;
|
||||
'--'?: 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 { CliOptions, ViteNodeServerOptionsCLI };
|
||||
+708
@@ -0,0 +1,708 @@
|
||||
import { EventEmitter } from 'events';
|
||||
import { p as picocolors } from './chunk-picocolors.mjs';
|
||||
import { createServer } from 'vite';
|
||||
import { ViteNodeServer } from './server.mjs';
|
||||
import { ViteNodeRunner } from './client.mjs';
|
||||
import { toArray } from './utils.mjs';
|
||||
import { v as viteNodeHmrPlugin, c as createHotContext, h as handleMessage } from './chunk-hmr.mjs';
|
||||
import { installSourcemapsSupport } from './source-map.mjs';
|
||||
import 'tty';
|
||||
import 'perf_hooks';
|
||||
import 'pathe';
|
||||
import 'debug';
|
||||
import 'fs';
|
||||
import 'mlly';
|
||||
import 'url';
|
||||
import 'source-map-support';
|
||||
import 'module';
|
||||
import 'vm';
|
||||
|
||||
function toArr(any) {
|
||||
return any == null ? [] : Array.isArray(any) ? any : [any];
|
||||
}
|
||||
|
||||
function toVal(out, key, val, opts) {
|
||||
var x, old=out[key], nxt=(
|
||||
!!~opts.string.indexOf(key) ? (val == null || val === true ? '' : String(val))
|
||||
: typeof val === 'boolean' ? val
|
||||
: !!~opts.boolean.indexOf(key) ? (val === 'false' ? false : val === 'true' || (out._.push((x = +val,x * 0 === 0) ? x : val),!!val))
|
||||
: (x = +val,x * 0 === 0) ? x : val
|
||||
);
|
||||
out[key] = old == null ? nxt : (Array.isArray(old) ? old.concat(nxt) : [old, nxt]);
|
||||
}
|
||||
|
||||
function mri2 (args, opts) {
|
||||
args = args || [];
|
||||
opts = opts || {};
|
||||
|
||||
var k, arr, arg, name, val, out={ _:[] };
|
||||
var i=0, j=0, idx=0, len=args.length;
|
||||
|
||||
const alibi = opts.alias !== void 0;
|
||||
const strict = opts.unknown !== void 0;
|
||||
const defaults = opts.default !== void 0;
|
||||
|
||||
opts.alias = opts.alias || {};
|
||||
opts.string = toArr(opts.string);
|
||||
opts.boolean = toArr(opts.boolean);
|
||||
|
||||
if (alibi) {
|
||||
for (k in opts.alias) {
|
||||
arr = opts.alias[k] = toArr(opts.alias[k]);
|
||||
for (i=0; i < arr.length; i++) {
|
||||
(opts.alias[arr[i]] = arr.concat(k)).splice(i, 1);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
for (i=opts.boolean.length; i-- > 0;) {
|
||||
arr = opts.alias[opts.boolean[i]] || [];
|
||||
for (j=arr.length; j-- > 0;) opts.boolean.push(arr[j]);
|
||||
}
|
||||
|
||||
for (i=opts.string.length; i-- > 0;) {
|
||||
arr = opts.alias[opts.string[i]] || [];
|
||||
for (j=arr.length; j-- > 0;) opts.string.push(arr[j]);
|
||||
}
|
||||
|
||||
if (defaults) {
|
||||
for (k in opts.default) {
|
||||
name = typeof opts.default[k];
|
||||
arr = opts.alias[k] = opts.alias[k] || [];
|
||||
if (opts[name] !== void 0) {
|
||||
opts[name].push(k);
|
||||
for (i=0; i < arr.length; i++) {
|
||||
opts[name].push(arr[i]);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
const keys = strict ? Object.keys(opts.alias) : [];
|
||||
|
||||
for (i=0; i < len; i++) {
|
||||
arg = args[i];
|
||||
|
||||
if (arg === '--') {
|
||||
out._ = out._.concat(args.slice(++i));
|
||||
break;
|
||||
}
|
||||
|
||||
for (j=0; j < arg.length; j++) {
|
||||
if (arg.charCodeAt(j) !== 45) break; // "-"
|
||||
}
|
||||
|
||||
if (j === 0) {
|
||||
out._.push(arg);
|
||||
} else if (arg.substring(j, j + 3) === 'no-') {
|
||||
name = arg.substring(j + 3);
|
||||
if (strict && !~keys.indexOf(name)) {
|
||||
return opts.unknown(arg);
|
||||
}
|
||||
out[name] = false;
|
||||
} else {
|
||||
for (idx=j+1; idx < arg.length; idx++) {
|
||||
if (arg.charCodeAt(idx) === 61) break; // "="
|
||||
}
|
||||
|
||||
name = arg.substring(j, idx);
|
||||
val = arg.substring(++idx) || (i+1 === len || (''+args[i+1]).charCodeAt(0) === 45 || args[++i]);
|
||||
arr = (j === 2 ? [name] : name);
|
||||
|
||||
for (idx=0; idx < arr.length; idx++) {
|
||||
name = arr[idx];
|
||||
if (strict && !~keys.indexOf(name)) return opts.unknown('-'.repeat(j) + name);
|
||||
toVal(out, name, (idx + 1 < arr.length) || val, opts);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if (defaults) {
|
||||
for (k in opts.default) {
|
||||
if (out[k] === void 0) {
|
||||
out[k] = opts.default[k];
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if (alibi) {
|
||||
for (k in out) {
|
||||
arr = opts.alias[k] || [];
|
||||
while (arr.length > 0) {
|
||||
out[arr.shift()] = out[k];
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return out;
|
||||
}
|
||||
|
||||
const removeBrackets = (v) => v.replace(/[<[].+/, "").trim();
|
||||
const findAllBrackets = (v) => {
|
||||
const ANGLED_BRACKET_RE_GLOBAL = /<([^>]+)>/g;
|
||||
const SQUARE_BRACKET_RE_GLOBAL = /\[([^\]]+)\]/g;
|
||||
const res = [];
|
||||
const parse = (match) => {
|
||||
let variadic = false;
|
||||
let value = match[1];
|
||||
if (value.startsWith("...")) {
|
||||
value = value.slice(3);
|
||||
variadic = true;
|
||||
}
|
||||
return {
|
||||
required: match[0].startsWith("<"),
|
||||
value,
|
||||
variadic
|
||||
};
|
||||
};
|
||||
let angledMatch;
|
||||
while (angledMatch = ANGLED_BRACKET_RE_GLOBAL.exec(v)) {
|
||||
res.push(parse(angledMatch));
|
||||
}
|
||||
let squareMatch;
|
||||
while (squareMatch = SQUARE_BRACKET_RE_GLOBAL.exec(v)) {
|
||||
res.push(parse(squareMatch));
|
||||
}
|
||||
return res;
|
||||
};
|
||||
const getMriOptions = (options) => {
|
||||
const result = {alias: {}, boolean: []};
|
||||
for (const [index, option] of options.entries()) {
|
||||
if (option.names.length > 1) {
|
||||
result.alias[option.names[0]] = option.names.slice(1);
|
||||
}
|
||||
if (option.isBoolean) {
|
||||
if (option.negated) {
|
||||
const hasStringTypeOption = options.some((o, i) => {
|
||||
return i !== index && o.names.some((name) => option.names.includes(name)) && typeof o.required === "boolean";
|
||||
});
|
||||
if (!hasStringTypeOption) {
|
||||
result.boolean.push(option.names[0]);
|
||||
}
|
||||
} else {
|
||||
result.boolean.push(option.names[0]);
|
||||
}
|
||||
}
|
||||
}
|
||||
return result;
|
||||
};
|
||||
const findLongest = (arr) => {
|
||||
return arr.sort((a, b) => {
|
||||
return a.length > b.length ? -1 : 1;
|
||||
})[0];
|
||||
};
|
||||
const padRight = (str, length) => {
|
||||
return str.length >= length ? str : `${str}${" ".repeat(length - str.length)}`;
|
||||
};
|
||||
const camelcase = (input) => {
|
||||
return input.replace(/([a-z])-([a-z])/g, (_, p1, p2) => {
|
||||
return p1 + p2.toUpperCase();
|
||||
});
|
||||
};
|
||||
const setDotProp = (obj, keys, val) => {
|
||||
let i = 0;
|
||||
let length = keys.length;
|
||||
let t = obj;
|
||||
let x;
|
||||
for (; i < length; ++i) {
|
||||
x = t[keys[i]];
|
||||
t = t[keys[i]] = i === length - 1 ? val : x != null ? x : !!~keys[i + 1].indexOf(".") || !(+keys[i + 1] > -1) ? {} : [];
|
||||
}
|
||||
};
|
||||
const setByType = (obj, transforms) => {
|
||||
for (const key of Object.keys(transforms)) {
|
||||
const transform = transforms[key];
|
||||
if (transform.shouldTransform) {
|
||||
obj[key] = Array.prototype.concat.call([], obj[key]);
|
||||
if (typeof transform.transformFunction === "function") {
|
||||
obj[key] = obj[key].map(transform.transformFunction);
|
||||
}
|
||||
}
|
||||
}
|
||||
};
|
||||
const getFileName = (input) => {
|
||||
const m = /([^\\\/]+)$/.exec(input);
|
||||
return m ? m[1] : "";
|
||||
};
|
||||
const camelcaseOptionName = (name) => {
|
||||
return name.split(".").map((v, i) => {
|
||||
return i === 0 ? camelcase(v) : v;
|
||||
}).join(".");
|
||||
};
|
||||
class CACError extends Error {
|
||||
constructor(message) {
|
||||
super(message);
|
||||
this.name = this.constructor.name;
|
||||
if (typeof Error.captureStackTrace === "function") {
|
||||
Error.captureStackTrace(this, this.constructor);
|
||||
} else {
|
||||
this.stack = new Error(message).stack;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
class Option {
|
||||
constructor(rawName, description, config) {
|
||||
this.rawName = rawName;
|
||||
this.description = description;
|
||||
this.config = Object.assign({}, config);
|
||||
rawName = rawName.replace(/\.\*/g, "");
|
||||
this.negated = false;
|
||||
this.names = removeBrackets(rawName).split(",").map((v) => {
|
||||
let name = v.trim().replace(/^-{1,2}/, "");
|
||||
if (name.startsWith("no-")) {
|
||||
this.negated = true;
|
||||
name = name.replace(/^no-/, "");
|
||||
}
|
||||
return camelcaseOptionName(name);
|
||||
}).sort((a, b) => a.length > b.length ? 1 : -1);
|
||||
this.name = this.names[this.names.length - 1];
|
||||
if (this.negated && this.config.default == null) {
|
||||
this.config.default = true;
|
||||
}
|
||||
if (rawName.includes("<")) {
|
||||
this.required = true;
|
||||
} else if (rawName.includes("[")) {
|
||||
this.required = false;
|
||||
} else {
|
||||
this.isBoolean = true;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
const processArgs = process.argv;
|
||||
const platformInfo = `${process.platform}-${process.arch} node-${process.version}`;
|
||||
|
||||
class Command {
|
||||
constructor(rawName, description, config = {}, cli) {
|
||||
this.rawName = rawName;
|
||||
this.description = description;
|
||||
this.config = config;
|
||||
this.cli = cli;
|
||||
this.options = [];
|
||||
this.aliasNames = [];
|
||||
this.name = removeBrackets(rawName);
|
||||
this.args = findAllBrackets(rawName);
|
||||
this.examples = [];
|
||||
}
|
||||
usage(text) {
|
||||
this.usageText = text;
|
||||
return this;
|
||||
}
|
||||
allowUnknownOptions() {
|
||||
this.config.allowUnknownOptions = true;
|
||||
return this;
|
||||
}
|
||||
ignoreOptionDefaultValue() {
|
||||
this.config.ignoreOptionDefaultValue = true;
|
||||
return this;
|
||||
}
|
||||
version(version, customFlags = "-v, --version") {
|
||||
this.versionNumber = version;
|
||||
this.option(customFlags, "Display version number");
|
||||
return this;
|
||||
}
|
||||
example(example) {
|
||||
this.examples.push(example);
|
||||
return this;
|
||||
}
|
||||
option(rawName, description, config) {
|
||||
const option = new Option(rawName, description, config);
|
||||
this.options.push(option);
|
||||
return this;
|
||||
}
|
||||
alias(name) {
|
||||
this.aliasNames.push(name);
|
||||
return this;
|
||||
}
|
||||
action(callback) {
|
||||
this.commandAction = callback;
|
||||
return this;
|
||||
}
|
||||
isMatched(name) {
|
||||
return this.name === name || this.aliasNames.includes(name);
|
||||
}
|
||||
get isDefaultCommand() {
|
||||
return this.name === "" || this.aliasNames.includes("!");
|
||||
}
|
||||
get isGlobalCommand() {
|
||||
return this instanceof GlobalCommand;
|
||||
}
|
||||
hasOption(name) {
|
||||
name = name.split(".")[0];
|
||||
return this.options.find((option) => {
|
||||
return option.names.includes(name);
|
||||
});
|
||||
}
|
||||
outputHelp() {
|
||||
const {name, commands} = this.cli;
|
||||
const {
|
||||
versionNumber,
|
||||
options: globalOptions,
|
||||
helpCallback
|
||||
} = this.cli.globalCommand;
|
||||
let sections = [
|
||||
{
|
||||
body: `${name}${versionNumber ? `/${versionNumber}` : ""}`
|
||||
}
|
||||
];
|
||||
sections.push({
|
||||
title: "Usage",
|
||||
body: ` $ ${name} ${this.usageText || this.rawName}`
|
||||
});
|
||||
const showCommands = (this.isGlobalCommand || this.isDefaultCommand) && commands.length > 0;
|
||||
if (showCommands) {
|
||||
const longestCommandName = findLongest(commands.map((command) => command.rawName));
|
||||
sections.push({
|
||||
title: "Commands",
|
||||
body: commands.map((command) => {
|
||||
return ` ${padRight(command.rawName, longestCommandName.length)} ${command.description}`;
|
||||
}).join("\n")
|
||||
});
|
||||
sections.push({
|
||||
title: `For more info, run any command with the \`--help\` flag`,
|
||||
body: commands.map((command) => ` $ ${name}${command.name === "" ? "" : ` ${command.name}`} --help`).join("\n")
|
||||
});
|
||||
}
|
||||
let options = this.isGlobalCommand ? globalOptions : [...this.options, ...globalOptions || []];
|
||||
if (!this.isGlobalCommand && !this.isDefaultCommand) {
|
||||
options = options.filter((option) => option.name !== "version");
|
||||
}
|
||||
if (options.length > 0) {
|
||||
const longestOptionName = findLongest(options.map((option) => option.rawName));
|
||||
sections.push({
|
||||
title: "Options",
|
||||
body: options.map((option) => {
|
||||
return ` ${padRight(option.rawName, longestOptionName.length)} ${option.description} ${option.config.default === void 0 ? "" : `(default: ${option.config.default})`}`;
|
||||
}).join("\n")
|
||||
});
|
||||
}
|
||||
if (this.examples.length > 0) {
|
||||
sections.push({
|
||||
title: "Examples",
|
||||
body: this.examples.map((example) => {
|
||||
if (typeof example === "function") {
|
||||
return example(name);
|
||||
}
|
||||
return example;
|
||||
}).join("\n")
|
||||
});
|
||||
}
|
||||
if (helpCallback) {
|
||||
sections = helpCallback(sections) || sections;
|
||||
}
|
||||
console.log(sections.map((section) => {
|
||||
return section.title ? `${section.title}:
|
||||
${section.body}` : section.body;
|
||||
}).join("\n\n"));
|
||||
}
|
||||
outputVersion() {
|
||||
const {name} = this.cli;
|
||||
const {versionNumber} = this.cli.globalCommand;
|
||||
if (versionNumber) {
|
||||
console.log(`${name}/${versionNumber} ${platformInfo}`);
|
||||
}
|
||||
}
|
||||
checkRequiredArgs() {
|
||||
const minimalArgsCount = this.args.filter((arg) => arg.required).length;
|
||||
if (this.cli.args.length < minimalArgsCount) {
|
||||
throw new CACError(`missing required args for command \`${this.rawName}\``);
|
||||
}
|
||||
}
|
||||
checkUnknownOptions() {
|
||||
const {options, globalCommand} = this.cli;
|
||||
if (!this.config.allowUnknownOptions) {
|
||||
for (const name of Object.keys(options)) {
|
||||
if (name !== "--" && !this.hasOption(name) && !globalCommand.hasOption(name)) {
|
||||
throw new CACError(`Unknown option \`${name.length > 1 ? `--${name}` : `-${name}`}\``);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
checkOptionValue() {
|
||||
const {options: parsedOptions, globalCommand} = this.cli;
|
||||
const options = [...globalCommand.options, ...this.options];
|
||||
for (const option of options) {
|
||||
const value = parsedOptions[option.name.split(".")[0]];
|
||||
if (option.required) {
|
||||
const hasNegated = options.some((o) => o.negated && o.names.includes(option.name));
|
||||
if (value === true || value === false && !hasNegated) {
|
||||
throw new CACError(`option \`${option.rawName}\` value is missing`);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
class GlobalCommand extends Command {
|
||||
constructor(cli) {
|
||||
super("@@global@@", "", {}, cli);
|
||||
}
|
||||
}
|
||||
|
||||
var __assign = Object.assign;
|
||||
class CAC extends EventEmitter {
|
||||
constructor(name = "") {
|
||||
super();
|
||||
this.name = name;
|
||||
this.commands = [];
|
||||
this.rawArgs = [];
|
||||
this.args = [];
|
||||
this.options = {};
|
||||
this.globalCommand = new GlobalCommand(this);
|
||||
this.globalCommand.usage("<command> [options]");
|
||||
}
|
||||
usage(text) {
|
||||
this.globalCommand.usage(text);
|
||||
return this;
|
||||
}
|
||||
command(rawName, description, config) {
|
||||
const command = new Command(rawName, description || "", config, this);
|
||||
command.globalCommand = this.globalCommand;
|
||||
this.commands.push(command);
|
||||
return command;
|
||||
}
|
||||
option(rawName, description, config) {
|
||||
this.globalCommand.option(rawName, description, config);
|
||||
return this;
|
||||
}
|
||||
help(callback) {
|
||||
this.globalCommand.option("-h, --help", "Display this message");
|
||||
this.globalCommand.helpCallback = callback;
|
||||
this.showHelpOnExit = true;
|
||||
return this;
|
||||
}
|
||||
version(version, customFlags = "-v, --version") {
|
||||
this.globalCommand.version(version, customFlags);
|
||||
this.showVersionOnExit = true;
|
||||
return this;
|
||||
}
|
||||
example(example) {
|
||||
this.globalCommand.example(example);
|
||||
return this;
|
||||
}
|
||||
outputHelp() {
|
||||
if (this.matchedCommand) {
|
||||
this.matchedCommand.outputHelp();
|
||||
} else {
|
||||
this.globalCommand.outputHelp();
|
||||
}
|
||||
}
|
||||
outputVersion() {
|
||||
this.globalCommand.outputVersion();
|
||||
}
|
||||
setParsedInfo({args, options}, matchedCommand, matchedCommandName) {
|
||||
this.args = args;
|
||||
this.options = options;
|
||||
if (matchedCommand) {
|
||||
this.matchedCommand = matchedCommand;
|
||||
}
|
||||
if (matchedCommandName) {
|
||||
this.matchedCommandName = matchedCommandName;
|
||||
}
|
||||
return this;
|
||||
}
|
||||
unsetMatchedCommand() {
|
||||
this.matchedCommand = void 0;
|
||||
this.matchedCommandName = void 0;
|
||||
}
|
||||
parse(argv = processArgs, {
|
||||
run = true
|
||||
} = {}) {
|
||||
this.rawArgs = argv;
|
||||
if (!this.name) {
|
||||
this.name = argv[1] ? getFileName(argv[1]) : "cli";
|
||||
}
|
||||
let shouldParse = true;
|
||||
for (const command of this.commands) {
|
||||
const parsed = this.mri(argv.slice(2), command);
|
||||
const commandName = parsed.args[0];
|
||||
if (command.isMatched(commandName)) {
|
||||
shouldParse = false;
|
||||
const parsedInfo = __assign(__assign({}, parsed), {
|
||||
args: parsed.args.slice(1)
|
||||
});
|
||||
this.setParsedInfo(parsedInfo, command, commandName);
|
||||
this.emit(`command:${commandName}`, command);
|
||||
}
|
||||
}
|
||||
if (shouldParse) {
|
||||
for (const command of this.commands) {
|
||||
if (command.name === "") {
|
||||
shouldParse = false;
|
||||
const parsed = this.mri(argv.slice(2), command);
|
||||
this.setParsedInfo(parsed, command);
|
||||
this.emit(`command:!`, command);
|
||||
}
|
||||
}
|
||||
}
|
||||
if (shouldParse) {
|
||||
const parsed = this.mri(argv.slice(2));
|
||||
this.setParsedInfo(parsed);
|
||||
}
|
||||
if (this.options.help && this.showHelpOnExit) {
|
||||
this.outputHelp();
|
||||
run = false;
|
||||
this.unsetMatchedCommand();
|
||||
}
|
||||
if (this.options.version && this.showVersionOnExit && this.matchedCommandName == null) {
|
||||
this.outputVersion();
|
||||
run = false;
|
||||
this.unsetMatchedCommand();
|
||||
}
|
||||
const parsedArgv = {args: this.args, options: this.options};
|
||||
if (run) {
|
||||
this.runMatchedCommand();
|
||||
}
|
||||
if (!this.matchedCommand && this.args[0]) {
|
||||
this.emit("command:*");
|
||||
}
|
||||
return parsedArgv;
|
||||
}
|
||||
mri(argv, command) {
|
||||
const cliOptions = [
|
||||
...this.globalCommand.options,
|
||||
...command ? command.options : []
|
||||
];
|
||||
const mriOptions = getMriOptions(cliOptions);
|
||||
let argsAfterDoubleDashes = [];
|
||||
const doubleDashesIndex = argv.indexOf("--");
|
||||
if (doubleDashesIndex > -1) {
|
||||
argsAfterDoubleDashes = argv.slice(doubleDashesIndex + 1);
|
||||
argv = argv.slice(0, doubleDashesIndex);
|
||||
}
|
||||
let parsed = mri2(argv, mriOptions);
|
||||
parsed = Object.keys(parsed).reduce((res, name) => {
|
||||
return __assign(__assign({}, res), {
|
||||
[camelcaseOptionName(name)]: parsed[name]
|
||||
});
|
||||
}, {_: []});
|
||||
const args = parsed._;
|
||||
const options = {
|
||||
"--": argsAfterDoubleDashes
|
||||
};
|
||||
const ignoreDefault = command && command.config.ignoreOptionDefaultValue ? command.config.ignoreOptionDefaultValue : this.globalCommand.config.ignoreOptionDefaultValue;
|
||||
let transforms = Object.create(null);
|
||||
for (const cliOption of cliOptions) {
|
||||
if (!ignoreDefault && cliOption.config.default !== void 0) {
|
||||
for (const name of cliOption.names) {
|
||||
options[name] = cliOption.config.default;
|
||||
}
|
||||
}
|
||||
if (Array.isArray(cliOption.config.type)) {
|
||||
if (transforms[cliOption.name] === void 0) {
|
||||
transforms[cliOption.name] = Object.create(null);
|
||||
transforms[cliOption.name]["shouldTransform"] = true;
|
||||
transforms[cliOption.name]["transformFunction"] = cliOption.config.type[0];
|
||||
}
|
||||
}
|
||||
}
|
||||
for (const key of Object.keys(parsed)) {
|
||||
if (key !== "_") {
|
||||
const keys = key.split(".");
|
||||
setDotProp(options, keys, parsed[key]);
|
||||
setByType(options, transforms);
|
||||
}
|
||||
}
|
||||
return {
|
||||
args,
|
||||
options
|
||||
};
|
||||
}
|
||||
runMatchedCommand() {
|
||||
const {args, options, matchedCommand: command} = this;
|
||||
if (!command || !command.commandAction)
|
||||
return;
|
||||
command.checkUnknownOptions();
|
||||
command.checkOptionValue();
|
||||
command.checkRequiredArgs();
|
||||
const actionArgs = [];
|
||||
command.args.forEach((arg, index) => {
|
||||
if (arg.variadic) {
|
||||
actionArgs.push(args.slice(index));
|
||||
} else {
|
||||
actionArgs.push(args[index]);
|
||||
}
|
||||
});
|
||||
actionArgs.push(options);
|
||||
return command.commandAction.apply(this, actionArgs);
|
||||
}
|
||||
}
|
||||
|
||||
const cac = (name = "") => new CAC(name);
|
||||
|
||||
var version = "0.25.8";
|
||||
|
||||
const cli = cac("vite-node");
|
||||
cli.version(version).option("-r, --root <path>", "Use specified root directory").option("-c, --config <path>", "Use specified config file").option("-w, --watch", 'Restart on file changes, similar to "nodemon"').option("--options <options>", "Use specified Vite server options").help();
|
||||
cli.command("[...files]").action(run);
|
||||
cli.parse();
|
||||
async function run(files, options = {}) {
|
||||
var _a;
|
||||
if (!files.length) {
|
||||
console.error(picocolors.exports.red("No files specified."));
|
||||
cli.outputHelp();
|
||||
process.exit(1);
|
||||
}
|
||||
process.argv = [...process.argv.slice(0, 2), ...options["--"] || []];
|
||||
const serverOptions = options.options ? parseServerOptions(options.options) : {};
|
||||
const server = await createServer({
|
||||
logLevel: "error",
|
||||
configFile: options.config,
|
||||
root: options.root,
|
||||
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(picocolors.exports.red("[vite-node] Failed to execute file: \n"), err);
|
||||
});
|
||||
}
|
||||
}
|
||||
function parseServerOptions(serverOptions) {
|
||||
var _a, _b, _c, _d, _e;
|
||||
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;
|
||||
})
|
||||
},
|
||||
transformMode: {
|
||||
...serverOptions.transformMode,
|
||||
ssr: toArray((_d = serverOptions.transformMode) == null ? void 0 : _d.ssr).map((dep) => new RegExp(dep)),
|
||||
web: toArray((_e = serverOptions.transformMode) == null ? void 0 : _e.web).map((dep) => new RegExp(dep))
|
||||
}
|
||||
};
|
||||
}
|
||||
+379
@@ -0,0 +1,379 @@
|
||||
'use strict';
|
||||
|
||||
Object.defineProperty(exports, '__esModule', { value: true });
|
||||
|
||||
var module$1 = require('module');
|
||||
var url = require('url');
|
||||
var vm = require('vm');
|
||||
var pathe = require('pathe');
|
||||
var mlly = require('mlly');
|
||||
var createDebug = require('debug');
|
||||
var utils = require('./utils.cjs');
|
||||
var sourceMap = require('./source-map.cjs');
|
||||
require('fs');
|
||||
require('source-map-support');
|
||||
|
||||
function _interopDefaultLegacy (e) { return e && typeof e === 'object' && 'default' in e ? e : { 'default': e }; }
|
||||
|
||||
function _interopNamespace(e) {
|
||||
if (e && e.__esModule) return e;
|
||||
var n = Object.create(null);
|
||||
if (e) {
|
||||
Object.keys(e).forEach(function (k) {
|
||||
if (k !== 'default') {
|
||||
var d = Object.getOwnPropertyDescriptor(e, k);
|
||||
Object.defineProperty(n, k, d.get ? d : {
|
||||
enumerable: true,
|
||||
get: function () { return e[k]; }
|
||||
});
|
||||
}
|
||||
});
|
||||
}
|
||||
n["default"] = e;
|
||||
return Object.freeze(n);
|
||||
}
|
||||
|
||||
var vm__default = /*#__PURE__*/_interopDefaultLegacy(vm);
|
||||
var createDebug__default = /*#__PURE__*/_interopDefaultLegacy(createDebug);
|
||||
|
||||
const debugExecute = createDebug__default["default"]("vite-node:client:execute");
|
||||
const debugNative = createDebug__default["default"]("vite-node:client:native");
|
||||
const DEFAULT_REQUEST_STUBS = {
|
||||
"/@vite/client": {
|
||||
injectQuery: (id) => id,
|
||||
createHotContext() {
|
||||
return {
|
||||
accept: () => {
|
||||
},
|
||||
prune: () => {
|
||||
},
|
||||
dispose: () => {
|
||||
},
|
||||
decline: () => {
|
||||
},
|
||||
invalidate: () => {
|
||||
},
|
||||
on: () => {
|
||||
}
|
||||
};
|
||||
},
|
||||
updateStyle(id, css) {
|
||||
if (typeof document === "undefined")
|
||||
return;
|
||||
const element = document.getElementById(id);
|
||||
if (element)
|
||||
element.remove();
|
||||
const head = document.querySelector("head");
|
||||
const style = document.createElement("style");
|
||||
style.setAttribute("type", "text/css");
|
||||
style.id = id;
|
||||
style.innerHTML = css;
|
||||
head == null ? void 0 : head.appendChild(style);
|
||||
}
|
||||
}
|
||||
};
|
||||
class ModuleCacheMap extends Map {
|
||||
normalizePath(fsPath) {
|
||||
return utils.normalizeModuleId(fsPath);
|
||||
}
|
||||
update(fsPath, mod) {
|
||||
fsPath = this.normalizePath(fsPath);
|
||||
if (!super.has(fsPath))
|
||||
super.set(fsPath, mod);
|
||||
else
|
||||
Object.assign(super.get(fsPath), mod);
|
||||
return this;
|
||||
}
|
||||
set(fsPath, mod) {
|
||||
fsPath = this.normalizePath(fsPath);
|
||||
return super.set(fsPath, mod);
|
||||
}
|
||||
get(fsPath) {
|
||||
fsPath = this.normalizePath(fsPath);
|
||||
if (!super.has(fsPath))
|
||||
super.set(fsPath, {});
|
||||
return super.get(fsPath);
|
||||
}
|
||||
delete(fsPath) {
|
||||
fsPath = this.normalizePath(fsPath);
|
||||
return super.delete(fsPath);
|
||||
}
|
||||
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;
|
||||
}
|
||||
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;
|
||||
}
|
||||
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);
|
||||
}
|
||||
async executeFile(file) {
|
||||
return await this.cachedRequest(`/@fs/${utils.slash(pathe.resolve(file))}`, []);
|
||||
}
|
||||
async executeId(id) {
|
||||
return await this.cachedRequest(id, []);
|
||||
}
|
||||
getSourceMap(id) {
|
||||
return this.moduleCache.getSourceMap(id);
|
||||
}
|
||||
async cachedRequest(rawId, callstack) {
|
||||
const id = utils.normalizeRequestId(rawId, this.options.base);
|
||||
const fsPath = utils.toFilePath(id, this.root);
|
||||
const mod = this.moduleCache.get(fsPath);
|
||||
const importee = callstack[callstack.length - 1];
|
||||
if (!mod.importers)
|
||||
mod.importers = /* @__PURE__ */ new Set();
|
||||
if (importee)
|
||||
mod.importers.add(importee);
|
||||
if (callstack.includes(fsPath) && mod.exports)
|
||||
return mod.exports;
|
||||
if (mod.promise)
|
||||
return mod.promise;
|
||||
const promise = this.directRequest(id, fsPath, callstack);
|
||||
Object.assign(mod, { promise, evaluated: false });
|
||||
try {
|
||||
return await promise;
|
||||
} finally {
|
||||
mod.evaluated = true;
|
||||
}
|
||||
}
|
||||
async directRequest(id, fsPath, _callstack) {
|
||||
const callstack = [..._callstack, fsPath];
|
||||
let mod = this.moduleCache.get(fsPath);
|
||||
const request = async (dep2) => {
|
||||
var _a;
|
||||
const depFsPath = utils.toFilePath(utils.normalizeRequestId(dep2, this.options.base), this.root);
|
||||
const getStack = () => {
|
||||
return `stack:
|
||||
${[...callstack, depFsPath].reverse().map((p) => `- ${p}`).join("\n")}`;
|
||||
};
|
||||
let debugTimer;
|
||||
if (this.debug)
|
||||
debugTimer = setTimeout(() => console.warn(() => `module ${depFsPath} takes over 2s to load.
|
||||
${getStack()}`), 2e3);
|
||||
try {
|
||||
if (callstack.includes(depFsPath)) {
|
||||
const depExports = (_a = this.moduleCache.get(depFsPath)) == null ? void 0 : _a.exports;
|
||||
if (depExports)
|
||||
return depExports;
|
||||
throw new Error(`[vite-node] Failed to resolve circular dependency, ${getStack()}`);
|
||||
}
|
||||
return await this.cachedRequest(dep2, callstack);
|
||||
} finally {
|
||||
if (debugTimer)
|
||||
clearTimeout(debugTimer);
|
||||
}
|
||||
};
|
||||
Object.defineProperty(request, "callstack", { get: () => callstack });
|
||||
const resolveId = async (dep2, callstackPosition = 1) => {
|
||||
if (this.options.resolveId && this.shouldResolveId(dep2)) {
|
||||
let importer = callstack[callstack.length - callstackPosition];
|
||||
if (importer && !dep2.startsWith("."))
|
||||
importer = void 0;
|
||||
if (importer && importer.startsWith("mock:"))
|
||||
importer = importer.slice(5);
|
||||
const resolved = await this.options.resolveId(utils.normalizeRequestId(dep2), importer);
|
||||
return [dep2, resolved == null ? void 0 : resolved.id];
|
||||
}
|
||||
return [dep2, void 0];
|
||||
};
|
||||
const [dep, resolvedId] = await resolveId(id, 2);
|
||||
const requestStubs = this.options.requestStubs || DEFAULT_REQUEST_STUBS;
|
||||
if (id in requestStubs)
|
||||
return requestStubs[id];
|
||||
let { code: transformed, externalize } = await this.options.fetchModule(resolvedId || dep);
|
||||
if (resolvedId && !fsPath.includes("?") && fsPath !== resolvedId) {
|
||||
if (this.moduleCache.has(resolvedId)) {
|
||||
mod = this.moduleCache.get(resolvedId);
|
||||
this.moduleCache.set(fsPath, mod);
|
||||
if (mod.promise)
|
||||
return mod.promise;
|
||||
if (mod.exports)
|
||||
return mod.exports;
|
||||
} else {
|
||||
this.moduleCache.set(resolvedId, mod);
|
||||
}
|
||||
}
|
||||
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}`);
|
||||
const file = utils.cleanUrl(resolvedId || fsPath);
|
||||
const url$1 = url.pathToFileURL(file).href;
|
||||
const meta = { url: url$1 };
|
||||
const exports = /* @__PURE__ */ Object.create(null);
|
||||
Object.defineProperty(exports, Symbol.toStringTag, {
|
||||
value: "Module",
|
||||
enumerable: false,
|
||||
configurable: false
|
||||
});
|
||||
const cjsExports = new Proxy(exports, {
|
||||
set(_, p, value) {
|
||||
if (!Reflect.has(exports, "default"))
|
||||
exports.default = {};
|
||||
if (utils.isPrimitive(exports.default)) {
|
||||
defineExport(exports, p, () => void 0);
|
||||
return true;
|
||||
}
|
||||
exports.default[p] = value;
|
||||
if (p !== "default")
|
||||
defineExport(exports, p, () => value);
|
||||
return true;
|
||||
}
|
||||
});
|
||||
Object.assign(mod, { code: transformed, exports });
|
||||
const __filename = url.fileURLToPath(url$1);
|
||||
const moduleProxy = {
|
||||
set exports(value) {
|
||||
exportAll(cjsExports, value);
|
||||
exports.default = value;
|
||||
},
|
||||
get exports() {
|
||||
return cjsExports;
|
||||
}
|
||||
};
|
||||
let hotContext;
|
||||
if (this.options.createHotContext) {
|
||||
Object.defineProperty(meta, "hot", {
|
||||
enumerable: true,
|
||||
get: () => {
|
||||
var _a, _b;
|
||||
hotContext || (hotContext = (_b = (_a = this.options).createHotContext) == null ? void 0 : _b.call(_a, this, `/@fs/${fsPath}`));
|
||||
return hotContext;
|
||||
}
|
||||
});
|
||||
}
|
||||
const context = this.prepareContext({
|
||||
__vite_ssr_import__: request,
|
||||
__vite_ssr_dynamic_import__: request,
|
||||
__vite_ssr_exports__: exports,
|
||||
__vite_ssr_exportAll__: (obj) => exportAll(exports, obj),
|
||||
__vite_ssr_import_meta__: meta,
|
||||
__vitest_resolve_id__: resolveId,
|
||||
require: module$1.createRequire(url$1),
|
||||
exports: cjsExports,
|
||||
module: moduleProxy,
|
||||
__filename,
|
||||
__dirname: pathe.dirname(__filename)
|
||||
});
|
||||
debugExecute(__filename);
|
||||
if (transformed[0] === "#")
|
||||
transformed = transformed.replace(/^\#\!.*/, (s) => " ".repeat(s.length));
|
||||
const codeDefinition = `'use strict';async (${Object.keys(context).join(",")})=>{{`;
|
||||
const code = `${codeDefinition}${transformed}
|
||||
}}`;
|
||||
const fn = vm__default["default"].runInThisContext(code, {
|
||||
filename: __filename,
|
||||
lineOffset: 0,
|
||||
columnOffset: -codeDefinition.length
|
||||
});
|
||||
await fn(...Object.values(context));
|
||||
return exports;
|
||||
}
|
||||
prepareContext(context) {
|
||||
return context;
|
||||
}
|
||||
shouldResolveId(dep) {
|
||||
if (mlly.isNodeBuiltin(dep) || dep in (this.options.requestStubs || DEFAULT_REQUEST_STUBS) || dep.startsWith("/@vite"))
|
||||
return false;
|
||||
return !pathe.isAbsolute(dep) || !pathe.extname(dep);
|
||||
}
|
||||
shouldInterop(path, mod) {
|
||||
if (this.options.interopDefault === false)
|
||||
return false;
|
||||
return !path.endsWith(".mjs") && "default" in mod;
|
||||
}
|
||||
async interopedImport(path) {
|
||||
const mod = await (function (t) { return Promise.resolve().then(function () { return /*#__PURE__*/_interopNamespace(require(t)); }); })(path);
|
||||
if (this.shouldInterop(path, mod)) {
|
||||
const tryDefault = this.hasNestedDefault(mod);
|
||||
return new Proxy(mod, {
|
||||
get: proxyMethod("get", tryDefault),
|
||||
set: proxyMethod("set", tryDefault),
|
||||
has: proxyMethod("has", tryDefault),
|
||||
deleteProperty: proxyMethod("deleteProperty", tryDefault)
|
||||
});
|
||||
}
|
||||
return mod;
|
||||
}
|
||||
hasNestedDefault(target) {
|
||||
return "__esModule" in target && target.__esModule && "default" in target.default;
|
||||
}
|
||||
}
|
||||
function proxyMethod(name, tryDefault) {
|
||||
return function(target, key, ...args) {
|
||||
const result = Reflect[name](target, key, ...args);
|
||||
if (utils.isPrimitive(target.default))
|
||||
return result;
|
||||
if (tryDefault && key === "default" || typeof result === "undefined")
|
||||
return Reflect[name](target.default, key, ...args);
|
||||
return result;
|
||||
};
|
||||
}
|
||||
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))
|
||||
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;
|
||||
+1
@@ -0,0 +1 @@
|
||||
export { j as DEFAULT_REQUEST_STUBS, M as ModuleCacheMap, h as ViteNodeRunner } from './types-fc7e68bc.js';
|
||||
+350
@@ -0,0 +1,350 @@
|
||||
import { createRequire } from 'module';
|
||||
import { pathToFileURL, fileURLToPath } from 'url';
|
||||
import vm from 'vm';
|
||||
import { resolve, dirname, isAbsolute, extname } from 'pathe';
|
||||
import { isNodeBuiltin } from 'mlly';
|
||||
import createDebug from 'debug';
|
||||
import { normalizeModuleId, slash, normalizeRequestId, toFilePath, cleanUrl, isPrimitive } from './utils.mjs';
|
||||
import { extractSourceMap } from './source-map.mjs';
|
||||
import 'fs';
|
||||
import 'source-map-support';
|
||||
|
||||
const debugExecute = createDebug("vite-node:client:execute");
|
||||
const debugNative = createDebug("vite-node:client:native");
|
||||
const DEFAULT_REQUEST_STUBS = {
|
||||
"/@vite/client": {
|
||||
injectQuery: (id) => id,
|
||||
createHotContext() {
|
||||
return {
|
||||
accept: () => {
|
||||
},
|
||||
prune: () => {
|
||||
},
|
||||
dispose: () => {
|
||||
},
|
||||
decline: () => {
|
||||
},
|
||||
invalidate: () => {
|
||||
},
|
||||
on: () => {
|
||||
}
|
||||
};
|
||||
},
|
||||
updateStyle(id, css) {
|
||||
if (typeof document === "undefined")
|
||||
return;
|
||||
const element = document.getElementById(id);
|
||||
if (element)
|
||||
element.remove();
|
||||
const head = document.querySelector("head");
|
||||
const style = document.createElement("style");
|
||||
style.setAttribute("type", "text/css");
|
||||
style.id = id;
|
||||
style.innerHTML = css;
|
||||
head == null ? void 0 : head.appendChild(style);
|
||||
}
|
||||
}
|
||||
};
|
||||
class ModuleCacheMap extends Map {
|
||||
normalizePath(fsPath) {
|
||||
return normalizeModuleId(fsPath);
|
||||
}
|
||||
update(fsPath, mod) {
|
||||
fsPath = this.normalizePath(fsPath);
|
||||
if (!super.has(fsPath))
|
||||
super.set(fsPath, mod);
|
||||
else
|
||||
Object.assign(super.get(fsPath), mod);
|
||||
return this;
|
||||
}
|
||||
set(fsPath, mod) {
|
||||
fsPath = this.normalizePath(fsPath);
|
||||
return super.set(fsPath, mod);
|
||||
}
|
||||
get(fsPath) {
|
||||
fsPath = this.normalizePath(fsPath);
|
||||
if (!super.has(fsPath))
|
||||
super.set(fsPath, {});
|
||||
return super.get(fsPath);
|
||||
}
|
||||
delete(fsPath) {
|
||||
fsPath = this.normalizePath(fsPath);
|
||||
return super.delete(fsPath);
|
||||
}
|
||||
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;
|
||||
}
|
||||
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;
|
||||
}
|
||||
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);
|
||||
}
|
||||
async executeFile(file) {
|
||||
return await this.cachedRequest(`/@fs/${slash(resolve(file))}`, []);
|
||||
}
|
||||
async executeId(id) {
|
||||
return await this.cachedRequest(id, []);
|
||||
}
|
||||
getSourceMap(id) {
|
||||
return this.moduleCache.getSourceMap(id);
|
||||
}
|
||||
async cachedRequest(rawId, callstack) {
|
||||
const id = normalizeRequestId(rawId, this.options.base);
|
||||
const fsPath = toFilePath(id, this.root);
|
||||
const mod = this.moduleCache.get(fsPath);
|
||||
const importee = callstack[callstack.length - 1];
|
||||
if (!mod.importers)
|
||||
mod.importers = /* @__PURE__ */ new Set();
|
||||
if (importee)
|
||||
mod.importers.add(importee);
|
||||
if (callstack.includes(fsPath) && mod.exports)
|
||||
return mod.exports;
|
||||
if (mod.promise)
|
||||
return mod.promise;
|
||||
const promise = this.directRequest(id, fsPath, callstack);
|
||||
Object.assign(mod, { promise, evaluated: false });
|
||||
try {
|
||||
return await promise;
|
||||
} finally {
|
||||
mod.evaluated = true;
|
||||
}
|
||||
}
|
||||
async directRequest(id, fsPath, _callstack) {
|
||||
const callstack = [..._callstack, fsPath];
|
||||
let mod = this.moduleCache.get(fsPath);
|
||||
const request = async (dep2) => {
|
||||
var _a;
|
||||
const depFsPath = toFilePath(normalizeRequestId(dep2, this.options.base), this.root);
|
||||
const getStack = () => {
|
||||
return `stack:
|
||||
${[...callstack, depFsPath].reverse().map((p) => `- ${p}`).join("\n")}`;
|
||||
};
|
||||
let debugTimer;
|
||||
if (this.debug)
|
||||
debugTimer = setTimeout(() => console.warn(() => `module ${depFsPath} takes over 2s to load.
|
||||
${getStack()}`), 2e3);
|
||||
try {
|
||||
if (callstack.includes(depFsPath)) {
|
||||
const depExports = (_a = this.moduleCache.get(depFsPath)) == null ? void 0 : _a.exports;
|
||||
if (depExports)
|
||||
return depExports;
|
||||
throw new Error(`[vite-node] Failed to resolve circular dependency, ${getStack()}`);
|
||||
}
|
||||
return await this.cachedRequest(dep2, callstack);
|
||||
} finally {
|
||||
if (debugTimer)
|
||||
clearTimeout(debugTimer);
|
||||
}
|
||||
};
|
||||
Object.defineProperty(request, "callstack", { get: () => callstack });
|
||||
const resolveId = async (dep2, callstackPosition = 1) => {
|
||||
if (this.options.resolveId && this.shouldResolveId(dep2)) {
|
||||
let importer = callstack[callstack.length - callstackPosition];
|
||||
if (importer && !dep2.startsWith("."))
|
||||
importer = void 0;
|
||||
if (importer && importer.startsWith("mock:"))
|
||||
importer = importer.slice(5);
|
||||
const resolved = await this.options.resolveId(normalizeRequestId(dep2), importer);
|
||||
return [dep2, resolved == null ? void 0 : resolved.id];
|
||||
}
|
||||
return [dep2, void 0];
|
||||
};
|
||||
const [dep, resolvedId] = await resolveId(id, 2);
|
||||
const requestStubs = this.options.requestStubs || DEFAULT_REQUEST_STUBS;
|
||||
if (id in requestStubs)
|
||||
return requestStubs[id];
|
||||
let { code: transformed, externalize } = await this.options.fetchModule(resolvedId || dep);
|
||||
if (resolvedId && !fsPath.includes("?") && fsPath !== resolvedId) {
|
||||
if (this.moduleCache.has(resolvedId)) {
|
||||
mod = this.moduleCache.get(resolvedId);
|
||||
this.moduleCache.set(fsPath, mod);
|
||||
if (mod.promise)
|
||||
return mod.promise;
|
||||
if (mod.exports)
|
||||
return mod.exports;
|
||||
} else {
|
||||
this.moduleCache.set(resolvedId, mod);
|
||||
}
|
||||
}
|
||||
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}`);
|
||||
const file = cleanUrl(resolvedId || fsPath);
|
||||
const url = pathToFileURL(file).href;
|
||||
const meta = { url };
|
||||
const exports = /* @__PURE__ */ Object.create(null);
|
||||
Object.defineProperty(exports, Symbol.toStringTag, {
|
||||
value: "Module",
|
||||
enumerable: false,
|
||||
configurable: false
|
||||
});
|
||||
const cjsExports = new Proxy(exports, {
|
||||
set(_, p, value) {
|
||||
if (!Reflect.has(exports, "default"))
|
||||
exports.default = {};
|
||||
if (isPrimitive(exports.default)) {
|
||||
defineExport(exports, p, () => void 0);
|
||||
return true;
|
||||
}
|
||||
exports.default[p] = value;
|
||||
if (p !== "default")
|
||||
defineExport(exports, p, () => value);
|
||||
return true;
|
||||
}
|
||||
});
|
||||
Object.assign(mod, { code: transformed, exports });
|
||||
const __filename = fileURLToPath(url);
|
||||
const moduleProxy = {
|
||||
set exports(value) {
|
||||
exportAll(cjsExports, value);
|
||||
exports.default = value;
|
||||
},
|
||||
get exports() {
|
||||
return cjsExports;
|
||||
}
|
||||
};
|
||||
let hotContext;
|
||||
if (this.options.createHotContext) {
|
||||
Object.defineProperty(meta, "hot", {
|
||||
enumerable: true,
|
||||
get: () => {
|
||||
var _a, _b;
|
||||
hotContext || (hotContext = (_b = (_a = this.options).createHotContext) == null ? void 0 : _b.call(_a, this, `/@fs/${fsPath}`));
|
||||
return hotContext;
|
||||
}
|
||||
});
|
||||
}
|
||||
const context = this.prepareContext({
|
||||
__vite_ssr_import__: request,
|
||||
__vite_ssr_dynamic_import__: request,
|
||||
__vite_ssr_exports__: exports,
|
||||
__vite_ssr_exportAll__: (obj) => exportAll(exports, obj),
|
||||
__vite_ssr_import_meta__: meta,
|
||||
__vitest_resolve_id__: resolveId,
|
||||
require: createRequire(url),
|
||||
exports: cjsExports,
|
||||
module: moduleProxy,
|
||||
__filename,
|
||||
__dirname: dirname(__filename)
|
||||
});
|
||||
debugExecute(__filename);
|
||||
if (transformed[0] === "#")
|
||||
transformed = transformed.replace(/^\#\!.*/, (s) => " ".repeat(s.length));
|
||||
const codeDefinition = `'use strict';async (${Object.keys(context).join(",")})=>{{`;
|
||||
const code = `${codeDefinition}${transformed}
|
||||
}}`;
|
||||
const fn = vm.runInThisContext(code, {
|
||||
filename: __filename,
|
||||
lineOffset: 0,
|
||||
columnOffset: -codeDefinition.length
|
||||
});
|
||||
await fn(...Object.values(context));
|
||||
return exports;
|
||||
}
|
||||
prepareContext(context) {
|
||||
return context;
|
||||
}
|
||||
shouldResolveId(dep) {
|
||||
if (isNodeBuiltin(dep) || dep in (this.options.requestStubs || DEFAULT_REQUEST_STUBS) || dep.startsWith("/@vite"))
|
||||
return false;
|
||||
return !isAbsolute(dep) || !extname(dep);
|
||||
}
|
||||
shouldInterop(path, mod) {
|
||||
if (this.options.interopDefault === false)
|
||||
return false;
|
||||
return !path.endsWith(".mjs") && "default" in mod;
|
||||
}
|
||||
async interopedImport(path) {
|
||||
const mod = await import(path);
|
||||
if (this.shouldInterop(path, mod)) {
|
||||
const tryDefault = this.hasNestedDefault(mod);
|
||||
return new Proxy(mod, {
|
||||
get: proxyMethod("get", tryDefault),
|
||||
set: proxyMethod("set", tryDefault),
|
||||
has: proxyMethod("has", tryDefault),
|
||||
deleteProperty: proxyMethod("deleteProperty", tryDefault)
|
||||
});
|
||||
}
|
||||
return mod;
|
||||
}
|
||||
hasNestedDefault(target) {
|
||||
return "__esModule" in target && target.__esModule && "default" in target.default;
|
||||
}
|
||||
}
|
||||
function proxyMethod(name, tryDefault) {
|
||||
return function(target, key, ...args) {
|
||||
const result = Reflect[name](target, key, ...args);
|
||||
if (isPrimitive(target.default))
|
||||
return result;
|
||||
if (tryDefault && key === "default" || typeof result === "undefined")
|
||||
return Reflect[name](target.default, key, ...args);
|
||||
return result;
|
||||
};
|
||||
}
|
||||
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))
|
||||
return;
|
||||
for (const key in sourceModule) {
|
||||
if (key !== "default") {
|
||||
try {
|
||||
defineExport(exports, key, () => sourceModule[key]);
|
||||
} catch (_err) {
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
export { DEFAULT_REQUEST_STUBS, ModuleCacheMap, ViteNodeRunner };
|
||||
+19
@@ -0,0 +1,19 @@
|
||||
'use strict';
|
||||
|
||||
Object.defineProperty(exports, '__esModule', { value: true });
|
||||
|
||||
var hmr = require('./chunk-hmr.cjs');
|
||||
require('events');
|
||||
require('./chunk-picocolors.cjs');
|
||||
require('tty');
|
||||
require('debug');
|
||||
|
||||
|
||||
|
||||
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;
|
||||
+51
@@ -0,0 +1,51 @@
|
||||
import { EventEmitter } from 'events';
|
||||
import { HMRPayload, Plugin } from 'vite';
|
||||
import { g as CustomEventMap, h as ViteNodeRunner, i as HMRPayload$1, H as HotContext } from './types-fc7e68bc.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;
|
||||
emit<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 InferCustomEventPayload<T extends string> = T extends keyof CustomEventMap ? CustomEventMap[T] : any;
|
||||
interface HotModule {
|
||||
id: string;
|
||||
callbacks: HotCallback[];
|
||||
}
|
||||
interface HotCallback {
|
||||
deps: string[];
|
||||
fn: (modules: object[]) => 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 { Emitter, EventType, HMREmitter, Handler, HotCallback, HotModule, InferCustomEventPayload, createHmrEmitter, createHotContext, getCache, handleMessage, reload, sendMessageBuffer, viteNodeHmrPlugin };
|
||||
+5
@@ -0,0 +1,5 @@
|
||||
export { a as createHmrEmitter, c as createHotContext, g as getCache, h as handleMessage, r as reload, s as sendMessageBuffer, v as viteNodeHmrPlugin } from './chunk-hmr.mjs';
|
||||
import 'events';
|
||||
import './chunk-picocolors.mjs';
|
||||
import 'tty';
|
||||
import 'debug';
|
||||
+2
@@ -0,0 +1,2 @@
|
||||
'use strict';
|
||||
|
||||
+1
@@ -0,0 +1 @@
|
||||
export { A as Arrayable, C as CreateHotContextFunction, f as DebuggerOptions, D as DepsHandlingOptions, a as FetchFunction, F as FetchResult, H as HotContext, c as ModuleCache, M as ModuleCacheMap, N as Nullable, R as RawSourceMap, b as ResolveIdFunction, S as StartOfSourceMap, d as ViteNodeResolveId, V as ViteNodeRunnerOptions, e as ViteNodeServerOptions } from './types-fc7e68bc.js';
|
||||
+1
@@ -0,0 +1 @@
|
||||
|
||||
+314
@@ -0,0 +1,314 @@
|
||||
'use strict';
|
||||
|
||||
Object.defineProperty(exports, '__esModule', { value: true });
|
||||
|
||||
var perf_hooks = require('perf_hooks');
|
||||
var pathe = require('pathe');
|
||||
var createDebug = require('debug');
|
||||
var fs = require('fs');
|
||||
var mlly = require('mlly');
|
||||
var utils = require('./utils.cjs');
|
||||
var picocolors = require('./chunk-picocolors.cjs');
|
||||
var sourceMap = require('./source-map.cjs');
|
||||
require('url');
|
||||
require('tty');
|
||||
require('source-map-support');
|
||||
|
||||
function _interopDefaultLegacy (e) { return e && typeof e === 'object' && 'default' in e ? e : { 'default': e }; }
|
||||
|
||||
var createDebug__default = /*#__PURE__*/_interopDefaultLegacy(createDebug);
|
||||
|
||||
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$/
|
||||
];
|
||||
const depsExternal = [
|
||||
/\.cjs\.js$/,
|
||||
/\.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;
|
||||
}
|
||||
}
|
||||
}
|
||||
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 (mlly.isNodeBuiltin(id))
|
||||
return id;
|
||||
if (id.startsWith("data:"))
|
||||
return id;
|
||||
id = patchWindowsImportPath(id);
|
||||
if (matchExternalizePattern(id, options == null ? void 0 : options.inline))
|
||||
return false;
|
||||
if (matchExternalizePattern(id, options == null ? void 0 : options.external))
|
||||
return id;
|
||||
const isNodeModule = id.includes("/node_modules/");
|
||||
const guessCJS = isNodeModule && (options == null ? void 0 : options.fallbackCJS);
|
||||
id = guessCJS ? guessCJSversion(id) || id : id;
|
||||
if (matchExternalizePattern(id, defaultInline))
|
||||
return false;
|
||||
if (matchExternalizePattern(id, depsExternal))
|
||||
return id;
|
||||
const isDist = id.includes("/dist/");
|
||||
if ((isNodeModule || isDist) && await mlly.isValidNodeImport(id))
|
||||
return id;
|
||||
return false;
|
||||
}
|
||||
function matchExternalizePattern(id, patterns) {
|
||||
if (patterns == null)
|
||||
return false;
|
||||
if (patterns === true)
|
||||
return true;
|
||||
for (const ex of patterns) {
|
||||
if (typeof ex === "string") {
|
||||
if (id.includes(`/node_modules/${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;
|
||||
this.externalizeMap = /* @__PURE__ */ new Map();
|
||||
if (options.dumpModules)
|
||||
this.dumpDir = pathe.resolve(root, options.dumpModules === true ? ".vite-node/dump" : options.dumpModules);
|
||||
if (this.dumpDir) {
|
||||
if (options.loadDumppedModules)
|
||||
console.info(picocolors.picocolors.exports.gray(`[vite-node] [debug] load modules from ${this.dumpDir}`));
|
||||
else
|
||||
console.info(picocolors.picocolors.exports.gray(`[vite-node] [debug] dump modules to ${this.dumpDir}`));
|
||||
}
|
||||
this.initPromise = this.clearDump();
|
||||
}
|
||||
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: 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__default["default"]("vite-node:server:request");
|
||||
class ViteNodeServer {
|
||||
constructor(server, options = {}) {
|
||||
this.server = server;
|
||||
this.options = options;
|
||||
this.fetchPromiseMap = /* @__PURE__ */ new Map();
|
||||
this.transformPromiseMap = /* @__PURE__ */ new Map();
|
||||
this.fetchCache = /* @__PURE__ */ new Map();
|
||||
this.externalizeCache = /* @__PURE__ */ new Map();
|
||||
var _a, _b;
|
||||
const ssrOptions = server.config.ssr;
|
||||
if (ssrOptions) {
|
||||
options.deps ?? (options.deps = {});
|
||||
if (ssrOptions.noExternal === true) {
|
||||
(_a = options.deps).inline ?? (_a.inline = true);
|
||||
} else if (options.deps.inline !== true) {
|
||||
(_b = options.deps).inline ?? (_b.inline = []);
|
||||
options.deps.inline.push(...utils.toArray(ssrOptions.noExternal));
|
||||
}
|
||||
}
|
||||
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);
|
||||
}
|
||||
shouldExternalize(id) {
|
||||
return shouldExternalize(id, this.options.deps, this.externalizeCache);
|
||||
}
|
||||
async resolveId(id, importer) {
|
||||
if (importer && !importer.startsWith(this.server.config.root))
|
||||
importer = pathe.resolve(this.server.config.root, importer);
|
||||
const mode = 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;
|
||||
}
|
||||
async fetchModule(id) {
|
||||
id = utils.normalizeModuleId(id);
|
||||
if (!this.fetchPromiseMap.has(id)) {
|
||||
this.fetchPromiseMap.set(
|
||||
id,
|
||||
this._fetchModule(id).then((r) => {
|
||||
return this.options.sourcemap !== true ? { ...r, map: void 0 } : r;
|
||||
}).finally(() => {
|
||||
this.fetchPromiseMap.delete(id);
|
||||
})
|
||||
);
|
||||
}
|
||||
return this.fetchPromiseMap.get(id);
|
||||
}
|
||||
async transformRequest(id) {
|
||||
if (!this.transformPromiseMap.has(id)) {
|
||||
this.transformPromiseMap.set(
|
||||
id,
|
||||
this._transformRequest(id).finally(() => {
|
||||
this.transformPromiseMap.delete(id);
|
||||
})
|
||||
);
|
||||
}
|
||||
return this.transformPromiseMap.get(id);
|
||||
}
|
||||
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";
|
||||
}
|
||||
async _fetchModule(id) {
|
||||
var _a;
|
||||
let result;
|
||||
const filePath = utils.toFilePath(id, this.server.config.root);
|
||||
const module = this.server.moduleGraph.getModuleById(id);
|
||||
const timestamp = module ? module.lastHMRTimestamp : null;
|
||||
const cache = this.fetchCache.get(filePath);
|
||||
if (timestamp !== null && cache && cache.timestamp >= timestamp)
|
||||
return cache.result;
|
||||
const time = Date.now();
|
||||
const externalize = await this.shouldExternalize(filePath);
|
||||
let duration;
|
||||
if (externalize) {
|
||||
result = { externalize };
|
||||
(_a = this.debugger) == null ? void 0 : _a.recordExternalize(id, externalize);
|
||||
} else {
|
||||
const start = perf_hooks.performance.now();
|
||||
const r = await this._transformRequest(id);
|
||||
duration = perf_hooks.performance.now() - start;
|
||||
result = { code: r == null ? void 0 : r.code, map: r == null ? void 0 : r.map };
|
||||
}
|
||||
this.fetchCache.set(filePath, {
|
||||
duration,
|
||||
timestamp: time,
|
||||
result
|
||||
});
|
||||
return result;
|
||||
}
|
||||
async _transformRequest(id) {
|
||||
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 (this.getTransformMode(id) === "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"))
|
||||
sourceMap.withInlineSourcemap(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;
|
||||
+44
@@ -0,0 +1,44 @@
|
||||
import { TransformResult, ViteDevServer } from 'vite';
|
||||
import { f as DebuggerOptions, D as DepsHandlingOptions, e as ViteNodeServerOptions, F as FetchResult, d as ViteNodeResolveId, R as RawSourceMap } from './types-fc7e68bc.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>;
|
||||
|
||||
declare class ViteNodeServer {
|
||||
server: ViteDevServer;
|
||||
options: ViteNodeServerOptions;
|
||||
private fetchPromiseMap;
|
||||
private transformPromiseMap;
|
||||
fetchCache: Map<string, {
|
||||
duration?: number | undefined;
|
||||
timestamp: number;
|
||||
result: FetchResult;
|
||||
}>;
|
||||
externalizeCache: Map<string, Promise<string | false>>;
|
||||
debugger?: Debugger;
|
||||
constructor(server: ViteDevServer, options?: ViteNodeServerOptions);
|
||||
shouldExternalize(id: string): Promise<string | false>;
|
||||
resolveId(id: string, importer?: string): Promise<ViteNodeResolveId | null>;
|
||||
getSourceMap(source: string): RawSourceMap | null;
|
||||
fetchModule(id: string): Promise<FetchResult>;
|
||||
transformRequest(id: string): Promise<TransformResult | null | undefined>;
|
||||
getTransformMode(id: string): "web" | "ssr";
|
||||
private _fetchModule;
|
||||
private _transformRequest;
|
||||
}
|
||||
|
||||
export { ViteNodeServer, guessCJSversion, shouldExternalize };
|
||||
+304
@@ -0,0 +1,304 @@
|
||||
import { performance } from 'perf_hooks';
|
||||
import { resolve, join } from 'pathe';
|
||||
import createDebug from 'debug';
|
||||
import { existsSync, promises } from 'fs';
|
||||
import { isNodeBuiltin, isValidNodeImport } from 'mlly';
|
||||
import { slash, toArray, normalizeModuleId, toFilePath } from './utils.mjs';
|
||||
import { p as picocolors } from './chunk-picocolors.mjs';
|
||||
import { withInlineSourcemap } from './source-map.mjs';
|
||||
import 'url';
|
||||
import 'tty';
|
||||
import 'source-map-support';
|
||||
|
||||
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$/
|
||||
];
|
||||
const depsExternal = [
|
||||
/\.cjs\.js$/,
|
||||
/\.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;
|
||||
}
|
||||
}
|
||||
}
|
||||
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:"))
|
||||
return id;
|
||||
id = patchWindowsImportPath(id);
|
||||
if (matchExternalizePattern(id, options == null ? void 0 : options.inline))
|
||||
return false;
|
||||
if (matchExternalizePattern(id, options == null ? void 0 : options.external))
|
||||
return id;
|
||||
const isNodeModule = id.includes("/node_modules/");
|
||||
const guessCJS = isNodeModule && (options == null ? void 0 : options.fallbackCJS);
|
||||
id = guessCJS ? guessCJSversion(id) || id : id;
|
||||
if (matchExternalizePattern(id, defaultInline))
|
||||
return false;
|
||||
if (matchExternalizePattern(id, depsExternal))
|
||||
return id;
|
||||
const isDist = id.includes("/dist/");
|
||||
if ((isNodeModule || isDist) && await isValidNodeImport(id))
|
||||
return id;
|
||||
return false;
|
||||
}
|
||||
function matchExternalizePattern(id, patterns) {
|
||||
if (patterns == null)
|
||||
return false;
|
||||
if (patterns === true)
|
||||
return true;
|
||||
for (const ex of patterns) {
|
||||
if (typeof ex === "string") {
|
||||
if (id.includes(`/node_modules/${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;
|
||||
this.externalizeMap = /* @__PURE__ */ new Map();
|
||||
if (options.dumpModules)
|
||||
this.dumpDir = resolve(root, options.dumpModules === true ? ".vite-node/dump" : options.dumpModules);
|
||||
if (this.dumpDir) {
|
||||
if (options.loadDumppedModules)
|
||||
console.info(picocolors.exports.gray(`[vite-node] [debug] load modules from ${this.dumpDir}`));
|
||||
else
|
||||
console.info(picocolors.exports.gray(`[vite-node] [debug] dump modules to ${this.dumpDir}`));
|
||||
}
|
||||
this.initPromise = this.clearDump();
|
||||
}
|
||||
async clearDump() {
|
||||
if (!this.dumpDir)
|
||||
return;
|
||||
if (!this.options.loadDumppedModules && existsSync(this.dumpDir))
|
||||
await promises.rm(this.dumpDir, { recursive: true, force: true });
|
||||
await promises.mkdir(this.dumpDir, { recursive: true });
|
||||
}
|
||||
encodeId(id) {
|
||||
return `${id.replace(/[^\w@_-]/g, "_").replace(/_+/g, "_")}-${hashCode(id)}.js`;
|
||||
}
|
||||
async recordExternalize(id, path) {
|
||||
if (!this.dumpDir)
|
||||
return;
|
||||
this.externalizeMap.set(id, path);
|
||||
await this.writeInfo();
|
||||
}
|
||||
async dumpFile(id, result) {
|
||||
if (!result || !this.dumpDir)
|
||||
return;
|
||||
await this.initPromise;
|
||||
const name = this.encodeId(id);
|
||||
return await promises.writeFile(join(this.dumpDir, name), `// ${id.replace(/\0/g, "\\0")}
|
||||
${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: 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;
|
||||
this.fetchPromiseMap = /* @__PURE__ */ new Map();
|
||||
this.transformPromiseMap = /* @__PURE__ */ new Map();
|
||||
this.fetchCache = /* @__PURE__ */ new Map();
|
||||
this.externalizeCache = /* @__PURE__ */ new Map();
|
||||
var _a, _b;
|
||||
const ssrOptions = server.config.ssr;
|
||||
if (ssrOptions) {
|
||||
options.deps ?? (options.deps = {});
|
||||
if (ssrOptions.noExternal === true) {
|
||||
(_a = options.deps).inline ?? (_a.inline = true);
|
||||
} else if (options.deps.inline !== true) {
|
||||
(_b = options.deps).inline ?? (_b.inline = []);
|
||||
options.deps.inline.push(...toArray(ssrOptions.noExternal));
|
||||
}
|
||||
}
|
||||
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);
|
||||
}
|
||||
shouldExternalize(id) {
|
||||
return shouldExternalize(id, this.options.deps, this.externalizeCache);
|
||||
}
|
||||
async resolveId(id, importer) {
|
||||
if (importer && !importer.startsWith(this.server.config.root))
|
||||
importer = resolve(this.server.config.root, importer);
|
||||
const mode = 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;
|
||||
}
|
||||
async fetchModule(id) {
|
||||
id = normalizeModuleId(id);
|
||||
if (!this.fetchPromiseMap.has(id)) {
|
||||
this.fetchPromiseMap.set(
|
||||
id,
|
||||
this._fetchModule(id).then((r) => {
|
||||
return this.options.sourcemap !== true ? { ...r, map: void 0 } : r;
|
||||
}).finally(() => {
|
||||
this.fetchPromiseMap.delete(id);
|
||||
})
|
||||
);
|
||||
}
|
||||
return this.fetchPromiseMap.get(id);
|
||||
}
|
||||
async transformRequest(id) {
|
||||
if (!this.transformPromiseMap.has(id)) {
|
||||
this.transformPromiseMap.set(
|
||||
id,
|
||||
this._transformRequest(id).finally(() => {
|
||||
this.transformPromiseMap.delete(id);
|
||||
})
|
||||
);
|
||||
}
|
||||
return this.transformPromiseMap.get(id);
|
||||
}
|
||||
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";
|
||||
}
|
||||
async _fetchModule(id) {
|
||||
var _a;
|
||||
let result;
|
||||
const filePath = toFilePath(id, this.server.config.root);
|
||||
const module = this.server.moduleGraph.getModuleById(id);
|
||||
const timestamp = module ? module.lastHMRTimestamp : null;
|
||||
const cache = this.fetchCache.get(filePath);
|
||||
if (timestamp !== null && cache && cache.timestamp >= timestamp)
|
||||
return cache.result;
|
||||
const time = Date.now();
|
||||
const externalize = await this.shouldExternalize(filePath);
|
||||
let duration;
|
||||
if (externalize) {
|
||||
result = { externalize };
|
||||
(_a = this.debugger) == null ? void 0 : _a.recordExternalize(id, externalize);
|
||||
} else {
|
||||
const start = performance.now();
|
||||
const r = await this._transformRequest(id);
|
||||
duration = performance.now() - start;
|
||||
result = { code: r == null ? void 0 : r.code, map: r == null ? void 0 : r.map };
|
||||
}
|
||||
this.fetchCache.set(filePath, {
|
||||
duration,
|
||||
timestamp: time,
|
||||
result
|
||||
});
|
||||
return result;
|
||||
}
|
||||
async _transformRequest(id) {
|
||||
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 (this.getTransformMode(id) === "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"))
|
||||
withInlineSourcemap(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 };
|
||||
+54
@@ -0,0 +1,54 @@
|
||||
'use strict';
|
||||
|
||||
Object.defineProperty(exports, '__esModule', { value: true });
|
||||
|
||||
var sourceMapSupport = require('source-map-support');
|
||||
|
||||
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,(.+)`);
|
||||
async function withInlineSourcemap(result) {
|
||||
const map = result.map;
|
||||
let code = result.code;
|
||||
if (!map || code.includes(VITE_NODE_SOURCEMAPPING_SOURCE))
|
||||
return result;
|
||||
const OTHER_SOURCE_MAP_REGEXP = new RegExp(`//# ${SOURCEMAPPING_URL}=data:application/json[^,]+base64,(.+)`, "g");
|
||||
while (OTHER_SOURCE_MAP_REGEXP.test(code))
|
||||
code = code.replace(OTHER_SOURCE_MAP_REGEXP, "");
|
||||
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) {
|
||||
sourceMapSupport.install({
|
||||
environment: "node",
|
||||
handleUncaughtExceptions: false,
|
||||
retrieveSourceMap(source) {
|
||||
const map = options.getSourceMap(source);
|
||||
if (map) {
|
||||
return {
|
||||
url: source,
|
||||
map
|
||||
};
|
||||
}
|
||||
return null;
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
exports.extractSourceMap = extractSourceMap;
|
||||
exports.installSourcemapsSupport = installSourcemapsSupport;
|
||||
exports.withInlineSourcemap = withInlineSourcemap;
|
||||
+11
@@ -0,0 +1,11 @@
|
||||
import { TransformResult } from 'vite';
|
||||
import { R as RawSourceMap } from './types-fc7e68bc.js';
|
||||
|
||||
interface InstallSourceMapSupportOptions {
|
||||
getSourceMap: (source: string) => RawSourceMap | null | undefined;
|
||||
}
|
||||
declare function withInlineSourcemap(result: TransformResult): Promise<TransformResult>;
|
||||
declare function extractSourceMap(code: string): RawSourceMap | null;
|
||||
declare function installSourcemapsSupport(options: InstallSourceMapSupportOptions): void;
|
||||
|
||||
export { extractSourceMap, installSourcemapsSupport, withInlineSourcemap };
|
||||
+48
@@ -0,0 +1,48 @@
|
||||
import { install } from 'source-map-support';
|
||||
|
||||
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,(.+)`);
|
||||
async function withInlineSourcemap(result) {
|
||||
const map = result.map;
|
||||
let code = result.code;
|
||||
if (!map || code.includes(VITE_NODE_SOURCEMAPPING_SOURCE))
|
||||
return result;
|
||||
const OTHER_SOURCE_MAP_REGEXP = new RegExp(`//# ${SOURCEMAPPING_URL}=data:application/json[^,]+base64,(.+)`, "g");
|
||||
while (OTHER_SOURCE_MAP_REGEXP.test(code))
|
||||
code = code.replace(OTHER_SOURCE_MAP_REGEXP, "");
|
||||
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({
|
||||
environment: "node",
|
||||
handleUncaughtExceptions: false,
|
||||
retrieveSourceMap(source) {
|
||||
const map = options.getSourceMap(source);
|
||||
if (map) {
|
||||
return {
|
||||
url: source,
|
||||
map
|
||||
};
|
||||
}
|
||||
return null;
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
export { extractSourceMap, installSourcemapsSupport, withInlineSourcemap };
|
||||
+270
@@ -0,0 +1,270 @@
|
||||
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
|
||||
/**
|
||||
* @experimental internal
|
||||
*/
|
||||
explicitImportRequired?: boolean | undefined
|
||||
}
|
||||
|
||||
interface PrunePayload {
|
||||
type: 'prune'
|
||||
paths: string[]
|
||||
}
|
||||
|
||||
interface FullReloadPayload {
|
||||
type: 'full-reload'
|
||||
path?: 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
|
||||
}
|
||||
|
||||
interface InvalidatePayload {
|
||||
path: string
|
||||
message: string | undefined
|
||||
}
|
||||
|
||||
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
|
||||
send<T extends string>(event: T, data?: InferCustomEventPayload<T>): void
|
||||
}
|
||||
|
||||
declare const DEFAULT_REQUEST_STUBS: {
|
||||
'/@vite/client': {
|
||||
injectQuery: (id: string) => string;
|
||||
createHotContext(): {
|
||||
accept: () => void;
|
||||
prune: () => void;
|
||||
dispose: () => void;
|
||||
decline: () => void;
|
||||
invalidate: () => void;
|
||||
on: () => void;
|
||||
};
|
||||
updateStyle(id: string, css: string): void;
|
||||
};
|
||||
};
|
||||
declare class ModuleCacheMap extends Map<string, ModuleCache> {
|
||||
normalizePath(fsPath: string): string;
|
||||
/**
|
||||
* Assign partial data to the map
|
||||
*/
|
||||
update(fsPath: string, mod: Partial<ModuleCache>): this;
|
||||
set(fsPath: string, mod: ModuleCache): this;
|
||||
get(fsPath: string): ModuleCache;
|
||||
delete(fsPath: string): 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): RawSourceMap | 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(id: string): Promise<any>;
|
||||
getSourceMap(id: string): RawSourceMap | null;
|
||||
/** @internal */
|
||||
cachedRequest(rawId: string, callstack: string[]): Promise<any>;
|
||||
/** @internal */
|
||||
directRequest(id: string, fsPath: string, _callstack: string[]): Promise<any>;
|
||||
prepareContext(context: Record<string, any>): Record<string, any>;
|
||||
shouldResolveId(dep: string): boolean;
|
||||
/**
|
||||
* Define if a module should be interop-ed
|
||||
* This function mostly for the ability to override by subclass
|
||||
*/
|
||||
shouldInterop(path: string, mod: any): boolean;
|
||||
/**
|
||||
* Import a module and interop it
|
||||
*/
|
||||
interopedImport(path: string): Promise<any>;
|
||||
hasNestedDefault(target: any): any;
|
||||
}
|
||||
|
||||
type Nullable<T> = T | null | undefined;
|
||||
type Arrayable<T> = T | Array<T>;
|
||||
interface DepsHandlingOptions {
|
||||
external?: (string | RegExp)[];
|
||||
inline?: (string | RegExp)[] | true;
|
||||
/**
|
||||
* 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: string;
|
||||
sources: string[];
|
||||
names: string[];
|
||||
sourcesContent?: string[];
|
||||
mappings: string;
|
||||
}
|
||||
interface FetchResult {
|
||||
code?: string;
|
||||
externalize?: string;
|
||||
map?: RawSourceMap;
|
||||
}
|
||||
type HotContext = Omit<ViteHotContext, 'acceptDeps' | 'decline'>;
|
||||
type FetchFunction = (id: string) => Promise<FetchResult>;
|
||||
type ResolveIdFunction = (id: string, importer?: string) => Promise<ViteNodeResolveId | null>;
|
||||
type CreateHotContextFunction = (runner: ViteNodeRunner, url: string) => HotContext;
|
||||
interface ModuleCache {
|
||||
promise?: Promise<any>;
|
||||
exports?: any;
|
||||
evaluated?: boolean;
|
||||
code?: string;
|
||||
map?: RawSourceMap;
|
||||
/**
|
||||
* Module ids that imports this module
|
||||
*/
|
||||
importers?: 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 { Arrayable as A, CreateHotContextFunction as C, DepsHandlingOptions as D, FetchResult as F, HotContext as H, ModuleCacheMap as M, Nullable as N, RawSourceMap as R, StartOfSourceMap as S, ViteNodeRunnerOptions as V, FetchFunction as a, ResolveIdFunction as b, ModuleCache as c, ViteNodeResolveId as d, ViteNodeServerOptions as e, DebuggerOptions as f, CustomEventMap as g, ViteNodeRunner as h, HMRPayload as i, DEFAULT_REQUEST_STUBS as j };
|
||||
+2
@@ -0,0 +1,2 @@
|
||||
'use strict';
|
||||
|
||||
+1
@@ -0,0 +1 @@
|
||||
export { A as Arrayable, C as CreateHotContextFunction, f as DebuggerOptions, D as DepsHandlingOptions, a as FetchFunction, F as FetchResult, H as HotContext, c as ModuleCache, M as ModuleCacheMap, N as Nullable, R as RawSourceMap, b as ResolveIdFunction, S as StartOfSourceMap, d as ViteNodeResolveId, V as ViteNodeRunnerOptions, e as ViteNodeServerOptions } from './types-fc7e68bc.js';
|
||||
+1
@@ -0,0 +1 @@
|
||||
|
||||
+76
@@ -0,0 +1,76 @@
|
||||
'use strict';
|
||||
|
||||
Object.defineProperty(exports, '__esModule', { value: true });
|
||||
|
||||
var url = require('url');
|
||||
var fs = require('fs');
|
||||
var pathe = require('pathe');
|
||||
var mlly = require('mlly');
|
||||
|
||||
const isWindows = process.platform === "win32";
|
||||
function slash(str) {
|
||||
return str.replace(/\\/g, "/");
|
||||
}
|
||||
function mergeSlashes(str) {
|
||||
return str.replace(/\/\//g, "/");
|
||||
}
|
||||
function normalizeRequestId(id, base) {
|
||||
if (base && id.startsWith(base))
|
||||
id = `/${id.slice(base.length)}`;
|
||||
return id.replace(/^\/@id\/__x00__/, "\0").replace(/^\/@id\//, "").replace(/^__vite-browser-external:/, "").replace(/^(node|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;
|
||||
const cleanUrl = (url) => url.replace(hashRE, "").replace(queryRE, "");
|
||||
function normalizeModuleId(id) {
|
||||
return id.replace(/\\/g, "/").replace(/^\/@fs\//, "/").replace(/^file:\//, "/").replace(/^\/+/, "/");
|
||||
}
|
||||
function isPrimitive(v) {
|
||||
return v !== Object(v);
|
||||
}
|
||||
function pathFromRoot(root, filename) {
|
||||
if (mlly.isNodeBuiltin(filename))
|
||||
return filename;
|
||||
filename = filename.replace(/^\/@fs\//, isWindows ? "" : "/");
|
||||
if (!filename.startsWith(root))
|
||||
return filename;
|
||||
const relativePath = pathe.relative(root, filename);
|
||||
const segments = relativePath.split("/");
|
||||
const startIndex = segments.findIndex((segment) => segment !== ".." && segment !== ".");
|
||||
return `/${segments.slice(startIndex).join("/")}`;
|
||||
}
|
||||
function toFilePath(id, root) {
|
||||
let absolute = (() => {
|
||||
if (id.startsWith("/@fs/"))
|
||||
return id.slice(4);
|
||||
if (!id.startsWith(root) && id.startsWith("/")) {
|
||||
const resolved = pathe.resolve(root, id.slice(1));
|
||||
if (fs.existsSync(resolved.replace(/\?.*$/, "")))
|
||||
return resolved;
|
||||
}
|
||||
return id;
|
||||
})();
|
||||
if (absolute.startsWith("//"))
|
||||
absolute = absolute.slice(1);
|
||||
return isWindows && absolute.startsWith("/") ? slash(url.fileURLToPath(url.pathToFileURL(absolute.slice(1)).href)) : absolute;
|
||||
}
|
||||
function toArray(array) {
|
||||
if (array === null || array === void 0)
|
||||
array = [];
|
||||
if (Array.isArray(array))
|
||||
return array;
|
||||
return [array];
|
||||
}
|
||||
|
||||
exports.cleanUrl = cleanUrl;
|
||||
exports.hashRE = hashRE;
|
||||
exports.isPrimitive = isPrimitive;
|
||||
exports.isWindows = isWindows;
|
||||
exports.mergeSlashes = mergeSlashes;
|
||||
exports.normalizeModuleId = normalizeModuleId;
|
||||
exports.normalizeRequestId = normalizeRequestId;
|
||||
exports.pathFromRoot = pathFromRoot;
|
||||
exports.queryRE = queryRE;
|
||||
exports.slash = slash;
|
||||
exports.toArray = toArray;
|
||||
exports.toFilePath = toFilePath;
|
||||
+21
@@ -0,0 +1,21 @@
|
||||
import { N as Nullable, A as Arrayable } from './types-fc7e68bc.js';
|
||||
|
||||
declare const isWindows: boolean;
|
||||
declare function slash(str: string): string;
|
||||
declare function mergeSlashes(str: string): string;
|
||||
declare function normalizeRequestId(id: string, base?: string): string;
|
||||
declare const queryRE: RegExp;
|
||||
declare const hashRE: RegExp;
|
||||
declare const cleanUrl: (url: string) => string;
|
||||
declare function normalizeModuleId(id: string): string;
|
||||
declare function isPrimitive(v: any): boolean;
|
||||
declare function pathFromRoot(root: string, filename: string): string;
|
||||
declare function toFilePath(id: string, root: string): string;
|
||||
/**
|
||||
* Convert `Arrayable<T>` to `Array<T>`
|
||||
*
|
||||
* @category Array
|
||||
*/
|
||||
declare function toArray<T>(array?: Nullable<Arrayable<T>>): Array<T>;
|
||||
|
||||
export { cleanUrl, hashRE, isPrimitive, isWindows, mergeSlashes, normalizeModuleId, normalizeRequestId, pathFromRoot, queryRE, slash, toArray, toFilePath };
|
||||
+61
@@ -0,0 +1,61 @@
|
||||
import { fileURLToPath, pathToFileURL } from 'url';
|
||||
import { existsSync } from 'fs';
|
||||
import { relative, resolve } from 'pathe';
|
||||
import { isNodeBuiltin } from 'mlly';
|
||||
|
||||
const isWindows = process.platform === "win32";
|
||||
function slash(str) {
|
||||
return str.replace(/\\/g, "/");
|
||||
}
|
||||
function mergeSlashes(str) {
|
||||
return str.replace(/\/\//g, "/");
|
||||
}
|
||||
function normalizeRequestId(id, base) {
|
||||
if (base && id.startsWith(base))
|
||||
id = `/${id.slice(base.length)}`;
|
||||
return id.replace(/^\/@id\/__x00__/, "\0").replace(/^\/@id\//, "").replace(/^__vite-browser-external:/, "").replace(/^(node|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;
|
||||
const cleanUrl = (url) => url.replace(hashRE, "").replace(queryRE, "");
|
||||
function normalizeModuleId(id) {
|
||||
return id.replace(/\\/g, "/").replace(/^\/@fs\//, "/").replace(/^file:\//, "/").replace(/^\/+/, "/");
|
||||
}
|
||||
function isPrimitive(v) {
|
||||
return v !== Object(v);
|
||||
}
|
||||
function pathFromRoot(root, filename) {
|
||||
if (isNodeBuiltin(filename))
|
||||
return filename;
|
||||
filename = filename.replace(/^\/@fs\//, isWindows ? "" : "/");
|
||||
if (!filename.startsWith(root))
|
||||
return filename;
|
||||
const relativePath = relative(root, filename);
|
||||
const segments = relativePath.split("/");
|
||||
const startIndex = segments.findIndex((segment) => segment !== ".." && segment !== ".");
|
||||
return `/${segments.slice(startIndex).join("/")}`;
|
||||
}
|
||||
function toFilePath(id, root) {
|
||||
let absolute = (() => {
|
||||
if (id.startsWith("/@fs/"))
|
||||
return id.slice(4);
|
||||
if (!id.startsWith(root) && id.startsWith("/")) {
|
||||
const resolved = resolve(root, id.slice(1));
|
||||
if (existsSync(resolved.replace(/\?.*$/, "")))
|
||||
return resolved;
|
||||
}
|
||||
return id;
|
||||
})();
|
||||
if (absolute.startsWith("//"))
|
||||
absolute = absolute.slice(1);
|
||||
return isWindows && absolute.startsWith("/") ? slash(fileURLToPath(pathToFileURL(absolute.slice(1)).href)) : absolute;
|
||||
}
|
||||
function toArray(array) {
|
||||
if (array === null || array === void 0)
|
||||
array = [];
|
||||
if (Array.isArray(array))
|
||||
return array;
|
||||
return [array];
|
||||
}
|
||||
|
||||
export { cleanUrl, hashRE, isPrimitive, isWindows, mergeSlashes, normalizeModuleId, normalizeRequestId, pathFromRoot, queryRE, slash, toArray, toFilePath };
|
||||
+32
@@ -0,0 +1,32 @@
|
||||
# Changelog
|
||||
|
||||
All notable changes to this project will be documented in this file. See [standard-version](https://github.com/conventional-changelog/standard-version) for commit guidelines.
|
||||
|
||||
## [0.2.0](https://github.com/unjs/pathe/compare/v0.1.0...v0.2.0) (2021-09-27)
|
||||
|
||||
|
||||
### ⚠ BREAKING CHANGES
|
||||
|
||||
* improved implementation with tests (#3)
|
||||
|
||||
### Features
|
||||
|
||||
* improved implementation with tests ([#3](https://github.com/unjs/pathe/issues/3)) ([d8d0cb5](https://github.com/unjs/pathe/commit/d8d0cb51dbca7295248c36f93510738057f2828d))
|
||||
|
||||
## [0.1.0](https://github.com/unjs/pathe/compare/v0.0.3...v0.1.0) (2021-09-24)
|
||||
|
||||
### [0.0.3](https://github.com/unjs/pathe/compare/v0.0.2...v0.0.3) (2021-09-24)
|
||||
|
||||
|
||||
### Bug Fixes
|
||||
|
||||
* add hotfix for resolve ([a221d34](https://github.com/unjs/pathe/commit/a221d3468c81802da03823bd606de70a524a7b55))
|
||||
|
||||
### [0.0.2](https://github.com/unjs/pathe/compare/v0.0.1...v0.0.2) (2021-09-22)
|
||||
|
||||
|
||||
### Bug Fixes
|
||||
|
||||
* **pkg:** expose types ([77000b1](https://github.com/unjs/pathe/commit/77000b1a45780fd62c93dc71d8264f10d97af864))
|
||||
|
||||
### 0.0.1 (2021-09-22)
|
||||
+44
@@ -0,0 +1,44 @@
|
||||
MIT License
|
||||
|
||||
Copyright (c) 2021 UnJS
|
||||
|
||||
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.
|
||||
+61
@@ -0,0 +1,61 @@
|
||||
# pathe
|
||||
|
||||
> Normalized paths for Node.js
|
||||
|
||||
[![version][npm-v-src]][npm-v-href]
|
||||
[![downloads][npm-d-src]][npm-d-href]
|
||||
[![size][size-src]][size-href]
|
||||
|
||||
🧪 This package is still experimental and might not handle all cases. Please track issues.
|
||||
|
||||
## ❓ 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.**
|
||||
|
||||
This package is a drop-in replacement of the Node.js's `path` module and ensures paths are normalized with slash `/`.
|
||||
|
||||
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**.
|
||||
|
||||
## 💿 Install
|
||||
|
||||
Install using npm or yarn:
|
||||
|
||||
```bash
|
||||
npm i pathe
|
||||
# or
|
||||
yarn add 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!
|
||||
|
||||
## License
|
||||
|
||||
MIT. Made with 💖
|
||||
|
||||
Some code used form 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
|
||||
+208
@@ -0,0 +1,208 @@
|
||||
'use strict';
|
||||
|
||||
Object.defineProperty(exports, '__esModule', { value: true });
|
||||
|
||||
const path = require('path');
|
||||
|
||||
function _interopDefaultLegacy (e) { return e && typeof e === 'object' && 'default' in e ? e : { 'default': e }; }
|
||||
|
||||
const path__default = /*#__PURE__*/_interopDefaultLegacy(path);
|
||||
|
||||
function normalizeWindowsPath(input = "") {
|
||||
if (!input.includes("\\")) {
|
||||
return input;
|
||||
}
|
||||
return input.replace(/\\/g, "/");
|
||||
}
|
||||
|
||||
const _UNC_REGEX = /^[/][/]/;
|
||||
const _UNC_DRIVE_REGEX = /^[/][/]([.]{1,2}[/])?([a-zA-Z]):[/]/;
|
||||
const _IS_ABSOLUTE_RE = /^\/|^\\|^[a-zA-Z]:[/\\]/;
|
||||
const sep = "/";
|
||||
const delimiter = ":";
|
||||
const normalize = function(path2) {
|
||||
if (path2.length === 0) {
|
||||
return ".";
|
||||
}
|
||||
path2 = normalizeWindowsPath(path2);
|
||||
const isUNCPath = path2.match(_UNC_REGEX);
|
||||
const hasUNCDrive = isUNCPath && path2.match(_UNC_DRIVE_REGEX);
|
||||
const isPathAbsolute = isAbsolute(path2);
|
||||
const trailingSeparator = path2[path2.length - 1] === "/";
|
||||
path2 = normalizeString(path2, !isPathAbsolute);
|
||||
if (path2.length === 0) {
|
||||
if (isPathAbsolute) {
|
||||
return "/";
|
||||
}
|
||||
return trailingSeparator ? "./" : ".";
|
||||
}
|
||||
if (trailingSeparator) {
|
||||
path2 += "/";
|
||||
}
|
||||
if (isUNCPath) {
|
||||
if (hasUNCDrive) {
|
||||
return `//./${path2}`;
|
||||
}
|
||||
return `//${path2}`;
|
||||
}
|
||||
return isPathAbsolute && !isAbsolute(path2) ? `/${path2}` : path2;
|
||||
};
|
||||
const join = function(...args) {
|
||||
if (args.length === 0) {
|
||||
return ".";
|
||||
}
|
||||
let joined;
|
||||
for (let i = 0; i < args.length; ++i) {
|
||||
const arg = args[i];
|
||||
if (arg.length > 0) {
|
||||
if (joined === void 0) {
|
||||
joined = arg;
|
||||
} else {
|
||||
joined += `/${arg}`;
|
||||
}
|
||||
}
|
||||
}
|
||||
if (joined === void 0) {
|
||||
return ".";
|
||||
}
|
||||
return normalize(joined);
|
||||
};
|
||||
const resolve = function(...args) {
|
||||
args = args.map((arg) => normalizeWindowsPath(arg));
|
||||
let resolvedPath = "";
|
||||
let resolvedAbsolute = false;
|
||||
for (let i = args.length - 1; i >= -1 && !resolvedAbsolute; i--) {
|
||||
const path2 = i >= 0 ? args[i] : process.cwd();
|
||||
if (path2.length === 0) {
|
||||
continue;
|
||||
}
|
||||
resolvedPath = `${path2}/${resolvedPath}`;
|
||||
resolvedAbsolute = isAbsolute(path2);
|
||||
}
|
||||
resolvedPath = normalizeString(resolvedPath, !resolvedAbsolute);
|
||||
if (resolvedAbsolute && !isAbsolute(resolvedPath)) {
|
||||
return `/${resolvedPath}`;
|
||||
}
|
||||
return resolvedPath.length > 0 ? resolvedPath : ".";
|
||||
};
|
||||
function normalizeString(path2, allowAboveRoot) {
|
||||
let res = "";
|
||||
let lastSegmentLength = 0;
|
||||
let lastSlash = -1;
|
||||
let dots = 0;
|
||||
let char = null;
|
||||
for (let i = 0; i <= path2.length; ++i) {
|
||||
if (i < path2.length) {
|
||||
char = path2[i];
|
||||
} else if (char === "/") {
|
||||
break;
|
||||
} else {
|
||||
char = "/";
|
||||
}
|
||||
if (char === "/") {
|
||||
if (lastSlash === i - 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 = i;
|
||||
dots = 0;
|
||||
continue;
|
||||
} else if (res.length !== 0) {
|
||||
res = "";
|
||||
lastSegmentLength = 0;
|
||||
lastSlash = i;
|
||||
dots = 0;
|
||||
continue;
|
||||
}
|
||||
}
|
||||
if (allowAboveRoot) {
|
||||
res += res.length > 0 ? "/.." : "..";
|
||||
lastSegmentLength = 2;
|
||||
}
|
||||
} else {
|
||||
if (res.length > 0) {
|
||||
res += `/${path2.slice(lastSlash + 1, i)}`;
|
||||
} else {
|
||||
res = path2.slice(lastSlash + 1, i);
|
||||
}
|
||||
lastSegmentLength = i - lastSlash - 1;
|
||||
}
|
||||
lastSlash = i;
|
||||
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 = function(p) {
|
||||
return path__default["default"].posix.extname(normalizeWindowsPath(p));
|
||||
};
|
||||
const relative = function(from, to) {
|
||||
return path__default["default"].posix.relative(normalizeWindowsPath(from), normalizeWindowsPath(to));
|
||||
};
|
||||
const dirname = function(p) {
|
||||
return path__default["default"].posix.dirname(normalizeWindowsPath(p));
|
||||
};
|
||||
const format = function(p) {
|
||||
return normalizeWindowsPath(path__default["default"].posix.format(p));
|
||||
};
|
||||
const basename = function(p, ext) {
|
||||
return path__default["default"].posix.basename(normalizeWindowsPath(p), ext);
|
||||
};
|
||||
const parse = function(p) {
|
||||
return path__default["default"].posix.parse(normalizeWindowsPath(p));
|
||||
};
|
||||
|
||||
const _path = /*#__PURE__*/Object.freeze({
|
||||
__proto__: null,
|
||||
sep: sep,
|
||||
delimiter: delimiter,
|
||||
normalize: normalize,
|
||||
join: join,
|
||||
resolve: resolve,
|
||||
normalizeString: normalizeString,
|
||||
isAbsolute: isAbsolute,
|
||||
toNamespacedPath: toNamespacedPath,
|
||||
extname: extname,
|
||||
relative: relative,
|
||||
dirname: dirname,
|
||||
format: format,
|
||||
basename: basename,
|
||||
parse: parse
|
||||
});
|
||||
|
||||
const index = {
|
||||
..._path
|
||||
};
|
||||
|
||||
exports.basename = basename;
|
||||
exports["default"] = index;
|
||||
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.parse = parse;
|
||||
exports.relative = relative;
|
||||
exports.resolve = resolve;
|
||||
exports.sep = sep;
|
||||
exports.toNamespacedPath = toNamespacedPath;
|
||||
+20
@@ -0,0 +1,20 @@
|
||||
import path from 'path';
|
||||
|
||||
declare const sep = "/";
|
||||
declare const delimiter = ":";
|
||||
declare const normalize: typeof path.normalize;
|
||||
declare const join: typeof path.join;
|
||||
declare const resolve: typeof path.resolve;
|
||||
declare function normalizeString(path: string, allowAboveRoot: boolean): string;
|
||||
declare const isAbsolute: typeof path.isAbsolute;
|
||||
declare const toNamespacedPath: typeof path.toNamespacedPath;
|
||||
declare const extname: typeof path.extname;
|
||||
declare const relative: typeof path.relative;
|
||||
declare const dirname: typeof path.dirname;
|
||||
declare const format: typeof path.format;
|
||||
declare const basename: typeof path.basename;
|
||||
declare const parse: typeof path.parse;
|
||||
|
||||
declare const _default: Omit<path.PlatformPath, "win32" | "posix">;
|
||||
|
||||
export { basename, _default as default, delimiter, dirname, extname, format, isAbsolute, join, normalize, normalizeString, parse, relative, resolve, sep, toNamespacedPath };
|
||||
+186
@@ -0,0 +1,186 @@
|
||||
import path from 'path';
|
||||
|
||||
function normalizeWindowsPath(input = "") {
|
||||
if (!input.includes("\\")) {
|
||||
return input;
|
||||
}
|
||||
return input.replace(/\\/g, "/");
|
||||
}
|
||||
|
||||
const _UNC_REGEX = /^[/][/]/;
|
||||
const _UNC_DRIVE_REGEX = /^[/][/]([.]{1,2}[/])?([a-zA-Z]):[/]/;
|
||||
const _IS_ABSOLUTE_RE = /^\/|^\\|^[a-zA-Z]:[/\\]/;
|
||||
const sep = "/";
|
||||
const delimiter = ":";
|
||||
const normalize = function(path2) {
|
||||
if (path2.length === 0) {
|
||||
return ".";
|
||||
}
|
||||
path2 = normalizeWindowsPath(path2);
|
||||
const isUNCPath = path2.match(_UNC_REGEX);
|
||||
const hasUNCDrive = isUNCPath && path2.match(_UNC_DRIVE_REGEX);
|
||||
const isPathAbsolute = isAbsolute(path2);
|
||||
const trailingSeparator = path2[path2.length - 1] === "/";
|
||||
path2 = normalizeString(path2, !isPathAbsolute);
|
||||
if (path2.length === 0) {
|
||||
if (isPathAbsolute) {
|
||||
return "/";
|
||||
}
|
||||
return trailingSeparator ? "./" : ".";
|
||||
}
|
||||
if (trailingSeparator) {
|
||||
path2 += "/";
|
||||
}
|
||||
if (isUNCPath) {
|
||||
if (hasUNCDrive) {
|
||||
return `//./${path2}`;
|
||||
}
|
||||
return `//${path2}`;
|
||||
}
|
||||
return isPathAbsolute && !isAbsolute(path2) ? `/${path2}` : path2;
|
||||
};
|
||||
const join = function(...args) {
|
||||
if (args.length === 0) {
|
||||
return ".";
|
||||
}
|
||||
let joined;
|
||||
for (let i = 0; i < args.length; ++i) {
|
||||
const arg = args[i];
|
||||
if (arg.length > 0) {
|
||||
if (joined === void 0) {
|
||||
joined = arg;
|
||||
} else {
|
||||
joined += `/${arg}`;
|
||||
}
|
||||
}
|
||||
}
|
||||
if (joined === void 0) {
|
||||
return ".";
|
||||
}
|
||||
return normalize(joined);
|
||||
};
|
||||
const resolve = function(...args) {
|
||||
args = args.map((arg) => normalizeWindowsPath(arg));
|
||||
let resolvedPath = "";
|
||||
let resolvedAbsolute = false;
|
||||
for (let i = args.length - 1; i >= -1 && !resolvedAbsolute; i--) {
|
||||
const path2 = i >= 0 ? args[i] : process.cwd();
|
||||
if (path2.length === 0) {
|
||||
continue;
|
||||
}
|
||||
resolvedPath = `${path2}/${resolvedPath}`;
|
||||
resolvedAbsolute = isAbsolute(path2);
|
||||
}
|
||||
resolvedPath = normalizeString(resolvedPath, !resolvedAbsolute);
|
||||
if (resolvedAbsolute && !isAbsolute(resolvedPath)) {
|
||||
return `/${resolvedPath}`;
|
||||
}
|
||||
return resolvedPath.length > 0 ? resolvedPath : ".";
|
||||
};
|
||||
function normalizeString(path2, allowAboveRoot) {
|
||||
let res = "";
|
||||
let lastSegmentLength = 0;
|
||||
let lastSlash = -1;
|
||||
let dots = 0;
|
||||
let char = null;
|
||||
for (let i = 0; i <= path2.length; ++i) {
|
||||
if (i < path2.length) {
|
||||
char = path2[i];
|
||||
} else if (char === "/") {
|
||||
break;
|
||||
} else {
|
||||
char = "/";
|
||||
}
|
||||
if (char === "/") {
|
||||
if (lastSlash === i - 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 = i;
|
||||
dots = 0;
|
||||
continue;
|
||||
} else if (res.length !== 0) {
|
||||
res = "";
|
||||
lastSegmentLength = 0;
|
||||
lastSlash = i;
|
||||
dots = 0;
|
||||
continue;
|
||||
}
|
||||
}
|
||||
if (allowAboveRoot) {
|
||||
res += res.length > 0 ? "/.." : "..";
|
||||
lastSegmentLength = 2;
|
||||
}
|
||||
} else {
|
||||
if (res.length > 0) {
|
||||
res += `/${path2.slice(lastSlash + 1, i)}`;
|
||||
} else {
|
||||
res = path2.slice(lastSlash + 1, i);
|
||||
}
|
||||
lastSegmentLength = i - lastSlash - 1;
|
||||
}
|
||||
lastSlash = i;
|
||||
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 = function(p) {
|
||||
return path.posix.extname(normalizeWindowsPath(p));
|
||||
};
|
||||
const relative = function(from, to) {
|
||||
return path.posix.relative(normalizeWindowsPath(from), normalizeWindowsPath(to));
|
||||
};
|
||||
const dirname = function(p) {
|
||||
return path.posix.dirname(normalizeWindowsPath(p));
|
||||
};
|
||||
const format = function(p) {
|
||||
return normalizeWindowsPath(path.posix.format(p));
|
||||
};
|
||||
const basename = function(p, ext) {
|
||||
return path.posix.basename(normalizeWindowsPath(p), ext);
|
||||
};
|
||||
const parse = function(p) {
|
||||
return path.posix.parse(normalizeWindowsPath(p));
|
||||
};
|
||||
|
||||
const _path = /*#__PURE__*/Object.freeze({
|
||||
__proto__: null,
|
||||
sep: sep,
|
||||
delimiter: delimiter,
|
||||
normalize: normalize,
|
||||
join: join,
|
||||
resolve: resolve,
|
||||
normalizeString: normalizeString,
|
||||
isAbsolute: isAbsolute,
|
||||
toNamespacedPath: toNamespacedPath,
|
||||
extname: extname,
|
||||
relative: relative,
|
||||
dirname: dirname,
|
||||
format: format,
|
||||
basename: basename,
|
||||
parse: parse
|
||||
});
|
||||
|
||||
const index = {
|
||||
..._path
|
||||
};
|
||||
|
||||
export { basename, index as default, delimiter, dirname, extname, format, isAbsolute, join, normalize, normalizeString, parse, relative, resolve, sep, toNamespacedPath };
|
||||
+40
@@ -0,0 +1,40 @@
|
||||
{
|
||||
"name": "pathe",
|
||||
"version": "0.2.0",
|
||||
"description": "Normalized paths for Node.js",
|
||||
"repository": "unjs/pathe",
|
||||
"license": "MIT",
|
||||
"sideEffects": false,
|
||||
"exports": {
|
||||
".": {
|
||||
"import": "./dist/index.mjs",
|
||||
"require": "./dist/index.cjs"
|
||||
}
|
||||
},
|
||||
"main": "./dist/index.cjs",
|
||||
"types": "./dist/index.d.ts",
|
||||
"files": [
|
||||
"dist"
|
||||
],
|
||||
"scripts": {
|
||||
"build": "siroc build",
|
||||
"lint": "eslint --ext .ts .",
|
||||
"prepublishOnly": "yarn build",
|
||||
"release": "yarn test && standard-version && git push --follow-tags && npm publish",
|
||||
"test": "nyc mocha -r jiti/register test/*"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@nuxtjs/eslint-config-typescript": "latest",
|
||||
"@types/chai": "^4.2.22",
|
||||
"@types/mocha": "^9.0.0",
|
||||
"@types/node": "^16.9.6",
|
||||
"chai": "^4.3.4",
|
||||
"eslint": "latest",
|
||||
"jiti": "^1.12.3",
|
||||
"mocha": "^9.1.1",
|
||||
"nyc": "^15.1.0",
|
||||
"siroc": "latest",
|
||||
"standard-version": "latest",
|
||||
"typescript": "^4.4.3"
|
||||
}
|
||||
}
|
||||
+301
@@ -0,0 +1,301 @@
|
||||
# Change Log
|
||||
|
||||
## 0.5.6
|
||||
|
||||
* Fix for regression when people were using numbers as names in source maps. See
|
||||
#236.
|
||||
|
||||
## 0.5.5
|
||||
|
||||
* Fix "regression" of unsupported, implementation behavior that half the world
|
||||
happens to have come to depend on. See #235.
|
||||
|
||||
* Fix regression involving function hoisting in SpiderMonkey. See #233.
|
||||
|
||||
## 0.5.4
|
||||
|
||||
* Large performance improvements to source-map serialization. See #228 and #229.
|
||||
|
||||
## 0.5.3
|
||||
|
||||
* Do not include unnecessary distribution files. See
|
||||
commit ef7006f8d1647e0a83fdc60f04f5a7ca54886f86.
|
||||
|
||||
## 0.5.2
|
||||
|
||||
* Include browser distributions of the library in package.json's `files`. See
|
||||
issue #212.
|
||||
|
||||
## 0.5.1
|
||||
|
||||
* Fix latent bugs in IndexedSourceMapConsumer.prototype._parseMappings. See
|
||||
ff05274becc9e6e1295ed60f3ea090d31d843379.
|
||||
|
||||
## 0.5.0
|
||||
|
||||
* Node 0.8 is no longer supported.
|
||||
|
||||
* Use webpack instead of dryice for bundling.
|
||||
|
||||
* Big speedups serializing source maps. See pull request #203.
|
||||
|
||||
* Fix a bug with `SourceMapConsumer.prototype.sourceContentFor` and sources that
|
||||
explicitly start with the source root. See issue #199.
|
||||
|
||||
## 0.4.4
|
||||
|
||||
* Fix an issue where using a `SourceMapGenerator` after having created a
|
||||
`SourceMapConsumer` from it via `SourceMapConsumer.fromSourceMap` failed. See
|
||||
issue #191.
|
||||
|
||||
* Fix an issue with where `SourceMapGenerator` would mistakenly consider
|
||||
different mappings as duplicates of each other and avoid generating them. See
|
||||
issue #192.
|
||||
|
||||
## 0.4.3
|
||||
|
||||
* A very large number of performance improvements, particularly when parsing
|
||||
source maps. Collectively about 75% of time shaved off of the source map
|
||||
parsing benchmark!
|
||||
|
||||
* Fix a bug in `SourceMapConsumer.prototype.allGeneratedPositionsFor` and fuzzy
|
||||
searching in the presence of a column option. See issue #177.
|
||||
|
||||
* Fix a bug with joining a source and its source root when the source is above
|
||||
the root. See issue #182.
|
||||
|
||||
* Add the `SourceMapConsumer.prototype.hasContentsOfAllSources` method to
|
||||
determine when all sources' contents are inlined into the source map. See
|
||||
issue #190.
|
||||
|
||||
## 0.4.2
|
||||
|
||||
* Add an `.npmignore` file so that the benchmarks aren't pulled down by
|
||||
dependent projects. Issue #169.
|
||||
|
||||
* Add an optional `column` argument to
|
||||
`SourceMapConsumer.prototype.allGeneratedPositionsFor` and better handle lines
|
||||
with no mappings. Issues #172 and #173.
|
||||
|
||||
## 0.4.1
|
||||
|
||||
* Fix accidentally defining a global variable. #170.
|
||||
|
||||
## 0.4.0
|
||||
|
||||
* The default direction for fuzzy searching was changed back to its original
|
||||
direction. See #164.
|
||||
|
||||
* There is now a `bias` option you can supply to `SourceMapConsumer` to control
|
||||
the fuzzy searching direction. See #167.
|
||||
|
||||
* About an 8% speed up in parsing source maps. See #159.
|
||||
|
||||
* Added a benchmark for parsing and generating source maps.
|
||||
|
||||
## 0.3.0
|
||||
|
||||
* Change the default direction that searching for positions fuzzes when there is
|
||||
not an exact match. See #154.
|
||||
|
||||
* Support for environments using json2.js for JSON serialization. See #156.
|
||||
|
||||
## 0.2.0
|
||||
|
||||
* Support for consuming "indexed" source maps which do not have any remote
|
||||
sections. See pull request #127. This introduces a minor backwards
|
||||
incompatibility if you are monkey patching `SourceMapConsumer.prototype`
|
||||
methods.
|
||||
|
||||
## 0.1.43
|
||||
|
||||
* Performance improvements for `SourceMapGenerator` and `SourceNode`. See issue
|
||||
#148 for some discussion and issues #150, #151, and #152 for implementations.
|
||||
|
||||
## 0.1.42
|
||||
|
||||
* Fix an issue where `SourceNode`s from different versions of the source-map
|
||||
library couldn't be used in conjunction with each other. See issue #142.
|
||||
|
||||
## 0.1.41
|
||||
|
||||
* Fix a bug with getting the source content of relative sources with a "./"
|
||||
prefix. See issue #145 and [Bug 1090768](bugzil.la/1090768).
|
||||
|
||||
* Add the `SourceMapConsumer.prototype.computeColumnSpans` method to compute the
|
||||
column span of each mapping.
|
||||
|
||||
* Add the `SourceMapConsumer.prototype.allGeneratedPositionsFor` method to find
|
||||
all generated positions associated with a given original source and line.
|
||||
|
||||
## 0.1.40
|
||||
|
||||
* Performance improvements for parsing source maps in SourceMapConsumer.
|
||||
|
||||
## 0.1.39
|
||||
|
||||
* Fix a bug where setting a source's contents to null before any source content
|
||||
had been set before threw a TypeError. See issue #131.
|
||||
|
||||
## 0.1.38
|
||||
|
||||
* Fix a bug where finding relative paths from an empty path were creating
|
||||
absolute paths. See issue #129.
|
||||
|
||||
## 0.1.37
|
||||
|
||||
* Fix a bug where if the source root was an empty string, relative source paths
|
||||
would turn into absolute source paths. Issue #124.
|
||||
|
||||
## 0.1.36
|
||||
|
||||
* Allow the `names` mapping property to be an empty string. Issue #121.
|
||||
|
||||
## 0.1.35
|
||||
|
||||
* A third optional parameter was added to `SourceNode.fromStringWithSourceMap`
|
||||
to specify a path that relative sources in the second parameter should be
|
||||
relative to. Issue #105.
|
||||
|
||||
* If no file property is given to a `SourceMapGenerator`, then the resulting
|
||||
source map will no longer have a `null` file property. The property will
|
||||
simply not exist. Issue #104.
|
||||
|
||||
* Fixed a bug where consecutive newlines were ignored in `SourceNode`s.
|
||||
Issue #116.
|
||||
|
||||
## 0.1.34
|
||||
|
||||
* Make `SourceNode` work with windows style ("\r\n") newlines. Issue #103.
|
||||
|
||||
* Fix bug involving source contents and the
|
||||
`SourceMapGenerator.prototype.applySourceMap`. Issue #100.
|
||||
|
||||
## 0.1.33
|
||||
|
||||
* Fix some edge cases surrounding path joining and URL resolution.
|
||||
|
||||
* Add a third parameter for relative path to
|
||||
`SourceMapGenerator.prototype.applySourceMap`.
|
||||
|
||||
* Fix issues with mappings and EOLs.
|
||||
|
||||
## 0.1.32
|
||||
|
||||
* Fixed a bug where SourceMapConsumer couldn't handle negative relative columns
|
||||
(issue 92).
|
||||
|
||||
* Fixed test runner to actually report number of failed tests as its process
|
||||
exit code.
|
||||
|
||||
* Fixed a typo when reporting bad mappings (issue 87).
|
||||
|
||||
## 0.1.31
|
||||
|
||||
* Delay parsing the mappings in SourceMapConsumer until queried for a source
|
||||
location.
|
||||
|
||||
* Support Sass source maps (which at the time of writing deviate from the spec
|
||||
in small ways) in SourceMapConsumer.
|
||||
|
||||
## 0.1.30
|
||||
|
||||
* Do not join source root with a source, when the source is a data URI.
|
||||
|
||||
* Extend the test runner to allow running single specific test files at a time.
|
||||
|
||||
* Performance improvements in `SourceNode.prototype.walk` and
|
||||
`SourceMapConsumer.prototype.eachMapping`.
|
||||
|
||||
* Source map browser builds will now work inside Workers.
|
||||
|
||||
* Better error messages when attempting to add an invalid mapping to a
|
||||
`SourceMapGenerator`.
|
||||
|
||||
## 0.1.29
|
||||
|
||||
* Allow duplicate entries in the `names` and `sources` arrays of source maps
|
||||
(usually from TypeScript) we are parsing. Fixes github issue 72.
|
||||
|
||||
## 0.1.28
|
||||
|
||||
* Skip duplicate mappings when creating source maps from SourceNode; github
|
||||
issue 75.
|
||||
|
||||
## 0.1.27
|
||||
|
||||
* Don't throw an error when the `file` property is missing in SourceMapConsumer,
|
||||
we don't use it anyway.
|
||||
|
||||
## 0.1.26
|
||||
|
||||
* Fix SourceNode.fromStringWithSourceMap for empty maps. Fixes github issue 70.
|
||||
|
||||
## 0.1.25
|
||||
|
||||
* Make compatible with browserify
|
||||
|
||||
## 0.1.24
|
||||
|
||||
* Fix issue with absolute paths and `file://` URIs. See
|
||||
https://bugzilla.mozilla.org/show_bug.cgi?id=885597
|
||||
|
||||
## 0.1.23
|
||||
|
||||
* Fix issue with absolute paths and sourcesContent, github issue 64.
|
||||
|
||||
## 0.1.22
|
||||
|
||||
* Ignore duplicate mappings in SourceMapGenerator. Fixes github issue 21.
|
||||
|
||||
## 0.1.21
|
||||
|
||||
* Fixed handling of sources that start with a slash so that they are relative to
|
||||
the source root's host.
|
||||
|
||||
## 0.1.20
|
||||
|
||||
* Fixed github issue #43: absolute URLs aren't joined with the source root
|
||||
anymore.
|
||||
|
||||
## 0.1.19
|
||||
|
||||
* Using Travis CI to run tests.
|
||||
|
||||
## 0.1.18
|
||||
|
||||
* Fixed a bug in the handling of sourceRoot.
|
||||
|
||||
## 0.1.17
|
||||
|
||||
* Added SourceNode.fromStringWithSourceMap.
|
||||
|
||||
## 0.1.16
|
||||
|
||||
* Added missing documentation.
|
||||
|
||||
* Fixed the generating of empty mappings in SourceNode.
|
||||
|
||||
## 0.1.15
|
||||
|
||||
* Added SourceMapGenerator.applySourceMap.
|
||||
|
||||
## 0.1.14
|
||||
|
||||
* The sourceRoot is now handled consistently.
|
||||
|
||||
## 0.1.13
|
||||
|
||||
* Added SourceMapGenerator.fromSourceMap.
|
||||
|
||||
## 0.1.12
|
||||
|
||||
* SourceNode now generates empty mappings too.
|
||||
|
||||
## 0.1.11
|
||||
|
||||
* Added name support to SourceNode.
|
||||
|
||||
## 0.1.10
|
||||
|
||||
* Added sourcesContent support to the customer and generator.
|
||||
+28
@@ -0,0 +1,28 @@
|
||||
|
||||
Copyright (c) 2009-2011, Mozilla Foundation and contributors
|
||||
All rights reserved.
|
||||
|
||||
Redistribution and use in source and binary forms, with or without
|
||||
modification, are permitted provided that the following conditions are met:
|
||||
|
||||
* Redistributions of source code must retain the above copyright notice, this
|
||||
list of conditions and the following disclaimer.
|
||||
|
||||
* Redistributions in binary form must reproduce the above copyright notice,
|
||||
this list of conditions and the following disclaimer in the documentation
|
||||
and/or other materials provided with the distribution.
|
||||
|
||||
* Neither the names of the Mozilla Foundation nor the names of project
|
||||
contributors may be used to endorse or promote products derived from this
|
||||
software without specific prior written permission.
|
||||
|
||||
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
|
||||
ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
|
||||
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
|
||||
DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
|
||||
FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
|
||||
DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
|
||||
SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
|
||||
CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
|
||||
OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
|
||||
OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
|
||||
+742
@@ -0,0 +1,742 @@
|
||||
# Source Map
|
||||
|
||||
[](https://travis-ci.org/mozilla/source-map)
|
||||
|
||||
[](https://www.npmjs.com/package/source-map)
|
||||
|
||||
This is a library to generate and consume the source map format
|
||||
[described here][format].
|
||||
|
||||
[format]: https://docs.google.com/document/d/1U1RGAehQwRypUTovF1KRlpiOFze0b-_2gc6fAH0KY0k/edit
|
||||
|
||||
## Use with Node
|
||||
|
||||
$ npm install source-map
|
||||
|
||||
## Use on the Web
|
||||
|
||||
<script src="https://raw.githubusercontent.com/mozilla/source-map/master/dist/source-map.min.js" defer></script>
|
||||
|
||||
--------------------------------------------------------------------------------
|
||||
|
||||
<!-- `npm run toc` to regenerate the Table of Contents -->
|
||||
|
||||
<!-- START doctoc generated TOC please keep comment here to allow auto update -->
|
||||
<!-- DON'T EDIT THIS SECTION, INSTEAD RE-RUN doctoc TO UPDATE -->
|
||||
## Table of Contents
|
||||
|
||||
- [Examples](#examples)
|
||||
- [Consuming a source map](#consuming-a-source-map)
|
||||
- [Generating a source map](#generating-a-source-map)
|
||||
- [With SourceNode (high level API)](#with-sourcenode-high-level-api)
|
||||
- [With SourceMapGenerator (low level API)](#with-sourcemapgenerator-low-level-api)
|
||||
- [API](#api)
|
||||
- [SourceMapConsumer](#sourcemapconsumer)
|
||||
- [new SourceMapConsumer(rawSourceMap)](#new-sourcemapconsumerrawsourcemap)
|
||||
- [SourceMapConsumer.prototype.computeColumnSpans()](#sourcemapconsumerprototypecomputecolumnspans)
|
||||
- [SourceMapConsumer.prototype.originalPositionFor(generatedPosition)](#sourcemapconsumerprototypeoriginalpositionforgeneratedposition)
|
||||
- [SourceMapConsumer.prototype.generatedPositionFor(originalPosition)](#sourcemapconsumerprototypegeneratedpositionfororiginalposition)
|
||||
- [SourceMapConsumer.prototype.allGeneratedPositionsFor(originalPosition)](#sourcemapconsumerprototypeallgeneratedpositionsfororiginalposition)
|
||||
- [SourceMapConsumer.prototype.hasContentsOfAllSources()](#sourcemapconsumerprototypehascontentsofallsources)
|
||||
- [SourceMapConsumer.prototype.sourceContentFor(source[, returnNullOnMissing])](#sourcemapconsumerprototypesourcecontentforsource-returnnullonmissing)
|
||||
- [SourceMapConsumer.prototype.eachMapping(callback, context, order)](#sourcemapconsumerprototypeeachmappingcallback-context-order)
|
||||
- [SourceMapGenerator](#sourcemapgenerator)
|
||||
- [new SourceMapGenerator([startOfSourceMap])](#new-sourcemapgeneratorstartofsourcemap)
|
||||
- [SourceMapGenerator.fromSourceMap(sourceMapConsumer)](#sourcemapgeneratorfromsourcemapsourcemapconsumer)
|
||||
- [SourceMapGenerator.prototype.addMapping(mapping)](#sourcemapgeneratorprototypeaddmappingmapping)
|
||||
- [SourceMapGenerator.prototype.setSourceContent(sourceFile, sourceContent)](#sourcemapgeneratorprototypesetsourcecontentsourcefile-sourcecontent)
|
||||
- [SourceMapGenerator.prototype.applySourceMap(sourceMapConsumer[, sourceFile[, sourceMapPath]])](#sourcemapgeneratorprototypeapplysourcemapsourcemapconsumer-sourcefile-sourcemappath)
|
||||
- [SourceMapGenerator.prototype.toString()](#sourcemapgeneratorprototypetostring)
|
||||
- [SourceNode](#sourcenode)
|
||||
- [new SourceNode([line, column, source[, chunk[, name]]])](#new-sourcenodeline-column-source-chunk-name)
|
||||
- [SourceNode.fromStringWithSourceMap(code, sourceMapConsumer[, relativePath])](#sourcenodefromstringwithsourcemapcode-sourcemapconsumer-relativepath)
|
||||
- [SourceNode.prototype.add(chunk)](#sourcenodeprototypeaddchunk)
|
||||
- [SourceNode.prototype.prepend(chunk)](#sourcenodeprototypeprependchunk)
|
||||
- [SourceNode.prototype.setSourceContent(sourceFile, sourceContent)](#sourcenodeprototypesetsourcecontentsourcefile-sourcecontent)
|
||||
- [SourceNode.prototype.walk(fn)](#sourcenodeprototypewalkfn)
|
||||
- [SourceNode.prototype.walkSourceContents(fn)](#sourcenodeprototypewalksourcecontentsfn)
|
||||
- [SourceNode.prototype.join(sep)](#sourcenodeprototypejoinsep)
|
||||
- [SourceNode.prototype.replaceRight(pattern, replacement)](#sourcenodeprototypereplacerightpattern-replacement)
|
||||
- [SourceNode.prototype.toString()](#sourcenodeprototypetostring)
|
||||
- [SourceNode.prototype.toStringWithSourceMap([startOfSourceMap])](#sourcenodeprototypetostringwithsourcemapstartofsourcemap)
|
||||
|
||||
<!-- END doctoc generated TOC please keep comment here to allow auto update -->
|
||||
|
||||
## Examples
|
||||
|
||||
### Consuming a source map
|
||||
|
||||
```js
|
||||
var rawSourceMap = {
|
||||
version: 3,
|
||||
file: 'min.js',
|
||||
names: ['bar', 'baz', 'n'],
|
||||
sources: ['one.js', 'two.js'],
|
||||
sourceRoot: 'http://example.com/www/js/',
|
||||
mappings: 'CAAC,IAAI,IAAM,SAAUA,GAClB,OAAOC,IAAID;CCDb,IAAI,IAAM,SAAUE,GAClB,OAAOA'
|
||||
};
|
||||
|
||||
var smc = new SourceMapConsumer(rawSourceMap);
|
||||
|
||||
console.log(smc.sources);
|
||||
// [ 'http://example.com/www/js/one.js',
|
||||
// 'http://example.com/www/js/two.js' ]
|
||||
|
||||
console.log(smc.originalPositionFor({
|
||||
line: 2,
|
||||
column: 28
|
||||
}));
|
||||
// { source: 'http://example.com/www/js/two.js',
|
||||
// line: 2,
|
||||
// column: 10,
|
||||
// name: 'n' }
|
||||
|
||||
console.log(smc.generatedPositionFor({
|
||||
source: 'http://example.com/www/js/two.js',
|
||||
line: 2,
|
||||
column: 10
|
||||
}));
|
||||
// { line: 2, column: 28 }
|
||||
|
||||
smc.eachMapping(function (m) {
|
||||
// ...
|
||||
});
|
||||
```
|
||||
|
||||
### Generating a source map
|
||||
|
||||
In depth guide:
|
||||
[**Compiling to JavaScript, and Debugging with Source Maps**](https://hacks.mozilla.org/2013/05/compiling-to-javascript-and-debugging-with-source-maps/)
|
||||
|
||||
#### With SourceNode (high level API)
|
||||
|
||||
```js
|
||||
function compile(ast) {
|
||||
switch (ast.type) {
|
||||
case 'BinaryExpression':
|
||||
return new SourceNode(
|
||||
ast.location.line,
|
||||
ast.location.column,
|
||||
ast.location.source,
|
||||
[compile(ast.left), " + ", compile(ast.right)]
|
||||
);
|
||||
case 'Literal':
|
||||
return new SourceNode(
|
||||
ast.location.line,
|
||||
ast.location.column,
|
||||
ast.location.source,
|
||||
String(ast.value)
|
||||
);
|
||||
// ...
|
||||
default:
|
||||
throw new Error("Bad AST");
|
||||
}
|
||||
}
|
||||
|
||||
var ast = parse("40 + 2", "add.js");
|
||||
console.log(compile(ast).toStringWithSourceMap({
|
||||
file: 'add.js'
|
||||
}));
|
||||
// { code: '40 + 2',
|
||||
// map: [object SourceMapGenerator] }
|
||||
```
|
||||
|
||||
#### With SourceMapGenerator (low level API)
|
||||
|
||||
```js
|
||||
var map = new SourceMapGenerator({
|
||||
file: "source-mapped.js"
|
||||
});
|
||||
|
||||
map.addMapping({
|
||||
generated: {
|
||||
line: 10,
|
||||
column: 35
|
||||
},
|
||||
source: "foo.js",
|
||||
original: {
|
||||
line: 33,
|
||||
column: 2
|
||||
},
|
||||
name: "christopher"
|
||||
});
|
||||
|
||||
console.log(map.toString());
|
||||
// '{"version":3,"file":"source-mapped.js","sources":["foo.js"],"names":["christopher"],"mappings":";;;;;;;;;mCAgCEA"}'
|
||||
```
|
||||
|
||||
## API
|
||||
|
||||
Get a reference to the module:
|
||||
|
||||
```js
|
||||
// Node.js
|
||||
var sourceMap = require('source-map');
|
||||
|
||||
// Browser builds
|
||||
var sourceMap = window.sourceMap;
|
||||
|
||||
// Inside Firefox
|
||||
const sourceMap = require("devtools/toolkit/sourcemap/source-map.js");
|
||||
```
|
||||
|
||||
### SourceMapConsumer
|
||||
|
||||
A SourceMapConsumer instance represents a parsed source map which we can query
|
||||
for information about the original file positions by giving it a file position
|
||||
in the generated source.
|
||||
|
||||
#### new SourceMapConsumer(rawSourceMap)
|
||||
|
||||
The only parameter is the raw source map (either as a string which can be
|
||||
`JSON.parse`'d, or an object). According to the spec, source maps have the
|
||||
following attributes:
|
||||
|
||||
* `version`: Which version of the source map spec this map is following.
|
||||
|
||||
* `sources`: An array of URLs to the original source files.
|
||||
|
||||
* `names`: An array of identifiers which can be referenced by individual
|
||||
mappings.
|
||||
|
||||
* `sourceRoot`: Optional. The URL root from which all sources are relative.
|
||||
|
||||
* `sourcesContent`: Optional. An array of contents of the original source files.
|
||||
|
||||
* `mappings`: A string of base64 VLQs which contain the actual mappings.
|
||||
|
||||
* `file`: Optional. The generated filename this source map is associated with.
|
||||
|
||||
```js
|
||||
var consumer = new sourceMap.SourceMapConsumer(rawSourceMapJsonData);
|
||||
```
|
||||
|
||||
#### SourceMapConsumer.prototype.computeColumnSpans()
|
||||
|
||||
Compute the last column for each generated mapping. The last column is
|
||||
inclusive.
|
||||
|
||||
```js
|
||||
// Before:
|
||||
consumer.allGeneratedPositionsFor({ line: 2, source: "foo.coffee" })
|
||||
// [ { line: 2,
|
||||
// column: 1 },
|
||||
// { line: 2,
|
||||
// column: 10 },
|
||||
// { line: 2,
|
||||
// column: 20 } ]
|
||||
|
||||
consumer.computeColumnSpans();
|
||||
|
||||
// After:
|
||||
consumer.allGeneratedPositionsFor({ line: 2, source: "foo.coffee" })
|
||||
// [ { line: 2,
|
||||
// column: 1,
|
||||
// lastColumn: 9 },
|
||||
// { line: 2,
|
||||
// column: 10,
|
||||
// lastColumn: 19 },
|
||||
// { line: 2,
|
||||
// column: 20,
|
||||
// lastColumn: Infinity } ]
|
||||
|
||||
```
|
||||
|
||||
#### SourceMapConsumer.prototype.originalPositionFor(generatedPosition)
|
||||
|
||||
Returns the original source, line, and column information for the generated
|
||||
source's line and column positions provided. The only argument is an object with
|
||||
the following properties:
|
||||
|
||||
* `line`: The line number in the generated source. Line numbers in
|
||||
this library are 1-based (note that the underlying source map
|
||||
specification uses 0-based line numbers -- this library handles the
|
||||
translation).
|
||||
|
||||
* `column`: The column number in the generated source. Column numbers
|
||||
in this library are 0-based.
|
||||
|
||||
* `bias`: Either `SourceMapConsumer.GREATEST_LOWER_BOUND` or
|
||||
`SourceMapConsumer.LEAST_UPPER_BOUND`. Specifies whether to return the closest
|
||||
element that is smaller than or greater than the one we are searching for,
|
||||
respectively, if the exact element cannot be found. Defaults to
|
||||
`SourceMapConsumer.GREATEST_LOWER_BOUND`.
|
||||
|
||||
and an object is returned with the following properties:
|
||||
|
||||
* `source`: The original source file, or null if this information is not
|
||||
available.
|
||||
|
||||
* `line`: The line number in the original source, or null if this information is
|
||||
not available. The line number is 1-based.
|
||||
|
||||
* `column`: The column number in the original source, or null if this
|
||||
information is not available. The column number is 0-based.
|
||||
|
||||
* `name`: The original identifier, or null if this information is not available.
|
||||
|
||||
```js
|
||||
consumer.originalPositionFor({ line: 2, column: 10 })
|
||||
// { source: 'foo.coffee',
|
||||
// line: 2,
|
||||
// column: 2,
|
||||
// name: null }
|
||||
|
||||
consumer.originalPositionFor({ line: 99999999999999999, column: 999999999999999 })
|
||||
// { source: null,
|
||||
// line: null,
|
||||
// column: null,
|
||||
// name: null }
|
||||
```
|
||||
|
||||
#### SourceMapConsumer.prototype.generatedPositionFor(originalPosition)
|
||||
|
||||
Returns the generated line and column information for the original source,
|
||||
line, and column positions provided. The only argument is an object with
|
||||
the following properties:
|
||||
|
||||
* `source`: The filename of the original source.
|
||||
|
||||
* `line`: The line number in the original source. The line number is
|
||||
1-based.
|
||||
|
||||
* `column`: The column number in the original source. The column
|
||||
number is 0-based.
|
||||
|
||||
and an object is returned with the following properties:
|
||||
|
||||
* `line`: The line number in the generated source, or null. The line
|
||||
number is 1-based.
|
||||
|
||||
* `column`: The column number in the generated source, or null. The
|
||||
column number is 0-based.
|
||||
|
||||
```js
|
||||
consumer.generatedPositionFor({ source: "example.js", line: 2, column: 10 })
|
||||
// { line: 1,
|
||||
// column: 56 }
|
||||
```
|
||||
|
||||
#### SourceMapConsumer.prototype.allGeneratedPositionsFor(originalPosition)
|
||||
|
||||
Returns all generated line and column information for the original source, line,
|
||||
and column provided. If no column is provided, returns all mappings
|
||||
corresponding to a either the line we are searching for or the next closest line
|
||||
that has any mappings. Otherwise, returns all mappings corresponding to the
|
||||
given line and either the column we are searching for or the next closest column
|
||||
that has any offsets.
|
||||
|
||||
The only argument is an object with the following properties:
|
||||
|
||||
* `source`: The filename of the original source.
|
||||
|
||||
* `line`: The line number in the original source. The line number is
|
||||
1-based.
|
||||
|
||||
* `column`: Optional. The column number in the original source. The
|
||||
column number is 0-based.
|
||||
|
||||
and an array of objects is returned, each with the following properties:
|
||||
|
||||
* `line`: The line number in the generated source, or null. The line
|
||||
number is 1-based.
|
||||
|
||||
* `column`: The column number in the generated source, or null. The
|
||||
column number is 0-based.
|
||||
|
||||
```js
|
||||
consumer.allGeneratedpositionsfor({ line: 2, source: "foo.coffee" })
|
||||
// [ { line: 2,
|
||||
// column: 1 },
|
||||
// { line: 2,
|
||||
// column: 10 },
|
||||
// { line: 2,
|
||||
// column: 20 } ]
|
||||
```
|
||||
|
||||
#### SourceMapConsumer.prototype.hasContentsOfAllSources()
|
||||
|
||||
Return true if we have the embedded source content for every source listed in
|
||||
the source map, false otherwise.
|
||||
|
||||
In other words, if this method returns `true`, then
|
||||
`consumer.sourceContentFor(s)` will succeed for every source `s` in
|
||||
`consumer.sources`.
|
||||
|
||||
```js
|
||||
// ...
|
||||
if (consumer.hasContentsOfAllSources()) {
|
||||
consumerReadyCallback(consumer);
|
||||
} else {
|
||||
fetchSources(consumer, consumerReadyCallback);
|
||||
}
|
||||
// ...
|
||||
```
|
||||
|
||||
#### SourceMapConsumer.prototype.sourceContentFor(source[, returnNullOnMissing])
|
||||
|
||||
Returns the original source content for the source provided. The only
|
||||
argument is the URL of the original source file.
|
||||
|
||||
If the source content for the given source is not found, then an error is
|
||||
thrown. Optionally, pass `true` as the second param to have `null` returned
|
||||
instead.
|
||||
|
||||
```js
|
||||
consumer.sources
|
||||
// [ "my-cool-lib.clj" ]
|
||||
|
||||
consumer.sourceContentFor("my-cool-lib.clj")
|
||||
// "..."
|
||||
|
||||
consumer.sourceContentFor("this is not in the source map");
|
||||
// Error: "this is not in the source map" is not in the source map
|
||||
|
||||
consumer.sourceContentFor("this is not in the source map", true);
|
||||
// null
|
||||
```
|
||||
|
||||
#### SourceMapConsumer.prototype.eachMapping(callback, context, order)
|
||||
|
||||
Iterate over each mapping between an original source/line/column and a
|
||||
generated line/column in this source map.
|
||||
|
||||
* `callback`: The function that is called with each mapping. Mappings have the
|
||||
form `{ source, generatedLine, generatedColumn, originalLine, originalColumn,
|
||||
name }`
|
||||
|
||||
* `context`: Optional. If specified, this object will be the value of `this`
|
||||
every time that `callback` is called.
|
||||
|
||||
* `order`: Either `SourceMapConsumer.GENERATED_ORDER` or
|
||||
`SourceMapConsumer.ORIGINAL_ORDER`. Specifies whether you want to iterate over
|
||||
the mappings sorted by the generated file's line/column order or the
|
||||
original's source/line/column order, respectively. Defaults to
|
||||
`SourceMapConsumer.GENERATED_ORDER`.
|
||||
|
||||
```js
|
||||
consumer.eachMapping(function (m) { console.log(m); })
|
||||
// ...
|
||||
// { source: 'illmatic.js',
|
||||
// generatedLine: 1,
|
||||
// generatedColumn: 0,
|
||||
// originalLine: 1,
|
||||
// originalColumn: 0,
|
||||
// name: null }
|
||||
// { source: 'illmatic.js',
|
||||
// generatedLine: 2,
|
||||
// generatedColumn: 0,
|
||||
// originalLine: 2,
|
||||
// originalColumn: 0,
|
||||
// name: null }
|
||||
// ...
|
||||
```
|
||||
### SourceMapGenerator
|
||||
|
||||
An instance of the SourceMapGenerator represents a source map which is being
|
||||
built incrementally.
|
||||
|
||||
#### new SourceMapGenerator([startOfSourceMap])
|
||||
|
||||
You may pass an object with the following properties:
|
||||
|
||||
* `file`: The filename of the generated source that this source map is
|
||||
associated with.
|
||||
|
||||
* `sourceRoot`: A root for all relative URLs in this source map.
|
||||
|
||||
* `skipValidation`: Optional. When `true`, disables validation of mappings as
|
||||
they are added. This can improve performance but should be used with
|
||||
discretion, as a last resort. Even then, one should avoid using this flag when
|
||||
running tests, if possible.
|
||||
|
||||
```js
|
||||
var generator = new sourceMap.SourceMapGenerator({
|
||||
file: "my-generated-javascript-file.js",
|
||||
sourceRoot: "http://example.com/app/js/"
|
||||
});
|
||||
```
|
||||
|
||||
#### SourceMapGenerator.fromSourceMap(sourceMapConsumer)
|
||||
|
||||
Creates a new `SourceMapGenerator` from an existing `SourceMapConsumer` instance.
|
||||
|
||||
* `sourceMapConsumer` The SourceMap.
|
||||
|
||||
```js
|
||||
var generator = sourceMap.SourceMapGenerator.fromSourceMap(consumer);
|
||||
```
|
||||
|
||||
#### SourceMapGenerator.prototype.addMapping(mapping)
|
||||
|
||||
Add a single mapping from original source line and column to the generated
|
||||
source's line and column for this source map being created. The mapping object
|
||||
should have the following properties:
|
||||
|
||||
* `generated`: An object with the generated line and column positions.
|
||||
|
||||
* `original`: An object with the original line and column positions.
|
||||
|
||||
* `source`: The original source file (relative to the sourceRoot).
|
||||
|
||||
* `name`: An optional original token name for this mapping.
|
||||
|
||||
```js
|
||||
generator.addMapping({
|
||||
source: "module-one.scm",
|
||||
original: { line: 128, column: 0 },
|
||||
generated: { line: 3, column: 456 }
|
||||
})
|
||||
```
|
||||
|
||||
#### SourceMapGenerator.prototype.setSourceContent(sourceFile, sourceContent)
|
||||
|
||||
Set the source content for an original source file.
|
||||
|
||||
* `sourceFile` the URL of the original source file.
|
||||
|
||||
* `sourceContent` the content of the source file.
|
||||
|
||||
```js
|
||||
generator.setSourceContent("module-one.scm",
|
||||
fs.readFileSync("path/to/module-one.scm"))
|
||||
```
|
||||
|
||||
#### SourceMapGenerator.prototype.applySourceMap(sourceMapConsumer[, sourceFile[, sourceMapPath]])
|
||||
|
||||
Applies a SourceMap for a source file to the SourceMap.
|
||||
Each mapping to the supplied source file is rewritten using the
|
||||
supplied SourceMap. Note: The resolution for the resulting mappings
|
||||
is the minimum of this map and the supplied map.
|
||||
|
||||
* `sourceMapConsumer`: The SourceMap to be applied.
|
||||
|
||||
* `sourceFile`: Optional. The filename of the source file.
|
||||
If omitted, sourceMapConsumer.file will be used, if it exists.
|
||||
Otherwise an error will be thrown.
|
||||
|
||||
* `sourceMapPath`: Optional. The dirname of the path to the SourceMap
|
||||
to be applied. If relative, it is relative to the SourceMap.
|
||||
|
||||
This parameter is needed when the two SourceMaps aren't in the same
|
||||
directory, and the SourceMap to be applied contains relative source
|
||||
paths. If so, those relative source paths need to be rewritten
|
||||
relative to the SourceMap.
|
||||
|
||||
If omitted, it is assumed that both SourceMaps are in the same directory,
|
||||
thus not needing any rewriting. (Supplying `'.'` has the same effect.)
|
||||
|
||||
#### SourceMapGenerator.prototype.toString()
|
||||
|
||||
Renders the source map being generated to a string.
|
||||
|
||||
```js
|
||||
generator.toString()
|
||||
// '{"version":3,"sources":["module-one.scm"],"names":[],"mappings":"...snip...","file":"my-generated-javascript-file.js","sourceRoot":"http://example.com/app/js/"}'
|
||||
```
|
||||
|
||||
### SourceNode
|
||||
|
||||
SourceNodes provide a way to abstract over interpolating and/or concatenating
|
||||
snippets of generated JavaScript source code, while maintaining the line and
|
||||
column information associated between those snippets and the original source
|
||||
code. This is useful as the final intermediate representation a compiler might
|
||||
use before outputting the generated JS and source map.
|
||||
|
||||
#### new SourceNode([line, column, source[, chunk[, name]]])
|
||||
|
||||
* `line`: The original line number associated with this source node, or null if
|
||||
it isn't associated with an original line. The line number is 1-based.
|
||||
|
||||
* `column`: The original column number associated with this source node, or null
|
||||
if it isn't associated with an original column. The column number
|
||||
is 0-based.
|
||||
|
||||
* `source`: The original source's filename; null if no filename is provided.
|
||||
|
||||
* `chunk`: Optional. Is immediately passed to `SourceNode.prototype.add`, see
|
||||
below.
|
||||
|
||||
* `name`: Optional. The original identifier.
|
||||
|
||||
```js
|
||||
var node = new SourceNode(1, 2, "a.cpp", [
|
||||
new SourceNode(3, 4, "b.cpp", "extern int status;\n"),
|
||||
new SourceNode(5, 6, "c.cpp", "std::string* make_string(size_t n);\n"),
|
||||
new SourceNode(7, 8, "d.cpp", "int main(int argc, char** argv) {}\n"),
|
||||
]);
|
||||
```
|
||||
|
||||
#### SourceNode.fromStringWithSourceMap(code, sourceMapConsumer[, relativePath])
|
||||
|
||||
Creates a SourceNode from generated code and a SourceMapConsumer.
|
||||
|
||||
* `code`: The generated code
|
||||
|
||||
* `sourceMapConsumer` The SourceMap for the generated code
|
||||
|
||||
* `relativePath` The optional path that relative sources in `sourceMapConsumer`
|
||||
should be relative to.
|
||||
|
||||
```js
|
||||
var consumer = new SourceMapConsumer(fs.readFileSync("path/to/my-file.js.map", "utf8"));
|
||||
var node = SourceNode.fromStringWithSourceMap(fs.readFileSync("path/to/my-file.js"),
|
||||
consumer);
|
||||
```
|
||||
|
||||
#### SourceNode.prototype.add(chunk)
|
||||
|
||||
Add a chunk of generated JS to this source node.
|
||||
|
||||
* `chunk`: A string snippet of generated JS code, another instance of
|
||||
`SourceNode`, or an array where each member is one of those things.
|
||||
|
||||
```js
|
||||
node.add(" + ");
|
||||
node.add(otherNode);
|
||||
node.add([leftHandOperandNode, " + ", rightHandOperandNode]);
|
||||
```
|
||||
|
||||
#### SourceNode.prototype.prepend(chunk)
|
||||
|
||||
Prepend a chunk of generated JS to this source node.
|
||||
|
||||
* `chunk`: A string snippet of generated JS code, another instance of
|
||||
`SourceNode`, or an array where each member is one of those things.
|
||||
|
||||
```js
|
||||
node.prepend("/** Build Id: f783haef86324gf **/\n\n");
|
||||
```
|
||||
|
||||
#### SourceNode.prototype.setSourceContent(sourceFile, sourceContent)
|
||||
|
||||
Set the source content for a source file. This will be added to the
|
||||
`SourceMap` in the `sourcesContent` field.
|
||||
|
||||
* `sourceFile`: The filename of the source file
|
||||
|
||||
* `sourceContent`: The content of the source file
|
||||
|
||||
```js
|
||||
node.setSourceContent("module-one.scm",
|
||||
fs.readFileSync("path/to/module-one.scm"))
|
||||
```
|
||||
|
||||
#### SourceNode.prototype.walk(fn)
|
||||
|
||||
Walk over the tree of JS snippets in this node and its children. The walking
|
||||
function is called once for each snippet of JS and is passed that snippet and
|
||||
the its original associated source's line/column location.
|
||||
|
||||
* `fn`: The traversal function.
|
||||
|
||||
```js
|
||||
var node = new SourceNode(1, 2, "a.js", [
|
||||
new SourceNode(3, 4, "b.js", "uno"),
|
||||
"dos",
|
||||
[
|
||||
"tres",
|
||||
new SourceNode(5, 6, "c.js", "quatro")
|
||||
]
|
||||
]);
|
||||
|
||||
node.walk(function (code, loc) { console.log("WALK:", code, loc); })
|
||||
// WALK: uno { source: 'b.js', line: 3, column: 4, name: null }
|
||||
// WALK: dos { source: 'a.js', line: 1, column: 2, name: null }
|
||||
// WALK: tres { source: 'a.js', line: 1, column: 2, name: null }
|
||||
// WALK: quatro { source: 'c.js', line: 5, column: 6, name: null }
|
||||
```
|
||||
|
||||
#### SourceNode.prototype.walkSourceContents(fn)
|
||||
|
||||
Walk over the tree of SourceNodes. The walking function is called for each
|
||||
source file content and is passed the filename and source content.
|
||||
|
||||
* `fn`: The traversal function.
|
||||
|
||||
```js
|
||||
var a = new SourceNode(1, 2, "a.js", "generated from a");
|
||||
a.setSourceContent("a.js", "original a");
|
||||
var b = new SourceNode(1, 2, "b.js", "generated from b");
|
||||
b.setSourceContent("b.js", "original b");
|
||||
var c = new SourceNode(1, 2, "c.js", "generated from c");
|
||||
c.setSourceContent("c.js", "original c");
|
||||
|
||||
var node = new SourceNode(null, null, null, [a, b, c]);
|
||||
node.walkSourceContents(function (source, contents) { console.log("WALK:", source, ":", contents); })
|
||||
// WALK: a.js : original a
|
||||
// WALK: b.js : original b
|
||||
// WALK: c.js : original c
|
||||
```
|
||||
|
||||
#### SourceNode.prototype.join(sep)
|
||||
|
||||
Like `Array.prototype.join` except for SourceNodes. Inserts the separator
|
||||
between each of this source node's children.
|
||||
|
||||
* `sep`: The separator.
|
||||
|
||||
```js
|
||||
var lhs = new SourceNode(1, 2, "a.rs", "my_copy");
|
||||
var operand = new SourceNode(3, 4, "a.rs", "=");
|
||||
var rhs = new SourceNode(5, 6, "a.rs", "orig.clone()");
|
||||
|
||||
var node = new SourceNode(null, null, null, [ lhs, operand, rhs ]);
|
||||
var joinedNode = node.join(" ");
|
||||
```
|
||||
|
||||
#### SourceNode.prototype.replaceRight(pattern, replacement)
|
||||
|
||||
Call `String.prototype.replace` on the very right-most source snippet. Useful
|
||||
for trimming white space from the end of a source node, etc.
|
||||
|
||||
* `pattern`: The pattern to replace.
|
||||
|
||||
* `replacement`: The thing to replace the pattern with.
|
||||
|
||||
```js
|
||||
// Trim trailing white space.
|
||||
node.replaceRight(/\s*$/, "");
|
||||
```
|
||||
|
||||
#### SourceNode.prototype.toString()
|
||||
|
||||
Return the string representation of this source node. Walks over the tree and
|
||||
concatenates all the various snippets together to one string.
|
||||
|
||||
```js
|
||||
var node = new SourceNode(1, 2, "a.js", [
|
||||
new SourceNode(3, 4, "b.js", "uno"),
|
||||
"dos",
|
||||
[
|
||||
"tres",
|
||||
new SourceNode(5, 6, "c.js", "quatro")
|
||||
]
|
||||
]);
|
||||
|
||||
node.toString()
|
||||
// 'unodostresquatro'
|
||||
```
|
||||
|
||||
#### SourceNode.prototype.toStringWithSourceMap([startOfSourceMap])
|
||||
|
||||
Returns the string representation of this tree of source nodes, plus a
|
||||
SourceMapGenerator which contains all the mappings between the generated and
|
||||
original sources.
|
||||
|
||||
The arguments are the same as those to `new SourceMapGenerator`.
|
||||
|
||||
```js
|
||||
var node = new SourceNode(1, 2, "a.js", [
|
||||
new SourceNode(3, 4, "b.js", "uno"),
|
||||
"dos",
|
||||
[
|
||||
"tres",
|
||||
new SourceNode(5, 6, "c.js", "quatro")
|
||||
]
|
||||
]);
|
||||
|
||||
node.toStringWithSourceMap({ file: "my-output-file.js" })
|
||||
// { code: 'unodostresquatro',
|
||||
// map: [object SourceMapGenerator] }
|
||||
```
|
||||
+3234
File diff suppressed because one or more lines are too long
+3233
File diff suppressed because it is too large
Load Diff
+2
File diff suppressed because one or more lines are too long
+1
File diff suppressed because one or more lines are too long
+121
@@ -0,0 +1,121 @@
|
||||
/* -*- Mode: js; js-indent-level: 2; -*- */
|
||||
/*
|
||||
* Copyright 2011 Mozilla Foundation and contributors
|
||||
* Licensed under the New BSD license. See LICENSE or:
|
||||
* http://opensource.org/licenses/BSD-3-Clause
|
||||
*/
|
||||
|
||||
var util = require('./util');
|
||||
var has = Object.prototype.hasOwnProperty;
|
||||
var hasNativeMap = typeof Map !== "undefined";
|
||||
|
||||
/**
|
||||
* A data structure which is a combination of an array and a set. Adding a new
|
||||
* member is O(1), testing for membership is O(1), and finding the index of an
|
||||
* element is O(1). Removing elements from the set is not supported. Only
|
||||
* strings are supported for membership.
|
||||
*/
|
||||
function ArraySet() {
|
||||
this._array = [];
|
||||
this._set = hasNativeMap ? new Map() : Object.create(null);
|
||||
}
|
||||
|
||||
/**
|
||||
* Static method for creating ArraySet instances from an existing array.
|
||||
*/
|
||||
ArraySet.fromArray = function ArraySet_fromArray(aArray, aAllowDuplicates) {
|
||||
var set = new ArraySet();
|
||||
for (var i = 0, len = aArray.length; i < len; i++) {
|
||||
set.add(aArray[i], aAllowDuplicates);
|
||||
}
|
||||
return set;
|
||||
};
|
||||
|
||||
/**
|
||||
* Return how many unique items are in this ArraySet. If duplicates have been
|
||||
* added, than those do not count towards the size.
|
||||
*
|
||||
* @returns Number
|
||||
*/
|
||||
ArraySet.prototype.size = function ArraySet_size() {
|
||||
return hasNativeMap ? this._set.size : Object.getOwnPropertyNames(this._set).length;
|
||||
};
|
||||
|
||||
/**
|
||||
* Add the given string to this set.
|
||||
*
|
||||
* @param String aStr
|
||||
*/
|
||||
ArraySet.prototype.add = function ArraySet_add(aStr, aAllowDuplicates) {
|
||||
var sStr = hasNativeMap ? aStr : util.toSetString(aStr);
|
||||
var isDuplicate = hasNativeMap ? this.has(aStr) : has.call(this._set, sStr);
|
||||
var idx = this._array.length;
|
||||
if (!isDuplicate || aAllowDuplicates) {
|
||||
this._array.push(aStr);
|
||||
}
|
||||
if (!isDuplicate) {
|
||||
if (hasNativeMap) {
|
||||
this._set.set(aStr, idx);
|
||||
} else {
|
||||
this._set[sStr] = idx;
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
/**
|
||||
* Is the given string a member of this set?
|
||||
*
|
||||
* @param String aStr
|
||||
*/
|
||||
ArraySet.prototype.has = function ArraySet_has(aStr) {
|
||||
if (hasNativeMap) {
|
||||
return this._set.has(aStr);
|
||||
} else {
|
||||
var sStr = util.toSetString(aStr);
|
||||
return has.call(this._set, sStr);
|
||||
}
|
||||
};
|
||||
|
||||
/**
|
||||
* What is the index of the given string in the array?
|
||||
*
|
||||
* @param String aStr
|
||||
*/
|
||||
ArraySet.prototype.indexOf = function ArraySet_indexOf(aStr) {
|
||||
if (hasNativeMap) {
|
||||
var idx = this._set.get(aStr);
|
||||
if (idx >= 0) {
|
||||
return idx;
|
||||
}
|
||||
} else {
|
||||
var sStr = util.toSetString(aStr);
|
||||
if (has.call(this._set, sStr)) {
|
||||
return this._set[sStr];
|
||||
}
|
||||
}
|
||||
|
||||
throw new Error('"' + aStr + '" is not in the set.');
|
||||
};
|
||||
|
||||
/**
|
||||
* What is the element at the given index?
|
||||
*
|
||||
* @param Number aIdx
|
||||
*/
|
||||
ArraySet.prototype.at = function ArraySet_at(aIdx) {
|
||||
if (aIdx >= 0 && aIdx < this._array.length) {
|
||||
return this._array[aIdx];
|
||||
}
|
||||
throw new Error('No element indexed by ' + aIdx);
|
||||
};
|
||||
|
||||
/**
|
||||
* Returns the array representation of this set (which has the proper indices
|
||||
* indicated by indexOf). Note that this is a copy of the internal array used
|
||||
* for storing the members so that no one can mess with internal state.
|
||||
*/
|
||||
ArraySet.prototype.toArray = function ArraySet_toArray() {
|
||||
return this._array.slice();
|
||||
};
|
||||
|
||||
exports.ArraySet = ArraySet;
|
||||
+140
@@ -0,0 +1,140 @@
|
||||
/* -*- Mode: js; js-indent-level: 2; -*- */
|
||||
/*
|
||||
* Copyright 2011 Mozilla Foundation and contributors
|
||||
* Licensed under the New BSD license. See LICENSE or:
|
||||
* http://opensource.org/licenses/BSD-3-Clause
|
||||
*
|
||||
* Based on the Base 64 VLQ implementation in Closure Compiler:
|
||||
* https://code.google.com/p/closure-compiler/source/browse/trunk/src/com/google/debugging/sourcemap/Base64VLQ.java
|
||||
*
|
||||
* Copyright 2011 The Closure Compiler Authors. All rights reserved.
|
||||
* Redistribution and use in source and binary forms, with or without
|
||||
* modification, are permitted provided that the following conditions are
|
||||
* met:
|
||||
*
|
||||
* * Redistributions of source code must retain the above copyright
|
||||
* notice, this list of conditions and the following disclaimer.
|
||||
* * Redistributions in binary form must reproduce the above
|
||||
* copyright notice, this list of conditions and the following
|
||||
* disclaimer in the documentation and/or other materials provided
|
||||
* with the distribution.
|
||||
* * Neither the name of Google Inc. nor the names of its
|
||||
* contributors may be used to endorse or promote products derived
|
||||
* from this software without specific prior written permission.
|
||||
*
|
||||
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
|
||||
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
|
||||
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
|
||||
* A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
|
||||
* OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
|
||||
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
|
||||
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
|
||||
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
|
||||
* THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
|
||||
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
|
||||
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
|
||||
*/
|
||||
|
||||
var base64 = require('./base64');
|
||||
|
||||
// A single base 64 digit can contain 6 bits of data. For the base 64 variable
|
||||
// length quantities we use in the source map spec, the first bit is the sign,
|
||||
// the next four bits are the actual value, and the 6th bit is the
|
||||
// continuation bit. The continuation bit tells us whether there are more
|
||||
// digits in this value following this digit.
|
||||
//
|
||||
// Continuation
|
||||
// | Sign
|
||||
// | |
|
||||
// V V
|
||||
// 101011
|
||||
|
||||
var VLQ_BASE_SHIFT = 5;
|
||||
|
||||
// binary: 100000
|
||||
var VLQ_BASE = 1 << VLQ_BASE_SHIFT;
|
||||
|
||||
// binary: 011111
|
||||
var VLQ_BASE_MASK = VLQ_BASE - 1;
|
||||
|
||||
// binary: 100000
|
||||
var VLQ_CONTINUATION_BIT = VLQ_BASE;
|
||||
|
||||
/**
|
||||
* Converts from a two-complement value to a value where the sign bit is
|
||||
* placed in the least significant bit. For example, as decimals:
|
||||
* 1 becomes 2 (10 binary), -1 becomes 3 (11 binary)
|
||||
* 2 becomes 4 (100 binary), -2 becomes 5 (101 binary)
|
||||
*/
|
||||
function toVLQSigned(aValue) {
|
||||
return aValue < 0
|
||||
? ((-aValue) << 1) + 1
|
||||
: (aValue << 1) + 0;
|
||||
}
|
||||
|
||||
/**
|
||||
* Converts to a two-complement value from a value where the sign bit is
|
||||
* placed in the least significant bit. For example, as decimals:
|
||||
* 2 (10 binary) becomes 1, 3 (11 binary) becomes -1
|
||||
* 4 (100 binary) becomes 2, 5 (101 binary) becomes -2
|
||||
*/
|
||||
function fromVLQSigned(aValue) {
|
||||
var isNegative = (aValue & 1) === 1;
|
||||
var shifted = aValue >> 1;
|
||||
return isNegative
|
||||
? -shifted
|
||||
: shifted;
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns the base 64 VLQ encoded value.
|
||||
*/
|
||||
exports.encode = function base64VLQ_encode(aValue) {
|
||||
var encoded = "";
|
||||
var digit;
|
||||
|
||||
var vlq = toVLQSigned(aValue);
|
||||
|
||||
do {
|
||||
digit = vlq & VLQ_BASE_MASK;
|
||||
vlq >>>= VLQ_BASE_SHIFT;
|
||||
if (vlq > 0) {
|
||||
// There are still more digits in this value, so we must make sure the
|
||||
// continuation bit is marked.
|
||||
digit |= VLQ_CONTINUATION_BIT;
|
||||
}
|
||||
encoded += base64.encode(digit);
|
||||
} while (vlq > 0);
|
||||
|
||||
return encoded;
|
||||
};
|
||||
|
||||
/**
|
||||
* Decodes the next base 64 VLQ value from the given string and returns the
|
||||
* value and the rest of the string via the out parameter.
|
||||
*/
|
||||
exports.decode = function base64VLQ_decode(aStr, aIndex, aOutParam) {
|
||||
var strLen = aStr.length;
|
||||
var result = 0;
|
||||
var shift = 0;
|
||||
var continuation, digit;
|
||||
|
||||
do {
|
||||
if (aIndex >= strLen) {
|
||||
throw new Error("Expected more digits in base 64 VLQ value.");
|
||||
}
|
||||
|
||||
digit = base64.decode(aStr.charCodeAt(aIndex++));
|
||||
if (digit === -1) {
|
||||
throw new Error("Invalid base64 digit: " + aStr.charAt(aIndex - 1));
|
||||
}
|
||||
|
||||
continuation = !!(digit & VLQ_CONTINUATION_BIT);
|
||||
digit &= VLQ_BASE_MASK;
|
||||
result = result + (digit << shift);
|
||||
shift += VLQ_BASE_SHIFT;
|
||||
} while (continuation);
|
||||
|
||||
aOutParam.value = fromVLQSigned(result);
|
||||
aOutParam.rest = aIndex;
|
||||
};
|
||||
+67
@@ -0,0 +1,67 @@
|
||||
/* -*- Mode: js; js-indent-level: 2; -*- */
|
||||
/*
|
||||
* Copyright 2011 Mozilla Foundation and contributors
|
||||
* Licensed under the New BSD license. See LICENSE or:
|
||||
* http://opensource.org/licenses/BSD-3-Clause
|
||||
*/
|
||||
|
||||
var intToCharMap = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/'.split('');
|
||||
|
||||
/**
|
||||
* Encode an integer in the range of 0 to 63 to a single base 64 digit.
|
||||
*/
|
||||
exports.encode = function (number) {
|
||||
if (0 <= number && number < intToCharMap.length) {
|
||||
return intToCharMap[number];
|
||||
}
|
||||
throw new TypeError("Must be between 0 and 63: " + number);
|
||||
};
|
||||
|
||||
/**
|
||||
* Decode a single base 64 character code digit to an integer. Returns -1 on
|
||||
* failure.
|
||||
*/
|
||||
exports.decode = function (charCode) {
|
||||
var bigA = 65; // 'A'
|
||||
var bigZ = 90; // 'Z'
|
||||
|
||||
var littleA = 97; // 'a'
|
||||
var littleZ = 122; // 'z'
|
||||
|
||||
var zero = 48; // '0'
|
||||
var nine = 57; // '9'
|
||||
|
||||
var plus = 43; // '+'
|
||||
var slash = 47; // '/'
|
||||
|
||||
var littleOffset = 26;
|
||||
var numberOffset = 52;
|
||||
|
||||
// 0 - 25: ABCDEFGHIJKLMNOPQRSTUVWXYZ
|
||||
if (bigA <= charCode && charCode <= bigZ) {
|
||||
return (charCode - bigA);
|
||||
}
|
||||
|
||||
// 26 - 51: abcdefghijklmnopqrstuvwxyz
|
||||
if (littleA <= charCode && charCode <= littleZ) {
|
||||
return (charCode - littleA + littleOffset);
|
||||
}
|
||||
|
||||
// 52 - 61: 0123456789
|
||||
if (zero <= charCode && charCode <= nine) {
|
||||
return (charCode - zero + numberOffset);
|
||||
}
|
||||
|
||||
// 62: +
|
||||
if (charCode == plus) {
|
||||
return 62;
|
||||
}
|
||||
|
||||
// 63: /
|
||||
if (charCode == slash) {
|
||||
return 63;
|
||||
}
|
||||
|
||||
// Invalid base64 digit.
|
||||
return -1;
|
||||
};
|
||||
+111
@@ -0,0 +1,111 @@
|
||||
/* -*- Mode: js; js-indent-level: 2; -*- */
|
||||
/*
|
||||
* Copyright 2011 Mozilla Foundation and contributors
|
||||
* Licensed under the New BSD license. See LICENSE or:
|
||||
* http://opensource.org/licenses/BSD-3-Clause
|
||||
*/
|
||||
|
||||
exports.GREATEST_LOWER_BOUND = 1;
|
||||
exports.LEAST_UPPER_BOUND = 2;
|
||||
|
||||
/**
|
||||
* Recursive implementation of binary search.
|
||||
*
|
||||
* @param aLow Indices here and lower do not contain the needle.
|
||||
* @param aHigh Indices here and higher do not contain the needle.
|
||||
* @param aNeedle The element being searched for.
|
||||
* @param aHaystack The non-empty array being searched.
|
||||
* @param aCompare Function which takes two elements and returns -1, 0, or 1.
|
||||
* @param aBias Either 'binarySearch.GREATEST_LOWER_BOUND' or
|
||||
* 'binarySearch.LEAST_UPPER_BOUND'. Specifies whether to return the
|
||||
* closest element that is smaller than or greater than the one we are
|
||||
* searching for, respectively, if the exact element cannot be found.
|
||||
*/
|
||||
function recursiveSearch(aLow, aHigh, aNeedle, aHaystack, aCompare, aBias) {
|
||||
// This function terminates when one of the following is true:
|
||||
//
|
||||
// 1. We find the exact element we are looking for.
|
||||
//
|
||||
// 2. We did not find the exact element, but we can return the index of
|
||||
// the next-closest element.
|
||||
//
|
||||
// 3. We did not find the exact element, and there is no next-closest
|
||||
// element than the one we are searching for, so we return -1.
|
||||
var mid = Math.floor((aHigh - aLow) / 2) + aLow;
|
||||
var cmp = aCompare(aNeedle, aHaystack[mid], true);
|
||||
if (cmp === 0) {
|
||||
// Found the element we are looking for.
|
||||
return mid;
|
||||
}
|
||||
else if (cmp > 0) {
|
||||
// Our needle is greater than aHaystack[mid].
|
||||
if (aHigh - mid > 1) {
|
||||
// The element is in the upper half.
|
||||
return recursiveSearch(mid, aHigh, aNeedle, aHaystack, aCompare, aBias);
|
||||
}
|
||||
|
||||
// The exact needle element was not found in this haystack. Determine if
|
||||
// we are in termination case (3) or (2) and return the appropriate thing.
|
||||
if (aBias == exports.LEAST_UPPER_BOUND) {
|
||||
return aHigh < aHaystack.length ? aHigh : -1;
|
||||
} else {
|
||||
return mid;
|
||||
}
|
||||
}
|
||||
else {
|
||||
// Our needle is less than aHaystack[mid].
|
||||
if (mid - aLow > 1) {
|
||||
// The element is in the lower half.
|
||||
return recursiveSearch(aLow, mid, aNeedle, aHaystack, aCompare, aBias);
|
||||
}
|
||||
|
||||
// we are in termination case (3) or (2) and return the appropriate thing.
|
||||
if (aBias == exports.LEAST_UPPER_BOUND) {
|
||||
return mid;
|
||||
} else {
|
||||
return aLow < 0 ? -1 : aLow;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* This is an implementation of binary search which will always try and return
|
||||
* the index of the closest element if there is no exact hit. This is because
|
||||
* mappings between original and generated line/col pairs are single points,
|
||||
* and there is an implicit region between each of them, so a miss just means
|
||||
* that you aren't on the very start of a region.
|
||||
*
|
||||
* @param aNeedle The element you are looking for.
|
||||
* @param aHaystack The array that is being searched.
|
||||
* @param aCompare A function which takes the needle and an element in the
|
||||
* array and returns -1, 0, or 1 depending on whether the needle is less
|
||||
* than, equal to, or greater than the element, respectively.
|
||||
* @param aBias Either 'binarySearch.GREATEST_LOWER_BOUND' or
|
||||
* 'binarySearch.LEAST_UPPER_BOUND'. Specifies whether to return the
|
||||
* closest element that is smaller than or greater than the one we are
|
||||
* searching for, respectively, if the exact element cannot be found.
|
||||
* Defaults to 'binarySearch.GREATEST_LOWER_BOUND'.
|
||||
*/
|
||||
exports.search = function search(aNeedle, aHaystack, aCompare, aBias) {
|
||||
if (aHaystack.length === 0) {
|
||||
return -1;
|
||||
}
|
||||
|
||||
var index = recursiveSearch(-1, aHaystack.length, aNeedle, aHaystack,
|
||||
aCompare, aBias || exports.GREATEST_LOWER_BOUND);
|
||||
if (index < 0) {
|
||||
return -1;
|
||||
}
|
||||
|
||||
// We have found either the exact element, or the next-closest element than
|
||||
// the one we are searching for. However, there may be more than one such
|
||||
// element. Make sure we always return the smallest of these.
|
||||
while (index - 1 >= 0) {
|
||||
if (aCompare(aHaystack[index], aHaystack[index - 1], true) !== 0) {
|
||||
break;
|
||||
}
|
||||
--index;
|
||||
}
|
||||
|
||||
return index;
|
||||
};
|
||||
+79
@@ -0,0 +1,79 @@
|
||||
/* -*- Mode: js; js-indent-level: 2; -*- */
|
||||
/*
|
||||
* Copyright 2014 Mozilla Foundation and contributors
|
||||
* Licensed under the New BSD license. See LICENSE or:
|
||||
* http://opensource.org/licenses/BSD-3-Clause
|
||||
*/
|
||||
|
||||
var util = require('./util');
|
||||
|
||||
/**
|
||||
* Determine whether mappingB is after mappingA with respect to generated
|
||||
* position.
|
||||
*/
|
||||
function generatedPositionAfter(mappingA, mappingB) {
|
||||
// Optimized for most common case
|
||||
var lineA = mappingA.generatedLine;
|
||||
var lineB = mappingB.generatedLine;
|
||||
var columnA = mappingA.generatedColumn;
|
||||
var columnB = mappingB.generatedColumn;
|
||||
return lineB > lineA || lineB == lineA && columnB >= columnA ||
|
||||
util.compareByGeneratedPositionsInflated(mappingA, mappingB) <= 0;
|
||||
}
|
||||
|
||||
/**
|
||||
* A data structure to provide a sorted view of accumulated mappings in a
|
||||
* performance conscious manner. It trades a neglibable overhead in general
|
||||
* case for a large speedup in case of mappings being added in order.
|
||||
*/
|
||||
function MappingList() {
|
||||
this._array = [];
|
||||
this._sorted = true;
|
||||
// Serves as infimum
|
||||
this._last = {generatedLine: -1, generatedColumn: 0};
|
||||
}
|
||||
|
||||
/**
|
||||
* Iterate through internal items. This method takes the same arguments that
|
||||
* `Array.prototype.forEach` takes.
|
||||
*
|
||||
* NOTE: The order of the mappings is NOT guaranteed.
|
||||
*/
|
||||
MappingList.prototype.unsortedForEach =
|
||||
function MappingList_forEach(aCallback, aThisArg) {
|
||||
this._array.forEach(aCallback, aThisArg);
|
||||
};
|
||||
|
||||
/**
|
||||
* Add the given source mapping.
|
||||
*
|
||||
* @param Object aMapping
|
||||
*/
|
||||
MappingList.prototype.add = function MappingList_add(aMapping) {
|
||||
if (generatedPositionAfter(this._last, aMapping)) {
|
||||
this._last = aMapping;
|
||||
this._array.push(aMapping);
|
||||
} else {
|
||||
this._sorted = false;
|
||||
this._array.push(aMapping);
|
||||
}
|
||||
};
|
||||
|
||||
/**
|
||||
* Returns the flat, sorted array of mappings. The mappings are sorted by
|
||||
* generated position.
|
||||
*
|
||||
* WARNING: This method returns internal data without copying, for
|
||||
* performance. The return value must NOT be mutated, and should be treated as
|
||||
* an immutable borrow. If you want to take ownership, you must make your own
|
||||
* copy.
|
||||
*/
|
||||
MappingList.prototype.toArray = function MappingList_toArray() {
|
||||
if (!this._sorted) {
|
||||
this._array.sort(util.compareByGeneratedPositionsInflated);
|
||||
this._sorted = true;
|
||||
}
|
||||
return this._array;
|
||||
};
|
||||
|
||||
exports.MappingList = MappingList;
|
||||
+114
@@ -0,0 +1,114 @@
|
||||
/* -*- Mode: js; js-indent-level: 2; -*- */
|
||||
/*
|
||||
* Copyright 2011 Mozilla Foundation and contributors
|
||||
* Licensed under the New BSD license. See LICENSE or:
|
||||
* http://opensource.org/licenses/BSD-3-Clause
|
||||
*/
|
||||
|
||||
// It turns out that some (most?) JavaScript engines don't self-host
|
||||
// `Array.prototype.sort`. This makes sense because C++ will likely remain
|
||||
// faster than JS when doing raw CPU-intensive sorting. However, when using a
|
||||
// custom comparator function, calling back and forth between the VM's C++ and
|
||||
// JIT'd JS is rather slow *and* loses JIT type information, resulting in
|
||||
// worse generated code for the comparator function than would be optimal. In
|
||||
// fact, when sorting with a comparator, these costs outweigh the benefits of
|
||||
// sorting in C++. By using our own JS-implemented Quick Sort (below), we get
|
||||
// a ~3500ms mean speed-up in `bench/bench.html`.
|
||||
|
||||
/**
|
||||
* Swap the elements indexed by `x` and `y` in the array `ary`.
|
||||
*
|
||||
* @param {Array} ary
|
||||
* The array.
|
||||
* @param {Number} x
|
||||
* The index of the first item.
|
||||
* @param {Number} y
|
||||
* The index of the second item.
|
||||
*/
|
||||
function swap(ary, x, y) {
|
||||
var temp = ary[x];
|
||||
ary[x] = ary[y];
|
||||
ary[y] = temp;
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns a random integer within the range `low .. high` inclusive.
|
||||
*
|
||||
* @param {Number} low
|
||||
* The lower bound on the range.
|
||||
* @param {Number} high
|
||||
* The upper bound on the range.
|
||||
*/
|
||||
function randomIntInRange(low, high) {
|
||||
return Math.round(low + (Math.random() * (high - low)));
|
||||
}
|
||||
|
||||
/**
|
||||
* The Quick Sort algorithm.
|
||||
*
|
||||
* @param {Array} ary
|
||||
* An array to sort.
|
||||
* @param {function} comparator
|
||||
* Function to use to compare two items.
|
||||
* @param {Number} p
|
||||
* Start index of the array
|
||||
* @param {Number} r
|
||||
* End index of the array
|
||||
*/
|
||||
function doQuickSort(ary, comparator, p, r) {
|
||||
// If our lower bound is less than our upper bound, we (1) partition the
|
||||
// array into two pieces and (2) recurse on each half. If it is not, this is
|
||||
// the empty array and our base case.
|
||||
|
||||
if (p < r) {
|
||||
// (1) Partitioning.
|
||||
//
|
||||
// The partitioning chooses a pivot between `p` and `r` and moves all
|
||||
// elements that are less than or equal to the pivot to the before it, and
|
||||
// all the elements that are greater than it after it. The effect is that
|
||||
// once partition is done, the pivot is in the exact place it will be when
|
||||
// the array is put in sorted order, and it will not need to be moved
|
||||
// again. This runs in O(n) time.
|
||||
|
||||
// Always choose a random pivot so that an input array which is reverse
|
||||
// sorted does not cause O(n^2) running time.
|
||||
var pivotIndex = randomIntInRange(p, r);
|
||||
var i = p - 1;
|
||||
|
||||
swap(ary, pivotIndex, r);
|
||||
var pivot = ary[r];
|
||||
|
||||
// Immediately after `j` is incremented in this loop, the following hold
|
||||
// true:
|
||||
//
|
||||
// * Every element in `ary[p .. i]` is less than or equal to the pivot.
|
||||
//
|
||||
// * Every element in `ary[i+1 .. j-1]` is greater than the pivot.
|
||||
for (var j = p; j < r; j++) {
|
||||
if (comparator(ary[j], pivot) <= 0) {
|
||||
i += 1;
|
||||
swap(ary, i, j);
|
||||
}
|
||||
}
|
||||
|
||||
swap(ary, i + 1, j);
|
||||
var q = i + 1;
|
||||
|
||||
// (2) Recurse on each half.
|
||||
|
||||
doQuickSort(ary, comparator, p, q - 1);
|
||||
doQuickSort(ary, comparator, q + 1, r);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Sort the given array in-place with the given comparator function.
|
||||
*
|
||||
* @param {Array} ary
|
||||
* An array to sort.
|
||||
* @param {function} comparator
|
||||
* Function to use to compare two items.
|
||||
*/
|
||||
exports.quickSort = function (ary, comparator) {
|
||||
doQuickSort(ary, comparator, 0, ary.length - 1);
|
||||
};
|
||||
+1145
File diff suppressed because it is too large
Load Diff
+425
@@ -0,0 +1,425 @@
|
||||
/* -*- Mode: js; js-indent-level: 2; -*- */
|
||||
/*
|
||||
* Copyright 2011 Mozilla Foundation and contributors
|
||||
* Licensed under the New BSD license. See LICENSE or:
|
||||
* http://opensource.org/licenses/BSD-3-Clause
|
||||
*/
|
||||
|
||||
var base64VLQ = require('./base64-vlq');
|
||||
var util = require('./util');
|
||||
var ArraySet = require('./array-set').ArraySet;
|
||||
var MappingList = require('./mapping-list').MappingList;
|
||||
|
||||
/**
|
||||
* An instance of the SourceMapGenerator represents a source map which is
|
||||
* being built incrementally. You may pass an object with the following
|
||||
* properties:
|
||||
*
|
||||
* - file: The filename of the generated source.
|
||||
* - sourceRoot: A root for all relative URLs in this source map.
|
||||
*/
|
||||
function SourceMapGenerator(aArgs) {
|
||||
if (!aArgs) {
|
||||
aArgs = {};
|
||||
}
|
||||
this._file = util.getArg(aArgs, 'file', null);
|
||||
this._sourceRoot = util.getArg(aArgs, 'sourceRoot', null);
|
||||
this._skipValidation = util.getArg(aArgs, 'skipValidation', false);
|
||||
this._sources = new ArraySet();
|
||||
this._names = new ArraySet();
|
||||
this._mappings = new MappingList();
|
||||
this._sourcesContents = null;
|
||||
}
|
||||
|
||||
SourceMapGenerator.prototype._version = 3;
|
||||
|
||||
/**
|
||||
* Creates a new SourceMapGenerator based on a SourceMapConsumer
|
||||
*
|
||||
* @param aSourceMapConsumer The SourceMap.
|
||||
*/
|
||||
SourceMapGenerator.fromSourceMap =
|
||||
function SourceMapGenerator_fromSourceMap(aSourceMapConsumer) {
|
||||
var sourceRoot = aSourceMapConsumer.sourceRoot;
|
||||
var generator = new SourceMapGenerator({
|
||||
file: aSourceMapConsumer.file,
|
||||
sourceRoot: sourceRoot
|
||||
});
|
||||
aSourceMapConsumer.eachMapping(function (mapping) {
|
||||
var newMapping = {
|
||||
generated: {
|
||||
line: mapping.generatedLine,
|
||||
column: mapping.generatedColumn
|
||||
}
|
||||
};
|
||||
|
||||
if (mapping.source != null) {
|
||||
newMapping.source = mapping.source;
|
||||
if (sourceRoot != null) {
|
||||
newMapping.source = util.relative(sourceRoot, newMapping.source);
|
||||
}
|
||||
|
||||
newMapping.original = {
|
||||
line: mapping.originalLine,
|
||||
column: mapping.originalColumn
|
||||
};
|
||||
|
||||
if (mapping.name != null) {
|
||||
newMapping.name = mapping.name;
|
||||
}
|
||||
}
|
||||
|
||||
generator.addMapping(newMapping);
|
||||
});
|
||||
aSourceMapConsumer.sources.forEach(function (sourceFile) {
|
||||
var sourceRelative = sourceFile;
|
||||
if (sourceRoot !== null) {
|
||||
sourceRelative = util.relative(sourceRoot, sourceFile);
|
||||
}
|
||||
|
||||
if (!generator._sources.has(sourceRelative)) {
|
||||
generator._sources.add(sourceRelative);
|
||||
}
|
||||
|
||||
var content = aSourceMapConsumer.sourceContentFor(sourceFile);
|
||||
if (content != null) {
|
||||
generator.setSourceContent(sourceFile, content);
|
||||
}
|
||||
});
|
||||
return generator;
|
||||
};
|
||||
|
||||
/**
|
||||
* Add a single mapping from original source line and column to the generated
|
||||
* source's line and column for this source map being created. The mapping
|
||||
* object should have the following properties:
|
||||
*
|
||||
* - generated: An object with the generated line and column positions.
|
||||
* - original: An object with the original line and column positions.
|
||||
* - source: The original source file (relative to the sourceRoot).
|
||||
* - name: An optional original token name for this mapping.
|
||||
*/
|
||||
SourceMapGenerator.prototype.addMapping =
|
||||
function SourceMapGenerator_addMapping(aArgs) {
|
||||
var generated = util.getArg(aArgs, 'generated');
|
||||
var original = util.getArg(aArgs, 'original', null);
|
||||
var source = util.getArg(aArgs, 'source', null);
|
||||
var name = util.getArg(aArgs, 'name', null);
|
||||
|
||||
if (!this._skipValidation) {
|
||||
this._validateMapping(generated, original, source, name);
|
||||
}
|
||||
|
||||
if (source != null) {
|
||||
source = String(source);
|
||||
if (!this._sources.has(source)) {
|
||||
this._sources.add(source);
|
||||
}
|
||||
}
|
||||
|
||||
if (name != null) {
|
||||
name = String(name);
|
||||
if (!this._names.has(name)) {
|
||||
this._names.add(name);
|
||||
}
|
||||
}
|
||||
|
||||
this._mappings.add({
|
||||
generatedLine: generated.line,
|
||||
generatedColumn: generated.column,
|
||||
originalLine: original != null && original.line,
|
||||
originalColumn: original != null && original.column,
|
||||
source: source,
|
||||
name: name
|
||||
});
|
||||
};
|
||||
|
||||
/**
|
||||
* Set the source content for a source file.
|
||||
*/
|
||||
SourceMapGenerator.prototype.setSourceContent =
|
||||
function SourceMapGenerator_setSourceContent(aSourceFile, aSourceContent) {
|
||||
var source = aSourceFile;
|
||||
if (this._sourceRoot != null) {
|
||||
source = util.relative(this._sourceRoot, source);
|
||||
}
|
||||
|
||||
if (aSourceContent != null) {
|
||||
// Add the source content to the _sourcesContents map.
|
||||
// Create a new _sourcesContents map if the property is null.
|
||||
if (!this._sourcesContents) {
|
||||
this._sourcesContents = Object.create(null);
|
||||
}
|
||||
this._sourcesContents[util.toSetString(source)] = aSourceContent;
|
||||
} else if (this._sourcesContents) {
|
||||
// Remove the source file from the _sourcesContents map.
|
||||
// If the _sourcesContents map is empty, set the property to null.
|
||||
delete this._sourcesContents[util.toSetString(source)];
|
||||
if (Object.keys(this._sourcesContents).length === 0) {
|
||||
this._sourcesContents = null;
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
/**
|
||||
* Applies the mappings of a sub-source-map for a specific source file to the
|
||||
* source map being generated. Each mapping to the supplied source file is
|
||||
* rewritten using the supplied source map. Note: The resolution for the
|
||||
* resulting mappings is the minimium of this map and the supplied map.
|
||||
*
|
||||
* @param aSourceMapConsumer The source map to be applied.
|
||||
* @param aSourceFile Optional. The filename of the source file.
|
||||
* If omitted, SourceMapConsumer's file property will be used.
|
||||
* @param aSourceMapPath Optional. The dirname of the path to the source map
|
||||
* to be applied. If relative, it is relative to the SourceMapConsumer.
|
||||
* This parameter is needed when the two source maps aren't in the same
|
||||
* directory, and the source map to be applied contains relative source
|
||||
* paths. If so, those relative source paths need to be rewritten
|
||||
* relative to the SourceMapGenerator.
|
||||
*/
|
||||
SourceMapGenerator.prototype.applySourceMap =
|
||||
function SourceMapGenerator_applySourceMap(aSourceMapConsumer, aSourceFile, aSourceMapPath) {
|
||||
var sourceFile = aSourceFile;
|
||||
// If aSourceFile is omitted, we will use the file property of the SourceMap
|
||||
if (aSourceFile == null) {
|
||||
if (aSourceMapConsumer.file == null) {
|
||||
throw new Error(
|
||||
'SourceMapGenerator.prototype.applySourceMap requires either an explicit source file, ' +
|
||||
'or the source map\'s "file" property. Both were omitted.'
|
||||
);
|
||||
}
|
||||
sourceFile = aSourceMapConsumer.file;
|
||||
}
|
||||
var sourceRoot = this._sourceRoot;
|
||||
// Make "sourceFile" relative if an absolute Url is passed.
|
||||
if (sourceRoot != null) {
|
||||
sourceFile = util.relative(sourceRoot, sourceFile);
|
||||
}
|
||||
// Applying the SourceMap can add and remove items from the sources and
|
||||
// the names array.
|
||||
var newSources = new ArraySet();
|
||||
var newNames = new ArraySet();
|
||||
|
||||
// Find mappings for the "sourceFile"
|
||||
this._mappings.unsortedForEach(function (mapping) {
|
||||
if (mapping.source === sourceFile && mapping.originalLine != null) {
|
||||
// Check if it can be mapped by the source map, then update the mapping.
|
||||
var original = aSourceMapConsumer.originalPositionFor({
|
||||
line: mapping.originalLine,
|
||||
column: mapping.originalColumn
|
||||
});
|
||||
if (original.source != null) {
|
||||
// Copy mapping
|
||||
mapping.source = original.source;
|
||||
if (aSourceMapPath != null) {
|
||||
mapping.source = util.join(aSourceMapPath, mapping.source)
|
||||
}
|
||||
if (sourceRoot != null) {
|
||||
mapping.source = util.relative(sourceRoot, mapping.source);
|
||||
}
|
||||
mapping.originalLine = original.line;
|
||||
mapping.originalColumn = original.column;
|
||||
if (original.name != null) {
|
||||
mapping.name = original.name;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
var source = mapping.source;
|
||||
if (source != null && !newSources.has(source)) {
|
||||
newSources.add(source);
|
||||
}
|
||||
|
||||
var name = mapping.name;
|
||||
if (name != null && !newNames.has(name)) {
|
||||
newNames.add(name);
|
||||
}
|
||||
|
||||
}, this);
|
||||
this._sources = newSources;
|
||||
this._names = newNames;
|
||||
|
||||
// Copy sourcesContents of applied map.
|
||||
aSourceMapConsumer.sources.forEach(function (sourceFile) {
|
||||
var content = aSourceMapConsumer.sourceContentFor(sourceFile);
|
||||
if (content != null) {
|
||||
if (aSourceMapPath != null) {
|
||||
sourceFile = util.join(aSourceMapPath, sourceFile);
|
||||
}
|
||||
if (sourceRoot != null) {
|
||||
sourceFile = util.relative(sourceRoot, sourceFile);
|
||||
}
|
||||
this.setSourceContent(sourceFile, content);
|
||||
}
|
||||
}, this);
|
||||
};
|
||||
|
||||
/**
|
||||
* A mapping can have one of the three levels of data:
|
||||
*
|
||||
* 1. Just the generated position.
|
||||
* 2. The Generated position, original position, and original source.
|
||||
* 3. Generated and original position, original source, as well as a name
|
||||
* token.
|
||||
*
|
||||
* To maintain consistency, we validate that any new mapping being added falls
|
||||
* in to one of these categories.
|
||||
*/
|
||||
SourceMapGenerator.prototype._validateMapping =
|
||||
function SourceMapGenerator_validateMapping(aGenerated, aOriginal, aSource,
|
||||
aName) {
|
||||
// When aOriginal is truthy but has empty values for .line and .column,
|
||||
// it is most likely a programmer error. In this case we throw a very
|
||||
// specific error message to try to guide them the right way.
|
||||
// For example: https://github.com/Polymer/polymer-bundler/pull/519
|
||||
if (aOriginal && typeof aOriginal.line !== 'number' && typeof aOriginal.column !== 'number') {
|
||||
throw new Error(
|
||||
'original.line and original.column are not numbers -- you probably meant to omit ' +
|
||||
'the original mapping entirely and only map the generated position. If so, pass ' +
|
||||
'null for the original mapping instead of an object with empty or null values.'
|
||||
);
|
||||
}
|
||||
|
||||
if (aGenerated && 'line' in aGenerated && 'column' in aGenerated
|
||||
&& aGenerated.line > 0 && aGenerated.column >= 0
|
||||
&& !aOriginal && !aSource && !aName) {
|
||||
// Case 1.
|
||||
return;
|
||||
}
|
||||
else if (aGenerated && 'line' in aGenerated && 'column' in aGenerated
|
||||
&& aOriginal && 'line' in aOriginal && 'column' in aOriginal
|
||||
&& aGenerated.line > 0 && aGenerated.column >= 0
|
||||
&& aOriginal.line > 0 && aOriginal.column >= 0
|
||||
&& aSource) {
|
||||
// Cases 2 and 3.
|
||||
return;
|
||||
}
|
||||
else {
|
||||
throw new Error('Invalid mapping: ' + JSON.stringify({
|
||||
generated: aGenerated,
|
||||
source: aSource,
|
||||
original: aOriginal,
|
||||
name: aName
|
||||
}));
|
||||
}
|
||||
};
|
||||
|
||||
/**
|
||||
* Serialize the accumulated mappings in to the stream of base 64 VLQs
|
||||
* specified by the source map format.
|
||||
*/
|
||||
SourceMapGenerator.prototype._serializeMappings =
|
||||
function SourceMapGenerator_serializeMappings() {
|
||||
var previousGeneratedColumn = 0;
|
||||
var previousGeneratedLine = 1;
|
||||
var previousOriginalColumn = 0;
|
||||
var previousOriginalLine = 0;
|
||||
var previousName = 0;
|
||||
var previousSource = 0;
|
||||
var result = '';
|
||||
var next;
|
||||
var mapping;
|
||||
var nameIdx;
|
||||
var sourceIdx;
|
||||
|
||||
var mappings = this._mappings.toArray();
|
||||
for (var i = 0, len = mappings.length; i < len; i++) {
|
||||
mapping = mappings[i];
|
||||
next = ''
|
||||
|
||||
if (mapping.generatedLine !== previousGeneratedLine) {
|
||||
previousGeneratedColumn = 0;
|
||||
while (mapping.generatedLine !== previousGeneratedLine) {
|
||||
next += ';';
|
||||
previousGeneratedLine++;
|
||||
}
|
||||
}
|
||||
else {
|
||||
if (i > 0) {
|
||||
if (!util.compareByGeneratedPositionsInflated(mapping, mappings[i - 1])) {
|
||||
continue;
|
||||
}
|
||||
next += ',';
|
||||
}
|
||||
}
|
||||
|
||||
next += base64VLQ.encode(mapping.generatedColumn
|
||||
- previousGeneratedColumn);
|
||||
previousGeneratedColumn = mapping.generatedColumn;
|
||||
|
||||
if (mapping.source != null) {
|
||||
sourceIdx = this._sources.indexOf(mapping.source);
|
||||
next += base64VLQ.encode(sourceIdx - previousSource);
|
||||
previousSource = sourceIdx;
|
||||
|
||||
// lines are stored 0-based in SourceMap spec version 3
|
||||
next += base64VLQ.encode(mapping.originalLine - 1
|
||||
- previousOriginalLine);
|
||||
previousOriginalLine = mapping.originalLine - 1;
|
||||
|
||||
next += base64VLQ.encode(mapping.originalColumn
|
||||
- previousOriginalColumn);
|
||||
previousOriginalColumn = mapping.originalColumn;
|
||||
|
||||
if (mapping.name != null) {
|
||||
nameIdx = this._names.indexOf(mapping.name);
|
||||
next += base64VLQ.encode(nameIdx - previousName);
|
||||
previousName = nameIdx;
|
||||
}
|
||||
}
|
||||
|
||||
result += next;
|
||||
}
|
||||
|
||||
return result;
|
||||
};
|
||||
|
||||
SourceMapGenerator.prototype._generateSourcesContent =
|
||||
function SourceMapGenerator_generateSourcesContent(aSources, aSourceRoot) {
|
||||
return aSources.map(function (source) {
|
||||
if (!this._sourcesContents) {
|
||||
return null;
|
||||
}
|
||||
if (aSourceRoot != null) {
|
||||
source = util.relative(aSourceRoot, source);
|
||||
}
|
||||
var key = util.toSetString(source);
|
||||
return Object.prototype.hasOwnProperty.call(this._sourcesContents, key)
|
||||
? this._sourcesContents[key]
|
||||
: null;
|
||||
}, this);
|
||||
};
|
||||
|
||||
/**
|
||||
* Externalize the source map.
|
||||
*/
|
||||
SourceMapGenerator.prototype.toJSON =
|
||||
function SourceMapGenerator_toJSON() {
|
||||
var map = {
|
||||
version: this._version,
|
||||
sources: this._sources.toArray(),
|
||||
names: this._names.toArray(),
|
||||
mappings: this._serializeMappings()
|
||||
};
|
||||
if (this._file != null) {
|
||||
map.file = this._file;
|
||||
}
|
||||
if (this._sourceRoot != null) {
|
||||
map.sourceRoot = this._sourceRoot;
|
||||
}
|
||||
if (this._sourcesContents) {
|
||||
map.sourcesContent = this._generateSourcesContent(map.sources, map.sourceRoot);
|
||||
}
|
||||
|
||||
return map;
|
||||
};
|
||||
|
||||
/**
|
||||
* Render the source map being generated to a string.
|
||||
*/
|
||||
SourceMapGenerator.prototype.toString =
|
||||
function SourceMapGenerator_toString() {
|
||||
return JSON.stringify(this.toJSON());
|
||||
};
|
||||
|
||||
exports.SourceMapGenerator = SourceMapGenerator;
|
||||
+413
@@ -0,0 +1,413 @@
|
||||
/* -*- Mode: js; js-indent-level: 2; -*- */
|
||||
/*
|
||||
* Copyright 2011 Mozilla Foundation and contributors
|
||||
* Licensed under the New BSD license. See LICENSE or:
|
||||
* http://opensource.org/licenses/BSD-3-Clause
|
||||
*/
|
||||
|
||||
var SourceMapGenerator = require('./source-map-generator').SourceMapGenerator;
|
||||
var util = require('./util');
|
||||
|
||||
// Matches a Windows-style `\r\n` newline or a `\n` newline used by all other
|
||||
// operating systems these days (capturing the result).
|
||||
var REGEX_NEWLINE = /(\r?\n)/;
|
||||
|
||||
// Newline character code for charCodeAt() comparisons
|
||||
var NEWLINE_CODE = 10;
|
||||
|
||||
// Private symbol for identifying `SourceNode`s when multiple versions of
|
||||
// the source-map library are loaded. This MUST NOT CHANGE across
|
||||
// versions!
|
||||
var isSourceNode = "$$$isSourceNode$$$";
|
||||
|
||||
/**
|
||||
* SourceNodes provide a way to abstract over interpolating/concatenating
|
||||
* snippets of generated JavaScript source code while maintaining the line and
|
||||
* column information associated with the original source code.
|
||||
*
|
||||
* @param aLine The original line number.
|
||||
* @param aColumn The original column number.
|
||||
* @param aSource The original source's filename.
|
||||
* @param aChunks Optional. An array of strings which are snippets of
|
||||
* generated JS, or other SourceNodes.
|
||||
* @param aName The original identifier.
|
||||
*/
|
||||
function SourceNode(aLine, aColumn, aSource, aChunks, aName) {
|
||||
this.children = [];
|
||||
this.sourceContents = {};
|
||||
this.line = aLine == null ? null : aLine;
|
||||
this.column = aColumn == null ? null : aColumn;
|
||||
this.source = aSource == null ? null : aSource;
|
||||
this.name = aName == null ? null : aName;
|
||||
this[isSourceNode] = true;
|
||||
if (aChunks != null) this.add(aChunks);
|
||||
}
|
||||
|
||||
/**
|
||||
* Creates a SourceNode from generated code and a SourceMapConsumer.
|
||||
*
|
||||
* @param aGeneratedCode The generated code
|
||||
* @param aSourceMapConsumer The SourceMap for the generated code
|
||||
* @param aRelativePath Optional. The path that relative sources in the
|
||||
* SourceMapConsumer should be relative to.
|
||||
*/
|
||||
SourceNode.fromStringWithSourceMap =
|
||||
function SourceNode_fromStringWithSourceMap(aGeneratedCode, aSourceMapConsumer, aRelativePath) {
|
||||
// The SourceNode we want to fill with the generated code
|
||||
// and the SourceMap
|
||||
var node = new SourceNode();
|
||||
|
||||
// All even indices of this array are one line of the generated code,
|
||||
// while all odd indices are the newlines between two adjacent lines
|
||||
// (since `REGEX_NEWLINE` captures its match).
|
||||
// Processed fragments are accessed by calling `shiftNextLine`.
|
||||
var remainingLines = aGeneratedCode.split(REGEX_NEWLINE);
|
||||
var remainingLinesIndex = 0;
|
||||
var shiftNextLine = function() {
|
||||
var lineContents = getNextLine();
|
||||
// The last line of a file might not have a newline.
|
||||
var newLine = getNextLine() || "";
|
||||
return lineContents + newLine;
|
||||
|
||||
function getNextLine() {
|
||||
return remainingLinesIndex < remainingLines.length ?
|
||||
remainingLines[remainingLinesIndex++] : undefined;
|
||||
}
|
||||
};
|
||||
|
||||
// We need to remember the position of "remainingLines"
|
||||
var lastGeneratedLine = 1, lastGeneratedColumn = 0;
|
||||
|
||||
// The generate SourceNodes we need a code range.
|
||||
// To extract it current and last mapping is used.
|
||||
// Here we store the last mapping.
|
||||
var lastMapping = null;
|
||||
|
||||
aSourceMapConsumer.eachMapping(function (mapping) {
|
||||
if (lastMapping !== null) {
|
||||
// We add the code from "lastMapping" to "mapping":
|
||||
// First check if there is a new line in between.
|
||||
if (lastGeneratedLine < mapping.generatedLine) {
|
||||
// Associate first line with "lastMapping"
|
||||
addMappingWithCode(lastMapping, shiftNextLine());
|
||||
lastGeneratedLine++;
|
||||
lastGeneratedColumn = 0;
|
||||
// The remaining code is added without mapping
|
||||
} else {
|
||||
// There is no new line in between.
|
||||
// Associate the code between "lastGeneratedColumn" and
|
||||
// "mapping.generatedColumn" with "lastMapping"
|
||||
var nextLine = remainingLines[remainingLinesIndex] || '';
|
||||
var code = nextLine.substr(0, mapping.generatedColumn -
|
||||
lastGeneratedColumn);
|
||||
remainingLines[remainingLinesIndex] = nextLine.substr(mapping.generatedColumn -
|
||||
lastGeneratedColumn);
|
||||
lastGeneratedColumn = mapping.generatedColumn;
|
||||
addMappingWithCode(lastMapping, code);
|
||||
// No more remaining code, continue
|
||||
lastMapping = mapping;
|
||||
return;
|
||||
}
|
||||
}
|
||||
// We add the generated code until the first mapping
|
||||
// to the SourceNode without any mapping.
|
||||
// Each line is added as separate string.
|
||||
while (lastGeneratedLine < mapping.generatedLine) {
|
||||
node.add(shiftNextLine());
|
||||
lastGeneratedLine++;
|
||||
}
|
||||
if (lastGeneratedColumn < mapping.generatedColumn) {
|
||||
var nextLine = remainingLines[remainingLinesIndex] || '';
|
||||
node.add(nextLine.substr(0, mapping.generatedColumn));
|
||||
remainingLines[remainingLinesIndex] = nextLine.substr(mapping.generatedColumn);
|
||||
lastGeneratedColumn = mapping.generatedColumn;
|
||||
}
|
||||
lastMapping = mapping;
|
||||
}, this);
|
||||
// We have processed all mappings.
|
||||
if (remainingLinesIndex < remainingLines.length) {
|
||||
if (lastMapping) {
|
||||
// Associate the remaining code in the current line with "lastMapping"
|
||||
addMappingWithCode(lastMapping, shiftNextLine());
|
||||
}
|
||||
// and add the remaining lines without any mapping
|
||||
node.add(remainingLines.splice(remainingLinesIndex).join(""));
|
||||
}
|
||||
|
||||
// Copy sourcesContent into SourceNode
|
||||
aSourceMapConsumer.sources.forEach(function (sourceFile) {
|
||||
var content = aSourceMapConsumer.sourceContentFor(sourceFile);
|
||||
if (content != null) {
|
||||
if (aRelativePath != null) {
|
||||
sourceFile = util.join(aRelativePath, sourceFile);
|
||||
}
|
||||
node.setSourceContent(sourceFile, content);
|
||||
}
|
||||
});
|
||||
|
||||
return node;
|
||||
|
||||
function addMappingWithCode(mapping, code) {
|
||||
if (mapping === null || mapping.source === undefined) {
|
||||
node.add(code);
|
||||
} else {
|
||||
var source = aRelativePath
|
||||
? util.join(aRelativePath, mapping.source)
|
||||
: mapping.source;
|
||||
node.add(new SourceNode(mapping.originalLine,
|
||||
mapping.originalColumn,
|
||||
source,
|
||||
code,
|
||||
mapping.name));
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
/**
|
||||
* Add a chunk of generated JS to this source node.
|
||||
*
|
||||
* @param aChunk A string snippet of generated JS code, another instance of
|
||||
* SourceNode, or an array where each member is one of those things.
|
||||
*/
|
||||
SourceNode.prototype.add = function SourceNode_add(aChunk) {
|
||||
if (Array.isArray(aChunk)) {
|
||||
aChunk.forEach(function (chunk) {
|
||||
this.add(chunk);
|
||||
}, this);
|
||||
}
|
||||
else if (aChunk[isSourceNode] || typeof aChunk === "string") {
|
||||
if (aChunk) {
|
||||
this.children.push(aChunk);
|
||||
}
|
||||
}
|
||||
else {
|
||||
throw new TypeError(
|
||||
"Expected a SourceNode, string, or an array of SourceNodes and strings. Got " + aChunk
|
||||
);
|
||||
}
|
||||
return this;
|
||||
};
|
||||
|
||||
/**
|
||||
* Add a chunk of generated JS to the beginning of this source node.
|
||||
*
|
||||
* @param aChunk A string snippet of generated JS code, another instance of
|
||||
* SourceNode, or an array where each member is one of those things.
|
||||
*/
|
||||
SourceNode.prototype.prepend = function SourceNode_prepend(aChunk) {
|
||||
if (Array.isArray(aChunk)) {
|
||||
for (var i = aChunk.length-1; i >= 0; i--) {
|
||||
this.prepend(aChunk[i]);
|
||||
}
|
||||
}
|
||||
else if (aChunk[isSourceNode] || typeof aChunk === "string") {
|
||||
this.children.unshift(aChunk);
|
||||
}
|
||||
else {
|
||||
throw new TypeError(
|
||||
"Expected a SourceNode, string, or an array of SourceNodes and strings. Got " + aChunk
|
||||
);
|
||||
}
|
||||
return this;
|
||||
};
|
||||
|
||||
/**
|
||||
* Walk over the tree of JS snippets in this node and its children. The
|
||||
* walking function is called once for each snippet of JS and is passed that
|
||||
* snippet and the its original associated source's line/column location.
|
||||
*
|
||||
* @param aFn The traversal function.
|
||||
*/
|
||||
SourceNode.prototype.walk = function SourceNode_walk(aFn) {
|
||||
var chunk;
|
||||
for (var i = 0, len = this.children.length; i < len; i++) {
|
||||
chunk = this.children[i];
|
||||
if (chunk[isSourceNode]) {
|
||||
chunk.walk(aFn);
|
||||
}
|
||||
else {
|
||||
if (chunk !== '') {
|
||||
aFn(chunk, { source: this.source,
|
||||
line: this.line,
|
||||
column: this.column,
|
||||
name: this.name });
|
||||
}
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
/**
|
||||
* Like `String.prototype.join` except for SourceNodes. Inserts `aStr` between
|
||||
* each of `this.children`.
|
||||
*
|
||||
* @param aSep The separator.
|
||||
*/
|
||||
SourceNode.prototype.join = function SourceNode_join(aSep) {
|
||||
var newChildren;
|
||||
var i;
|
||||
var len = this.children.length;
|
||||
if (len > 0) {
|
||||
newChildren = [];
|
||||
for (i = 0; i < len-1; i++) {
|
||||
newChildren.push(this.children[i]);
|
||||
newChildren.push(aSep);
|
||||
}
|
||||
newChildren.push(this.children[i]);
|
||||
this.children = newChildren;
|
||||
}
|
||||
return this;
|
||||
};
|
||||
|
||||
/**
|
||||
* Call String.prototype.replace on the very right-most source snippet. Useful
|
||||
* for trimming whitespace from the end of a source node, etc.
|
||||
*
|
||||
* @param aPattern The pattern to replace.
|
||||
* @param aReplacement The thing to replace the pattern with.
|
||||
*/
|
||||
SourceNode.prototype.replaceRight = function SourceNode_replaceRight(aPattern, aReplacement) {
|
||||
var lastChild = this.children[this.children.length - 1];
|
||||
if (lastChild[isSourceNode]) {
|
||||
lastChild.replaceRight(aPattern, aReplacement);
|
||||
}
|
||||
else if (typeof lastChild === 'string') {
|
||||
this.children[this.children.length - 1] = lastChild.replace(aPattern, aReplacement);
|
||||
}
|
||||
else {
|
||||
this.children.push(''.replace(aPattern, aReplacement));
|
||||
}
|
||||
return this;
|
||||
};
|
||||
|
||||
/**
|
||||
* Set the source content for a source file. This will be added to the SourceMapGenerator
|
||||
* in the sourcesContent field.
|
||||
*
|
||||
* @param aSourceFile The filename of the source file
|
||||
* @param aSourceContent The content of the source file
|
||||
*/
|
||||
SourceNode.prototype.setSourceContent =
|
||||
function SourceNode_setSourceContent(aSourceFile, aSourceContent) {
|
||||
this.sourceContents[util.toSetString(aSourceFile)] = aSourceContent;
|
||||
};
|
||||
|
||||
/**
|
||||
* Walk over the tree of SourceNodes. The walking function is called for each
|
||||
* source file content and is passed the filename and source content.
|
||||
*
|
||||
* @param aFn The traversal function.
|
||||
*/
|
||||
SourceNode.prototype.walkSourceContents =
|
||||
function SourceNode_walkSourceContents(aFn) {
|
||||
for (var i = 0, len = this.children.length; i < len; i++) {
|
||||
if (this.children[i][isSourceNode]) {
|
||||
this.children[i].walkSourceContents(aFn);
|
||||
}
|
||||
}
|
||||
|
||||
var sources = Object.keys(this.sourceContents);
|
||||
for (var i = 0, len = sources.length; i < len; i++) {
|
||||
aFn(util.fromSetString(sources[i]), this.sourceContents[sources[i]]);
|
||||
}
|
||||
};
|
||||
|
||||
/**
|
||||
* Return the string representation of this source node. Walks over the tree
|
||||
* and concatenates all the various snippets together to one string.
|
||||
*/
|
||||
SourceNode.prototype.toString = function SourceNode_toString() {
|
||||
var str = "";
|
||||
this.walk(function (chunk) {
|
||||
str += chunk;
|
||||
});
|
||||
return str;
|
||||
};
|
||||
|
||||
/**
|
||||
* Returns the string representation of this source node along with a source
|
||||
* map.
|
||||
*/
|
||||
SourceNode.prototype.toStringWithSourceMap = function SourceNode_toStringWithSourceMap(aArgs) {
|
||||
var generated = {
|
||||
code: "",
|
||||
line: 1,
|
||||
column: 0
|
||||
};
|
||||
var map = new SourceMapGenerator(aArgs);
|
||||
var sourceMappingActive = false;
|
||||
var lastOriginalSource = null;
|
||||
var lastOriginalLine = null;
|
||||
var lastOriginalColumn = null;
|
||||
var lastOriginalName = null;
|
||||
this.walk(function (chunk, original) {
|
||||
generated.code += chunk;
|
||||
if (original.source !== null
|
||||
&& original.line !== null
|
||||
&& original.column !== null) {
|
||||
if(lastOriginalSource !== original.source
|
||||
|| lastOriginalLine !== original.line
|
||||
|| lastOriginalColumn !== original.column
|
||||
|| lastOriginalName !== original.name) {
|
||||
map.addMapping({
|
||||
source: original.source,
|
||||
original: {
|
||||
line: original.line,
|
||||
column: original.column
|
||||
},
|
||||
generated: {
|
||||
line: generated.line,
|
||||
column: generated.column
|
||||
},
|
||||
name: original.name
|
||||
});
|
||||
}
|
||||
lastOriginalSource = original.source;
|
||||
lastOriginalLine = original.line;
|
||||
lastOriginalColumn = original.column;
|
||||
lastOriginalName = original.name;
|
||||
sourceMappingActive = true;
|
||||
} else if (sourceMappingActive) {
|
||||
map.addMapping({
|
||||
generated: {
|
||||
line: generated.line,
|
||||
column: generated.column
|
||||
}
|
||||
});
|
||||
lastOriginalSource = null;
|
||||
sourceMappingActive = false;
|
||||
}
|
||||
for (var idx = 0, length = chunk.length; idx < length; idx++) {
|
||||
if (chunk.charCodeAt(idx) === NEWLINE_CODE) {
|
||||
generated.line++;
|
||||
generated.column = 0;
|
||||
// Mappings end at eol
|
||||
if (idx + 1 === length) {
|
||||
lastOriginalSource = null;
|
||||
sourceMappingActive = false;
|
||||
} else if (sourceMappingActive) {
|
||||
map.addMapping({
|
||||
source: original.source,
|
||||
original: {
|
||||
line: original.line,
|
||||
column: original.column
|
||||
},
|
||||
generated: {
|
||||
line: generated.line,
|
||||
column: generated.column
|
||||
},
|
||||
name: original.name
|
||||
});
|
||||
}
|
||||
} else {
|
||||
generated.column++;
|
||||
}
|
||||
}
|
||||
});
|
||||
this.walkSourceContents(function (sourceFile, sourceContent) {
|
||||
map.setSourceContent(sourceFile, sourceContent);
|
||||
});
|
||||
|
||||
return { code: generated.code, map: map };
|
||||
};
|
||||
|
||||
exports.SourceNode = SourceNode;
|
||||
+488
@@ -0,0 +1,488 @@
|
||||
/* -*- Mode: js; js-indent-level: 2; -*- */
|
||||
/*
|
||||
* Copyright 2011 Mozilla Foundation and contributors
|
||||
* Licensed under the New BSD license. See LICENSE or:
|
||||
* http://opensource.org/licenses/BSD-3-Clause
|
||||
*/
|
||||
|
||||
/**
|
||||
* This is a helper function for getting values from parameter/options
|
||||
* objects.
|
||||
*
|
||||
* @param args The object we are extracting values from
|
||||
* @param name The name of the property we are getting.
|
||||
* @param defaultValue An optional value to return if the property is missing
|
||||
* from the object. If this is not specified and the property is missing, an
|
||||
* error will be thrown.
|
||||
*/
|
||||
function getArg(aArgs, aName, aDefaultValue) {
|
||||
if (aName in aArgs) {
|
||||
return aArgs[aName];
|
||||
} else if (arguments.length === 3) {
|
||||
return aDefaultValue;
|
||||
} else {
|
||||
throw new Error('"' + aName + '" is a required argument.');
|
||||
}
|
||||
}
|
||||
exports.getArg = getArg;
|
||||
|
||||
var urlRegexp = /^(?:([\w+\-.]+):)?\/\/(?:(\w+:\w+)@)?([\w.-]*)(?::(\d+))?(.*)$/;
|
||||
var dataUrlRegexp = /^data:.+\,.+$/;
|
||||
|
||||
function urlParse(aUrl) {
|
||||
var match = aUrl.match(urlRegexp);
|
||||
if (!match) {
|
||||
return null;
|
||||
}
|
||||
return {
|
||||
scheme: match[1],
|
||||
auth: match[2],
|
||||
host: match[3],
|
||||
port: match[4],
|
||||
path: match[5]
|
||||
};
|
||||
}
|
||||
exports.urlParse = urlParse;
|
||||
|
||||
function urlGenerate(aParsedUrl) {
|
||||
var url = '';
|
||||
if (aParsedUrl.scheme) {
|
||||
url += aParsedUrl.scheme + ':';
|
||||
}
|
||||
url += '//';
|
||||
if (aParsedUrl.auth) {
|
||||
url += aParsedUrl.auth + '@';
|
||||
}
|
||||
if (aParsedUrl.host) {
|
||||
url += aParsedUrl.host;
|
||||
}
|
||||
if (aParsedUrl.port) {
|
||||
url += ":" + aParsedUrl.port
|
||||
}
|
||||
if (aParsedUrl.path) {
|
||||
url += aParsedUrl.path;
|
||||
}
|
||||
return url;
|
||||
}
|
||||
exports.urlGenerate = urlGenerate;
|
||||
|
||||
/**
|
||||
* Normalizes a path, or the path portion of a URL:
|
||||
*
|
||||
* - Replaces consecutive slashes with one slash.
|
||||
* - Removes unnecessary '.' parts.
|
||||
* - Removes unnecessary '<dir>/..' parts.
|
||||
*
|
||||
* Based on code in the Node.js 'path' core module.
|
||||
*
|
||||
* @param aPath The path or url to normalize.
|
||||
*/
|
||||
function normalize(aPath) {
|
||||
var path = aPath;
|
||||
var url = urlParse(aPath);
|
||||
if (url) {
|
||||
if (!url.path) {
|
||||
return aPath;
|
||||
}
|
||||
path = url.path;
|
||||
}
|
||||
var isAbsolute = exports.isAbsolute(path);
|
||||
|
||||
var parts = path.split(/\/+/);
|
||||
for (var part, up = 0, i = parts.length - 1; i >= 0; i--) {
|
||||
part = parts[i];
|
||||
if (part === '.') {
|
||||
parts.splice(i, 1);
|
||||
} else if (part === '..') {
|
||||
up++;
|
||||
} else if (up > 0) {
|
||||
if (part === '') {
|
||||
// The first part is blank if the path is absolute. Trying to go
|
||||
// above the root is a no-op. Therefore we can remove all '..' parts
|
||||
// directly after the root.
|
||||
parts.splice(i + 1, up);
|
||||
up = 0;
|
||||
} else {
|
||||
parts.splice(i, 2);
|
||||
up--;
|
||||
}
|
||||
}
|
||||
}
|
||||
path = parts.join('/');
|
||||
|
||||
if (path === '') {
|
||||
path = isAbsolute ? '/' : '.';
|
||||
}
|
||||
|
||||
if (url) {
|
||||
url.path = path;
|
||||
return urlGenerate(url);
|
||||
}
|
||||
return path;
|
||||
}
|
||||
exports.normalize = normalize;
|
||||
|
||||
/**
|
||||
* Joins two paths/URLs.
|
||||
*
|
||||
* @param aRoot The root path or URL.
|
||||
* @param aPath The path or URL to be joined with the root.
|
||||
*
|
||||
* - If aPath is a URL or a data URI, aPath is returned, unless aPath is a
|
||||
* scheme-relative URL: Then the scheme of aRoot, if any, is prepended
|
||||
* first.
|
||||
* - Otherwise aPath is a path. If aRoot is a URL, then its path portion
|
||||
* is updated with the result and aRoot is returned. Otherwise the result
|
||||
* is returned.
|
||||
* - If aPath is absolute, the result is aPath.
|
||||
* - Otherwise the two paths are joined with a slash.
|
||||
* - Joining for example 'http://' and 'www.example.com' is also supported.
|
||||
*/
|
||||
function join(aRoot, aPath) {
|
||||
if (aRoot === "") {
|
||||
aRoot = ".";
|
||||
}
|
||||
if (aPath === "") {
|
||||
aPath = ".";
|
||||
}
|
||||
var aPathUrl = urlParse(aPath);
|
||||
var aRootUrl = urlParse(aRoot);
|
||||
if (aRootUrl) {
|
||||
aRoot = aRootUrl.path || '/';
|
||||
}
|
||||
|
||||
// `join(foo, '//www.example.org')`
|
||||
if (aPathUrl && !aPathUrl.scheme) {
|
||||
if (aRootUrl) {
|
||||
aPathUrl.scheme = aRootUrl.scheme;
|
||||
}
|
||||
return urlGenerate(aPathUrl);
|
||||
}
|
||||
|
||||
if (aPathUrl || aPath.match(dataUrlRegexp)) {
|
||||
return aPath;
|
||||
}
|
||||
|
||||
// `join('http://', 'www.example.com')`
|
||||
if (aRootUrl && !aRootUrl.host && !aRootUrl.path) {
|
||||
aRootUrl.host = aPath;
|
||||
return urlGenerate(aRootUrl);
|
||||
}
|
||||
|
||||
var joined = aPath.charAt(0) === '/'
|
||||
? aPath
|
||||
: normalize(aRoot.replace(/\/+$/, '') + '/' + aPath);
|
||||
|
||||
if (aRootUrl) {
|
||||
aRootUrl.path = joined;
|
||||
return urlGenerate(aRootUrl);
|
||||
}
|
||||
return joined;
|
||||
}
|
||||
exports.join = join;
|
||||
|
||||
exports.isAbsolute = function (aPath) {
|
||||
return aPath.charAt(0) === '/' || urlRegexp.test(aPath);
|
||||
};
|
||||
|
||||
/**
|
||||
* Make a path relative to a URL or another path.
|
||||
*
|
||||
* @param aRoot The root path or URL.
|
||||
* @param aPath The path or URL to be made relative to aRoot.
|
||||
*/
|
||||
function relative(aRoot, aPath) {
|
||||
if (aRoot === "") {
|
||||
aRoot = ".";
|
||||
}
|
||||
|
||||
aRoot = aRoot.replace(/\/$/, '');
|
||||
|
||||
// It is possible for the path to be above the root. In this case, simply
|
||||
// checking whether the root is a prefix of the path won't work. Instead, we
|
||||
// need to remove components from the root one by one, until either we find
|
||||
// a prefix that fits, or we run out of components to remove.
|
||||
var level = 0;
|
||||
while (aPath.indexOf(aRoot + '/') !== 0) {
|
||||
var index = aRoot.lastIndexOf("/");
|
||||
if (index < 0) {
|
||||
return aPath;
|
||||
}
|
||||
|
||||
// If the only part of the root that is left is the scheme (i.e. http://,
|
||||
// file:///, etc.), one or more slashes (/), or simply nothing at all, we
|
||||
// have exhausted all components, so the path is not relative to the root.
|
||||
aRoot = aRoot.slice(0, index);
|
||||
if (aRoot.match(/^([^\/]+:\/)?\/*$/)) {
|
||||
return aPath;
|
||||
}
|
||||
|
||||
++level;
|
||||
}
|
||||
|
||||
// Make sure we add a "../" for each component we removed from the root.
|
||||
return Array(level + 1).join("../") + aPath.substr(aRoot.length + 1);
|
||||
}
|
||||
exports.relative = relative;
|
||||
|
||||
var supportsNullProto = (function () {
|
||||
var obj = Object.create(null);
|
||||
return !('__proto__' in obj);
|
||||
}());
|
||||
|
||||
function identity (s) {
|
||||
return s;
|
||||
}
|
||||
|
||||
/**
|
||||
* Because behavior goes wacky when you set `__proto__` on objects, we
|
||||
* have to prefix all the strings in our set with an arbitrary character.
|
||||
*
|
||||
* See https://github.com/mozilla/source-map/pull/31 and
|
||||
* https://github.com/mozilla/source-map/issues/30
|
||||
*
|
||||
* @param String aStr
|
||||
*/
|
||||
function toSetString(aStr) {
|
||||
if (isProtoString(aStr)) {
|
||||
return '$' + aStr;
|
||||
}
|
||||
|
||||
return aStr;
|
||||
}
|
||||
exports.toSetString = supportsNullProto ? identity : toSetString;
|
||||
|
||||
function fromSetString(aStr) {
|
||||
if (isProtoString(aStr)) {
|
||||
return aStr.slice(1);
|
||||
}
|
||||
|
||||
return aStr;
|
||||
}
|
||||
exports.fromSetString = supportsNullProto ? identity : fromSetString;
|
||||
|
||||
function isProtoString(s) {
|
||||
if (!s) {
|
||||
return false;
|
||||
}
|
||||
|
||||
var length = s.length;
|
||||
|
||||
if (length < 9 /* "__proto__".length */) {
|
||||
return false;
|
||||
}
|
||||
|
||||
if (s.charCodeAt(length - 1) !== 95 /* '_' */ ||
|
||||
s.charCodeAt(length - 2) !== 95 /* '_' */ ||
|
||||
s.charCodeAt(length - 3) !== 111 /* 'o' */ ||
|
||||
s.charCodeAt(length - 4) !== 116 /* 't' */ ||
|
||||
s.charCodeAt(length - 5) !== 111 /* 'o' */ ||
|
||||
s.charCodeAt(length - 6) !== 114 /* 'r' */ ||
|
||||
s.charCodeAt(length - 7) !== 112 /* 'p' */ ||
|
||||
s.charCodeAt(length - 8) !== 95 /* '_' */ ||
|
||||
s.charCodeAt(length - 9) !== 95 /* '_' */) {
|
||||
return false;
|
||||
}
|
||||
|
||||
for (var i = length - 10; i >= 0; i--) {
|
||||
if (s.charCodeAt(i) !== 36 /* '$' */) {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
/**
|
||||
* Comparator between two mappings where the original positions are compared.
|
||||
*
|
||||
* Optionally pass in `true` as `onlyCompareGenerated` to consider two
|
||||
* mappings with the same original source/line/column, but different generated
|
||||
* line and column the same. Useful when searching for a mapping with a
|
||||
* stubbed out mapping.
|
||||
*/
|
||||
function compareByOriginalPositions(mappingA, mappingB, onlyCompareOriginal) {
|
||||
var cmp = strcmp(mappingA.source, mappingB.source);
|
||||
if (cmp !== 0) {
|
||||
return cmp;
|
||||
}
|
||||
|
||||
cmp = mappingA.originalLine - mappingB.originalLine;
|
||||
if (cmp !== 0) {
|
||||
return cmp;
|
||||
}
|
||||
|
||||
cmp = mappingA.originalColumn - mappingB.originalColumn;
|
||||
if (cmp !== 0 || onlyCompareOriginal) {
|
||||
return cmp;
|
||||
}
|
||||
|
||||
cmp = mappingA.generatedColumn - mappingB.generatedColumn;
|
||||
if (cmp !== 0) {
|
||||
return cmp;
|
||||
}
|
||||
|
||||
cmp = mappingA.generatedLine - mappingB.generatedLine;
|
||||
if (cmp !== 0) {
|
||||
return cmp;
|
||||
}
|
||||
|
||||
return strcmp(mappingA.name, mappingB.name);
|
||||
}
|
||||
exports.compareByOriginalPositions = compareByOriginalPositions;
|
||||
|
||||
/**
|
||||
* Comparator between two mappings with deflated source and name indices where
|
||||
* the generated positions are compared.
|
||||
*
|
||||
* Optionally pass in `true` as `onlyCompareGenerated` to consider two
|
||||
* mappings with the same generated line and column, but different
|
||||
* source/name/original line and column the same. Useful when searching for a
|
||||
* mapping with a stubbed out mapping.
|
||||
*/
|
||||
function compareByGeneratedPositionsDeflated(mappingA, mappingB, onlyCompareGenerated) {
|
||||
var cmp = mappingA.generatedLine - mappingB.generatedLine;
|
||||
if (cmp !== 0) {
|
||||
return cmp;
|
||||
}
|
||||
|
||||
cmp = mappingA.generatedColumn - mappingB.generatedColumn;
|
||||
if (cmp !== 0 || onlyCompareGenerated) {
|
||||
return cmp;
|
||||
}
|
||||
|
||||
cmp = strcmp(mappingA.source, mappingB.source);
|
||||
if (cmp !== 0) {
|
||||
return cmp;
|
||||
}
|
||||
|
||||
cmp = mappingA.originalLine - mappingB.originalLine;
|
||||
if (cmp !== 0) {
|
||||
return cmp;
|
||||
}
|
||||
|
||||
cmp = mappingA.originalColumn - mappingB.originalColumn;
|
||||
if (cmp !== 0) {
|
||||
return cmp;
|
||||
}
|
||||
|
||||
return strcmp(mappingA.name, mappingB.name);
|
||||
}
|
||||
exports.compareByGeneratedPositionsDeflated = compareByGeneratedPositionsDeflated;
|
||||
|
||||
function strcmp(aStr1, aStr2) {
|
||||
if (aStr1 === aStr2) {
|
||||
return 0;
|
||||
}
|
||||
|
||||
if (aStr1 === null) {
|
||||
return 1; // aStr2 !== null
|
||||
}
|
||||
|
||||
if (aStr2 === null) {
|
||||
return -1; // aStr1 !== null
|
||||
}
|
||||
|
||||
if (aStr1 > aStr2) {
|
||||
return 1;
|
||||
}
|
||||
|
||||
return -1;
|
||||
}
|
||||
|
||||
/**
|
||||
* Comparator between two mappings with inflated source and name strings where
|
||||
* the generated positions are compared.
|
||||
*/
|
||||
function compareByGeneratedPositionsInflated(mappingA, mappingB) {
|
||||
var cmp = mappingA.generatedLine - mappingB.generatedLine;
|
||||
if (cmp !== 0) {
|
||||
return cmp;
|
||||
}
|
||||
|
||||
cmp = mappingA.generatedColumn - mappingB.generatedColumn;
|
||||
if (cmp !== 0) {
|
||||
return cmp;
|
||||
}
|
||||
|
||||
cmp = strcmp(mappingA.source, mappingB.source);
|
||||
if (cmp !== 0) {
|
||||
return cmp;
|
||||
}
|
||||
|
||||
cmp = mappingA.originalLine - mappingB.originalLine;
|
||||
if (cmp !== 0) {
|
||||
return cmp;
|
||||
}
|
||||
|
||||
cmp = mappingA.originalColumn - mappingB.originalColumn;
|
||||
if (cmp !== 0) {
|
||||
return cmp;
|
||||
}
|
||||
|
||||
return strcmp(mappingA.name, mappingB.name);
|
||||
}
|
||||
exports.compareByGeneratedPositionsInflated = compareByGeneratedPositionsInflated;
|
||||
|
||||
/**
|
||||
* Strip any JSON XSSI avoidance prefix from the string (as documented
|
||||
* in the source maps specification), and then parse the string as
|
||||
* JSON.
|
||||
*/
|
||||
function parseSourceMapInput(str) {
|
||||
return JSON.parse(str.replace(/^\)]}'[^\n]*\n/, ''));
|
||||
}
|
||||
exports.parseSourceMapInput = parseSourceMapInput;
|
||||
|
||||
/**
|
||||
* Compute the URL of a source given the the source root, the source's
|
||||
* URL, and the source map's URL.
|
||||
*/
|
||||
function computeSourceURL(sourceRoot, sourceURL, sourceMapURL) {
|
||||
sourceURL = sourceURL || '';
|
||||
|
||||
if (sourceRoot) {
|
||||
// This follows what Chrome does.
|
||||
if (sourceRoot[sourceRoot.length - 1] !== '/' && sourceURL[0] !== '/') {
|
||||
sourceRoot += '/';
|
||||
}
|
||||
// The spec says:
|
||||
// Line 4: An optional source root, useful for relocating source
|
||||
// files on a server or removing repeated values in the
|
||||
// “sources” entry. This value is prepended to the individual
|
||||
// entries in the “source” field.
|
||||
sourceURL = sourceRoot + sourceURL;
|
||||
}
|
||||
|
||||
// Historically, SourceMapConsumer did not take the sourceMapURL as
|
||||
// a parameter. This mode is still somewhat supported, which is why
|
||||
// this code block is conditional. However, it's preferable to pass
|
||||
// the source map URL to SourceMapConsumer, so that this function
|
||||
// can implement the source URL resolution algorithm as outlined in
|
||||
// the spec. This block is basically the equivalent of:
|
||||
// new URL(sourceURL, sourceMapURL).toString()
|
||||
// ... except it avoids using URL, which wasn't available in the
|
||||
// older releases of node still supported by this library.
|
||||
//
|
||||
// The spec says:
|
||||
// If the sources are not absolute URLs after prepending of the
|
||||
// “sourceRoot”, the sources are resolved relative to the
|
||||
// SourceMap (like resolving script src in a html document).
|
||||
if (sourceMapURL) {
|
||||
var parsed = urlParse(sourceMapURL);
|
||||
if (!parsed) {
|
||||
throw new Error("sourceMapURL could not be parsed");
|
||||
}
|
||||
if (parsed.path) {
|
||||
// Strip the last path component, but keep the "/".
|
||||
var index = parsed.path.lastIndexOf('/');
|
||||
if (index >= 0) {
|
||||
parsed.path = parsed.path.substring(0, index + 1);
|
||||
}
|
||||
}
|
||||
sourceURL = join(urlGenerate(parsed), sourceURL);
|
||||
}
|
||||
|
||||
return normalize(sourceURL);
|
||||
}
|
||||
exports.computeSourceURL = computeSourceURL;
|
||||
+73
@@ -0,0 +1,73 @@
|
||||
{
|
||||
"name": "source-map",
|
||||
"description": "Generates and consumes source maps",
|
||||
"version": "0.6.1",
|
||||
"homepage": "https://github.com/mozilla/source-map",
|
||||
"author": "Nick Fitzgerald <nfitzgerald@mozilla.com>",
|
||||
"contributors": [
|
||||
"Tobias Koppers <tobias.koppers@googlemail.com>",
|
||||
"Duncan Beevers <duncan@dweebd.com>",
|
||||
"Stephen Crane <scrane@mozilla.com>",
|
||||
"Ryan Seddon <seddon.ryan@gmail.com>",
|
||||
"Miles Elam <miles.elam@deem.com>",
|
||||
"Mihai Bazon <mihai.bazon@gmail.com>",
|
||||
"Michael Ficarra <github.public.email@michael.ficarra.me>",
|
||||
"Todd Wolfson <todd@twolfson.com>",
|
||||
"Alexander Solovyov <alexander@solovyov.net>",
|
||||
"Felix Gnass <fgnass@gmail.com>",
|
||||
"Conrad Irwin <conrad.irwin@gmail.com>",
|
||||
"usrbincc <usrbincc@yahoo.com>",
|
||||
"David Glasser <glasser@davidglasser.net>",
|
||||
"Chase Douglas <chase@newrelic.com>",
|
||||
"Evan Wallace <evan.exe@gmail.com>",
|
||||
"Heather Arthur <fayearthur@gmail.com>",
|
||||
"Hugh Kennedy <hughskennedy@gmail.com>",
|
||||
"David Glasser <glasser@davidglasser.net>",
|
||||
"Simon Lydell <simon.lydell@gmail.com>",
|
||||
"Jmeas Smith <jellyes2@gmail.com>",
|
||||
"Michael Z Goddard <mzgoddard@gmail.com>",
|
||||
"azu <azu@users.noreply.github.com>",
|
||||
"John Gozde <john@gozde.ca>",
|
||||
"Adam Kirkton <akirkton@truefitinnovation.com>",
|
||||
"Chris Montgomery <christopher.montgomery@dowjones.com>",
|
||||
"J. Ryan Stinnett <jryans@gmail.com>",
|
||||
"Jack Herrington <jherrington@walmartlabs.com>",
|
||||
"Chris Truter <jeffpalentine@gmail.com>",
|
||||
"Daniel Espeset <daniel@danielespeset.com>",
|
||||
"Jamie Wong <jamie.lf.wong@gmail.com>",
|
||||
"Eddy Bruël <ejpbruel@mozilla.com>",
|
||||
"Hawken Rives <hawkrives@gmail.com>",
|
||||
"Gilad Peleg <giladp007@gmail.com>",
|
||||
"djchie <djchie.dev@gmail.com>",
|
||||
"Gary Ye <garysye@gmail.com>",
|
||||
"Nicolas Lalevée <nicolas.lalevee@hibnet.org>"
|
||||
],
|
||||
"repository": {
|
||||
"type": "git",
|
||||
"url": "http://github.com/mozilla/source-map.git"
|
||||
},
|
||||
"main": "./source-map.js",
|
||||
"files": [
|
||||
"source-map.js",
|
||||
"source-map.d.ts",
|
||||
"lib/",
|
||||
"dist/source-map.debug.js",
|
||||
"dist/source-map.js",
|
||||
"dist/source-map.min.js",
|
||||
"dist/source-map.min.js.map"
|
||||
],
|
||||
"engines": {
|
||||
"node": ">=0.10.0"
|
||||
},
|
||||
"license": "BSD-3-Clause",
|
||||
"scripts": {
|
||||
"test": "npm run build && node test/run-tests.js",
|
||||
"build": "webpack --color",
|
||||
"toc": "doctoc --title '## Table of Contents' README.md && doctoc --title '## Table of Contents' CONTRIBUTING.md"
|
||||
},
|
||||
"devDependencies": {
|
||||
"doctoc": "^0.15.0",
|
||||
"webpack": "^1.12.0"
|
||||
},
|
||||
"typings": "source-map"
|
||||
}
|
||||
+98
@@ -0,0 +1,98 @@
|
||||
export interface StartOfSourceMap {
|
||||
file?: string;
|
||||
sourceRoot?: string;
|
||||
}
|
||||
|
||||
export interface RawSourceMap extends StartOfSourceMap {
|
||||
version: string;
|
||||
sources: string[];
|
||||
names: string[];
|
||||
sourcesContent?: string[];
|
||||
mappings: string;
|
||||
}
|
||||
|
||||
export interface Position {
|
||||
line: number;
|
||||
column: number;
|
||||
}
|
||||
|
||||
export interface LineRange extends Position {
|
||||
lastColumn: number;
|
||||
}
|
||||
|
||||
export interface FindPosition extends Position {
|
||||
// SourceMapConsumer.GREATEST_LOWER_BOUND or SourceMapConsumer.LEAST_UPPER_BOUND
|
||||
bias?: number;
|
||||
}
|
||||
|
||||
export interface SourceFindPosition extends FindPosition {
|
||||
source: string;
|
||||
}
|
||||
|
||||
export interface MappedPosition extends Position {
|
||||
source: string;
|
||||
name?: string;
|
||||
}
|
||||
|
||||
export interface MappingItem {
|
||||
source: string;
|
||||
generatedLine: number;
|
||||
generatedColumn: number;
|
||||
originalLine: number;
|
||||
originalColumn: number;
|
||||
name: string;
|
||||
}
|
||||
|
||||
export class SourceMapConsumer {
|
||||
static GENERATED_ORDER: number;
|
||||
static ORIGINAL_ORDER: number;
|
||||
|
||||
static GREATEST_LOWER_BOUND: number;
|
||||
static LEAST_UPPER_BOUND: number;
|
||||
|
||||
constructor(rawSourceMap: RawSourceMap);
|
||||
computeColumnSpans(): void;
|
||||
originalPositionFor(generatedPosition: FindPosition): MappedPosition;
|
||||
generatedPositionFor(originalPosition: SourceFindPosition): LineRange;
|
||||
allGeneratedPositionsFor(originalPosition: MappedPosition): Position[];
|
||||
hasContentsOfAllSources(): boolean;
|
||||
sourceContentFor(source: string, returnNullOnMissing?: boolean): string;
|
||||
eachMapping(callback: (mapping: MappingItem) => void, context?: any, order?: number): void;
|
||||
}
|
||||
|
||||
export interface Mapping {
|
||||
generated: Position;
|
||||
original: Position;
|
||||
source: string;
|
||||
name?: string;
|
||||
}
|
||||
|
||||
export class SourceMapGenerator {
|
||||
constructor(startOfSourceMap?: StartOfSourceMap);
|
||||
static fromSourceMap(sourceMapConsumer: SourceMapConsumer): SourceMapGenerator;
|
||||
addMapping(mapping: Mapping): void;
|
||||
setSourceContent(sourceFile: string, sourceContent: string): void;
|
||||
applySourceMap(sourceMapConsumer: SourceMapConsumer, sourceFile?: string, sourceMapPath?: string): void;
|
||||
toString(): string;
|
||||
}
|
||||
|
||||
export interface CodeWithSourceMap {
|
||||
code: string;
|
||||
map: SourceMapGenerator;
|
||||
}
|
||||
|
||||
export class SourceNode {
|
||||
constructor();
|
||||
constructor(line: number, column: number, source: string);
|
||||
constructor(line: number, column: number, source: string, chunk?: string, name?: string);
|
||||
static fromStringWithSourceMap(code: string, sourceMapConsumer: SourceMapConsumer, relativePath?: string): SourceNode;
|
||||
add(chunk: string): void;
|
||||
prepend(chunk: string): void;
|
||||
setSourceContent(sourceFile: string, sourceContent: string): void;
|
||||
walk(fn: (chunk: string, mapping: MappedPosition) => void): void;
|
||||
walkSourceContents(fn: (file: string, content: string) => void): void;
|
||||
join(sep: string): SourceNode;
|
||||
replaceRight(pattern: string, replacement: string): SourceNode;
|
||||
toString(): string;
|
||||
toStringWithSourceMap(startOfSourceMap?: StartOfSourceMap): CodeWithSourceMap;
|
||||
}
|
||||
+8
@@ -0,0 +1,8 @@
|
||||
/*
|
||||
* Copyright 2009-2011 Mozilla Foundation and contributors
|
||||
* Licensed under the New BSD license. See LICENSE.txt or:
|
||||
* http://opensource.org/licenses/BSD-3-Clause
|
||||
*/
|
||||
exports.SourceMapGenerator = require('./lib/source-map-generator').SourceMapGenerator;
|
||||
exports.SourceMapConsumer = require('./lib/source-map-consumer').SourceMapConsumer;
|
||||
exports.SourceNode = require('./lib/source-node').SourceNode;
|
||||
+92
@@ -0,0 +1,92 @@
|
||||
{
|
||||
"name": "vite-node",
|
||||
"version": "0.25.8",
|
||||
"description": "Vite as Node.js runtime",
|
||||
"author": "Anthony Fu <anthonyfu117@hotmail.com>",
|
||||
"license": "MIT",
|
||||
"funding": "https://github.com/sponsors/antfu",
|
||||
"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"
|
||||
},
|
||||
"exports": {
|
||||
".": {
|
||||
"types": "./dist/index.d.ts",
|
||||
"require": "./dist/index.cjs",
|
||||
"import": "./dist/index.mjs"
|
||||
},
|
||||
"./client": {
|
||||
"types": "./dist/client.d.ts",
|
||||
"require": "./dist/client.cjs",
|
||||
"import": "./dist/client.mjs"
|
||||
},
|
||||
"./server": {
|
||||
"types": "./dist/server.d.ts",
|
||||
"require": "./dist/server.cjs",
|
||||
"import": "./dist/server.mjs"
|
||||
},
|
||||
"./utils": {
|
||||
"types": "./dist/utils.d.ts",
|
||||
"require": "./dist/utils.cjs",
|
||||
"import": "./dist/utils.mjs"
|
||||
},
|
||||
"./hmr": {
|
||||
"types": "./dist/hmr.d.ts",
|
||||
"require": "./dist/hmr.cjs",
|
||||
"import": "./dist/hmr.mjs"
|
||||
},
|
||||
"./source-map": {
|
||||
"types": "./dist/source-map.d.ts",
|
||||
"require": "./dist/source-map.cjs",
|
||||
"import": "./dist/source-map.mjs"
|
||||
}
|
||||
},
|
||||
"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": [
|
||||
"dist",
|
||||
"*.d.ts",
|
||||
"*.mjs"
|
||||
],
|
||||
"engines": {
|
||||
"node": ">=v14.16.0"
|
||||
},
|
||||
"dependencies": {
|
||||
"debug": "^4.3.4",
|
||||
"mlly": "^1.0.0",
|
||||
"pathe": "^0.2.0",
|
||||
"source-map": "^0.6.1",
|
||||
"source-map-support": "^0.5.21",
|
||||
"vite": "^3.0.0 || ^4.0.0"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@types/debug": "^4.1.7",
|
||||
"@types/source-map": "^0.5.7",
|
||||
"@types/source-map-support": "^0.5.6",
|
||||
"cac": "^6.7.14",
|
||||
"picocolors": "^1.0.0",
|
||||
"rollup": "^2.79.1"
|
||||
},
|
||||
"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