feat: init

This commit is contained in:
2026-02-13 22:02:30 +01:00
commit 8f9ff830fb
16711 changed files with 3307340 additions and 0 deletions

21
node_modules/vite-plugin-vue-tracer/LICENSE.md generated vendored Normal file
View File

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

106
node_modules/vite-plugin-vue-tracer/README.md generated vendored Normal file
View File

@@ -0,0 +1,106 @@
# vite-plugin-vue-tracer
[![npm version][npm-version-src]][npm-version-href]
[![npm downloads][npm-downloads-src]][npm-downloads-href]
[![bundle][bundle-src]][bundle-href]
[![JSDocs][jsdocs-src]][jsdocs-href]
[![License][license-src]][license-href]
Tracer for the source code of elements and vdoms in Vue SFC.
This is a designed to be a replacement of [`vite-plugin-vue-inspector`](https://www.npmjs.com/package/vite-plugin-vue-inspector) with a new approach, that utilize Vite's internal source map to resolve the source location, without injecting data-attributes to the DOM.
This plugin is also designed to be more modular, where you can use it as a standalone inspector plugin, or as a headless APIs to build your own inspector.
## Usage
```bash
npm i -D vite-plugin-vue-tracer
```
```ts
import { defineConfig } from 'vite'
import { VueTracer } from 'vite-plugin-vue-tracer'
export default defineConfig({
plugins: [
VueTracer(),
],
})
```
In the your entry file, add the following code:
```ts
// Only apply in development
if (import.meta.hot) {
import('vite-plugin-vue-tracer/client/overlay').then(({ events, state }) => {
// Enables the overlay
state.isEnabled = true
events.on('hover', (info) => {
// ...
})
events.on('click', (info) => {
// ...
openInEditor(info.fullpath) // 'src/app.vue:10:1'
state.isEnabled = false
})
})
}
```
Of if you want headless APIs, import `vite-plugin-vue-tracer/client/record` instead.
```ts
if (import.meta.hot) {
import('vite-plugin-vue-tracer/client/record')
.then(({
hasData,
findTraceFromElement,
findraceFromVNode,
findTraceAtPointer,
}) => {
const el = document.querySelector('.foo')
const trace = findTraceFromElement(el)
if (trace) {
console.log(trace)
}
})
}
```
## References
### Exports
- `vite-plugin-vue-tracer` - The Vite plugin entry, should be used in `vite.config.ts`
- `vite-plugin-vue-tracer/client/record` - The client entry for recording the trace data, this will be automatically injected into each component by the plugin. You don't normally need to import this.
- `vite-plugin-vue-tracer/client/listener` - The client entry for adding event listeners to the DOM and listening to the mouse events. It expose a ref `isEnabled` to control if the listeners are active. A `events` object is exposed for listening to those events. This entry is purely headless, does not come with any UI or styling.
- `vite-plugin-vue-tracer/client/overlay` - The builtin overlay UI for easier to use. A reactive `state` object is exposed to control the overlay's state. If you want to build your own UI, you can use the `listener` entry instead.
## 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 © [Anthony Fu](https://github.com/antfu)
<!-- Badges -->
[npm-version-src]: https://img.shields.io/npm/v/vite-plugin-vue-tracer?style=flat&colorA=080f12&colorB=1fa669
[npm-version-href]: https://npmjs.com/package/vite-plugin-vue-tracer
[npm-downloads-src]: https://img.shields.io/npm/dm/vite-plugin-vue-tracer?style=flat&colorA=080f12&colorB=1fa669
[npm-downloads-href]: https://npmjs.com/package/vite-plugin-vue-tracer
[bundle-src]: https://img.shields.io/bundlephobia/minzip/vite-plugin-vue-tracer?style=flat&colorA=080f12&colorB=1fa669&label=minzip
[bundle-href]: https://bundlephobia.com/result?p=vite-plugin-vue-tracer
[license-src]: https://img.shields.io/github/license/antfu/vite-plugin-vue-tracer.svg?style=flat&colorA=080f12&colorB=1fa669
[license-href]: https://github.com/antfu/vite-plugin-vue-tracer/blob/main/LICENSE
[jsdocs-src]: https://img.shields.io/badge/jsdocs-reference-080f12?style=flat&colorA=080f12&colorB=1fa669
[jsdocs-href]: https://www.jsdocs.io/package/vite-plugin-vue-tracer

View File

@@ -0,0 +1,75 @@
import * as vue from 'vue';
import { ElementTraceInfo } from './record.mjs';
export { PositionInfo, findTraceAtPointer, findTraceFromElement, findTraceFromVNode, getInternalStore, hasData, recordPosition } from './record.mjs';
interface EventsMap {
[event: string]: any
}
interface DefaultEvents extends EventsMap {
[event: string]: (...args: any) => void
}
interface Unsubscribe {
(): void
}
interface Emitter<Events extends EventsMap = DefaultEvents> {
/**
* Calls each of the listeners registered for a given event.
*
* ```js
* ee.emit('tick', tickType, tickDuration)
* ```
*
* @param event The event name.
* @param args The arguments for listeners.
*/
emit<K extends keyof Events>(
this: this,
event: K,
...args: Parameters<Events[K]>
): void
/**
* Event names in keys and arrays with listeners in values.
*
* ```js
* emitter1.events = emitter2.events
* emitter2.events = { }
* ```
*/
events: Partial<{ [E in keyof Events]: Events[E][] }>
/**
* Add a listener for a given event.
*
* ```js
* const unbind = ee.on('tick', (tickType, tickDuration) => {
* count += 1
* })
*
* disable () {
* unbind()
* }
* ```
*
* @param event The event name.
* @param cb The listener function.
* @returns Unbind listener from event.
*/
on<K extends keyof Events>(this: this, event: K, cb: Events[K]): Unsubscribe
}
declare const lastMatchedElement: vue.ShallowRef<ElementTraceInfo | undefined, ElementTraceInfo | undefined>;
interface Events {
hover: (info: ElementTraceInfo | undefined, event: MouseEvent | PointerEvent) => void;
click: (info: ElementTraceInfo, event: MouseEvent | PointerEvent) => void;
enabled: () => void;
disabled: () => void;
}
declare const events: Emitter<Events>;
declare const isEnabled: vue.Ref<boolean, boolean>;
export { ElementTraceInfo, events, isEnabled, lastMatchedElement };
export type { Events };

View File

@@ -0,0 +1,70 @@
import { shallowRef, customRef, ref } from 'vue';
import { getInternalStore, findTraceAtPointer } from './record.mjs';
export { ElementTraceInfo, findTraceFromElement, findTraceFromVNode, hasData, recordPosition } from './record.mjs';
let createNanoEvents = () => ({
emit(event, ...args) {
for (
let callbacks = this.events[event] || [],
i = 0,
length = callbacks.length;
i < length;
i++
) {
callbacks[i](...args);
}
},
events: {},
on(event, cb) {
(this.events[event] ||= []).push(cb);
return () => {
this.events[event] = this.events[event]?.filter(i => cb !== i);
}
}
});
const lastMatchedElement = shallowRef();
const _store = getInternalStore();
const events = _store.events ||= createNanoEvents();
const isEnabled = customRef(() => {
const value = ref(false);
return {
get() {
return value.value;
},
set(newValue) {
if (newValue === value.value)
return;
value.value = newValue;
if (newValue)
events.emit("enabled");
else
events.emit("disabled");
}
};
});
if (typeof document !== "undefined") {
document.addEventListener("pointermove", (e) => {
if (!isEnabled.value)
return;
const result = findTraceAtPointer({ x: e.clientX, y: e.clientY });
if (result?.el === lastMatchedElement.value?.el)
return;
lastMatchedElement.value = result;
events.emit("hover", result, e);
});
document.addEventListener("click", (e) => {
if (!isEnabled.value)
return;
const result = findTraceAtPointer({ x: e.clientX, y: e.clientY });
if (result) {
events.emit("click", result, e);
e.preventDefault();
e.stopPropagation();
e.stopImmediatePropagation();
return false;
}
}, true);
}
export { events, findTraceAtPointer, getInternalStore, isEnabled, lastMatchedElement };

View File

@@ -0,0 +1,50 @@
import * as vue from 'vue';
import { ElementTraceInfo } from './record.mjs';
export { PositionInfo, findTraceAtPointer, findTraceFromElement, findTraceFromVNode, getInternalStore, hasData, recordPosition } from './record.mjs';
export { Events, events, isEnabled, lastMatchedElement } from './listeners.mjs';
declare const state: {
isEnabled: boolean;
isVisible: boolean;
isAnimated: boolean;
isFocused: boolean;
main?: {
pos: [source: string, line: number, column: number];
vnode: vue.VNode | undefined;
el: Element | undefined;
readonly filepath: string;
readonly fullpath: string;
readonly rect: {
height: number;
width: number;
x: number;
y: number;
readonly bottom: number;
readonly left: number;
readonly right: number;
readonly top: number;
toJSON: () => any;
} | undefined;
getElementsSameFile: () => Element[] | undefined;
getParent: () => ElementTraceInfo | undefined;
getElementsSamePosition: () => Element[] | undefined;
} | undefined;
sub: {
rects?: {
id: string;
rect: {
height: number;
width: number;
x: number;
y: number;
readonly bottom: number;
readonly left: number;
readonly right: number;
readonly top: number;
toJSON: () => any;
};
}[] | undefined;
};
};
export { ElementTraceInfo, state };

View File

@@ -0,0 +1,193 @@
import { reactive, watchEffect } from 'vue';
import { isEnabled, events, lastMatchedElement } from './listeners.mjs';
export { ElementTraceInfo, findTraceAtPointer, findTraceFromElement, findTraceFromVNode, getInternalStore, hasData, recordPosition } from './record.mjs';
const state = reactive({
isEnabled,
isVisible: false,
isFocused: false,
isAnimated: true,
sub: {}
});
const ANIMATE_DURATION = "0.15s";
const PADDING_FOCUSED = 10;
function createOverlay() {
const overlay = document.createElement("div");
overlay.id = "vue-tracer-overlay";
Object.assign(overlay.style, {
position: "fixed",
top: "0",
left: "0",
bottom: "0",
right: "0",
zIndex: "999999",
pointerEvents: "none",
opacity: "0"
});
const svg = document.createElementNS("http://www.w3.org/2000/svg", "svg");
Object.assign(svg.style, {
position: "fixed",
top: "0",
left: "0",
bottom: "0",
pointerEvents: "none",
right: "0"
});
svg.setAttribute("width", "100%");
svg.setAttribute("height", "100%");
const mainText = document.createElement("div");
Object.assign(mainText.style, {
position: "fixed",
top: "0",
left: "0",
transition: `all ${ANIMATE_DURATION}`,
backgroundColor: "#197",
color: "#fff",
borderBottomLeftRadius: "4px",
borderBottomRightRadius: "4px",
padding: "1px 4px",
pointerEvents: "none",
fontSize: "10px",
fontFamily: "monospace",
display: "flex",
gap: "0.25rem",
boxShadow: "0 0 2px rgba(0,0,0,0.2)"
});
const mainTextTag = document.createElement("div");
const mainTextPath = document.createElement("div");
Object.assign(mainTextPath.style, {
opacity: "0.75",
fontSize: "9px"
});
mainText.appendChild(mainTextTag);
mainText.appendChild(mainTextPath);
const mainRect = document.createElementNS("http://www.w3.org/2000/svg", "rect");
mainRect.setAttribute("fill", "#1972");
mainRect.setAttribute("stroke", "#197");
mainRect.setAttribute("rx", "4");
mainRect.setAttribute("ry", "4");
overlay.appendChild(svg);
overlay.appendChild(mainText);
svg.appendChild(mainRect);
document.body.appendChild(overlay);
watchEffect(() => {
overlay.style.transition = state.isAnimated ? `all ${ANIMATE_DURATION}` : "none";
mainText.style.transition = state.isAnimated ? `all ${ANIMATE_DURATION}` : "none";
mainRect.style.transition = state.isAnimated ? `all ${ANIMATE_DURATION}` : "none";
overlay.style.opacity = state.isVisible ? "1" : "0";
});
watchEffect(() => {
if (state.main && state.main.rect) {
const rect = state.main.rect;
mainRect.style.opacity = "1";
if (state.isFocused) {
mainRect.setAttribute("rx", "8");
mainRect.setAttribute("ry", "8");
mainRect.setAttribute("x", String(rect.left - PADDING_FOCUSED));
mainRect.setAttribute("y", String(rect.top - PADDING_FOCUSED));
mainRect.setAttribute("width", String(rect.width + PADDING_FOCUSED * 2));
mainRect.setAttribute("height", String(rect.height + PADDING_FOCUSED * 2));
mainRect.style.filter = "blur(1px)";
} else {
mainRect.setAttribute("rx", "4");
mainRect.setAttribute("ry", "4");
mainRect.setAttribute("x", String(rect.left));
mainRect.setAttribute("y", String(rect.top));
mainRect.setAttribute("width", String(rect.width));
mainRect.setAttribute("height", String(rect.height));
mainRect.style.filter = "";
}
mainRect.style.fill = state.isFocused ? "transparent" : "#1972";
mainText.style.opacity = state.isFocused ? "0" : "1";
mainTextTag.textContent = "";
let tagName = "";
if (state.main?.vnode?.type) {
if (typeof state.main?.vnode?.type === "string")
tagName = state.main.vnode.type;
else
tagName = state.main.vnode.type.name;
}
mainTextTag.textContent = tagName ? `<${tagName}>` : "";
mainTextPath.textContent = `${state.main.pos[0]}:${state.main.pos[1]}:${state.main.pos[2]}`;
Object.assign(mainText.style, {
left: `${rect.left + 3}px`,
top: `${rect.top + rect.height - 1}px`
});
} else {
mainText.style.opacity = "0";
mainRect.style.opacity = "0";
}
});
const subMap = /* @__PURE__ */ new Map();
watchEffect(() => {
const toRemove = new Set(subMap.keys());
for (const { id, rect } of state.sub.rects || []) {
toRemove.delete(id);
let cover = subMap.get(id);
if (!cover) {
cover = document.createElementNS("http://www.w3.org/2000/svg", "rect");
cover.setAttribute("fill", "#8482");
cover.setAttribute("stroke", "#848");
cover.setAttribute("rx", "4");
cover.setAttribute("ry", "4");
svg.appendChild(cover);
subMap.set(id, cover);
}
cover.style.transition = state.isAnimated ? `all ${ANIMATE_DURATION}` : "none";
cover.setAttribute("x", String(rect.left));
cover.setAttribute("y", String(rect.top));
cover.setAttribute("width", String(rect.width));
cover.setAttribute("height", String(rect.height));
cover.style.opacity = "1";
}
for (const id of toRemove) {
const cover = subMap.get(id);
if (cover) {
cover.style.opacity = "0";
setTimeout(() => cover.remove(), 300);
subMap.delete(id);
}
}
});
}
const elementId = /* @__PURE__ */ new WeakMap();
function getElementId(el) {
let id = elementId.get(el);
if (!id) {
id = Math.random().toString(16).slice(2);
elementId.set(el, id);
}
return id;
}
function update(result) {
if (!result) {
state.isVisible = false;
state.sub.rects = void 0;
state.main = void 0;
return;
}
state.isVisible = true;
state.main = result;
const samePos = result.getElementsSamePosition();
state.sub.rects = samePos?.map((el) => ({
id: getElementId(el),
rect: el.getBoundingClientRect()
}));
}
function init() {
createOverlay();
events.on("hover", (result) => {
update(result);
});
document.addEventListener("scroll", () => {
if (state.isVisible)
update(lastMatchedElement.value);
});
window.addEventListener("resize", () => {
if (state.isVisible)
update(lastMatchedElement.value);
});
}
init();
export { events, isEnabled, lastMatchedElement, state };

View File

@@ -0,0 +1,44 @@
import { VNode } from 'vue';
type PositionInfo = [
source: string,
line: number,
column: number
];
interface Store {
hasData: boolean;
vnodeToPos: WeakMap<any, PositionInfo>;
fileToVNode: Map<string, WeakSet<any>>;
posToVNode: Map<string, Map<number, Map<number, WeakSet<any>>>>;
events?: any;
}
/**
* @internal
*/
declare function getInternalStore(): Store;
/**
* @internal
*/
declare function recordPosition(source: string, line: number, column: number, node: VNode): VNode;
declare class ElementTraceInfo {
pos: PositionInfo;
vnode: VNode | undefined;
el: Element | undefined;
constructor(pos: PositionInfo, el?: Element, vnode?: VNode);
get filepath(): string;
get fullpath(): string;
get rect(): DOMRect | undefined;
getElementsSameFile(): Element[] | undefined;
getParent(): ElementTraceInfo | undefined;
getElementsSamePosition(): Element[] | undefined;
}
declare function findTraceFromElement(el?: Element | null): ElementTraceInfo | undefined;
declare function findTraceFromVNode(vnode?: VNode, el?: Element): ElementTraceInfo | undefined;
declare function findTraceAtPointer(e: {
x: number;
y: number;
}): ElementTraceInfo | undefined;
declare function hasData(): boolean;
export { ElementTraceInfo, findTraceAtPointer, findTraceFromElement, findTraceFromVNode, getInternalStore, hasData, recordPosition };
export type { PositionInfo };

View File

@@ -0,0 +1,123 @@
const KEY_IGNORE = "data-v-inspector-ignore";
const KEY_GLOBAL = "__vue_tracer__";
let _store = globalThis[KEY_GLOBAL];
if (!_store) {
_store = {
hasData: false,
vnodeToPos: /* @__PURE__ */ new WeakMap(),
fileToVNode: /* @__PURE__ */ new Map(),
posToVNode: /* @__PURE__ */ new Map()
};
Object.defineProperty(globalThis, KEY_GLOBAL, {
value: _store,
configurable: true,
enumerable: false
});
}
function getInternalStore() {
return _store;
}
function recordPosition(source, line, column, node) {
if (!node || typeof node === "string" || typeof node === "number")
return node;
if (!_store.hasData)
_store.hasData = true;
const props = node.props ||= {};
_store.vnodeToPos.set(props, [source, line, column]);
if (!_store.fileToVNode.has(source))
_store.fileToVNode.set(source, /* @__PURE__ */ new WeakSet());
_store.fileToVNode.get(source).add(props);
if (!_store.posToVNode.has(source))
_store.posToVNode.set(source, /* @__PURE__ */ new Map());
const lineMap = _store.posToVNode.get(source);
if (!lineMap.has(line))
lineMap.set(line, /* @__PURE__ */ new Map());
const columnMap = lineMap.get(line);
if (!columnMap.has(column))
columnMap.set(column, /* @__PURE__ */ new WeakSet());
columnMap.get(column).add(props);
return node;
}
function getPositionFromVNode(node) {
const props = node?.props;
if (props)
return _store.vnodeToPos.get(props);
}
class ElementTraceInfo {
pos;
vnode;
el;
constructor(pos, el, vnode) {
this.vnode = vnode;
this.pos = pos;
this.el = el;
}
get filepath() {
return this.pos[0];
}
get fullpath() {
let path = this.pos[0];
if (this.pos[1]) {
path += `:${this.pos[1]}`;
if (this.pos[2])
path += `:${this.pos[2]}`;
}
return path;
}
get rect() {
return this.el?.getBoundingClientRect();
}
getElementsSameFile() {
const pos = this.pos;
const fileVNodeSet = _store.fileToVNode.get(pos[0]);
if (!fileVNodeSet)
return;
const sameFile = fileVNodeSet ? Array.from(document.querySelectorAll("*")).filter((e) => e !== this.el && e.__vnode?.props && fileVNodeSet.has(e.__vnode?.props)) : [];
return sameFile;
}
getParent() {
const parentVNode = this.vnode?.parent;
const parentEl = this.el?.parentElement;
return findTraceFromVNode(parentVNode) ?? findTraceFromElement(parentEl);
}
getElementsSamePosition() {
if (typeof this.vnode?.type !== "string")
return;
const pos = this.pos;
const posVNodeSet = _store.posToVNode.get(pos[0])?.get(pos[1])?.get(pos[2]);
if (!posVNodeSet)
return;
const samePos = posVNodeSet ? Array.from(document.querySelectorAll(this.vnode.type)).filter((e) => e !== this.el && e.__vnode?.props && posVNodeSet.has(e.__vnode?.props)) : [];
return samePos;
}
}
function findTraceFromElement(el) {
if (!el)
return;
const vnode = el.__vnode;
return findTraceFromVNode(vnode, el);
}
function findTraceFromVNode(vnode, el) {
if (!vnode)
return;
const pos = getPositionFromVNode(vnode);
if (!pos)
return;
return new ElementTraceInfo(pos, el ?? vnode?.el ?? void 0, vnode);
}
function findTraceAtPointer(e) {
let elements = document.elementsFromPoint(e.x, e.y);
const ignoreIndex = elements.findIndex((node) => node?.hasAttribute?.(KEY_IGNORE));
if (ignoreIndex !== -1)
elements = elements.slice(ignoreIndex);
for (const el of elements) {
const match = findTraceFromElement(el);
if (match)
return match;
}
}
function hasData() {
return _store.hasData;
}
export { ElementTraceInfo, findTraceAtPointer, findTraceFromElement, findTraceFromVNode, getInternalStore, hasData, recordPosition };

View File

@@ -0,0 +1,5 @@
import { DockClientScriptContext } from '@vitejs/devtools-kit/client';
declare function clientScriptSetup(ctx: DockClientScriptContext): void;
export { clientScriptSetup as default };

View File

@@ -0,0 +1,21 @@
import { events, isEnabled } from 'vite-plugin-vue-tracer/client/listeners';
import { state } from 'vite-plugin-vue-tracer/client/overlay';
function clientScriptSetup(ctx) {
ctx.current.events.on("entry:activated", () => {
events.on("click", (e) => {
ctx.rpc.call("vite:core:open-in-editor", `${e.pos[0]}:${e.pos[1]}:${e.pos[2]}`);
state.isVisible = false;
state.isEnabled = false;
ctx.docks.switchEntry(null);
});
isEnabled.value = true;
state.isVisible = true;
});
ctx.current.events.on("entry:deactivated", () => {
isEnabled.value = false;
state.isVisible = false;
});
}
export { clientScriptSetup as default };

26
node_modules/vite-plugin-vue-tracer/dist/index.d.mts generated vendored Normal file
View File

@@ -0,0 +1,26 @@
import { Plugin } from 'vite';
interface VueTracerOptions {
/**
* Enable this plugin or not, or only enable in certain environment.
*
* @default 'dev'
*/
enabled?: boolean | 'dev' | 'prod';
/**
* Resolve the record entry path to relative path.
* Normally, it should be true.
*
* @default true
*/
resolveRecordEntryPath?: boolean;
/**
* Enable Vite DevTools integration.
*
* @default false
*/
viteDevtools?: boolean;
}
declare function VueTracer(options?: VueTracerOptions): Plugin | undefined;
export { VueTracer, VueTracer as default };

115
node_modules/vite-plugin-vue-tracer/dist/index.mjs generated vendored Normal file
View File

@@ -0,0 +1,115 @@
import process from 'node:process';
import { walk } from 'estree-walker';
import { resolveModulePath } from 'exsolve';
import MagicString from 'magic-string';
import { relative, dirname, isAbsolute } from 'pathe';
import { SourceMapConsumer } from 'source-map-js';
const functions = [
"h",
"_createElementVNode",
"_createElementBlock",
"_createBlock",
"_createVNode",
"_createStaticVNode"
];
const testRe = new RegExp(`\\b(?:${functions.join("|")})\\(`);
function VueTracer(options) {
let {
enabled = "dev",
resolveRecordEntryPath = true,
viteDevtools = false
} = options || {};
if (enabled === false)
return;
const pathRecordDist = resolveModulePath("vite-plugin-vue-tracer/client/record", { from: import.meta.url });
const getRecordPath = (id) => {
if (!resolveRecordEntryPath)
return "vite-plugin-vue-tracer/client/record";
let related = relative(dirname(id), pathRecordDist);
if (!related.startsWith("./") && !isAbsolute(related))
related = `./${related}`;
return related;
};
return {
name: "vite-plugin-vue-tracer",
enforce: "post",
configResolved(config) {
if (enabled === "dev")
enabled = config.command === "serve";
else if (enabled === "prod")
enabled = config.command === "build";
},
transform(code, id) {
if (!enabled)
return;
if (this.environment.name !== "client")
return;
if (!code.includes("_sfc_render("))
return;
if (!code.match(testRe))
return;
if (code.includes("_tracer("))
return;
function offsetToPos(index) {
const lines = code.slice(0, index).split("\n");
return {
line: lines.length,
column: lines[lines.length - 1].length
};
}
const map = this.getCombinedSourcemap();
const consumer = new SourceMapConsumer(map);
const s = new MagicString(code);
const ast = this.parse(code);
let hit = false;
walk(ast, {
enter(node) {
if (node.type !== "CallExpression" || node.callee.type !== "Identifier")
return;
if (!functions.includes(node.callee.name))
return;
const { start, end } = node;
const pos = offsetToPos(start);
const original = consumer.originalPositionFor(pos);
if (original.source === null)
return;
hit = true;
s.appendLeft(start, `_tracer(${original.line},${original.column},`);
s.appendRight(end, `)`);
}
});
if (!hit)
return;
const related = relative(process.cwd(), id);
s.prepend(`import { recordPosition as _tracerRecordPosition } from ${JSON.stringify(getRecordPath(id))}
`);
s.append(`
function _tracer(line, column, vnode) { return _tracerRecordPosition(${JSON.stringify(related)}, line, column, vnode) }
`);
return {
code: s.toString(),
map: s.generateMap({ hires: true })
};
},
// Vite DevTools integration
...viteDevtools ? {
devtools: {
setup(ctx) {
ctx.docks.register({
id: "vue-tracer",
title: "Vue Tracer",
icon: "ph:crosshair-simple-duotone",
type: "action",
action: {
importFrom: "vite-plugin-vue-tracer/client/vite-devtools",
importName: "default"
}
});
}
}
} : {}
};
}
export { VueTracer, VueTracer as default };

View File

@@ -0,0 +1,7 @@
Copyright (c) 2015-20 [these people](https://github.com/Rich-Harris/estree-walker/graphs/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.

View File

@@ -0,0 +1,48 @@
# estree-walker
Simple utility for walking an [ESTree](https://github.com/estree/estree)-compliant AST, such as one generated by [acorn](https://github.com/marijnh/acorn).
## Installation
```bash
npm i estree-walker
```
## Usage
```js
var walk = require('estree-walker').walk;
var acorn = require('acorn');
ast = acorn.parse(sourceCode, options); // https://github.com/acornjs/acorn
walk(ast, {
enter(node, parent, prop, index) {
// some code happens
},
leave(node, parent, prop, index) {
// some code happens
}
});
```
Inside the `enter` function, calling `this.skip()` will prevent the node's children being walked, or the `leave` function (which is optional) being called.
Call `this.replace(new_node)` in either `enter` or `leave` to replace the current node with a new one.
Call `this.remove()` in either `enter` or `leave` to remove the current node.
## Why not use estraverse?
The ESTree spec is evolving to accommodate ES6/7. I've had a couple of experiences where [estraverse](https://github.com/estools/estraverse) was unable to handle an AST generated by recent versions of acorn, because it hard-codes visitor keys.
estree-walker, by contrast, simply enumerates a node's properties to find child nodes (and child lists of nodes), and is therefore resistant to spec changes. It's also much smaller. (The performance, if you're wondering, is basically identical.)
None of which should be taken as criticism of estraverse, which has more features and has been battle-tested in many more situations, and for which I'm very grateful.
## License
MIT

View File

@@ -0,0 +1,38 @@
{
"name": "estree-walker",
"description": "Traverse an ESTree-compliant AST",
"version": "3.0.3",
"private": false,
"author": "Rich Harris",
"license": "MIT",
"repository": {
"type": "git",
"url": "https://github.com/Rich-Harris/estree-walker"
},
"type": "module",
"module": "./src/index.js",
"exports": {
"./package.json": "./package.json",
".": {
"types": "./types/index.d.ts",
"import": "./src/index.js"
}
},
"types": "types/index.d.ts",
"scripts": {
"prepublishOnly": "tsc && npm test",
"test": "uvu test"
},
"dependencies": {
"@types/estree": "^1.0.0"
},
"devDependencies": {
"typescript": "^4.9.0",
"uvu": "^0.5.1"
},
"files": [
"src",
"types",
"README.md"
]
}

View File

@@ -0,0 +1,152 @@
import { WalkerBase } from './walker.js';
/**
* @typedef { import('estree').Node} Node
* @typedef { import('./walker.js').WalkerContext} WalkerContext
* @typedef {(
* this: WalkerContext,
* node: Node,
* parent: Node | null,
* key: string | number | symbol | null | undefined,
* index: number | null | undefined
* ) => Promise<void>} AsyncHandler
*/
export class AsyncWalker extends WalkerBase {
/**
*
* @param {AsyncHandler} [enter]
* @param {AsyncHandler} [leave]
*/
constructor(enter, leave) {
super();
/** @type {boolean} */
this.should_skip = false;
/** @type {boolean} */
this.should_remove = false;
/** @type {Node | null} */
this.replacement = null;
/** @type {WalkerContext} */
this.context = {
skip: () => (this.should_skip = true),
remove: () => (this.should_remove = true),
replace: (node) => (this.replacement = node)
};
/** @type {AsyncHandler | undefined} */
this.enter = enter;
/** @type {AsyncHandler | undefined} */
this.leave = leave;
}
/**
* @template {Node} Parent
* @param {Node} node
* @param {Parent | null} parent
* @param {keyof Parent} [prop]
* @param {number | null} [index]
* @returns {Promise<Node | null>}
*/
async visit(node, parent, prop, index) {
if (node) {
if (this.enter) {
const _should_skip = this.should_skip;
const _should_remove = this.should_remove;
const _replacement = this.replacement;
this.should_skip = false;
this.should_remove = false;
this.replacement = null;
await this.enter.call(this.context, node, parent, prop, index);
if (this.replacement) {
node = this.replacement;
this.replace(parent, prop, index, node);
}
if (this.should_remove) {
this.remove(parent, prop, index);
}
const skipped = this.should_skip;
const removed = this.should_remove;
this.should_skip = _should_skip;
this.should_remove = _should_remove;
this.replacement = _replacement;
if (skipped) return node;
if (removed) return null;
}
/** @type {keyof Node} */
let key;
for (key in node) {
/** @type {unknown} */
const value = node[key];
if (value && typeof value === 'object') {
if (Array.isArray(value)) {
const nodes = /** @type {Array<unknown>} */ (value);
for (let i = 0; i < nodes.length; i += 1) {
const item = nodes[i];
if (isNode(item)) {
if (!(await this.visit(item, node, key, i))) {
// removed
i--;
}
}
}
} else if (isNode(value)) {
await this.visit(value, node, key, null);
}
}
}
if (this.leave) {
const _replacement = this.replacement;
const _should_remove = this.should_remove;
this.replacement = null;
this.should_remove = false;
await this.leave.call(this.context, node, parent, prop, index);
if (this.replacement) {
node = this.replacement;
this.replace(parent, prop, index, node);
}
if (this.should_remove) {
this.remove(parent, prop, index);
}
const removed = this.should_remove;
this.replacement = _replacement;
this.should_remove = _should_remove;
if (removed) return null;
}
}
return node;
}
}
/**
* Ducktype a node.
*
* @param {unknown} value
* @returns {value is Node}
*/
function isNode(value) {
return (
value !== null && typeof value === 'object' && 'type' in value && typeof value.type === 'string'
);
}

View File

@@ -0,0 +1,34 @@
import { SyncWalker } from './sync.js';
import { AsyncWalker } from './async.js';
/**
* @typedef {import('estree').Node} Node
* @typedef {import('./sync.js').SyncHandler} SyncHandler
* @typedef {import('./async.js').AsyncHandler} AsyncHandler
*/
/**
* @param {Node} ast
* @param {{
* enter?: SyncHandler
* leave?: SyncHandler
* }} walker
* @returns {Node | null}
*/
export function walk(ast, { enter, leave }) {
const instance = new SyncWalker(enter, leave);
return instance.visit(ast, null);
}
/**
* @param {Node} ast
* @param {{
* enter?: AsyncHandler
* leave?: AsyncHandler
* }} walker
* @returns {Promise<Node | null>}
*/
export async function asyncWalk(ast, { enter, leave }) {
const instance = new AsyncWalker(enter, leave);
return await instance.visit(ast, null);
}

View File

@@ -0,0 +1,152 @@
import { WalkerBase } from './walker.js';
/**
* @typedef { import('estree').Node} Node
* @typedef { import('./walker.js').WalkerContext} WalkerContext
* @typedef {(
* this: WalkerContext,
* node: Node,
* parent: Node | null,
* key: string | number | symbol | null | undefined,
* index: number | null | undefined
* ) => void} SyncHandler
*/
export class SyncWalker extends WalkerBase {
/**
*
* @param {SyncHandler} [enter]
* @param {SyncHandler} [leave]
*/
constructor(enter, leave) {
super();
/** @type {boolean} */
this.should_skip = false;
/** @type {boolean} */
this.should_remove = false;
/** @type {Node | null} */
this.replacement = null;
/** @type {WalkerContext} */
this.context = {
skip: () => (this.should_skip = true),
remove: () => (this.should_remove = true),
replace: (node) => (this.replacement = node)
};
/** @type {SyncHandler | undefined} */
this.enter = enter;
/** @type {SyncHandler | undefined} */
this.leave = leave;
}
/**
* @template {Node} Parent
* @param {Node} node
* @param {Parent | null} parent
* @param {keyof Parent} [prop]
* @param {number | null} [index]
* @returns {Node | null}
*/
visit(node, parent, prop, index) {
if (node) {
if (this.enter) {
const _should_skip = this.should_skip;
const _should_remove = this.should_remove;
const _replacement = this.replacement;
this.should_skip = false;
this.should_remove = false;
this.replacement = null;
this.enter.call(this.context, node, parent, prop, index);
if (this.replacement) {
node = this.replacement;
this.replace(parent, prop, index, node);
}
if (this.should_remove) {
this.remove(parent, prop, index);
}
const skipped = this.should_skip;
const removed = this.should_remove;
this.should_skip = _should_skip;
this.should_remove = _should_remove;
this.replacement = _replacement;
if (skipped) return node;
if (removed) return null;
}
/** @type {keyof Node} */
let key;
for (key in node) {
/** @type {unknown} */
const value = node[key];
if (value && typeof value === 'object') {
if (Array.isArray(value)) {
const nodes = /** @type {Array<unknown>} */ (value);
for (let i = 0; i < nodes.length; i += 1) {
const item = nodes[i];
if (isNode(item)) {
if (!this.visit(item, node, key, i)) {
// removed
i--;
}
}
}
} else if (isNode(value)) {
this.visit(value, node, key, null);
}
}
}
if (this.leave) {
const _replacement = this.replacement;
const _should_remove = this.should_remove;
this.replacement = null;
this.should_remove = false;
this.leave.call(this.context, node, parent, prop, index);
if (this.replacement) {
node = this.replacement;
this.replace(parent, prop, index, node);
}
if (this.should_remove) {
this.remove(parent, prop, index);
}
const removed = this.should_remove;
this.replacement = _replacement;
this.should_remove = _should_remove;
if (removed) return null;
}
}
return node;
}
}
/**
* Ducktype a node.
*
* @param {unknown} value
* @returns {value is Node}
*/
function isNode(value) {
return (
value !== null && typeof value === 'object' && 'type' in value && typeof value.type === 'string'
);
}

View File

@@ -0,0 +1,61 @@
/**
* @typedef { import('estree').Node} Node
* @typedef {{
* skip: () => void;
* remove: () => void;
* replace: (node: Node) => void;
* }} WalkerContext
*/
export class WalkerBase {
constructor() {
/** @type {boolean} */
this.should_skip = false;
/** @type {boolean} */
this.should_remove = false;
/** @type {Node | null} */
this.replacement = null;
/** @type {WalkerContext} */
this.context = {
skip: () => (this.should_skip = true),
remove: () => (this.should_remove = true),
replace: (node) => (this.replacement = node)
};
}
/**
* @template {Node} Parent
* @param {Parent | null | undefined} parent
* @param {keyof Parent | null | undefined} prop
* @param {number | null | undefined} index
* @param {Node} node
*/
replace(parent, prop, index, node) {
if (parent && prop) {
if (index != null) {
/** @type {Array<Node>} */ (parent[prop])[index] = node;
} else {
/** @type {Node} */ (parent[prop]) = node;
}
}
}
/**
* @template {Node} Parent
* @param {Parent | null | undefined} parent
* @param {keyof Parent | null | undefined} prop
* @param {number | null | undefined} index
*/
remove(parent, prop, index) {
if (parent && prop) {
if (index !== null && index !== undefined) {
/** @type {Array<Node>} */ (parent[prop]).splice(index, 1);
} else {
delete parent[prop];
}
}
}
}

View File

@@ -0,0 +1,36 @@
/**
* @typedef { import('estree').Node} Node
* @typedef { import('./walker.js').WalkerContext} WalkerContext
* @typedef {(
* this: WalkerContext,
* node: Node,
* parent: Node | null,
* key: string | number | symbol | null | undefined,
* index: number | null | undefined
* ) => Promise<void>} AsyncHandler
*/
export class AsyncWalker extends WalkerBase {
/**
*
* @param {AsyncHandler} [enter]
* @param {AsyncHandler} [leave]
*/
constructor(enter?: AsyncHandler | undefined, leave?: AsyncHandler | undefined);
/** @type {AsyncHandler | undefined} */
enter: AsyncHandler | undefined;
/** @type {AsyncHandler | undefined} */
leave: AsyncHandler | undefined;
/**
* @template {Node} Parent
* @param {Node} node
* @param {Parent | null} parent
* @param {keyof Parent} [prop]
* @param {number | null} [index]
* @returns {Promise<Node | null>}
*/
visit<Parent extends import("estree").Node>(node: Node, parent: Parent | null, prop?: keyof Parent | undefined, index?: number | null | undefined): Promise<Node | null>;
}
export type Node = import('estree').Node;
export type WalkerContext = import('./walker.js').WalkerContext;
export type AsyncHandler = (this: WalkerContext, node: Node, parent: Node | null, key: string | number | symbol | null | undefined, index: number | null | undefined) => Promise<void>;
import { WalkerBase } from "./walker.js";

View File

@@ -0,0 +1,32 @@
/**
* @typedef {import('estree').Node} Node
* @typedef {import('./sync.js').SyncHandler} SyncHandler
* @typedef {import('./async.js').AsyncHandler} AsyncHandler
*/
/**
* @param {Node} ast
* @param {{
* enter?: SyncHandler
* leave?: SyncHandler
* }} walker
* @returns {Node | null}
*/
export function walk(ast: Node, { enter, leave }: {
enter?: SyncHandler;
leave?: SyncHandler;
}): Node | null;
/**
* @param {Node} ast
* @param {{
* enter?: AsyncHandler
* leave?: AsyncHandler
* }} walker
* @returns {Promise<Node | null>}
*/
export function asyncWalk(ast: Node, { enter, leave }: {
enter?: AsyncHandler;
leave?: AsyncHandler;
}): Promise<Node | null>;
export type Node = import('estree').Node;
export type SyncHandler = import('./sync.js').SyncHandler;
export type AsyncHandler = import('./async.js').AsyncHandler;

View File

@@ -0,0 +1,36 @@
/**
* @typedef { import('estree').Node} Node
* @typedef { import('./walker.js').WalkerContext} WalkerContext
* @typedef {(
* this: WalkerContext,
* node: Node,
* parent: Node | null,
* key: string | number | symbol | null | undefined,
* index: number | null | undefined
* ) => void} SyncHandler
*/
export class SyncWalker extends WalkerBase {
/**
*
* @param {SyncHandler} [enter]
* @param {SyncHandler} [leave]
*/
constructor(enter?: SyncHandler | undefined, leave?: SyncHandler | undefined);
/** @type {SyncHandler | undefined} */
enter: SyncHandler | undefined;
/** @type {SyncHandler | undefined} */
leave: SyncHandler | undefined;
/**
* @template {Node} Parent
* @param {Node} node
* @param {Parent | null} parent
* @param {keyof Parent} [prop]
* @param {number | null} [index]
* @returns {Node | null}
*/
visit<Parent extends import("estree").Node>(node: Node, parent: Parent | null, prop?: keyof Parent | undefined, index?: number | null | undefined): Node | null;
}
export type Node = import('estree').Node;
export type WalkerContext = import('./walker.js').WalkerContext;
export type SyncHandler = (this: WalkerContext, node: Node, parent: Node | null, key: string | number | symbol | null | undefined, index: number | null | undefined) => void;
import { WalkerBase } from "./walker.js";

View File

@@ -0,0 +1,39 @@
/**
* @typedef { import('estree').Node} Node
* @typedef {{
* skip: () => void;
* remove: () => void;
* replace: (node: Node) => void;
* }} WalkerContext
*/
export class WalkerBase {
/** @type {boolean} */
should_skip: boolean;
/** @type {boolean} */
should_remove: boolean;
/** @type {Node | null} */
replacement: Node | null;
/** @type {WalkerContext} */
context: WalkerContext;
/**
* @template {Node} Parent
* @param {Parent | null | undefined} parent
* @param {keyof Parent | null | undefined} prop
* @param {number | null | undefined} index
* @param {Node} node
*/
replace<Parent extends import("estree").Node>(parent: Parent | null | undefined, prop: keyof Parent | null | undefined, index: number | null | undefined, node: Node): void;
/**
* @template {Node} Parent
* @param {Parent | null | undefined} parent
* @param {keyof Parent | null | undefined} prop
* @param {number | null | undefined} index
*/
remove<Parent_1 extends import("estree").Node>(parent: Parent_1 | null | undefined, prop: keyof Parent_1 | null | undefined, index: number | null | undefined): void;
}
export type Node = import('estree').Node;
export type WalkerContext = {
skip: () => void;
remove: () => void;
replace: (node: Node) => void;
};

View File

@@ -0,0 +1,70 @@
MIT License
Copyright (c) Pooya Parsa <pooya@pi0.io> - Daniel Roe <daniel@roe.dev>
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
---
Copyright Joyent, Inc. and other Node contributors.
Permission is hereby granted, free of charge, to any person obtaining a
copy of this software and associated documentation files (the
"Software"), to deal in the Software without restriction, including
without limitation the rights to use, copy, modify, merge, publish,
distribute, sublicense, and/or sell copies of the Software, and to permit
persons to whom the Software is furnished to do so, subject to the
following conditions:
The above copyright notice and this permission notice shall be included
in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
USE OR OTHER DEALINGS IN THE SOFTWARE.
---
Bundled zeptomatch (https://github.com/fabiospampinato/zeptomatch)
The MIT License (MIT)
Copyright (c) 2023-present Fabio Spampinato
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.

View File

@@ -0,0 +1,73 @@
# 🛣️ pathe
> Universal filesystem path utils
[![version][npm-v-src]][npm-v-href]
[![downloads][npm-d-src]][npm-d-href]
[![size][size-src]][size-href]
## ❓ Why
For [historical reasons](https://docs.microsoft.com/en-us/archive/blogs/larryosterman/why-is-the-dos-path-character), windows followed MS-DOS and used backslash for separating paths rather than slash used for macOS, Linux, and other Posix operating systems. Nowadays, [Windows](https://docs.microsoft.com/en-us/windows/win32/fileio/naming-a-file?redirectedfrom=MSDN) supports both Slash and Backslash for paths. [Node.js's built-in `path` module](https://nodejs.org/api/path.html) in the default operation of the path module varies based on the operating system on which a Node.js application is running. Specifically, when running on a Windows operating system, the path module will assume that Windows-style paths are being used. **This makes inconsistent code behavior between Windows and POSIX.**
Compared to popular [upath](https://github.com/anodynos/upath), pathe provides **identical exports** of Node.js with normalization on **all operations** and is written in modern **ESM/TypeScript** and has **no dependency on Node.js**!
This package is a drop-in replacement of the Node.js's [path module](https://nodejs.org/api/path.html) module and ensures paths are normalized with slash `/` and work in environments including Node.js.
## 💿 Usage
Install using npm or yarn:
```bash
# npm
npm i pathe
# yarn
yarn add pathe
# pnpm
pnpm i pathe
```
Import:
```js
// ESM / Typescript
import { resolve, matchesGlob } from "pathe";
// CommonJS
const { resolve, matchesGlob } = require("pathe");
```
Read more about path utils from [Node.js documentation](https://nodejs.org/api/path.html) and rest assured behavior is consistently like POSIX regardless of your input paths format and running platform (the only exception is `delimiter` constant export, it will be set to `;` on windows platform).
### Extra utilities
Pathe exports some extra utilities that do not exist in standard Node.js [path module](https://nodejs.org/api/path.html).
In order to use them, you can import from `pathe/utils` subpath:
```js
import {
filename,
normalizeAliases,
resolveAlias,
reverseResolveAlias,
} from "pathe/utils";
```
## License
Made with 💛 Published under the [MIT](./LICENSE) license.
Some code was used from the Node.js project. Glob supported is powered by [zeptomatch](https://github.com/fabiospampinato/zeptomatch).
<!-- 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

View File

@@ -0,0 +1,39 @@
'use strict';
Object.defineProperty(exports, '__esModule', { value: true });
const _path = require('./shared/pathe.BSlhyZSM.cjs');
const delimiter = /* @__PURE__ */ (() => globalThis.process?.platform === "win32" ? ";" : ":")();
const _platforms = { posix: void 0, win32: void 0 };
const mix = (del = delimiter) => {
return new Proxy(_path._path, {
get(_, prop) {
if (prop === "delimiter") return del;
if (prop === "posix") return posix;
if (prop === "win32") return win32;
return _platforms[prop] || _path._path[prop];
}
});
};
const posix = /* @__PURE__ */ mix(":");
const win32 = /* @__PURE__ */ mix(";");
exports.basename = _path.basename;
exports.dirname = _path.dirname;
exports.extname = _path.extname;
exports.format = _path.format;
exports.isAbsolute = _path.isAbsolute;
exports.join = _path.join;
exports.matchesGlob = _path.matchesGlob;
exports.normalize = _path.normalize;
exports.normalizeString = _path.normalizeString;
exports.parse = _path.parse;
exports.relative = _path.relative;
exports.resolve = _path.resolve;
exports.sep = _path.sep;
exports.toNamespacedPath = _path.toNamespacedPath;
exports.default = posix;
exports.delimiter = delimiter;
exports.posix = posix;
exports.win32 = win32;

View File

@@ -0,0 +1,47 @@
import * as path from 'node:path';
import path__default from 'node:path';
/**
* Constant for path separator.
*
* Always equals to `"/"`.
*/
declare const sep = "/";
declare const normalize: typeof path__default.normalize;
declare const join: typeof path__default.join;
declare const resolve: typeof path__default.resolve;
/**
* Resolves a string path, resolving '.' and '.' segments and allowing paths above the root.
*
* @param path - The path to normalise.
* @param allowAboveRoot - Whether to allow the resulting path to be above the root directory.
* @returns the normalised path string.
*/
declare function normalizeString(path: string, allowAboveRoot: boolean): string;
declare const isAbsolute: typeof path__default.isAbsolute;
declare const toNamespacedPath: typeof path__default.toNamespacedPath;
declare const extname: typeof path__default.extname;
declare const relative: typeof path__default.relative;
declare const dirname: typeof path__default.dirname;
declare const format: typeof path__default.format;
declare const basename: typeof path__default.basename;
declare const parse: typeof path__default.parse;
/**
* The `path.matchesGlob()` method determines if `path` matches the `pattern`.
* @param path The path to glob-match against.
* @param pattern The glob to check the path against.
*/
declare const matchesGlob: (path: string, pattern: string | string[]) => boolean;
type NodePath = typeof path;
/**
* The platform-specific file delimiter.
*
* Equals to `";"` in windows and `":"` in all other platforms.
*/
declare const delimiter: ";" | ":";
declare const posix: NodePath["posix"];
declare const win32: NodePath["win32"];
declare const _default: NodePath;
export { basename, _default as default, delimiter, dirname, extname, format, isAbsolute, join, matchesGlob, normalize, normalizeString, parse, posix, relative, resolve, sep, toNamespacedPath, win32 };

View File

@@ -0,0 +1,47 @@
import * as path from 'node:path';
import path__default from 'node:path';
/**
* Constant for path separator.
*
* Always equals to `"/"`.
*/
declare const sep = "/";
declare const normalize: typeof path__default.normalize;
declare const join: typeof path__default.join;
declare const resolve: typeof path__default.resolve;
/**
* Resolves a string path, resolving '.' and '.' segments and allowing paths above the root.
*
* @param path - The path to normalise.
* @param allowAboveRoot - Whether to allow the resulting path to be above the root directory.
* @returns the normalised path string.
*/
declare function normalizeString(path: string, allowAboveRoot: boolean): string;
declare const isAbsolute: typeof path__default.isAbsolute;
declare const toNamespacedPath: typeof path__default.toNamespacedPath;
declare const extname: typeof path__default.extname;
declare const relative: typeof path__default.relative;
declare const dirname: typeof path__default.dirname;
declare const format: typeof path__default.format;
declare const basename: typeof path__default.basename;
declare const parse: typeof path__default.parse;
/**
* The `path.matchesGlob()` method determines if `path` matches the `pattern`.
* @param path The path to glob-match against.
* @param pattern The glob to check the path against.
*/
declare const matchesGlob: (path: string, pattern: string | string[]) => boolean;
type NodePath = typeof path;
/**
* The platform-specific file delimiter.
*
* Equals to `";"` in windows and `":"` in all other platforms.
*/
declare const delimiter: ";" | ":";
declare const posix: NodePath["posix"];
declare const win32: NodePath["win32"];
declare const _default: NodePath;
export { basename, _default as default, delimiter, dirname, extname, format, isAbsolute, join, matchesGlob, normalize, normalizeString, parse, posix, relative, resolve, sep, toNamespacedPath, win32 };

View File

@@ -0,0 +1,47 @@
import * as path from 'node:path';
import path__default from 'node:path';
/**
* Constant for path separator.
*
* Always equals to `"/"`.
*/
declare const sep = "/";
declare const normalize: typeof path__default.normalize;
declare const join: typeof path__default.join;
declare const resolve: typeof path__default.resolve;
/**
* Resolves a string path, resolving '.' and '.' segments and allowing paths above the root.
*
* @param path - The path to normalise.
* @param allowAboveRoot - Whether to allow the resulting path to be above the root directory.
* @returns the normalised path string.
*/
declare function normalizeString(path: string, allowAboveRoot: boolean): string;
declare const isAbsolute: typeof path__default.isAbsolute;
declare const toNamespacedPath: typeof path__default.toNamespacedPath;
declare const extname: typeof path__default.extname;
declare const relative: typeof path__default.relative;
declare const dirname: typeof path__default.dirname;
declare const format: typeof path__default.format;
declare const basename: typeof path__default.basename;
declare const parse: typeof path__default.parse;
/**
* The `path.matchesGlob()` method determines if `path` matches the `pattern`.
* @param path The path to glob-match against.
* @param pattern The glob to check the path against.
*/
declare const matchesGlob: (path: string, pattern: string | string[]) => boolean;
type NodePath = typeof path;
/**
* The platform-specific file delimiter.
*
* Equals to `";"` in windows and `":"` in all other platforms.
*/
declare const delimiter: ";" | ":";
declare const posix: NodePath["posix"];
declare const win32: NodePath["win32"];
declare const _default: NodePath;
export { basename, _default as default, delimiter, dirname, extname, format, isAbsolute, join, matchesGlob, normalize, normalizeString, parse, posix, relative, resolve, sep, toNamespacedPath, win32 };

View File

@@ -0,0 +1,19 @@
import { _ as _path } from './shared/pathe.M-eThtNZ.mjs';
export { c as basename, d as dirname, e as extname, f as format, i as isAbsolute, j as join, m as matchesGlob, n as normalize, a as normalizeString, p as parse, b as relative, r as resolve, s as sep, t as toNamespacedPath } from './shared/pathe.M-eThtNZ.mjs';
const delimiter = /* @__PURE__ */ (() => globalThis.process?.platform === "win32" ? ";" : ":")();
const _platforms = { posix: void 0, win32: void 0 };
const mix = (del = delimiter) => {
return new Proxy(_path, {
get(_, prop) {
if (prop === "delimiter") return del;
if (prop === "posix") return posix;
if (prop === "win32") return win32;
return _platforms[prop] || _path[prop];
}
});
};
const posix = /* @__PURE__ */ mix(":");
const win32 = /* @__PURE__ */ mix(";");
export { posix as default, delimiter, posix, win32 };

File diff suppressed because one or more lines are too long

File diff suppressed because one or more lines are too long

View File

@@ -0,0 +1,82 @@
'use strict';
const _path = require('./shared/pathe.BSlhyZSM.cjs');
const pathSeparators = /* @__PURE__ */ new Set(["/", "\\", void 0]);
const normalizedAliasSymbol = Symbol.for("pathe:normalizedAlias");
const SLASH_RE = /[/\\]/;
function normalizeAliases(_aliases) {
if (_aliases[normalizedAliasSymbol]) {
return _aliases;
}
const aliases = Object.fromEntries(
Object.entries(_aliases).sort(([a], [b]) => _compareAliases(a, b))
);
for (const key in aliases) {
for (const alias in aliases) {
if (alias === key || key.startsWith(alias)) {
continue;
}
if (aliases[key]?.startsWith(alias) && pathSeparators.has(aliases[key][alias.length])) {
aliases[key] = aliases[alias] + aliases[key].slice(alias.length);
}
}
}
Object.defineProperty(aliases, normalizedAliasSymbol, {
value: true,
enumerable: false
});
return aliases;
}
function resolveAlias(path, aliases) {
const _path$1 = _path.normalizeWindowsPath(path);
aliases = normalizeAliases(aliases);
for (const [alias, to] of Object.entries(aliases)) {
if (!_path$1.startsWith(alias)) {
continue;
}
const _alias = hasTrailingSlash(alias) ? alias.slice(0, -1) : alias;
if (hasTrailingSlash(_path$1[_alias.length])) {
return _path.join(to, _path$1.slice(alias.length));
}
}
return _path$1;
}
function reverseResolveAlias(path, aliases) {
const _path$1 = _path.normalizeWindowsPath(path);
aliases = normalizeAliases(aliases);
const matches = [];
for (const [to, alias] of Object.entries(aliases)) {
if (!_path$1.startsWith(alias)) {
continue;
}
const _alias = hasTrailingSlash(alias) ? alias.slice(0, -1) : alias;
if (hasTrailingSlash(_path$1[_alias.length])) {
matches.push(_path.join(to, _path$1.slice(alias.length)));
}
}
return matches.sort((a, b) => b.length - a.length);
}
function filename(path) {
const base = path.split(SLASH_RE).pop();
if (!base) {
return void 0;
}
const separatorIndex = base.lastIndexOf(".");
if (separatorIndex <= 0) {
return base;
}
return base.slice(0, separatorIndex);
}
function _compareAliases(a, b) {
return b.split("/").length - a.split("/").length;
}
function hasTrailingSlash(path = "/") {
const lastChar = path[path.length - 1];
return lastChar === "/" || lastChar === "\\";
}
exports.filename = filename;
exports.normalizeAliases = normalizeAliases;
exports.resolveAlias = resolveAlias;
exports.reverseResolveAlias = reverseResolveAlias;

View File

@@ -0,0 +1,32 @@
/**
* Normalises alias mappings, ensuring that more specific aliases are resolved before less specific ones.
* This function also ensures that aliases do not resolve to themselves cyclically.
*
* @param _aliases - A set of alias mappings where each key is an alias and its value is the actual path it points to.
* @returns a set of normalised alias mappings.
*/
declare function normalizeAliases(_aliases: Record<string, string>): Record<string, string>;
/**
* Resolves a path string to its alias if applicable, otherwise returns the original path.
* This function normalises the path, resolves the alias and then joins it to the alias target if necessary.
*
* @param path - The path string to resolve.
* @param aliases - A set of alias mappings to use for resolution.
* @returns the resolved path as a string.
*/
declare function resolveAlias(path: string, aliases: Record<string, string>): string;
/**
* Resolves a path string to its possible alias.
*
* Returns an array of possible alias resolutions (could be empty), sorted by specificity (longest first).
*/
declare function reverseResolveAlias(path: string, aliases: Record<string, string>): string[];
/**
* Extracts the filename from a given path, excluding any directory paths and the file extension.
*
* @param path - The full path of the file from which to extract the filename.
* @returns the filename without the extension, or `undefined` if the filename cannot be extracted.
*/
declare function filename(path: string): string | undefined;
export { filename, normalizeAliases, resolveAlias, reverseResolveAlias };

View File

@@ -0,0 +1,32 @@
/**
* Normalises alias mappings, ensuring that more specific aliases are resolved before less specific ones.
* This function also ensures that aliases do not resolve to themselves cyclically.
*
* @param _aliases - A set of alias mappings where each key is an alias and its value is the actual path it points to.
* @returns a set of normalised alias mappings.
*/
declare function normalizeAliases(_aliases: Record<string, string>): Record<string, string>;
/**
* Resolves a path string to its alias if applicable, otherwise returns the original path.
* This function normalises the path, resolves the alias and then joins it to the alias target if necessary.
*
* @param path - The path string to resolve.
* @param aliases - A set of alias mappings to use for resolution.
* @returns the resolved path as a string.
*/
declare function resolveAlias(path: string, aliases: Record<string, string>): string;
/**
* Resolves a path string to its possible alias.
*
* Returns an array of possible alias resolutions (could be empty), sorted by specificity (longest first).
*/
declare function reverseResolveAlias(path: string, aliases: Record<string, string>): string[];
/**
* Extracts the filename from a given path, excluding any directory paths and the file extension.
*
* @param path - The full path of the file from which to extract the filename.
* @returns the filename without the extension, or `undefined` if the filename cannot be extracted.
*/
declare function filename(path: string): string | undefined;
export { filename, normalizeAliases, resolveAlias, reverseResolveAlias };

View File

@@ -0,0 +1,32 @@
/**
* Normalises alias mappings, ensuring that more specific aliases are resolved before less specific ones.
* This function also ensures that aliases do not resolve to themselves cyclically.
*
* @param _aliases - A set of alias mappings where each key is an alias and its value is the actual path it points to.
* @returns a set of normalised alias mappings.
*/
declare function normalizeAliases(_aliases: Record<string, string>): Record<string, string>;
/**
* Resolves a path string to its alias if applicable, otherwise returns the original path.
* This function normalises the path, resolves the alias and then joins it to the alias target if necessary.
*
* @param path - The path string to resolve.
* @param aliases - A set of alias mappings to use for resolution.
* @returns the resolved path as a string.
*/
declare function resolveAlias(path: string, aliases: Record<string, string>): string;
/**
* Resolves a path string to its possible alias.
*
* Returns an array of possible alias resolutions (could be empty), sorted by specificity (longest first).
*/
declare function reverseResolveAlias(path: string, aliases: Record<string, string>): string[];
/**
* Extracts the filename from a given path, excluding any directory paths and the file extension.
*
* @param path - The full path of the file from which to extract the filename.
* @returns the filename without the extension, or `undefined` if the filename cannot be extracted.
*/
declare function filename(path: string): string | undefined;
export { filename, normalizeAliases, resolveAlias, reverseResolveAlias };

View File

@@ -0,0 +1,77 @@
import { g as normalizeWindowsPath, j as join } from './shared/pathe.M-eThtNZ.mjs';
const pathSeparators = /* @__PURE__ */ new Set(["/", "\\", void 0]);
const normalizedAliasSymbol = Symbol.for("pathe:normalizedAlias");
const SLASH_RE = /[/\\]/;
function normalizeAliases(_aliases) {
if (_aliases[normalizedAliasSymbol]) {
return _aliases;
}
const aliases = Object.fromEntries(
Object.entries(_aliases).sort(([a], [b]) => _compareAliases(a, b))
);
for (const key in aliases) {
for (const alias in aliases) {
if (alias === key || key.startsWith(alias)) {
continue;
}
if (aliases[key]?.startsWith(alias) && pathSeparators.has(aliases[key][alias.length])) {
aliases[key] = aliases[alias] + aliases[key].slice(alias.length);
}
}
}
Object.defineProperty(aliases, normalizedAliasSymbol, {
value: true,
enumerable: false
});
return aliases;
}
function resolveAlias(path, aliases) {
const _path = normalizeWindowsPath(path);
aliases = normalizeAliases(aliases);
for (const [alias, to] of Object.entries(aliases)) {
if (!_path.startsWith(alias)) {
continue;
}
const _alias = hasTrailingSlash(alias) ? alias.slice(0, -1) : alias;
if (hasTrailingSlash(_path[_alias.length])) {
return join(to, _path.slice(alias.length));
}
}
return _path;
}
function reverseResolveAlias(path, aliases) {
const _path = normalizeWindowsPath(path);
aliases = normalizeAliases(aliases);
const matches = [];
for (const [to, alias] of Object.entries(aliases)) {
if (!_path.startsWith(alias)) {
continue;
}
const _alias = hasTrailingSlash(alias) ? alias.slice(0, -1) : alias;
if (hasTrailingSlash(_path[_alias.length])) {
matches.push(join(to, _path.slice(alias.length)));
}
}
return matches.sort((a, b) => b.length - a.length);
}
function filename(path) {
const base = path.split(SLASH_RE).pop();
if (!base) {
return void 0;
}
const separatorIndex = base.lastIndexOf(".");
if (separatorIndex <= 0) {
return base;
}
return base.slice(0, separatorIndex);
}
function _compareAliases(a, b) {
return b.split("/").length - a.split("/").length;
}
function hasTrailingSlash(path = "/") {
const lastChar = path[path.length - 1];
return lastChar === "/" || lastChar === "\\";
}
export { filename, normalizeAliases, resolveAlias, reverseResolveAlias };

View File

@@ -0,0 +1,61 @@
{
"name": "pathe",
"version": "2.0.3",
"description": "Universal filesystem path utils",
"repository": "unjs/pathe",
"license": "MIT",
"sideEffects": false,
"type": "module",
"exports": {
".": {
"import": {
"types": "./dist/index.d.mts",
"default": "./dist/index.mjs"
},
"require": {
"types": "./dist/index.d.cts",
"default": "./dist/index.cjs"
}
},
"./utils": {
"import": {
"types": "./dist/utils.d.mts",
"default": "./dist/utils.mjs"
},
"require": {
"types": "./dist/utils.d.cts",
"default": "./dist/utils.cjs"
}
}
},
"main": "./dist/index.cjs",
"module": "./dist/index.mjs",
"types": "./dist/index.d.ts",
"files": [
"dist",
"utils.d.ts"
],
"devDependencies": {
"@types/node": "^22.13.1",
"@vitest/coverage-v8": "^3.0.5",
"changelogen": "^0.5.7",
"esbuild": "^0.25.0",
"eslint": "^9.20.1",
"eslint-config-unjs": "^0.4.2",
"jiti": "^2.4.2",
"prettier": "^3.5.0",
"typescript": "^5.7.3",
"unbuild": "^3.3.1",
"vitest": "^3.0.5",
"zeptomatch": "^2.0.0"
},
"scripts": {
"build": "unbuild",
"dev": "vitest",
"lint": "eslint . && prettier -c src test",
"lint:fix": "eslint . --fix && prettier -w src test",
"release": "pnpm test && pnpm build && changelogen --release && pnpm publish && git push --follow-tags",
"test": "pnpm lint && vitest run --coverage",
"test:types": "tsc --noEmit"
}
}

View File

@@ -0,0 +1 @@
export * from "./dist/utils";

81
node_modules/vite-plugin-vue-tracer/package.json generated vendored Normal file
View File

@@ -0,0 +1,81 @@
{
"name": "vite-plugin-vue-tracer",
"type": "module",
"version": "1.2.0",
"description": "Tracer for the source code of elements and vdoms in Vue SFC",
"author": "Anthony Fu <anthonyfu117@hotmail.com>",
"license": "MIT",
"funding": "https://github.com/sponsors/antfu",
"homepage": "https://github.com/antfu/vite-plugin-vue-tracer#readme",
"repository": {
"type": "git",
"url": "git+https://github.com/antfu/vite-plugin-vue-tracer.git"
},
"bugs": "https://github.com/antfu/vite-plugin-vue-tracer/issues",
"keywords": [
"vue",
"vite-plugin",
"devtools"
],
"exports": {
".": "./dist/index.mjs",
"./client/record": "./dist/client/record.mjs",
"./client/overlay": "./dist/client/overlay.mjs",
"./client/listeners": "./dist/client/listeners.mjs",
"./client/vite-devtools": "./dist/client/vite-devtools.mjs"
},
"main": "./dist/index.mjs",
"module": "./dist/index.mjs",
"types": "./dist/index.d.mts",
"files": [
"dist"
],
"peerDependencies": {
"vite": "^6.0.0 || ^7.0.0",
"vue": "^3.5.0"
},
"dependencies": {
"estree-walker": "^3.0.3",
"exsolve": "^1.0.8",
"magic-string": "^0.30.21",
"pathe": "^2.0.3",
"source-map-js": "^1.2.1"
},
"devDependencies": {
"@antfu/eslint-config": "^6.7.1",
"@antfu/ni": "^28.0.0",
"@antfu/utils": "^9.3.0",
"@types/node": "^25.0.2",
"@vitejs/devtools": "^0.0.0-alpha.20",
"@vitejs/devtools-kit": "^0.0.0-alpha.20",
"bumpp": "^10.3.2",
"eslint": "^9.39.2",
"lint-staged": "^16.2.7",
"nanoevents": "^9.1.0",
"simple-git-hooks": "^2.13.1",
"tsx": "^4.21.0",
"typescript": "^5.9.3",
"unbuild": "^3.6.1",
"vite": "^7.3.0",
"vitest": "^4.0.15",
"vue": "^3.5.25",
"vue-tsc": "^3.1.8",
"vite-plugin-vue-tracer": "1.2.0"
},
"simple-git-hooks": {
"pre-commit": "pnpm lint-staged"
},
"lint-staged": {
"*": "eslint --fix"
},
"scripts": {
"build": "unbuild",
"dev": "unbuild --stub",
"lint": "eslint .",
"play": "nr -C playground play",
"release": "bumpp",
"start": "tsx src/index.ts",
"test": "vitest",
"typecheck": "vue-tsc --noEmit"
}
}